@kabxx/dsh-session-move 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -7
- package/package.json +1 -1
- package/src/client.js +317 -15
- package/src/history-process.js +190 -0
- package/src/history-stream.js +483 -0
- package/src/history-worker.js +180 -0
- package/src/history.js +44 -0
- package/src/ledger.js +0 -20
- package/src/move.js +74 -42
- package/src/plan.js +22 -2
- package/src/platform-fs.js +11 -2
- package/src/recovery.js +21 -19
- package/src/sidebar.js +100 -25
- package/src/transaction.js +426 -84
- package/src/zstd-frame.js +87 -51
- package/src/inbox.js +0 -39
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { isAbsolute } from 'node:path'
|
|
2
|
+
import { historyMessageBytes, historyReady, historyWorkerArg, verifyHistoryIsolation } from './history-process.js'
|
|
3
|
+
import { MAX_SUMMARY_STRING_BYTES, scanHistory } from './history-stream.js'
|
|
4
|
+
|
|
5
|
+
const maxPendingMessages = 8192
|
|
6
|
+
const maxPendingIdBytes = 1024 * 1024
|
|
7
|
+
const oversizedSummary = Symbol('oversized summary')
|
|
8
|
+
const sequence = (value) => Number.isSafeInteger(value) && value >= 0
|
|
9
|
+
const directory = (value) => typeof value === 'string' && isAbsolute(value) && !value.includes('\0')
|
|
10
|
+
|
|
11
|
+
// A short JSON string may otherwise retain its whole decoded source line.
|
|
12
|
+
function retainString(value) {
|
|
13
|
+
return Buffer.from(value, 'utf16le').toString('utf16le')
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function retainSummary(value) {
|
|
17
|
+
return Buffer.byteLength(value) <= MAX_SUMMARY_STRING_BYTES ? retainString(value) : oversizedSummary
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function historyError(code, message, cause) {
|
|
21
|
+
return Object.assign(new Error(message, { cause }), { code })
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function requireEvent(condition, message) {
|
|
25
|
+
if (!condition) throw historyError('unsupported', message)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Incremental equivalent of AgentLoop's inbox fold, retaining only pending message identities. */
|
|
29
|
+
function createInbox() {
|
|
30
|
+
const queue = { 'next-turn': [], 'next-step': [] }
|
|
31
|
+
const pending = new Set()
|
|
32
|
+
let idBytes = 0
|
|
33
|
+
return {
|
|
34
|
+
get busy() { return pending.size !== 0 },
|
|
35
|
+
apply(event) {
|
|
36
|
+
const { target, start, removedCount, inserted } = event.data
|
|
37
|
+
requireEvent(Object.hasOwn(queue, target) && Array.isArray(inserted), 'Invalid durable inbox splice')
|
|
38
|
+
const current = queue[target]
|
|
39
|
+
const count = removedCount ?? 0
|
|
40
|
+
requireEvent(sequence(start) && start <= current.length && sequence(count) && count <= current.length - start,
|
|
41
|
+
'Invalid durable inbox splice range')
|
|
42
|
+
if (pending.size - count + inserted.length > maxPendingMessages) {
|
|
43
|
+
throw historyError('history-resource', 'Durable inbox exceeds the pending message limit')
|
|
44
|
+
}
|
|
45
|
+
// Removing first also permits replacing an item with the same identity.
|
|
46
|
+
// A malformed insertion aborts the scan, so no partial state can escape.
|
|
47
|
+
for (let index = start; index < start + count; index++) {
|
|
48
|
+
const id = current[index]
|
|
49
|
+
pending.delete(id)
|
|
50
|
+
idBytes -= Buffer.byteLength(id)
|
|
51
|
+
}
|
|
52
|
+
const newIds = []
|
|
53
|
+
for (const message of inserted) {
|
|
54
|
+
const id = message?.id
|
|
55
|
+
requireEvent(typeof id === 'string' && id.length > 0 && !pending.has(id), 'Invalid or duplicate durable inbox message identity')
|
|
56
|
+
idBytes += Buffer.byteLength(id)
|
|
57
|
+
if (idBytes > maxPendingIdBytes) throw historyError('history-resource', 'Durable inbox identities exceed the byte limit')
|
|
58
|
+
const retained = retainString(id)
|
|
59
|
+
pending.add(retained)
|
|
60
|
+
newIds.push(retained)
|
|
61
|
+
}
|
|
62
|
+
current.splice(start, count, ...newIds)
|
|
63
|
+
},
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Inspect one native v4 log without holding an event list or forwarding user message payloads. */
|
|
68
|
+
export async function inspectHistory(request) {
|
|
69
|
+
const { path, id, cwd, cwdChangeSeq, noticeId, checkInbox = false } = request ?? {}
|
|
70
|
+
requireEvent(directory(path) && typeof id === 'string' && id.length > 0 && directory(cwd)
|
|
71
|
+
&& (cwdChangeSeq === undefined || sequence(cwdChangeSeq))
|
|
72
|
+
&& (noticeId === undefined || (typeof noticeId === 'string' && noticeId.length > 0))
|
|
73
|
+
&& typeof checkInbox === 'boolean', 'Invalid history inspection parameters')
|
|
74
|
+
|
|
75
|
+
const inbox = createInbox()
|
|
76
|
+
const sessionListMetadata = { blank: true, lastPromptAt: null }
|
|
77
|
+
let title = null
|
|
78
|
+
let workingDirectory = cwd
|
|
79
|
+
let agentPreset = null
|
|
80
|
+
let proof = false
|
|
81
|
+
let foundLegacyNotice = false
|
|
82
|
+
let previousWasDirectoryChange = false
|
|
83
|
+
const legacy = cwdChangeSeq === undefined && noticeId !== undefined
|
|
84
|
+
|
|
85
|
+
const history = await scanHistory(path, {
|
|
86
|
+
onHeader(header) {
|
|
87
|
+
if (header.id !== id || header.cwd !== cwd) throw historyError('changed', 'Session header no longer matches the expected session and path')
|
|
88
|
+
if (header.agentPreset !== undefined && header.agentPreset !== null) {
|
|
89
|
+
requireEvent(typeof header.agentPreset === 'string', 'Invalid session agent preset')
|
|
90
|
+
agentPreset = retainSummary(header.agentPreset)
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
onEvent(event) {
|
|
94
|
+
const { type, data, seq, time } = event
|
|
95
|
+
// These summary fields mirror the registered stock DSH projections.
|
|
96
|
+
switch (type) {
|
|
97
|
+
case 'agent/inbox/spliced':
|
|
98
|
+
inbox.apply(event)
|
|
99
|
+
break
|
|
100
|
+
case 'session/title':
|
|
101
|
+
requireEvent(typeof data?.title === 'string' && data.title.length > 0, 'Invalid session title')
|
|
102
|
+
title = retainSummary(data.title)
|
|
103
|
+
break
|
|
104
|
+
case 'working-directory/change':
|
|
105
|
+
requireEvent(typeof data?.cwd === 'string', 'Invalid session working directory')
|
|
106
|
+
workingDirectory = retainSummary(data.cwd)
|
|
107
|
+
break
|
|
108
|
+
case 'agent-preset/selected':
|
|
109
|
+
requireEvent(typeof data?.agentPreset === 'string', 'Invalid session agent preset')
|
|
110
|
+
agentPreset = retainSummary(data.agentPreset)
|
|
111
|
+
break
|
|
112
|
+
case 'turn/start':
|
|
113
|
+
sessionListMetadata.blank = false
|
|
114
|
+
break
|
|
115
|
+
case 'user/message':
|
|
116
|
+
if (data.source?.kind === 'user') sessionListMetadata.lastPromptAt = time
|
|
117
|
+
break
|
|
118
|
+
}
|
|
119
|
+
const isDirectoryChange = type === 'working-directory/change' && data?.cwd === cwd
|
|
120
|
+
if (cwdChangeSeq !== undefined) {
|
|
121
|
+
if (seq === cwdChangeSeq) proof = isDirectoryChange
|
|
122
|
+
} else if (legacy && !foundLegacyNotice && type === 'user/message' && data?.id === noticeId) {
|
|
123
|
+
proof = previousWasDirectoryChange
|
|
124
|
+
foundLegacyNotice = true
|
|
125
|
+
}
|
|
126
|
+
previousWasDirectoryChange = isDirectoryChange
|
|
127
|
+
},
|
|
128
|
+
})
|
|
129
|
+
if (checkInbox && inbox.busy) throw historyError('busy', 'Session has pending input')
|
|
130
|
+
if (title === oversizedSummary || workingDirectory === oversizedSummary || agentPreset === oversizedSummary) {
|
|
131
|
+
throw historyError('history-resource', 'Session summary exceeds its string byte limit')
|
|
132
|
+
}
|
|
133
|
+
requireEvent(directory(workingDirectory), 'Invalid session working directory')
|
|
134
|
+
return {
|
|
135
|
+
lastSeq: history.lastSeq,
|
|
136
|
+
eventCount: history.eventCount,
|
|
137
|
+
inheritedEventCount: history.inheritedEventCount,
|
|
138
|
+
summary: { title, workingDirectory, agentPreset, sessionListMetadata },
|
|
139
|
+
proof,
|
|
140
|
+
...(history.tornTruncateTo === undefined ? {} : {
|
|
141
|
+
tornTruncateTo: history.tornTruncateTo,
|
|
142
|
+
tornRecoveredCount: history.tornRecoveredCount,
|
|
143
|
+
}),
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function readRequest(maxBytes) {
|
|
148
|
+
const chunks = []
|
|
149
|
+
let bytes = 0
|
|
150
|
+
for await (const chunk of process.stdin) {
|
|
151
|
+
bytes += chunk.length
|
|
152
|
+
if (bytes > maxBytes) throw historyError('history-ipc-limit', 'History inspection request exceeds the communication limit')
|
|
153
|
+
chunks.push(chunk)
|
|
154
|
+
}
|
|
155
|
+
return JSON.parse(Buffer.concat(chunks, bytes).toString('utf8'))
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const supportedCodes = new Set(['busy', 'changed', 'unsupported', 'history-resource', 'history-ipc-limit'])
|
|
159
|
+
|
|
160
|
+
async function main() {
|
|
161
|
+
await verifyHistoryIsolation(process.argv[3])
|
|
162
|
+
process.stdout.write(historyReady)
|
|
163
|
+
let output
|
|
164
|
+
try {
|
|
165
|
+
const value = await inspectHistory(await readRequest(historyMessageBytes))
|
|
166
|
+
output = JSON.stringify({ ok: true, value })
|
|
167
|
+
if (Buffer.byteLength(output) + Buffer.byteLength(historyReady) > historyMessageBytes) {
|
|
168
|
+
throw historyError('history-ipc-limit', 'History inspection response exceeds the communication limit')
|
|
169
|
+
}
|
|
170
|
+
} catch (error) {
|
|
171
|
+
const code = supportedCodes.has(error?.code) ? error.code : 'unsupported'
|
|
172
|
+
const message = String(error?.message ?? 'History inspection failed').slice(0, 512)
|
|
173
|
+
output = JSON.stringify({ ok: false, code, message })
|
|
174
|
+
}
|
|
175
|
+
await new Promise((resolve, reject) => process.stdout.write(output, error => error ? reject(error) : resolve()))
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (process.argv[2] === historyWorkerArg) {
|
|
179
|
+
await main().catch(() => { process.exitCode = 1 })
|
|
180
|
+
}
|
package/src/history.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { runHistory } from './history-process.js'
|
|
2
|
+
import { MAX_SUMMARY_STRING_BYTES } from './history-stream.js'
|
|
3
|
+
import { fail } from './plan.js'
|
|
4
|
+
import { sessionInstallDirectory } from './platform-fs.js'
|
|
5
|
+
|
|
6
|
+
/** Read only bounded derived metadata from a v4 transcript. */
|
|
7
|
+
export async function inspectMoveHistory({ path, id, cwd, checkInbox, cwdChangeSeq, noticeId }, options) {
|
|
8
|
+
let result
|
|
9
|
+
try {
|
|
10
|
+
result = await runHistory({ path, id, cwd, checkInbox, cwdChangeSeq, noticeId },
|
|
11
|
+
{ ...options, installDirectory: sessionInstallDirectory() })
|
|
12
|
+
} catch (error) {
|
|
13
|
+
assertPreparing(options?.signal)
|
|
14
|
+
if (error.code === 'unsupported') throw fail('history-invalid', error)
|
|
15
|
+
if (error.code === 'history-ipc-limit' || error.code === 'history-limit') throw fail('history-resource', error)
|
|
16
|
+
throw error
|
|
17
|
+
}
|
|
18
|
+
const { lastSeq, eventCount, inheritedEventCount, summary, proof, tornTruncateTo, tornRecoveredCount } = result ?? {}
|
|
19
|
+
const { title, workingDirectory, agentPreset, sessionListMetadata: metadata } = summary ?? {}
|
|
20
|
+
const hasTorn = tornTruncateTo !== undefined || tornRecoveredCount !== undefined
|
|
21
|
+
const validTorn = !hasTorn || (
|
|
22
|
+
Number.isSafeInteger(tornTruncateTo) && tornTruncateTo > 0
|
|
23
|
+
&& Number.isSafeInteger(tornRecoveredCount) && tornRecoveredCount >= 0 && tornRecoveredCount <= eventCount
|
|
24
|
+
)
|
|
25
|
+
if (!Number.isSafeInteger(lastSeq) || lastSeq < -1 || lastSeq >= Number.MAX_SAFE_INTEGER
|
|
26
|
+
|| !Number.isSafeInteger(eventCount) || eventCount < 0 || eventCount !== lastSeq + 1
|
|
27
|
+
|| !Number.isSafeInteger(inheritedEventCount) || inheritedEventCount < 0 || inheritedEventCount > eventCount
|
|
28
|
+
|| (typeof title !== 'string' && title !== null)
|
|
29
|
+
|| (typeof workingDirectory !== 'string' && workingDirectory !== null)
|
|
30
|
+
|| (typeof agentPreset !== 'string' && agentPreset !== null)
|
|
31
|
+
|| (title !== null && Buffer.byteLength(title) > MAX_SUMMARY_STRING_BYTES)
|
|
32
|
+
|| (workingDirectory !== null && Buffer.byteLength(workingDirectory) > MAX_SUMMARY_STRING_BYTES)
|
|
33
|
+
|| (agentPreset !== null && Buffer.byteLength(agentPreset) > MAX_SUMMARY_STRING_BYTES)
|
|
34
|
+
|| typeof metadata?.blank !== 'boolean' || (metadata.lastPromptAt !== null && !Number.isFinite(metadata.lastPromptAt))
|
|
35
|
+
|| ((cwdChangeSeq !== undefined || noticeId !== undefined) && typeof proof !== 'boolean')
|
|
36
|
+
|| !validTorn) throw fail('history-protocol')
|
|
37
|
+
return result
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function assertPreparing(signal) {
|
|
41
|
+
if (signal?.aborted) {
|
|
42
|
+
throw fail(signal.reason?.name === 'TimeoutError' ? 'history-timeout' : 'history-cancelled', signal.reason)
|
|
43
|
+
}
|
|
44
|
+
}
|
package/src/ledger.js
CHANGED
|
@@ -301,23 +301,3 @@ export async function repairLegacyDuplicates(ctx, options) {
|
|
|
301
301
|
})
|
|
302
302
|
return repaired
|
|
303
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
CHANGED
|
@@ -1,19 +1,23 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
1
2
|
import { assertExpectedSource, buildPlan, fail, validId, validSourceWorkspaceId } from './plan.js'
|
|
3
|
+
import { LOG_FILENAME } from './paths.js'
|
|
2
4
|
import { idleWebWriter, releaseIdleWebWriters } from './lease.js'
|
|
3
|
-
import { captureLedger, moveLedger, restoreLedger
|
|
5
|
+
import { captureLedger, moveLedger, restoreLedger } from './ledger.js'
|
|
4
6
|
import { recoverMove } from './recovery.js'
|
|
5
7
|
import { moveStorage } from './transaction.js'
|
|
6
|
-
import {
|
|
7
|
-
import { refreshSessionSummaries } from './sidebar.js'
|
|
8
|
+
import { assertPreparing, inspectMoveHistory } from './history.js'
|
|
9
|
+
import { captureLiveSummaries, refreshSessionSummaries } from './sidebar.js'
|
|
8
10
|
|
|
9
11
|
const knownErrors = new Set([
|
|
10
12
|
'bad-request', 'busy', 'locked', 'missing', 'target-missing', 'target-not-canonical',
|
|
11
13
|
'same-workspace', 'stale-source', 'collision', 'changed', 'unsupported', 'restore-pending', 'cleanup-pending',
|
|
12
|
-
'archived', 'subagent', 'unsafe-path', 'cross-device', 'restored',
|
|
14
|
+
'archived', 'subagent', 'unsafe-path', 'cross-device', 'restored', 'disk-space', 'family-limit',
|
|
15
|
+
'history-busy', 'history-timeout', 'history-cancelled', 'history-resource', 'history-isolation-unavailable',
|
|
16
|
+
'history-protocol', 'history-ipc-limit', 'history-invalid', 'history-limit',
|
|
13
17
|
])
|
|
14
18
|
|
|
15
19
|
function destinationMembers(plan) {
|
|
16
|
-
return plan.members.map(({ id }) => ({ id, cwd: plan.targetCwd }))
|
|
20
|
+
return plan.members.map(({ id, oldCwd }) => ({ id, cwd: plan.targetCwd, moved: oldCwd !== plan.targetCwd }))
|
|
17
21
|
}
|
|
18
22
|
|
|
19
23
|
export function createSessionMove(ctx, { root, base, previous, checkpoint, activity = async (id) => {
|
|
@@ -23,34 +27,42 @@ export function createSessionMove(ctx, { root, base, previous, checkpoint, activ
|
|
|
23
27
|
.map((directory) => moveStorage(root, directory))
|
|
24
28
|
let chain = Promise.resolve()
|
|
25
29
|
|
|
26
|
-
async function checkIdle(plan) {
|
|
27
|
-
for (const { id } of plan.members)
|
|
30
|
+
async function checkIdle(plan, signal) {
|
|
31
|
+
for (const { id } of plan.members) {
|
|
32
|
+
assertPreparing(signal)
|
|
33
|
+
if ((await activity(id)).length) throw fail('busy')
|
|
34
|
+
}
|
|
35
|
+
assertPreparing(signal)
|
|
28
36
|
}
|
|
29
37
|
|
|
30
38
|
async function verifyDestination(state) {
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
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() }
|
|
39
|
+
for (const { id, nextDir } of state.members) {
|
|
40
|
+
const snapshot = await ctx.sessionPersistence.stat(id)
|
|
41
|
+
if (snapshot?.header?.id !== id || snapshot.header.cwd !== state.targetCwd
|
|
42
|
+
|| snapshot.formatStatus !== 'current' || snapshot.location?.kind !== 'jsonl'
|
|
43
|
+
|| snapshot.location.path !== join(nextDir, LOG_FILENAME)) throw fail('changed')
|
|
43
44
|
}
|
|
44
|
-
|
|
45
|
+
// The staged digest covers the validated source body, rewritten header,
|
|
46
|
+
// and appended directory event. Require the exact stage before committing.
|
|
47
|
+
await storage.verifyPublished(state, { exact: true })
|
|
45
48
|
}
|
|
46
49
|
|
|
47
|
-
async function move(body,
|
|
50
|
+
async function move(body, requestSignal) {
|
|
48
51
|
for (const previousStorage of previousStorages) await recoverMove(ctx, previousStorage)
|
|
49
52
|
await recoverMove(ctx, storage)
|
|
50
53
|
return storage.withLock(async () => {
|
|
51
54
|
if (await storage.readState()) throw fail('restore-pending')
|
|
52
|
-
|
|
53
|
-
|
|
55
|
+
if (typeof storage.sweepOrphans === 'function') {
|
|
56
|
+
await storage.sweepOrphans().catch((error) => {
|
|
57
|
+
ctx.logger?.warn?.('Session move: orphan cleanup deferred: %s', error)
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
const timeout = AbortSignal.timeout(180_000)
|
|
61
|
+
const signal = requestSignal ? AbortSignal.any([requestSignal, timeout]) : timeout
|
|
62
|
+
const summaries = new Map()
|
|
63
|
+
assertPreparing(signal)
|
|
64
|
+
const plan = await buildPlan(ctx, { root }, body, { signal })
|
|
65
|
+
await checkIdle(plan, signal)
|
|
54
66
|
assertExpectedSource(ctx.workspaceRegistry.list(), body)
|
|
55
67
|
const writers = plan.members.flatMap(({ id }) => {
|
|
56
68
|
const session = ctx.sessions.get(id)
|
|
@@ -59,40 +71,53 @@ export function createSessionMove(ctx, { root, base, previous, checkpoint, activ
|
|
|
59
71
|
if (writer.settling) throw fail('busy')
|
|
60
72
|
return [writer]
|
|
61
73
|
})
|
|
62
|
-
signal
|
|
74
|
+
assertPreparing(signal)
|
|
75
|
+
const restored = captureLiveSummaries(ctx, writers)
|
|
76
|
+
let preparing = true
|
|
63
77
|
try {
|
|
64
78
|
await release(ctx, writers)
|
|
65
79
|
return await storage.withSessionLocks(plan, async (lockStage) => {
|
|
66
80
|
if (plan.members.some(({ id }) => ctx.sessions.get(id))) throw fail('locked')
|
|
67
|
-
await checkIdle(plan)
|
|
68
|
-
const current = await buildPlan(ctx, { root }, body)
|
|
81
|
+
await checkIdle(plan, signal)
|
|
82
|
+
const current = await buildPlan(ctx, { root }, body, { signal })
|
|
69
83
|
if (current.targetCwd !== plan.targetCwd || current.members.length !== plan.members.length
|
|
70
84
|
|| current.members.some((member, i) => member.id !== plan.members[i].id
|
|
71
85
|
|| member.oldCwd !== plan.members[i].oldCwd || member.oldFile !== plan.members[i].oldFile)) throw fail('changed')
|
|
72
86
|
assertExpectedSource(ctx.workspaceRegistry.list(), body)
|
|
73
87
|
const ledger = captureLedger(ctx, current)
|
|
74
|
-
signal
|
|
88
|
+
assertPreparing(signal)
|
|
75
89
|
if (current.members.every(({ oldCwd }) => oldCwd === current.targetCwd)) {
|
|
76
90
|
// Reattaching to the same project only changes its workspace record.
|
|
77
|
-
for (const
|
|
78
|
-
|
|
91
|
+
for (const { id, oldFile, oldCwd } of current.members) {
|
|
92
|
+
summaries.set(id, await inspectMoveHistory({ path: oldFile, id, cwd: oldCwd, checkInbox: true }, { signal }))
|
|
93
|
+
}
|
|
94
|
+
assertPreparing(signal)
|
|
95
|
+
preparing = false
|
|
79
96
|
try {
|
|
80
97
|
await moveLedger(ctx, current, ledger)
|
|
81
98
|
} catch (error) {
|
|
82
99
|
if (error.code === 'unknown-state') throw fail('restore-pending', error)
|
|
83
100
|
throw error
|
|
84
101
|
}
|
|
85
|
-
const synced = await refreshSessionSummaries(ctx, destinationMembers(current))
|
|
102
|
+
const synced = await refreshSessionSummaries(ctx, destinationMembers(current), summaries)
|
|
86
103
|
return synced ? { moved: true } : { moved: true, sidebarPending: true }
|
|
87
104
|
}
|
|
88
|
-
const state = await storage.prepare(ctx, current, ledger, lockStage)
|
|
89
|
-
|
|
105
|
+
const state = await storage.prepare(ctx, current, ledger, lockStage, { signal, summaries })
|
|
106
|
+
try {
|
|
107
|
+
await storage.save(state)
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (await storage.hasJournal()) throw fail('restore-pending', error)
|
|
110
|
+
if (typeof storage.discardPrepared === 'function') {
|
|
111
|
+
await storage.discardPrepared(state.ticket).catch(() => {})
|
|
112
|
+
}
|
|
113
|
+
throw error
|
|
114
|
+
}
|
|
115
|
+
preparing = false
|
|
90
116
|
let committing = false
|
|
91
|
-
let verified
|
|
92
117
|
try {
|
|
93
118
|
await checkpoint?.('prepared', state)
|
|
94
119
|
await storage.publish(state)
|
|
95
|
-
|
|
120
|
+
await verifyDestination(state)
|
|
96
121
|
await moveLedger(ctx, state, ledger)
|
|
97
122
|
committing = true
|
|
98
123
|
await checkpoint?.('ledger-published', state)
|
|
@@ -120,18 +145,25 @@ export function createSessionMove(ctx, { root, base, previous, checkpoint, activ
|
|
|
120
145
|
cleanupPending = true
|
|
121
146
|
ctx.logger?.warn?.('Session move cleanup: %s', error)
|
|
122
147
|
}
|
|
123
|
-
const synced = await refreshSessionSummaries(ctx, destinationMembers(state),
|
|
124
|
-
await refreshSearchIndex(ctx)
|
|
148
|
+
const synced = await refreshSessionSummaries(ctx, destinationMembers(state), summaries)
|
|
125
149
|
return { moved: true, ...(cleanupPending ? { cleanupPending } : {}), ...(!synced ? { sidebarPending: true } : {}) }
|
|
126
150
|
})
|
|
127
151
|
} catch (error) {
|
|
152
|
+
let outcome = error
|
|
153
|
+
if (preparing && signal.aborted && !knownErrors.has(error?.code)) {
|
|
154
|
+
try { assertPreparing(signal) } catch (aborted) { outcome = aborted }
|
|
155
|
+
}
|
|
128
156
|
// Disposing a resident writer also removes its list row. Republish
|
|
129
|
-
// an unchanged or restored source if the move failed after disposal
|
|
130
|
-
|
|
157
|
+
// an unchanged or restored source if the move failed after disposal,
|
|
158
|
+
// without starting another full history scan.
|
|
159
|
+
if (outcome.code !== 'restore-pending') {
|
|
131
160
|
const disposed = writers.filter(({ session }) => !ctx.sessions.get(session.id))
|
|
132
|
-
await refreshSessionSummaries(ctx, disposed.map(({ session }) => ({ id: session.id, cwd: session.header.cwd }))
|
|
161
|
+
await refreshSessionSummaries(ctx, disposed.map(({ session }) => ({ id: session.id, cwd: session.header.cwd })), summaries, {
|
|
162
|
+
restored,
|
|
163
|
+
allowScan: false,
|
|
164
|
+
})
|
|
133
165
|
}
|
|
134
|
-
throw
|
|
166
|
+
throw outcome
|
|
135
167
|
}
|
|
136
168
|
})
|
|
137
169
|
}
|
|
@@ -149,8 +181,8 @@ export function createSessionMove(ctx, { root, base, previous, checkpoint, activ
|
|
|
149
181
|
|| (body.beforeSessionId !== undefined && !validId(body.beforeSessionId))) throw fail('bad-request')
|
|
150
182
|
return Response.json(await move(body, request.signal), { headers })
|
|
151
183
|
} 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)
|
|
184
|
+
const code = error?.code === 'ENOSPC' ? 'disk-space' : knownErrors.has(error?.code) ? error.code : 'failed'
|
|
185
|
+
if (code === 'failed' || code === 'restore-pending' || code.startsWith('history-')) ctx.logger?.warn?.('Session move: %s', error)
|
|
154
186
|
return Response.json({ error: code }, { headers, status: code === 'bad-request' ? 400 : code === 'failed' ? 500 : 409 })
|
|
155
187
|
}
|
|
156
188
|
})
|
package/src/plan.js
CHANGED
|
@@ -27,6 +27,12 @@ export function fail(code, cause) {
|
|
|
27
27
|
return Object.assign(new Error(`Session move (${code})`), { code, cause })
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
function checkPreparing(signal) {
|
|
31
|
+
if (signal?.aborted) {
|
|
32
|
+
throw fail(signal.reason?.name === 'TimeoutError' ? 'history-timeout' : 'history-cancelled', signal.reason)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
30
36
|
/**
|
|
31
37
|
* Expand a session into itself plus every subagent session created from it.
|
|
32
38
|
* Children move with their parent so the delegation tree never spans two
|
|
@@ -53,6 +59,7 @@ export function moveScope(root, stored, live) {
|
|
|
53
59
|
const visit = (id) => {
|
|
54
60
|
if (seen.has(id)) return
|
|
55
61
|
seen.add(id)
|
|
62
|
+
if (ordered.length === 128) throw fail('family-limit')
|
|
56
63
|
ordered.push(id)
|
|
57
64
|
for (const child of children.get(id) ?? []) visit(child)
|
|
58
65
|
}
|
|
@@ -79,7 +86,8 @@ export function assertExpectedSource(workspaces, request) {
|
|
|
79
86
|
* `targetWorkspaceId`, optional `beforeSessionId`.
|
|
80
87
|
* @returns the plan, ready to execute.
|
|
81
88
|
*/
|
|
82
|
-
export async function buildPlan(ctx, { root }, request) {
|
|
89
|
+
export async function buildPlan(ctx, { root }, request, { signal } = {}) {
|
|
90
|
+
checkPreparing(signal)
|
|
83
91
|
const registry = ctx.workspaceRegistry
|
|
84
92
|
const workspaces = registry.list()
|
|
85
93
|
const sourceWorkspaceId = assertExpectedSource(workspaces, request)
|
|
@@ -96,6 +104,7 @@ export async function buildPlan(ctx, { root }, request) {
|
|
|
96
104
|
} catch {
|
|
97
105
|
targetIsDirectory = false
|
|
98
106
|
}
|
|
107
|
+
checkPreparing(signal)
|
|
99
108
|
if (!targetIsDirectory) throw fail('target-missing')
|
|
100
109
|
|
|
101
110
|
// The attach validation compares the header's realpath against the stored
|
|
@@ -103,13 +112,21 @@ export async function buildPlan(ctx, { root }, request) {
|
|
|
103
112
|
// path this plugin composed itself.
|
|
104
113
|
const targetCwd = targetPath
|
|
105
114
|
|
|
106
|
-
|
|
115
|
+
let stored
|
|
116
|
+
try {
|
|
117
|
+
stored = await ctx.sessionPersistence.list(signal ? { signal } : undefined)
|
|
118
|
+
} catch (error) {
|
|
119
|
+
checkPreparing(signal)
|
|
120
|
+
throw error
|
|
121
|
+
}
|
|
122
|
+
checkPreparing(signal)
|
|
107
123
|
const members = moveScope(request.sessionId, stored, ctx.sessions.list())
|
|
108
124
|
if (registry.archivedSessionIds?.includes(request.sessionId)) throw fail('archived')
|
|
109
125
|
const snapshots = new Map(stored.map((snapshot) => [snapshot.header.id, snapshot]))
|
|
110
126
|
|
|
111
127
|
const planned = []
|
|
112
128
|
for (const id of members) {
|
|
129
|
+
checkPreparing(signal)
|
|
113
130
|
const snapshot = snapshots.get(id)
|
|
114
131
|
if (snapshot === undefined) throw fail('missing')
|
|
115
132
|
const oldCwd = snapshot.header.cwd
|
|
@@ -127,6 +144,7 @@ export async function buildPlan(ctx, { root }, request) {
|
|
|
127
144
|
// A destination that already holds this session's directory means the move
|
|
128
145
|
// would merge two transcripts. Refuse rather than guess which one wins.
|
|
129
146
|
for (const member of planned) {
|
|
147
|
+
checkPreparing(signal)
|
|
130
148
|
if (member.oldDir === member.nextDir) continue
|
|
131
149
|
try {
|
|
132
150
|
await lstat(member.nextDir)
|
|
@@ -139,12 +157,14 @@ export async function buildPlan(ctx, { root }, request) {
|
|
|
139
157
|
// `attachSession` re-reads the header and canonicalizes it; a target whose
|
|
140
158
|
// realpath differs from its record path could never be attached, so refuse
|
|
141
159
|
// now instead of after the files moved.
|
|
160
|
+
checkPreparing(signal)
|
|
142
161
|
let canonicalTarget
|
|
143
162
|
try {
|
|
144
163
|
canonicalTarget = await realpath(targetPath)
|
|
145
164
|
} catch {
|
|
146
165
|
throw fail('target-missing')
|
|
147
166
|
}
|
|
167
|
+
checkPreparing(signal)
|
|
148
168
|
if (canonicalTarget !== targetPath) {
|
|
149
169
|
// Canonicalizing would change the string attach compares against, so the
|
|
150
170
|
// only safe outcome is refusing while nothing has moved.
|
package/src/platform-fs.js
CHANGED
|
@@ -27,7 +27,7 @@ function failure(code, message, cause) {
|
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
/** Resolve from the host, including an ASAR inside Electron and pnpm package layouts. */
|
|
30
|
-
|
|
30
|
+
function sessionInstall() {
|
|
31
31
|
const anchors = [process.env.DSH_INSTALL_DIR];
|
|
32
32
|
if (process.versions.electron) {
|
|
33
33
|
// The Desktop CLI can boot a profile in Electron without exporting DSH_INSTALL_DIR.
|
|
@@ -56,7 +56,7 @@ export function sessionRequire() {
|
|
|
56
56
|
}
|
|
57
57
|
const manifest = hostRequire.resolve(jsonlManifest);
|
|
58
58
|
if (hostRequire(manifest).version !== '0.2.2-rc.5') throw new Error('Unexpected DSH session lease version');
|
|
59
|
-
return
|
|
59
|
+
return { directory, manifest };
|
|
60
60
|
} catch (error) {
|
|
61
61
|
cause = error;
|
|
62
62
|
}
|
|
@@ -64,6 +64,15 @@ export function sessionRequire() {
|
|
|
64
64
|
throw failure('unsupported', 'Cannot locate the shipped DSH session lock implementation', cause);
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
/** The worker has a different argv[1]; pass it the installation we already validated. */
|
|
68
|
+
export function sessionInstallDirectory() {
|
|
69
|
+
return sessionInstall().directory;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function sessionRequire() {
|
|
73
|
+
return createRequire(sessionInstall().manifest);
|
|
74
|
+
}
|
|
75
|
+
|
|
67
76
|
function windowsApi() {
|
|
68
77
|
if (windowsBindings) return windowsBindings;
|
|
69
78
|
try {
|
package/src/recovery.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { join } from 'node:path'
|
|
2
2
|
import { pathToFileURL } from 'node:url'
|
|
3
3
|
import { storagePaths } from './config.js'
|
|
4
|
-
import {
|
|
4
|
+
import { repairLegacyDuplicates, restoreLedger, withPublishedLedger } from './ledger.js'
|
|
5
5
|
import { refreshSessionSummaries } from './sidebar.js'
|
|
6
6
|
import { LOG_FILENAME } from './paths.js'
|
|
7
7
|
import { fail } from './plan.js'
|
|
8
|
+
import { inspectMoveHistory } from './history.js'
|
|
8
9
|
import { sessionRequire } from './platform-fs.js'
|
|
9
10
|
import { moveStorage, recoverLegacyDisk } from './transaction.js'
|
|
10
11
|
|
|
@@ -36,22 +37,13 @@ async function hasPublishedHistory(ctx, storage, state) {
|
|
|
36
37
|
if (error.code === 'changed') return false
|
|
37
38
|
throw error
|
|
38
39
|
}
|
|
39
|
-
|
|
40
|
+
const signal = AbortSignal.timeout(180_000)
|
|
41
|
+
for (const { id, oldCwd, nextDir, cwdChangeSeq, noticeId } of state.members) {
|
|
40
42
|
if (oldCwd === state.targetCwd) continue
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
let directory
|
|
46
|
-
if (cwdChangeSeq !== undefined) {
|
|
47
|
-
directory = events.find(({ seq }) => seq === cwdChangeSeq)
|
|
48
|
-
} else if (typeof noticeId === 'string') {
|
|
49
|
-
// Older v2 journals identified the change by the following notice.
|
|
50
|
-
const noticeIndex = events.findIndex(({ type, data }) => type === 'user/message' && data?.id === noticeId)
|
|
51
|
-
if (noticeIndex > 0) directory = events[noticeIndex - 1]
|
|
52
|
-
}
|
|
53
|
-
if (directory?.type !== 'working-directory/change' || directory.data?.cwd !== state.targetCwd) return false
|
|
54
|
-
} finally { await handle.close() }
|
|
43
|
+
if (cwdChangeSeq === undefined && typeof noticeId !== 'string') return false
|
|
44
|
+
const result = await inspectMoveHistory({ path: join(nextDir, LOG_FILENAME), id,
|
|
45
|
+
cwd: state.targetCwd, cwdChangeSeq, noticeId }, { signal })
|
|
46
|
+
if (!result.proof) return false
|
|
55
47
|
}
|
|
56
48
|
return true
|
|
57
49
|
}
|
|
@@ -70,7 +62,16 @@ async function verifyWhileContended(ctx, storage) {
|
|
|
70
62
|
|
|
71
63
|
/** Retry a journal. Only startup may defer work after proving scan safety. */
|
|
72
64
|
export async function recoverMove(ctx, storage, { startup = false, withLedger = (run) => run() } = {}) {
|
|
73
|
-
if (!await storage.hasJournal())
|
|
65
|
+
if (!await storage.hasJournal()) {
|
|
66
|
+
if (typeof storage.hasOrphans === 'function' && await storage.hasOrphans()) {
|
|
67
|
+
try {
|
|
68
|
+
await storage.withLock(() => storage.sweepOrphans())
|
|
69
|
+
} catch (error) {
|
|
70
|
+
ctx.logger?.warn?.('Session move: orphan cleanup deferred: %s', error)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return
|
|
74
|
+
}
|
|
74
75
|
let scanSafe = false
|
|
75
76
|
try {
|
|
76
77
|
await storage.withLock(async () => {
|
|
@@ -98,8 +99,9 @@ export async function recoverMove(ctx, storage, { startup = false, withLedger =
|
|
|
98
99
|
}, { recovery: true })
|
|
99
100
|
if (committed) {
|
|
100
101
|
if (!startup) {
|
|
101
|
-
await refreshSessionSummaries(ctx, state.members.map(({ id }) => ({ id, cwd: state.targetCwd }))
|
|
102
|
-
|
|
102
|
+
await refreshSessionSummaries(ctx, state.members.map(({ id }) => ({ id, cwd: state.targetCwd })), undefined, {
|
|
103
|
+
signal: AbortSignal.timeout(180_000),
|
|
104
|
+
})
|
|
103
105
|
}
|
|
104
106
|
return
|
|
105
107
|
}
|