@kabxx/dsh-session-move 0.0.0-stage → 0.1.1

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/plan.js ADDED
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Resolve a move request into an executable plan, or refuse it before anything
3
+ * changes.
4
+ *
5
+ * The plan is the whole point of this module: every check that can reject the
6
+ * move runs here, so the caller never starts a relocation it cannot finish.
7
+ * Mirrors the "refused before anything moved" contract of OMP's
8
+ * `SessionManager.moveTo`.
9
+ *
10
+ * @module dsh-session-move/plan
11
+ */
12
+
13
+ import { lstat, realpath, stat } from 'node:fs/promises'
14
+ import { dirname, join } from 'node:path'
15
+ import { LOG_FILENAME, sessionDir } from './paths.js'
16
+
17
+ export function validId(id) {
18
+ return typeof id === 'string' && id.length > 0 && id.length <= 200 && !/[\u0000-\u001f]/u.test(id)
19
+ }
20
+
21
+ export function validSourceWorkspaceId(id) {
22
+ return id === null || validId(id)
23
+ }
24
+
25
+ /** Refuse a move with a code the client maps to a message. */
26
+ export function fail(code, cause) {
27
+ return Object.assign(new Error(`Session move (${code})`), { code, cause })
28
+ }
29
+
30
+ /**
31
+ * Expand a session into itself plus every subagent session created from it.
32
+ * Children move with their parent so the delegation tree never spans two
33
+ * workspaces.
34
+ * @param root - the session to expand.
35
+ * @param stored - stored snapshots from `sessionPersistence.list()`.
36
+ * @param live - live sessions from `ctx.sessions.list()`.
37
+ * @returns the member ids, parents before children.
38
+ */
39
+ export function moveScope(root, stored, live) {
40
+ const headers = new Map(stored.map(({ header }) => [header.id, header]))
41
+ for (const session of live) headers.set(session.id, session.header)
42
+ if (!headers.has(root)) throw fail('missing')
43
+ if (headers.get(root).origin === 'subagent') throw fail('subagent')
44
+ const children = new Map()
45
+ for (const header of headers.values()) {
46
+ if (header.origin !== 'subagent' || !header.parentSession) continue
47
+ const siblings = children.get(header.parentSession) ?? []
48
+ siblings.push(header.id)
49
+ children.set(header.parentSession, siblings)
50
+ }
51
+ const ordered = []
52
+ const seen = new Set()
53
+ const visit = (id) => {
54
+ if (seen.has(id)) return
55
+ seen.add(id)
56
+ ordered.push(id)
57
+ for (const child of children.get(id) ?? []) visit(child)
58
+ }
59
+ visit(root)
60
+ return ordered
61
+ }
62
+
63
+ /** Compare the request with the same projected membership used by the sidebar. */
64
+ export function assertExpectedSource(workspaces, request) {
65
+ if (!validSourceWorkspaceId(request.sourceWorkspaceId)) throw fail('bad-request')
66
+ // The header's cwd can match a workspace even if its list no longer contains
67
+ // the session. Ambiguous membership is not safe to interpret as one source.
68
+ const sources = workspaces.filter((workspace) => workspace.sessionIds.includes(request.sessionId))
69
+ const actual = sources[0]?.id ?? null
70
+ if (sources.length > 1 || actual !== request.sourceWorkspaceId) throw fail('stale-source')
71
+ return actual
72
+ }
73
+
74
+ /**
75
+ * Build the plan for one move.
76
+ * @param ctx - the plugin context.
77
+ * @param options - `root` is the session storage root.
78
+ * @param request - `sessionId`, `sourceWorkspaceId` (null for ungrouped),
79
+ * `targetWorkspaceId`, optional `beforeSessionId`.
80
+ * @returns the plan, ready to execute.
81
+ */
82
+ export async function buildPlan(ctx, { root }, request) {
83
+ const registry = ctx.workspaceRegistry
84
+ const workspaces = registry.list()
85
+ const sourceWorkspaceId = assertExpectedSource(workspaces, request)
86
+
87
+ const target = workspaces.find((workspace) => workspace.id === request.targetWorkspaceId)
88
+ if (target === undefined) throw fail('target-missing')
89
+ if (sourceWorkspaceId === target.id) throw fail('same-workspace')
90
+
91
+ const targetPath = target.path
92
+ if (typeof targetPath !== 'string' || targetPath.length === 0) throw fail('target-missing')
93
+ let targetIsDirectory = false
94
+ try {
95
+ targetIsDirectory = (await stat(targetPath)).isDirectory()
96
+ } catch {
97
+ targetIsDirectory = false
98
+ }
99
+ if (!targetIsDirectory) throw fail('target-missing')
100
+
101
+ // The attach validation compares the header's realpath against the stored
102
+ // record path verbatim, so the plan carries that exact string and never a
103
+ // path this plugin composed itself.
104
+ const targetCwd = targetPath
105
+
106
+ const stored = await ctx.sessionPersistence.list()
107
+ const members = moveScope(request.sessionId, stored, ctx.sessions.list())
108
+ if (registry.archivedSessionIds?.includes(request.sessionId)) throw fail('archived')
109
+ const snapshots = new Map(stored.map((snapshot) => [snapshot.header.id, snapshot]))
110
+
111
+ const planned = []
112
+ for (const id of members) {
113
+ const snapshot = snapshots.get(id)
114
+ if (snapshot === undefined) throw fail('missing')
115
+ const oldCwd = snapshot.header.cwd
116
+ if (typeof oldCwd !== 'string' || oldCwd.length === 0) throw fail('unsupported')
117
+ const oldFile = snapshot.location?.path
118
+ const oldDir = sessionDir(root, oldCwd, id)
119
+ if (snapshot.location?.kind !== 'jsonl' || snapshot.formatStatus !== 'current'
120
+ || oldFile !== join(oldDir, LOG_FILENAME)) throw fail('unsupported')
121
+
122
+ const nextDir = sessionDir(root, targetCwd, id)
123
+ const nextFile = join(nextDir, LOG_FILENAME)
124
+ planned.push({ id, header: snapshot.header, oldCwd, oldDir, oldFile, nextDir, nextFile })
125
+ }
126
+
127
+ // A destination that already holds this session's directory means the move
128
+ // would merge two transcripts. Refuse rather than guess which one wins.
129
+ for (const member of planned) {
130
+ if (member.oldDir === member.nextDir) continue
131
+ try {
132
+ await lstat(member.nextDir)
133
+ throw fail('collision')
134
+ } catch (error) {
135
+ if (error.code !== 'ENOENT') throw error
136
+ }
137
+ }
138
+
139
+ // `attachSession` re-reads the header and canonicalizes it; a target whose
140
+ // realpath differs from its record path could never be attached, so refuse
141
+ // now instead of after the files moved.
142
+ let canonicalTarget
143
+ try {
144
+ canonicalTarget = await realpath(targetPath)
145
+ } catch {
146
+ throw fail('target-missing')
147
+ }
148
+ if (canonicalTarget !== targetPath) {
149
+ // Canonicalizing would change the string attach compares against, so the
150
+ // only safe outcome is refusing while nothing has moved.
151
+ throw fail('target-not-canonical')
152
+ }
153
+
154
+ return {
155
+ sessionId: request.sessionId,
156
+ sourceWorkspaceId,
157
+ targetWorkspaceId: target.id,
158
+ targetCwd,
159
+ beforeSessionId: request.beforeSessionId,
160
+ members: planned,
161
+ targetProjectDir: dirname(planned[0].nextDir),
162
+ }
163
+ }
@@ -0,0 +1,253 @@
1
+ // Adapted from @kabxx/dsh-session-delete for the same pinned DSH host.
2
+ import { spawn } from 'node:child_process';
3
+ import { createHash } from 'node:crypto';
4
+ import { constants, realpathSync } from 'node:fs';
5
+ import { lstat, open, rename } from 'node:fs/promises';
6
+ import { createRequire } from 'node:module';
7
+ import { basename, dirname, isAbsolute, join, parse, resolve, toNamespacedPath } from 'node:path';
8
+ import { pathToFileURL } from 'node:url';
9
+
10
+ const conflictExit = 73;
11
+ const windows = process.platform === 'win32';
12
+ const jsonlManifest = '@deepseek-ai/dsh-session-persistence-jsonl/package.json';
13
+ const windowLockPrefix = 'Local\\dsh-session-lock-';
14
+ const MOVEFILE_REPLACE_EXISTING = 0x01;
15
+ const MOVEFILE_WRITE_THROUGH = 0x08;
16
+ const INVALID_FILE_ATTRIBUTES = 0xffffffff;
17
+ const FILE_ATTRIBUTE_REPARSE_POINT = 0x400;
18
+ const WAIT_OBJECT_0 = 0;
19
+ const WAIT_TIMEOUT = 0x102;
20
+ const DRIVE_FIXED = 3;
21
+ let windowsBindings;
22
+ let darwinFlock;
23
+ let exclusiveRename;
24
+
25
+ function failure(code, message, cause) {
26
+ return Object.assign(new Error(message, { cause }), { code });
27
+ }
28
+
29
+ /** Resolve from the host, including an ASAR inside Electron and pnpm package layouts. */
30
+ export function sessionRequire() {
31
+ const anchors = [process.env.DSH_INSTALL_DIR];
32
+ if (process.versions.electron) {
33
+ // The Desktop CLI can boot a profile in Electron without exporting DSH_INSTALL_DIR.
34
+ const resources = process.resourcesPath ?? (process.platform === 'darwin'
35
+ ? join(dirname(process.execPath), '..', 'Resources')
36
+ : join(dirname(process.execPath), 'resources'));
37
+ anchors.push(join(resources, 'app.asar', 'dsh', 'node_modules', '@deepseek-ai', 'dsh'));
38
+ }
39
+ // The npm shims launch the declared entry point, possibly through a symlink.
40
+ // Check that exact shape instead of looking for arbitrary packages above cwd.
41
+ let cliEntry;
42
+ try {
43
+ if (process.argv[1]) cliEntry = realpathSync(process.argv[1]);
44
+ } catch { /* Depend on the other verified anchors. */ }
45
+ const cliRoot = cliEntry && basename(cliEntry) === 'bin.js' && basename(dirname(cliEntry)) === 'lib'
46
+ ? dirname(dirname(cliEntry)) : undefined;
47
+ let cause;
48
+ for (const directory of new Set([...anchors, cliRoot])) {
49
+ if (!directory || !isAbsolute(directory)) continue;
50
+ try {
51
+ const hostRequire = createRequire(join(directory, 'package.json'));
52
+ const hostManifest = hostRequire('./package.json');
53
+ if (hostManifest.name !== '@deepseek-ai/dsh') throw new Error('Invalid DSH install');
54
+ if (directory === cliRoot && resolve(directory, hostManifest.bin?.dsh ?? '') !== cliEntry) {
55
+ throw new Error('Unexpected DSH CLI entry point');
56
+ }
57
+ const manifest = hostRequire.resolve(jsonlManifest);
58
+ if (hostRequire(manifest).version !== '0.2.2-rc.5') throw new Error('Unexpected DSH session lease version');
59
+ return createRequire(manifest);
60
+ } catch (error) {
61
+ cause = error;
62
+ }
63
+ }
64
+ throw failure('unsupported', 'Cannot locate the shipped DSH session lock implementation', cause);
65
+ }
66
+
67
+ function windowsApi() {
68
+ if (windowsBindings) return windowsBindings;
69
+ try {
70
+ const koffi = sessionRequire()('koffi');
71
+ const kernel32 = koffi.load('kernel32.dll');
72
+ const bind = (name, type, args) => kernel32.func('__stdcall', name, type, args);
73
+ windowsBindings = {
74
+ create: bind('CreateSemaphoreW', 'intptr', ['void*', 'int', 'int', 'str16']),
75
+ wait: bind('WaitForSingleObject', 'uint', ['intptr', 'uint']),
76
+ release: bind('ReleaseSemaphore', 'int', ['intptr', 'int', 'void*']),
77
+ close: bind('CloseHandle', 'int', ['intptr']),
78
+ move: bind('MoveFileExW', 'int', ['str16', 'str16', 'uint']),
79
+ attributes: bind('GetFileAttributesW', 'uint', ['str16']),
80
+ driveType: bind('GetDriveTypeW', 'uint', ['str16']),
81
+ lastError: bind('GetLastError', 'uint', []),
82
+ };
83
+ return windowsBindings;
84
+ } catch (error) {
85
+ throw failure('unsupported', 'Cannot load the DSH Windows filesystem bindings', error);
86
+ }
87
+ }
88
+
89
+ function win32Failure(method, number) {
90
+ const code = { 2: 'ENOENT', 3: 'ENOENT', 5: 'EACCES', 17: 'cross-device', 32: 'locked',
91
+ 33: 'locked', 80: 'collision', 123: 'unsafe-path', 183: 'collision' }[number] ?? 'EIO';
92
+ return failure(code, `${method} failed (Win32 ${number})`);
93
+ }
94
+
95
+ function win32Identity(path) {
96
+ // This is the exact case-folded semaphore key used by DSH's JSONL backend.
97
+ const digest = createHash('sha256').update(resolve(path).toLowerCase()).digest('hex');
98
+ return { dev: 'win32-semaphore', ino: digest };
99
+ }
100
+
101
+ export function acquireWindowsLock(path) {
102
+ const api = windowsApi();
103
+ const lockedIdentity = win32Identity(path);
104
+ const nativeHandle = api.create(null, 1, 1, `${windowLockPrefix}${lockedIdentity.ino}`);
105
+ if (nativeHandle === 0 || nativeHandle === 0n) throw win32Failure('CreateSemaphoreW', api.lastError());
106
+ const status = api.wait(nativeHandle, 0);
107
+ if (status !== WAIT_OBJECT_0) {
108
+ const code = status === WAIT_TIMEOUT ? 32 : api.lastError();
109
+ api.close(nativeHandle);
110
+ throw win32Failure('WaitForSingleObject', code);
111
+ }
112
+ let closed = false;
113
+ return { lockedIdentity, handle: { async close() {
114
+ if (closed) return;
115
+ closed = true;
116
+ const released = api.release(nativeHandle, 1, null);
117
+ const releaseError = released ? undefined : api.lastError();
118
+ const didClose = api.close(nativeHandle);
119
+ if (!released) throw win32Failure('ReleaseSemaphore', releaseError);
120
+ if (!didClose) throw win32Failure('CloseHandle', api.lastError());
121
+ } } };
122
+ }
123
+
124
+ function kernelFlockLinux(fd) {
125
+ return new Promise((done, reject) => {
126
+ // The inherited descriptor shares the parent's open file description.
127
+ const child = spawn('/usr/bin/flock', ['-xn', '-E', String(conflictExit), '3'], {
128
+ stdio: ['ignore', 'ignore', 'ignore', fd], timeout: 3000,
129
+ });
130
+ child.once('error', (error) => reject(failure('unsupported', 'Cannot execute flock', error)));
131
+ child.once('close', (code) => {
132
+ if (code === 0) done();
133
+ else reject(failure(code === conflictExit ? 'locked' : 'unsupported', 'Cannot acquire the DSH session flock'));
134
+ });
135
+ });
136
+ }
137
+
138
+ async function kernelFlockDarwin(fd) {
139
+ try {
140
+ const { tryLockExclusive } = await (darwinFlock ??= import(pathToFileURL(sessionRequire()
141
+ .resolve('@deepseek-ai/node-addon-system/flock')).href));
142
+ await tryLockExclusive(fd);
143
+ } catch (error) {
144
+ const contention = error.code === 'EAGAIN' || error.code === 'EWOULDBLOCK';
145
+ throw failure(contention ? 'locked' : 'unsupported', 'Cannot acquire the DSH session flock', error);
146
+ }
147
+ }
148
+
149
+ async function statExisting(path) {
150
+ try { return await lstat(path, { bigint: true }); }
151
+ catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
152
+ }
153
+
154
+ function identity(info) {
155
+ return { dev: String(info.dev), ino: String(info.ino) };
156
+ }
157
+
158
+ export async function verifyPathLock(path, expected) {
159
+ let actual;
160
+ if (windows) {
161
+ actual = win32Identity(path);
162
+ } else {
163
+ const info = await statExisting(path);
164
+ if (info?.isFile() && info.nlink === 1n) actual = identity(info);
165
+ }
166
+ if (!actual || actual.dev !== expected?.dev || actual.ino !== expected?.ino) {
167
+ throw failure('collision', 'The DSH lock path no longer matches the acquired lock');
168
+ }
169
+ }
170
+
171
+ export async function acquirePathLock(path, device) {
172
+ if (windows) return acquireWindowsLock(path);
173
+ if (process.platform !== 'linux' && process.platform !== 'darwin') {
174
+ throw failure('unsupported', 'DSH session locking is unavailable on this platform');
175
+ }
176
+ const existing = await statExisting(path);
177
+ const safeFile = (info) => info.isFile() && info.nlink === 1n && (device === undefined || info.dev === device);
178
+ if (existing && !safeFile(existing)) throw failure('unsafe-path', 'Unsafe DSH lock path');
179
+ const handle = await open(path, constants.O_CREAT | constants.O_RDWR | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
180
+ try {
181
+ const held = await handle.stat({ bigint: true });
182
+ if (!safeFile(held)) throw failure('unsafe-path', 'Unsafe DSH lock descriptor');
183
+ const flock = process.platform === 'darwin' ? kernelFlockDarwin : kernelFlockLinux;
184
+ await flock(handle.fd);
185
+ const lockedIdentity = identity(held);
186
+ await verifyPathLock(path, lockedIdentity);
187
+ return { handle, lockedIdentity };
188
+ } catch (error) {
189
+ await handle.close();
190
+ throw error;
191
+ }
192
+ }
193
+
194
+ /** Inspect an existing local Windows path without following its terminal reparse point. */
195
+ export function isWindowsReparsePoint(path) {
196
+ if (!windows) return false;
197
+ const api = windowsApi();
198
+ const root = parse(path).root;
199
+ if (!/^[A-Za-z]:\\$/u.test(root) || api.driveType(root) !== DRIVE_FIXED) {
200
+ throw failure('unsupported', 'DSH session movement requires a local Windows volume');
201
+ }
202
+ const attributes = api.attributes(path === root ? root : toNamespacedPath(path));
203
+ if (attributes === INVALID_FILE_ATTRIBUTES) throw win32Failure('GetFileAttributesW', api.lastError());
204
+ return Boolean(attributes & FILE_ATTRIBUTE_REPARSE_POINT);
205
+ }
206
+
207
+ export function assertPlainWindowsPath(path) {
208
+ if (isWindowsReparsePoint(path)) throw failure('unsafe-path', 'Windows reparse point in the session storage path');
209
+ }
210
+
211
+ export async function syncDirectory(path) {
212
+ // On Windows the journal and detach renames use MoveFileExW WRITE_THROUGH.
213
+ if (windows) return;
214
+ const handle = await open(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
215
+ try { await handle.sync(); }
216
+ finally { await handle.close(); }
217
+ }
218
+
219
+ /** Restore into a live namespace without replacing even an empty directory. */
220
+ export async function restorePath(source, dest) {
221
+ if (windows) return publishPath(source, dest);
222
+ if (!exclusiveRename) {
223
+ try {
224
+ const koffi = sessionRequire()('koffi');
225
+ const libc = koffi.load(process.platform === 'darwin' ? '/usr/lib/libSystem.B.dylib' : 'libc.so.6');
226
+ if (process.platform === 'darwin') {
227
+ const renamex = libc.func('int renamex_np(const char *, const char *, unsigned int)');
228
+ exclusiveRename = (from, to) => renamex(from, to, 0x04);
229
+ } else {
230
+ const renameAt = libc.func('int renameat2(int, const char *, int, const char *, unsigned int)');
231
+ exclusiveRename = (from, to) => renameAt(-100, from, -100, to, 1);
232
+ }
233
+ } catch (error) {
234
+ throw failure('unsupported', 'Cannot load the native no-replace rename', error);
235
+ }
236
+ }
237
+ if (exclusiveRename(source, dest) !== 0) {
238
+ throw failure(await statExisting(dest) ? 'collision' : 'EIO', 'Cannot publish without replacing the destination');
239
+ }
240
+ }
241
+
242
+ export async function publishPath(source, dest, { replace = false } = {}) {
243
+ if (!windows) {
244
+ // The transaction directory is private, and only the current operation writes to it.
245
+ if (!replace && await statExisting(dest)) throw failure('collision', 'The target path already exists');
246
+ return rename(source, dest);
247
+ }
248
+ const api = windowsApi();
249
+ const flags = MOVEFILE_WRITE_THROUGH | (replace ? MOVEFILE_REPLACE_EXISTING : 0);
250
+ if (!api.move(toNamespacedPath(source), toNamespacedPath(dest), flags)) {
251
+ throw win32Failure('MoveFileExW', api.lastError());
252
+ }
253
+ }
@@ -0,0 +1,161 @@
1
+ import { join } from 'node:path'
2
+ import { pathToFileURL } from 'node:url'
3
+ import { storagePaths } from './config.js'
4
+ import { refreshSearchIndex, repairLegacyDuplicates, restoreLedger, withPublishedLedger } from './ledger.js'
5
+ import { refreshSessionSummaries } from './sidebar.js'
6
+ import { LOG_FILENAME } from './paths.js'
7
+ import { fail } from './plan.js'
8
+ import { sessionRequire } from './platform-fs.js'
9
+ import { moveStorage, recoverLegacyDisk } from './transaction.js'
10
+
11
+ export const inject = ['storageDomain', 'sessionPersistence', 'dshHomePath']
12
+
13
+ function atLocation(snapshot, id, cwd, directory) {
14
+ return snapshot?.header?.id === id && snapshot.header.cwd === cwd
15
+ && snapshot.location?.kind === 'jsonl' && snapshot.location.path === join(directory, LOG_FILENAME)
16
+ }
17
+
18
+ /** The native reader verifies that each member is unique and matches its path. */
19
+ async function verifyScanSafety(ctx, state, { allowEitherSide = false } = {}) {
20
+ for (const { id, oldCwd, oldDir, nextDir } of state.members) {
21
+ const snapshot = await ctx.sessionPersistence.stat(id)
22
+ const atSource = atLocation(snapshot, id, oldCwd, oldDir)
23
+ const atTarget = atLocation(snapshot, id, state.targetCwd, nextDir)
24
+ const safe = allowEitherSide ? atSource || atTarget : state.phase === 'committed' ? atTarget : atSource
25
+ if (!safe) throw fail('restore-pending')
26
+ }
27
+ }
28
+
29
+ /** Confirm that the move's exact output still precedes any subsequent appends. */
30
+ async function hasPublishedHistory(ctx, storage, state) {
31
+ for (const { id, nextDir } of state.members) {
32
+ const snapshot = await ctx.sessionPersistence.stat(id)
33
+ if (!atLocation(snapshot, id, state.targetCwd, nextDir)) return false
34
+ }
35
+ try { await storage.verifyPublished(state) } catch (error) {
36
+ if (error.code === 'changed') return false
37
+ throw error
38
+ }
39
+ for (const { id, oldCwd, cwdChangeSeq, noticeId } of state.members) {
40
+ if (oldCwd === state.targetCwd) continue
41
+ const handle = await ctx.sessionPersistence.open(id, 'read')
42
+ try {
43
+ if (handle.header.id !== id || handle.header.cwd !== state.targetCwd) return false
44
+ const { events } = await handle.read()
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() }
55
+ }
56
+ return true
57
+ }
58
+
59
+ async function verifyWhileContended(ctx, storage) {
60
+ // A prepared intent may belong to an active mover that has yet to hide the
61
+ // source. Only terminal intents have an authoritative visible side while
62
+ // another process owns the move lock.
63
+ const state = await storage.readState()
64
+ if (!state) return
65
+ if (state.phase === 'prepared') throw fail('restore-pending')
66
+ await verifyScanSafety(ctx, state)
67
+ const latest = await storage.readState()
68
+ if (latest && (latest.ticket !== state.ticket || latest.phase !== state.phase)) throw fail('restore-pending')
69
+ }
70
+
71
+ /** Retry a journal. Only startup may defer work after proving scan safety. */
72
+ export async function recoverMove(ctx, storage, { startup = false, withLedger = (run) => run() } = {}) {
73
+ if (!await storage.hasJournal()) return
74
+ let scanSafe = false
75
+ try {
76
+ await storage.withLock(async () => {
77
+ const state = await storage.readState()
78
+ if (!state) {
79
+ scanSafe = true
80
+ return
81
+ }
82
+ if (state.phase === 'prepared' && await storage.hasHeld(state)) {
83
+ try {
84
+ const committed = await storage.withSessionLocks(state, async () => {
85
+ if (await hasPublishedHistory(ctx, storage, state)) {
86
+ const terminal = { ...state, phase: 'committed' }
87
+ const confirmed = await withLedger((options) => withPublishedLedger(ctx, state, state.ledger, async () => {
88
+ scanSafe = true
89
+ await storage.save(terminal)
90
+ }, options))
91
+ if (confirmed) {
92
+ await storage.cleanCommitted(terminal)
93
+ return true
94
+ }
95
+ }
96
+ await storage.rollback(state)
97
+ return false
98
+ }, { recovery: true })
99
+ if (committed) {
100
+ if (!startup) {
101
+ await refreshSessionSummaries(ctx, state.members.map(({ id }) => ({ id, cwd: state.targetCwd })))
102
+ await refreshSearchIndex(ctx)
103
+ }
104
+ return
105
+ }
106
+ } catch (error) {
107
+ // A failed rollback can still leave every transcript visible. Its
108
+ // journal and original bytes remain available for a later retry.
109
+ if (startup) {
110
+ try {
111
+ await verifyScanSafety(ctx, state, { allowEitherSide: true })
112
+ scanSafe = true
113
+ } catch { /* Resolve the invisible or inconsistent log before startup. */ }
114
+ }
115
+ throw error
116
+ }
117
+ }
118
+ await verifyScanSafety(ctx, state)
119
+ scanSafe = true
120
+
121
+ if (state.phase === 'committed') {
122
+ await storage.withSessionLocks(state, () => storage.cleanCommitted(state), { recovery: true })
123
+ return
124
+ }
125
+ if (state.phase === 'prepared') {
126
+ await withLedger((options) => restoreLedger(ctx, state, state.ledger, options))
127
+ await storage.save({ ...state, phase: 'rolled-back' })
128
+ }
129
+ await storage.finish(state)
130
+ })
131
+ } catch (error) {
132
+ if (startup && !scanSafe && error.code === 'locked') {
133
+ try {
134
+ await verifyWhileContended(ctx, storage)
135
+ scanSafe = true
136
+ } catch { /* The active journal has not reached a verifiable stable side. */ }
137
+ }
138
+ if (!startup || !scanSafe) throw fail('restore-pending', error)
139
+ ctx.logger?.warn?.('Session move: recovery deferred until the next move or restart: %s', error)
140
+ }
141
+ }
142
+
143
+ export async function apply(ctx) {
144
+ const { root, base, legacy, previous } = storagePaths(ctx)
145
+ const withLedger = async (run) => {
146
+ const resolve = sessionRequire()
147
+ const { workspaceDomainSpec } = await import(pathToFileURL(resolve.resolve('@deepseek-ai/dsh-workspace')).href)
148
+ const domain = await ctx.storageDomain.open(workspaceDomainSpec)
149
+ try { return await run({ domain }) } finally { await domain.close() }
150
+ }
151
+ await recoverLegacyDisk(root, legacy)
152
+ for (const directory of new Set([...[].concat(previous ?? []), base].filter(Boolean))) {
153
+ await recoverMove(ctx, moveStorage(root, directory), { startup: true, withLedger })
154
+ }
155
+ try {
156
+ await withLedger((options) => repairLegacyDuplicates(ctx, options))
157
+ } catch (error) {
158
+ if (error.code !== 'unsupported') ctx.logger?.warn?.('Session move: legacy ledger cleanup deferred: %s', error)
159
+ }
160
+ ctx.provide('sessionMoveRecovery', true)
161
+ }
package/src/sidebar.js ADDED
@@ -0,0 +1,45 @@
1
+ const original = Symbol.for('cordis.original')
2
+
3
+ /** Publish ordinary DSH list rows without starting an Agent or attaching a Session. */
4
+ export async function refreshSessionSummaries(ctx, members, verified = new Map()) {
5
+ const service = ctx.get('sessionController')
6
+ if (!service) return true
7
+ // The pinned DSH controller has no public single-row summary operation.
8
+ const list = (service[original] ?? service).listState
9
+ if (typeof list?.summaryFor !== 'function') return false
10
+ const cache = ctx.get('sessionProjectionCache')
11
+ let synced = true
12
+
13
+ for (const { id, cwd } of members) {
14
+ try {
15
+ let session = ctx.sessions.get(id)
16
+ if (session === undefined) {
17
+ let cut = verified.get(id)
18
+ if (!cut) {
19
+ const handle = await ctx.sessionPersistence.open(id, 'read')
20
+ try {
21
+ cut = { header: handle.header, inheritedEventCount: handle.inheritedEventCount, ...await handle.read() }
22
+ } finally { await handle.close() }
23
+ }
24
+ session = ctx.sessions.get(id) ?? ctx.sessions.prepare(id, {
25
+ meta: cut.header, inheritedEventCount: cut.inheritedEventCount,
26
+ seed: cut.events, eventState: cut.eventState,
27
+ })
28
+ }
29
+ if (session.id !== id || session.header.cwd !== cwd) throw new Error('Session header changed')
30
+ if (cache && ctx.sessions.get(id) === undefined) {
31
+ // Bind the checkpoint to the new header for freshly connected lists.
32
+ try { await cache.write(session) } catch (error) {
33
+ ctx.logger?.warn?.('Session move: could not checkpoint "%s": %s', id, error)
34
+ }
35
+ }
36
+ const current = ctx.sessions.get(id) ?? session
37
+ if (current.header.cwd !== cwd) throw new Error('Session header changed')
38
+ ctx.emit('api-session/added', list.summaryFor(current))
39
+ } catch (error) {
40
+ synced = false
41
+ ctx.logger?.warn?.('Session move: could not publish summary for "%s": %s', id, error)
42
+ }
43
+ }
44
+ return synced
45
+ }