dsh-taskbridge 0.0.0-stage → 1.3.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.
Files changed (75) hide show
  1. package/CHANGELOG.md +763 -0
  2. package/LICENSE +21 -0
  3. package/README.md +622 -3
  4. package/bin/dsh-delegate-codex-agent.js +115 -0
  5. package/bin/dsh-delegate-control.d.ts +90 -0
  6. package/bin/dsh-delegate-control.js +450 -0
  7. package/bin/dsh-delegate-mcp.d.ts +121 -0
  8. package/bin/dsh-delegate-mcp.js +273 -0
  9. package/codex/dsh-taskbridge.toml +247 -0
  10. package/cordis.patch.yml +6 -0
  11. package/docs/INTRODUCTION.md +15 -0
  12. package/docs/INTRODUCTION.zh.md +34 -0
  13. package/docs/auth-contract.md +138 -0
  14. package/docs/claude-code.md +31 -0
  15. package/docs/codex-integration.md +937 -0
  16. package/docs/contracts-stage-b.md +443 -0
  17. package/docs/conversation-placement.md +304 -0
  18. package/docs/plugin-market.md +30 -0
  19. package/docs/redaction-contract.md +127 -0
  20. package/docs/runtime-compatibility.md +223 -0
  21. package/docs/silent-wait.md +191 -0
  22. package/docs/taskbridge-upgrade.md +28 -0
  23. package/docs/taskdispatch-upgrade.md +25 -0
  24. package/docs/worker-permissions.md +347 -0
  25. package/docs/workspace-contract.md +538 -0
  26. package/icon.svg +1 -0
  27. package/lib/client.d.ts +118 -0
  28. package/lib/client.js +3232 -0
  29. package/locale/en.json +7 -0
  30. package/locale/zh.json +7 -0
  31. package/package.json +138 -4
  32. package/src/auth/fence.js +361 -0
  33. package/src/auth/grants.js +789 -0
  34. package/src/client/api.js +2322 -0
  35. package/src/client/index.jsx +2333 -0
  36. package/src/client/styles.js +251 -0
  37. package/src/codex/installer.js +3299 -0
  38. package/src/codex/seam.js +429 -0
  39. package/src/codex/toml.js +784 -0
  40. package/src/config/defaults.js +164 -0
  41. package/src/config/redact.js +184 -0
  42. package/src/config/settings.js +629 -0
  43. package/src/config/store.js +186 -0
  44. package/src/config/validate.js +763 -0
  45. package/src/credentials/seam.js +202 -0
  46. package/src/http/execution-plane.js +456 -0
  47. package/src/http/respond.js +175 -0
  48. package/src/http/user-plane.js +1122 -0
  49. package/src/index.d.ts +332 -0
  50. package/src/index.js +657 -0
  51. package/src/jobs/activity.js +1008 -0
  52. package/src/jobs/engine.js +3614 -0
  53. package/src/jobs/history.js +1467 -0
  54. package/src/jobs/title.js +17 -0
  55. package/src/mcp/server.js +1821 -0
  56. package/src/mcp/wait.js +536 -0
  57. package/src/model/connectivity.js +371 -0
  58. package/src/model/discovery.js +582 -0
  59. package/src/model/native-catalog.js +68 -0
  60. package/src/model/openai-adapter.js +671 -0
  61. package/src/model/probe.js +264 -0
  62. package/src/model/providers.js +756 -0
  63. package/src/model/routing.js +321 -0
  64. package/src/review/preset.js +868 -0
  65. package/src/review/prompts.js +126 -0
  66. package/src/review/reviewer.js +933 -0
  67. package/src/runtime/agent-runner.js +1740 -0
  68. package/src/runtime/endpoint-discovery.js +118 -0
  69. package/src/runtime/permissions.js +1429 -0
  70. package/src/runtime/sandbox.js +358 -0
  71. package/src/runtime/session-placement.js +1121 -0
  72. package/src/workspace/audit.js +775 -0
  73. package/src/workspace/locks.js +167 -0
  74. package/src/workspace/preflight.js +424 -0
  75. package/src/workspace/worktrees.js +613 -0
@@ -0,0 +1,1121 @@
1
+ // Session placement: which DSH Workspace a delegated run appears in, and which
2
+ // native Session it drives inside that Workspace.
3
+ //
4
+ // There is exactly ONE placement policy, and it is per task, not per directory:
5
+ //
6
+ // * **A new submission is a new conversation.** Every ordinary dispatch creates a
7
+ // fresh DSH Session in the Workspace for its execution directory. Nothing an
8
+ // earlier task did in the same directory can make a new submission continue
9
+ // somebody else's conversation — there is no directory-level mode to read, and
10
+ // a settings document that still stores the legacy `conversation.mode: "reuse"`
11
+ // is accepted as input but is incapable of causing an implicit reuse
12
+ // ({@link LEGACY_CONVERSATION_MODE}).
13
+ //
14
+ // * **A follow-up continues one named task thread.** `continueFromTaskId` names
15
+ // the previous task explicitly, and only that identity is continued: the same
16
+ // Workspace, the same Session. This is why the durable map below is keyed by
17
+ // *task id* rather than by directory — one directory may hold many independent
18
+ // conversations, and only the operator's explicit choice can join them.
19
+ //
20
+ // Two questions, answered by two explicit native APIs and never by a guess:
21
+ //
22
+ // * **Workspace.** A run must be accounted to a real DSH Workspace keyed by the
23
+ // directory it actually executes in (`task.executionPath`) — the worktree when
24
+ // isolation prepared one, the source checkout when it did not.
25
+ // `ctx.workspaceController.create({ path })` creates or reuses that Workspace
26
+ // and returns `{ workspace, created }`.
27
+ //
28
+ // * **Session.** `ctx.sessionController.create({ workspaceId })` creates a new
29
+ // Session in that Workspace; `ctx.sessionController.resolveAgent(sessionId)`
30
+ // returns the live Agent of an existing one, which is what a follow-up drives.
31
+ //
32
+ // Dependencies are named by the service they are: `deps.workspaces` is
33
+ // `ctx.workspaceController` and `deps.sessionController` is `ctx.sessionController`.
34
+ // `deps.sessions` is the native `ctx.sessions` persistence service (used for
35
+ // `flush`, not for planning a Session) and this module never reads it.
36
+ //
37
+ // Both controllers are optional native services. Their absence, or a continuation
38
+ // whose recorded thread can no longer be reached, is a stated refusal
39
+ // ({@link SESSION_CODES}) — never a silent fall back to a new, ungrouped session.
40
+ //
41
+ // What survives a run is deliberately minimal: `{ taskId, sourcePath,
42
+ // executionPath, workspaceId, sessionId, isolation, worktreeId, worktreeState,
43
+ // updatedAt }` per task, in `sessions.json` beside the settings document. No
44
+ // prompt, no transcript, no model output, no credential and no token count is
45
+ // written here. The native session log stays the single owner of conversation
46
+ // content, so this map cannot leak anything it did not receive.
47
+
48
+ import { readFile, rename, rm, writeFile, mkdir } from 'node:fs/promises';
49
+ import { dirname, join } from 'node:path';
50
+
51
+ import { ISOLATION_MODES, SESSIONS_FILE } from '../config/defaults.js';
52
+ import { diagnostic } from '../config/redact.js';
53
+
54
+ /** Stable ids of a managed worktree life cycle, mirrored as a plain string set here. */
55
+ const WORKTREE_STATE_DISPOSED = 'disposed';
56
+
57
+ /** Fields one stored row may carry. Anything else is dropped on the way in. */
58
+ const RECORD_FIELDS = Object.freeze([
59
+ 'taskId',
60
+ 'sourcePath',
61
+ 'executionPath',
62
+ 'workspaceId',
63
+ 'sessionId',
64
+ 'isolation',
65
+ 'worktreeId',
66
+ 'worktreeState',
67
+ 'updatedAt',
68
+ ]);
69
+
70
+ /** Session-placement refusal codes. Each one means the run did not start. */
71
+ export const SESSION_CODES = Object.freeze({
72
+ // The native workspaces service is not composed into this harness.
73
+ workspacesUnavailable: 'SESSION_WORKSPACES_UNAVAILABLE',
74
+ // The native session controller is not composed into this harness.
75
+ sessionsUnavailable: 'SESSION_CONTROLLER_UNAVAILABLE',
76
+ // `workspaceController.create` existed but refused or reported nothing usable.
77
+ workspaceRefused: 'SESSION_WORKSPACE_REFUSED',
78
+ // `sessionController.create` existed but refused or reported no session.
79
+ sessionCreateFailed: 'SESSION_CREATE_FAILED',
80
+ // A continuation named a task that this data directory has no identity for.
81
+ // Unknown, stale and never-retained parents are the same operator situation:
82
+ // there is nothing to continue, and nothing is invented in its place.
83
+ continuationUnknown: 'SESSION_CONTINUATION_UNKNOWN',
84
+ // The named parent exists but is not in a state a thread can be continued from
85
+ // (still running, or ended without ever driving a conversation).
86
+ continuationState: 'SESSION_CONTINUATION_STATE',
87
+ // The persisted identity cannot be used to reach a session: no session id, or a
88
+ // worktree identity that is gone or refused.
89
+ continuationUnavailable: 'SESSION_CONTINUATION_UNAVAILABLE',
90
+ // The named parent ran somewhere else than this submission's execution
91
+ // directory. A task chain never crosses directories.
92
+ continuationPathMismatch: 'SESSION_CONTINUATION_PATH_MISMATCH',
93
+ // The recorded Workspace belongs to another source repository.
94
+ continuationWorkspaceMismatch: 'SESSION_CONTINUATION_WORKSPACE_MISMATCH',
95
+ // Continuation was requested and the controller cannot resolve a session at all.
96
+ resumeUnavailable: 'SESSION_RESUME_UNAVAILABLE',
97
+ // The session exists but could not be resolved to a drivable Agent.
98
+ resumeFailed: 'SESSION_RESUME_FAILED',
99
+ // A resolved session's own header names another directory.
100
+ resumePathMismatch: 'SESSION_RESUME_PATH_MISMATCH',
101
+ // The session recorded for the named task no longer exists.
102
+ sessionNotFound: 'SESSION_NOT_FOUND',
103
+ });
104
+
105
+ /**
106
+ * The conversation mode a stored settings document may still carry.
107
+ *
108
+ * It is accepted so an upgraded document keeps loading, and it is recorded on the
109
+ * legacy boundary only. It has no effect: a new submission is always new, and a
110
+ * follow-up is always the thread named by `continueFromTaskId`. Nothing in this
111
+ * module reads it, which is the property that makes the legacy value incapable of
112
+ * causing an implicit reuse.
113
+ */
114
+ export const LEGACY_CONVERSATION_MODE = 'reuse';
115
+
116
+ /** Placement outcomes, as reported to an operator. */
117
+ export const PLACEMENT_KINDS = Object.freeze({
118
+ // A fresh DSH Session was created for this run.
119
+ new: 'new',
120
+ // An earlier task's Session was continued.
121
+ continuation: 'continuation',
122
+ });
123
+
124
+ /** Refusal raised by {@link placeSession}. */
125
+ export class SessionPlacementError extends Error {
126
+ /**
127
+ * @param {string} code - stable machine code.
128
+ * @param {string} message - operator-readable explanation.
129
+ * @param {object} [details] - bounded, non-secret context.
130
+ */
131
+ constructor(code, message, details = {}) {
132
+ super(message);
133
+ this.name = 'SessionPlacementError';
134
+ this.code = code;
135
+ this.details = details;
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Canonical form of one directory, as an identity key.
141
+ *
142
+ * The identity of a Workspace is a path string the harness canonicalized once, so
143
+ * this mirrors that spelling and folds case on Windows (NTFS is
144
+ * case-insensitive), exactly as the project-override keys do. Two spellings of
145
+ * one directory therefore address one directory, and two different directories
146
+ * never do.
147
+ * @param {unknown} value - candidate directory path.
148
+ * @returns {string | null} canonical key, or `null` when it is not a path.
149
+ */
150
+ export function sessionPathKey(value) {
151
+ if (typeof value !== 'string') return null;
152
+ const trimmed = value.trim();
153
+ if (trimmed === '') return null;
154
+ const stripped = trimmed.length > 1 ? trimmed.replace(/[\\/]+$/, '') : trimmed;
155
+ return process.platform === 'win32' ? stripped.toLowerCase() : stripped;
156
+ }
157
+
158
+ /**
159
+ * Whether a recorded path is the same canonical path as a current one.
160
+ * @param {unknown} a - first path.
161
+ * @param {unknown} b - second path.
162
+ * @returns {boolean} true when both name one directory.
163
+ */
164
+ export function sameSessionPath(a, b) {
165
+ const left = sessionPathKey(a);
166
+ const right = sessionPathKey(b);
167
+ return left !== null && right !== null && left === right;
168
+ }
169
+
170
+ /**
171
+ * Narrow a dependency object to the two native controllers.
172
+ *
173
+ * Both are read here, once per placement, so every caller sees the same capability
174
+ * decision and a missing service is one refusal code instead of a property read
175
+ * that happens to throw.
176
+ *
177
+ * The two names are not interchangeable and this function is the only place that
178
+ * answers the question, so the mapping is stated once:
179
+ *
180
+ * * `deps.workspaces` — `ctx.workspaceController`;
181
+ * * `deps.sessionController` — `ctx.sessionController`, the service that owns
182
+ * `create`/`resolveAgent`. This is the planner of Sessions.
183
+ *
184
+ * `deps.sessions` is deliberately NOT consulted: that is the native
185
+ * `ctx.sessions` persistence service (the one the runner calls `flush` on), and it
186
+ * has no `create`/`resolveAgent` at all.
187
+ * @param {object} deps - dependency object with optional `workspaces` and `sessionController`.
188
+ * @returns {{ workspaces: object | null, sessions: object | null, worktrees: object | null }} the available services.
189
+ */
190
+ function controllersOf(deps) {
191
+ const workspaces = controllerOf(deps?.workspaces);
192
+ const sessions = controllerOf(deps?.sessionController);
193
+ const worktrees = controllerOf(deps?.worktrees);
194
+ return {
195
+ // `create` is the capability `ensureWorkspace`/`createWorkspaceSession` need;
196
+ // nothing is placed through a service that cannot create.
197
+ workspaces: typeof workspaces?.create === 'function' ? workspaces : null,
198
+ sessions: typeof sessions?.create === 'function' ? sessions : null,
199
+ // The worktree registry is optional: it exists only to prove that a
200
+ // continuation runs in the tree its parent actually used.
201
+ worktrees: typeof worktrees?.get === 'function' ? worktrees : null,
202
+ };
203
+ }
204
+
205
+ /**
206
+ * The runtime-resolved accessor for one native controller.
207
+ *
208
+ * A DSH harness may compose `workspaceController` / `sessionController` *after*
209
+ * this plugin activated, or replace one later in the same process. A dependency
210
+ * object that captured `ctx.get(name, false)` once during `apply` fixes the answer
211
+ * at load, so every later run would see `null`. This accessor is deliberately live
212
+ * on both axes: `create` is a getter, and the service is never cached, so what a
213
+ * placement sees is what the harness exposes right now.
214
+ * @param {() => unknown} resolve - reads the current service; may throw or answer null.
215
+ * @param {object} [options] - `onError(error)`: called with a read refusal, which is
216
+ * reported as an absent controller.
217
+ * @returns {{ readonly current: object | null }} accessor; `null` means absent.
218
+ */
219
+ export function liveControllerAccessor(resolve, options = {}) {
220
+ const onError = typeof options?.onError === 'function' ? options.onError : null;
221
+ return {
222
+ /**
223
+ * The service as it is NOW, or null when the harness does not expose it.
224
+ * @returns {object | null} live service.
225
+ */
226
+ get current() {
227
+ try {
228
+ const service = resolve();
229
+ return service === undefined || service === null ? null : service;
230
+ } catch (error) {
231
+ // An unreadable service is an absent service for placement purposes: the
232
+ // caller then refuses with `SESSION_*_UNAVAILABLE` instead of surfacing a
233
+ // property-access error as an execution failure.
234
+ onError?.(error);
235
+ return null;
236
+ }
237
+ },
238
+ get create() {
239
+ const service = this.current;
240
+ const method = service?.create;
241
+ // Bound to the LIVE service, so a caller reading `create` calls through the
242
+ // service this instant rather than through an object it saw before.
243
+ return typeof method === 'function' ? method.bind(service) : null;
244
+ },
245
+ };
246
+ }
247
+
248
+ /**
249
+ * Read one controller off a dependency value, following an accessor when it is one.
250
+ * @param {unknown} value - a controller, an accessor, or nothing.
251
+ * @returns {object | null} the service as it is now, or null.
252
+ */
253
+ function controllerOf(value) {
254
+ if (value === undefined || value === null) return null;
255
+ // An accessor is the only dependency value that carries a live `current`
256
+ // member; the services themselves never do.
257
+ if (typeof value === 'object' && 'current' in value) {
258
+ const live = value.current;
259
+ return live === null || live === undefined ? null : live;
260
+ }
261
+ return value;
262
+ }
263
+
264
+ /**
265
+ * Normalize a requested continuation identity, or `null` when none was asked for.
266
+ *
267
+ * An absent, blank or non-string value means "this is a new submission". A blank
268
+ * string is deliberately treated as absent rather than as a refusal: it is what an
269
+ * MCP client sends for "no value", and refusing it would turn "start a new
270
+ * conversation" into an error.
271
+ * @param {unknown} value - caller-supplied `continueFromTaskId`.
272
+ * @returns {string | null} the task id to continue, or null.
273
+ */
274
+ export function continuationOf(value) {
275
+ if (typeof value !== 'string') return null;
276
+ const trimmed = value.trim();
277
+ return trimmed === '' ? null : trimmed;
278
+ }
279
+
280
+ /**
281
+ * Resolve the native Workspace a delegated run belongs to.
282
+ *
283
+ * `workspaceController.create({ path })` creates the Workspace for an existing
284
+ * directory or returns the one that already owns it (`created: false`).
285
+ * @param {object} workspaces - the native Workspace controller.
286
+ * @param {string} path - the directory the run executes in.
287
+ * @returns {Promise<{ workspaceId: string, path: string, created: boolean }>} the Workspace fact.
288
+ * @throws {SessionPlacementError} when the controller refuses or reports nothing usable.
289
+ */
290
+ export async function ensureWorkspace(workspaces, path, title = null, taskId = '') {
291
+ let value;
292
+ try {
293
+ value = await workspaces.create({ path });
294
+ } catch (error) {
295
+ throw new SessionPlacementError(
296
+ SESSION_CODES.workspaceRefused,
297
+ 'DSH refused to group this run into a Workspace for its execution directory',
298
+ { cause: typeof error?.code === 'string' ? error.code : null, detail: diagnostic(error?.message ?? error, 200) },
299
+ );
300
+ }
301
+ const workspace = value?.workspace ?? null;
302
+ const workspaceId = workspace?.workspaceId ?? null;
303
+ if (typeof workspaceId !== 'string' || workspaceId === '') {
304
+ // Fail closed: a run without a Workspace is the unpartitioned state this
305
+ // feature exists to remove, so an unusable answer may not become a session.
306
+ throw new SessionPlacementError(
307
+ SESSION_CODES.workspaceRefused,
308
+ 'the Workspace controller returned no Workspace identity for this directory',
309
+ { returned: value === null || typeof value !== 'object' ? typeof value : 'object without workspace.workspaceId' },
310
+ );
311
+ }
312
+ let workspaceTitle = workspace.title ?? null;
313
+ let namingError = null;
314
+ if (value.created === true && typeof title === 'string' && title.trim() !== '' && typeof workspaces.rename === 'function') {
315
+ try {
316
+ let renamed;
317
+ try { renamed = await workspaces.rename({ workspaceId, title }); }
318
+ catch (error) {
319
+ if (error?.code !== 'workspace/name-conflict') throw error;
320
+ renamed = await workspaces.rename({ workspaceId, title: `${title} · ${taskId.slice(-6) || workspaceId.slice(-6)}` });
321
+ }
322
+ workspaceTitle = renamed?.workspace?.title ?? title;
323
+ } catch (error) { namingError = diagnostic(error?.message ?? error, 200); }
324
+ }
325
+ return {
326
+ workspaceId,
327
+ workspaceTitle,
328
+ namingError,
329
+ path: typeof workspace.path === 'string' && workspace.path !== '' ? workspace.path : path,
330
+ created: value?.created === true,
331
+ };
332
+ }
333
+
334
+ /**
335
+ * Place one run: a new Session, or the explicit continuation of one task thread.
336
+ *
337
+ * The decision is made here and only here, from two facts the caller supplies:
338
+ *
339
+ * 1. **capability checks first** — no Session is created and no Agent resolved
340
+ * before it is known that the run can be driven at all, so a refusal never
341
+ * leaves a Session behind;
342
+ * 2. **`continueFromTaskId` omitted** — a fresh Session is created in the
343
+ * Workspace for this run's execution directory, then resolved to a live Agent.
344
+ * Nothing is read from the identity map: a new submission is new even when the
345
+ * same directory has a long history, which is the property the removed
346
+ * directory-level `reuse` setting used to violate;
347
+ * 3. **`continueFromTaskId` supplied** — the recorded identity of *that task* is
348
+ * loaded and every fact a thread continuation depends on is re-checked
349
+ * ({@link validateContinuation}). A continuation that cannot be honoured is a
350
+ * refusal; it is never quietly replaced by the new-Session path, because that
351
+ * would report a continued conversation the operator is not actually in.
352
+ *
353
+ * Both paths return a live `agent`, and neither creates a Session or an Agent
354
+ * twice.
355
+ * @param {object} deps - dependency object with `workspaces`, `sessionController`,
356
+ * `sessionStore`, optional `worktrees`, and the task/connection facts a
357
+ * continuation must match (`taskId`, `connectionId`, `sourcePath`).
358
+ * @param {object} request - `path` (the actual execution directory), `presetId`,
359
+ * and optional `continueFromTaskId`.
360
+ * @returns {Promise<object>} placement fact: kind, Workspace, Session, Agent and
361
+ * the continuation facts.
362
+ * @throws {SessionPlacementError} when the run cannot be placed.
363
+ */
364
+ export async function placeSession(deps, request) {
365
+ const { workspaces, sessions } = controllersOf(deps);
366
+ if (workspaces === null) {
367
+ throw new SessionPlacementError(
368
+ SESSION_CODES.workspacesUnavailable,
369
+ 'the DSH Workspace controller is unavailable, so this run could not be grouped into a Workspace',
370
+ {},
371
+ );
372
+ }
373
+ if (sessions === null) {
374
+ throw new SessionPlacementError(
375
+ SESSION_CODES.sessionsUnavailable,
376
+ 'the DSH session controller is unavailable, so no Workspace-scoped session could be created',
377
+ {},
378
+ );
379
+ }
380
+ const path = sessionPathKey(request?.path);
381
+ if (path === null) {
382
+ throw new SessionPlacementError(SESSION_CODES.sessionCreateFailed, 'no execution directory was resolved for this run', {});
383
+ }
384
+ const execPath = request.path;
385
+ const continueFromTaskId = continuationOf(request?.continueFromTaskId);
386
+
387
+ const workspace = await ensureWorkspace(workspaces, execPath, continueFromTaskId === null ? request?.title : null, request?.taskId ?? deps.taskId ?? '');
388
+ if (workspace.namingError) deps.logger?.warn?.(`TaskBridge workspace title: ${workspace.namingError}`);
389
+
390
+ if (continueFromTaskId !== null) {
391
+ const parent = await loadContinuation(deps, continueFromTaskId);
392
+ const resumed = await continueTaskThread({
393
+ deps,
394
+ sessions,
395
+ workspace,
396
+ parent,
397
+ execPath,
398
+ presetId: request?.presetId,
399
+ });
400
+ return {
401
+ kind: PLACEMENT_KINDS.continuation,
402
+ continuedFromTaskId: continueFromTaskId,
403
+ reused: true,
404
+ workspaceId: workspace.workspaceId,
405
+ workspaceTitle: workspace.workspaceTitle,
406
+ workspacePath: workspace.path,
407
+ workspaceCreated: workspace.created,
408
+ sessionId: resumed.sessionId,
409
+ sessionCreated: false,
410
+ agent: resumed.agent,
411
+ };
412
+ }
413
+
414
+ const sessionId = await createWorkspaceSession(sessions, workspace.workspaceId, request?.presetId);
415
+ // A freshly created Session is joined to its Agent by resolving it, through the
416
+ // same call a continuation uses. Nothing else attaches an Agent to a Session
417
+ // that the caller did not create through `agents.create`, and `agents.create`
418
+ // cannot be used here: it would create a SECOND Session under the id it is handed.
419
+ const created = await attachWorkspaceAgent({ sessions, workspace, sessionId, execPath });
420
+ return {
421
+ kind: PLACEMENT_KINDS.new,
422
+ continuedFromTaskId: null,
423
+ reused: false,
424
+ workspaceId: workspace.workspaceId,
425
+ workspaceTitle: workspace.workspaceTitle,
426
+ workspacePath: workspace.path,
427
+ workspaceCreated: workspace.created,
428
+ sessionId: created.sessionId,
429
+ sessionCreated: true,
430
+ agent: created.agent,
431
+ };
432
+ }
433
+
434
+ /**
435
+ * Create one new Session inside a Workspace.
436
+ *
437
+ * `workspaceId` is passed instead of `cwd` on purpose: the native controller
438
+ * derives the Session's directory from the Workspace, which is the same canonical
439
+ * path membership is validated against. Passing both is refused by the controller.
440
+ * @param {object} sessions - the native session controller.
441
+ * @param {string} workspaceId - Workspace identity.
442
+ * @param {string | undefined} presetId - agent preset the Session must own, if any.
443
+ * @returns {Promise<string>} the created Session's id.
444
+ * @throws {SessionPlacementError} when the controller refuses or reports none.
445
+ */
446
+ async function createWorkspaceSession(sessions, workspaceId, presetId) {
447
+ let value;
448
+ try {
449
+ value = await sessions.create({
450
+ workspaceId,
451
+ ...(typeof presetId === 'string' && presetId !== '' ? { agentPreset: presetId } : {}),
452
+ });
453
+ } catch (error) {
454
+ throw new SessionPlacementError(
455
+ SESSION_CODES.sessionCreateFailed,
456
+ 'DSH could not create a session in the Workspace for this run',
457
+ { cause: typeof error?.code === 'string' ? error.code : null, detail: diagnostic(error?.message ?? error, 200) },
458
+ );
459
+ }
460
+ const sessionId = value?.sessionId ?? null;
461
+ if (typeof sessionId !== 'string' || sessionId === '') {
462
+ throw new SessionPlacementError(
463
+ SESSION_CODES.sessionCreateFailed,
464
+ 'the session controller returned no session identity for this run',
465
+ {},
466
+ );
467
+ }
468
+ return sessionId;
469
+ }
470
+
471
+ /**
472
+ * Read the persisted identity of one parent task, or refuse.
473
+ *
474
+ * Unknown, stale, pruned and never-recorded parents are one refusal code
475
+ * (`SESSION_CONTINUATION_UNKNOWN`) because they are one operator situation: the
476
+ * named thread does not exist here, so there is nothing to continue. A continuation
477
+ * is never widened to "some other task in this directory".
478
+ * @param {object} deps - dependency object.
479
+ * @param {string} taskId - the task id the caller named.
480
+ * @returns {Promise<object>} the stored identity.
481
+ * @throws {SessionPlacementError} when no identity exists for that task.
482
+ */
483
+ async function loadContinuation(deps, taskId) {
484
+ const store = deps?.sessionStore ?? null;
485
+ // A task this process still holds is judged by the engine's own record, which is
486
+ // strictly more informative than the persisted row: liveness, connection
487
+ // ownership and "did it ever drive a conversation" are all live facts there. The
488
+ // engine reports the refusal itself and returns here only when the parent is not
489
+ // one of its own, so this check cannot hide an unknown id.
490
+ if (typeof deps?.assertAdmissible === 'function') {
491
+ deps.assertAdmissible(taskId);
492
+ }
493
+ if (store === null || store === undefined || typeof store.get !== 'function') {
494
+ throw new SessionPlacementError(
495
+ SESSION_CODES.continuationUnavailable,
496
+ 'this deployment keeps no task-to-conversation identity, so the named task cannot be continued',
497
+ { continueFromTaskId: taskId, reason: 'no session identity store' },
498
+ );
499
+ }
500
+ let record;
501
+ try {
502
+ record = await store.get(taskId);
503
+ } catch (error) {
504
+ throw new SessionPlacementError(
505
+ SESSION_CODES.continuationUnavailable,
506
+ 'the stored task-to-conversation identity could not be read, so the named task cannot be continued',
507
+ { continueFromTaskId: taskId, detail: diagnostic(error?.message ?? error, 200) },
508
+ );
509
+ }
510
+ if (record === null || record === undefined || typeof record !== 'object') {
511
+ throw new SessionPlacementError(
512
+ SESSION_CODES.continuationUnknown,
513
+ 'no conversation is recorded for the named task, so it cannot be continued',
514
+ {
515
+ continueFromTaskId: taskId,
516
+ reason: 'unknown, pruned or started by another deployment',
517
+ hint: 'omit continueFromTaskId to start a new task conversation',
518
+ },
519
+ );
520
+ }
521
+ return record;
522
+ }
523
+
524
+ /**
525
+ * Validate one continuation and resolve the parent thread's live Agent.
526
+ *
527
+ * Every guard below is a *refusal*, never a repair, because each of them names a
528
+ * case in which continuing would silently join the wrong conversation:
529
+ *
530
+ * 1. the recorded identity must name a session at all;
531
+ * 2. the parent must have run in exactly this run's execution directory — a chain
532
+ * never crosses directories, and a plugin-managed worktree is a different
533
+ * directory from its source on purpose;
534
+ * 3. the parent must have run for the same source repository: the recorded
535
+ * Workspace path must be that repository;
536
+ * 4. a worktree parent must still be a live managed tree whose recorded
537
+ * `worktreeId` matches, because that tree is where the earlier uncommitted
538
+ * worker changes are;
539
+ * 5. the native controller must be able to resolve the session, and the resolved
540
+ * Agent's own header must name the same directory.
541
+ *
542
+ * The ownership facts checked here are the ones that are knowable from the record
543
+ * and the native services. Connection ownership is enforced before placement, where
544
+ * the engine still holds the connection identity: this module never sees one.
545
+ * @param {object} request - `deps`, `sessions`, `workspace`, `parent`, `execPath`, `presetId`.
546
+ * @returns {Promise<{ sessionId: string, agent: object }>} the live Agent of the continued thread.
547
+ * @throws {SessionPlacementError} when the thread cannot be continued.
548
+ */
549
+ async function continueTaskThread({ deps, sessions, workspace, parent, execPath, presetId }) {
550
+ const parentTaskId = parent.taskId ?? null;
551
+ const sessionId = typeof parent.sessionId === 'string' ? parent.sessionId.trim() : '';
552
+ if (sessionId === '') {
553
+ throw new SessionPlacementError(
554
+ SESSION_CODES.continuationUnavailable,
555
+ 'the named task drove no conversation, so there is no thread to continue',
556
+ { continueFromTaskId: parentTaskId, reason: 'no recorded session' },
557
+ );
558
+ }
559
+ const recordedExec = parent.executionPath ?? parent.path ?? null;
560
+ if (!sameSessionPath(recordedExec, execPath)) {
561
+ throw new SessionPlacementError(
562
+ SESSION_CODES.continuationPathMismatch,
563
+ 'the named task ran in another execution directory, so its conversation was not continued',
564
+ {
565
+ continueFromTaskId: parentTaskId,
566
+ recordedExecutionPath: typeof recordedExec === 'string' ? recordedExec : null,
567
+ executionPath: execPath,
568
+ hint: 'a follow-up must run where its task ran; a plugin-managed worktree is its own directory',
569
+ },
570
+ );
571
+ }
572
+
573
+ const isolation = parent.isolation ?? null;
574
+ if (isolation === 'worktree') {
575
+ assertWorktreeContinuable(deps, parent, execPath);
576
+ }
577
+
578
+ const recordedSource = parent.sourcePath ?? null;
579
+ const currentSource = deps?.sourcePath ?? null;
580
+ if (typeof recordedSource === 'string' && recordedSource !== '' && typeof currentSource === 'string' && currentSource !== ''
581
+ && !sameSessionPath(recordedSource, currentSource)) {
582
+ throw new SessionPlacementError(
583
+ SESSION_CODES.continuationWorkspaceMismatch,
584
+ 'the named task was authorized for another source repository, so its conversation was not continued',
585
+ {
586
+ continueFromTaskId: parentTaskId,
587
+ reason: 'different source repository',
588
+ },
589
+ );
590
+ }
591
+ if (typeof parent.workspaceId === 'string' && parent.workspaceId !== ''
592
+ && parent.workspaceId !== workspace.workspaceId) {
593
+ // The Workspace is keyed by the execution directory: reaching a Workspace from
594
+ // another directory would be a cross-directory continuation by another name.
595
+ throw new SessionPlacementError(
596
+ SESSION_CODES.continuationWorkspaceMismatch,
597
+ 'the named task belongs to another DSH Workspace, so its conversation was not continued',
598
+ {
599
+ continueFromTaskId: parentTaskId,
600
+ reason: 'different workspace',
601
+ },
602
+ );
603
+ }
604
+
605
+ const resolved = await resumeExistingSession({ sessions, workspace, sessionId, execPath, presetId, parentTaskId });
606
+ return resolved;
607
+ }
608
+
609
+ /**
610
+ * Prove that a worktree parent is still the tree this continuation must reuse.
611
+ *
612
+ * The follow-up has to run in the tree the parent executed in, because that is
613
+ * where the parent's uncommitted changes are. Creating a fresh tree would start
614
+ * from a clean commit and silently hide them, so a tree that is gone, disposed, or
615
+ * no longer the one the record names is a refusal.
616
+ * @param {object} deps - dependency object with the optional `worktrees` registry.
617
+ * @param {object} parent - recorded identity of the parent task.
618
+ * @param {string} execPath - the execution directory this continuation resolved.
619
+ * @returns {void}
620
+ * @throws {SessionPlacementError} when the tree cannot be reused.
621
+ */
622
+ function assertWorktreeContinuable(deps, parent, execPath) {
623
+ const taskId = parent.taskId ?? null;
624
+ const worktreeId = typeof parent.worktreeId === 'string' ? parent.worktreeId.trim() : '';
625
+ if (worktreeId === '') {
626
+ throw new SessionPlacementError(
627
+ SESSION_CODES.continuationUnavailable,
628
+ 'the named task ran in an isolated tree whose identity was not recorded, so it cannot be reused safely',
629
+ { continueFromTaskId: taskId, reason: 'no recorded worktree identity' },
630
+ );
631
+ }
632
+ if (parent.worktreeState === WORKTREE_STATE_DISPOSED) {
633
+ throw new SessionPlacementError(
634
+ SESSION_CODES.continuationUnavailable,
635
+ 'the isolated tree the named task ran in has been removed, so the thread cannot be continued',
636
+ { continueFromTaskId: taskId, reason: 'worktree disposed' },
637
+ );
638
+ }
639
+ const registry = deps?.worktrees ?? null;
640
+ if (registry === null || registry === undefined || typeof registry.get !== 'function') {
641
+ throw new SessionPlacementError(
642
+ SESSION_CODES.continuationUnavailable,
643
+ 'this harness cannot report its managed trees, so the named task\'s tree cannot be proven reusable',
644
+ { continueFromTaskId: taskId, reason: 'no worktree registry' },
645
+ );
646
+ }
647
+ let tree;
648
+ try {
649
+ tree = registry.get(execPath);
650
+ } catch (error) {
651
+ throw new SessionPlacementError(
652
+ SESSION_CODES.continuationUnavailable,
653
+ 'this harness refused to report the named task\'s tree, so the thread cannot be continued',
654
+ { continueFromTaskId: taskId, detail: diagnostic(error?.message ?? error, 200) },
655
+ );
656
+ }
657
+ if (tree === null || tree === undefined || typeof tree !== 'object') {
658
+ throw new SessionPlacementError(
659
+ SESSION_CODES.continuationUnavailable,
660
+ 'no managed tree exists at the named task\'s execution path, so the thread cannot be continued',
661
+ { continueFromTaskId: taskId, reason: 'tree not managed here' },
662
+ );
663
+ }
664
+ if (tree.state === WORKTREE_STATE_DISPOSED) {
665
+ throw new SessionPlacementError(
666
+ SESSION_CODES.continuationUnavailable,
667
+ 'the isolated tree the named task ran in has been removed, so the thread cannot be continued',
668
+ { continueFromTaskId: taskId, reason: 'worktree disposed' },
669
+ );
670
+ }
671
+ const foundId = typeof tree.worktreeId === 'string' && tree.worktreeId !== '' ? tree.worktreeId : (tree.taskId ?? null);
672
+ if (typeof foundId === 'string' && foundId !== '' && !sameWorktreeId(foundId, worktreeId)) {
673
+ throw new SessionPlacementError(
674
+ SESSION_CODES.continuationUnavailable,
675
+ 'the tree at the named task\'s execution path belongs to another run, so it was not reused',
676
+ { continueFromTaskId: taskId, reason: 'worktree identity mismatch' },
677
+ );
678
+ }
679
+ }
680
+
681
+ /**
682
+ * Whether two worktree identities name one tree.
683
+ *
684
+ * The registry historically exposes the tree's own `taskId` (the id of the task
685
+ * that prepared it) and a `worktreeId` in newer views, so both spellings are
686
+ * compared the way a path is compared: exactly, then case-folded on Windows.
687
+ * @param {string} a - first identity.
688
+ * @param {string} b - second identity.
689
+ * @returns {boolean} true when both name one tree.
690
+ */
691
+ export function sameWorktreeId(a, b) {
692
+ if (typeof a !== 'string' || typeof b !== 'string') return false;
693
+ if (a === b) return true;
694
+ return process.platform === 'win32' && a.toLowerCase() === b.toLowerCase();
695
+ }
696
+
697
+ /**
698
+ * Resolve an existing Session to the live, drivable Agent a continuation drives.
699
+ *
700
+ * `sessionController.resolveAgent(sessionId)` is the only documented way to reach
701
+ * the Agent of a Session the caller did not create through `agents.create`, and
702
+ * driving the resolved Agent (rather than its logged header) is what makes the
703
+ * turn land in the SAME native session log.
704
+ * @param {object} request - `sessions`, `workspace`, `sessionId`, `execPath`, `presetId`, `parentTaskId`.
705
+ * @returns {Promise<{ sessionId: string, agent: object }>} the live Agent and its id.
706
+ * @throws {SessionPlacementError} when no drivable Agent can be resolved.
707
+ */
708
+ async function resumeExistingSession({ sessions, workspace, sessionId, execPath, presetId, parentTaskId }) {
709
+ if (typeof sessions.resolveAgent !== 'function') {
710
+ throw new SessionPlacementError(
711
+ SESSION_CODES.resumeUnavailable,
712
+ 'this DSH build cannot resolve an existing session, so the follow-up cannot be continued',
713
+ { reason: 'sessionController.resolveAgent is missing', continueFromTaskId: parentTaskId ?? null },
714
+ );
715
+ }
716
+ return await attachWorkspaceAgent({
717
+ sessions,
718
+ workspace,
719
+ sessionId,
720
+ execPath,
721
+ presetId,
722
+ parentTaskId,
723
+ failureCode: SESSION_CODES.resumeFailed,
724
+ });
725
+ }
726
+
727
+ /**
728
+ * Resolve one existing Session to the live Agent this run will drive.
729
+ *
730
+ * The same call serves both paths, which is deliberate:
731
+ *
732
+ * * for a continuation it continues the recorded conversation;
733
+ * * for a new submission it attaches the Agent to the Session that was just
734
+ * created in the Workspace, instead of creating a second one.
735
+ *
736
+ * Nothing here creates a Session or an Agent; a Session that was created but whose
737
+ * Agent cannot be resolved is refused. The alternative — driving an Agent that is
738
+ * not attached to the placed Session — would report a Workspace grouping the run
739
+ * did not actually have.
740
+ * @param {object} request - `sessions`, `workspace`, `sessionId`, `execPath`, `presetId`,
741
+ * optional `parentTaskId`, optional `failureCode`.
742
+ * @returns {Promise<{ sessionId: string, agent: object }>} the live Agent and its id.
743
+ * @throws {SessionPlacementError} when no drivable Agent can be resolved.
744
+ */
745
+ async function attachWorkspaceAgent({ sessions, workspace, sessionId, execPath, presetId, parentTaskId = null, failureCode = null }) {
746
+ if (typeof sessions.resolveAgent !== 'function') {
747
+ throw new SessionPlacementError(
748
+ SESSION_CODES.resumeUnavailable,
749
+ 'this DSH build cannot resolve a session to a drivable agent, so the run was not started',
750
+ { reason: 'sessionController.resolveAgent is missing', presetId: presetId ?? null },
751
+ );
752
+ }
753
+ let found;
754
+ try {
755
+ found = await sessions.resolveAgent(sessionId);
756
+ } catch (error) {
757
+ throw resumeFailure(workspace, error, parentTaskId, failureCode);
758
+ }
759
+ if (found === null || typeof found !== 'object' || found.error !== undefined) {
760
+ throw resumeFailure(workspace, found?.error ?? { message: 'no agent was returned' }, parentTaskId, failureCode);
761
+ }
762
+ const agent = found.agent ?? null;
763
+ if (agent === null || typeof agent !== 'object' || typeof agent.whenIdle !== 'function'
764
+ || typeof agent.followup !== 'function') {
765
+ throw new SessionPlacementError(
766
+ failureCode ?? SESSION_CODES.resumeFailed,
767
+ 'the resolved session did not yield a drivable agent, so the run was not started',
768
+ { code: 'SESSION_NOT_DRIVABLE', continueFromTaskId: parentTaskId },
769
+ );
770
+ }
771
+ const headerCwd = agent.session?.header?.cwd ?? null;
772
+ if (typeof headerCwd === 'string' && headerCwd !== '' && !sameSessionPath(headerCwd, execPath)) {
773
+ throw new SessionPlacementError(
774
+ SESSION_CODES.resumePathMismatch,
775
+ 'the resolved session runs in another directory, so it was refused',
776
+ { sessionPath: headerCwd, executionPath: execPath, continueFromTaskId: parentTaskId },
777
+ );
778
+ }
779
+ return { sessionId: agent.session?.id ?? sessionId, agent };
780
+ }
781
+
782
+ /**
783
+ * Shape one resume failure into the bounded refusal the engine reports.
784
+ *
785
+ * The native codes an operator can act on are preserved (`session/not-found`,
786
+ * `session/writer-held`), and the recorded identity is dropped from the
787
+ * diagnostic, which also keeps the report free of a resumable handle.
788
+ * @param {object} workspace - Workspace fact.
789
+ * @param {unknown} error - whatever the controller answered with.
790
+ * @param {string | null} parentTaskId - the task whose thread was being continued.
791
+ * @param {string | null} failureCode - the placement code to report.
792
+ * @returns {SessionPlacementError} refusal.
793
+ */
794
+ function resumeFailure(workspace, error, parentTaskId = null, failureCode = null) {
795
+ const code = typeof error?.code === 'string' ? error.code : null;
796
+ const message = code === 'session/not-found'
797
+ ? 'the DSH session recorded for the named task no longer exists, so it was not continued'
798
+ : 'the DSH session recorded for the named task could not be resumed';
799
+ return new SessionPlacementError(failureCode ?? SESSION_CODES.resumeFailed, message, {
800
+ cause: code,
801
+ detail: diagnostic(error?.message ?? error, 200),
802
+ workspaceId: workspace.workspaceId,
803
+ continueFromTaskId: parentTaskId,
804
+ });
805
+ }
806
+
807
+ /**
808
+ * Durable, minimal task-thread identity map: task id -> DSH ids and paths.
809
+ *
810
+ * The map is keyed by TASK, not by directory, because a directory may hold many
811
+ * independent conversations and only an explicit `continueFromTaskId` may join
812
+ * them. One row holds {@link RECORD_FIELDS} and nothing else: a follow-up needs
813
+ * exactly the identity of the thread it continues, the two paths a continuation is
814
+ * validated against, and the safe ownership facts about a managed tree.
815
+ *
816
+ * Writes are serialized and land through a temporary sibling plus rename, so a
817
+ * concurrent save cannot lose an earlier one and a crash leaves either the old or
818
+ * the new complete document. Reads are cached after the first successful load.
819
+ */
820
+ export class SessionStore {
821
+ /**
822
+ * @param {string} dataDir - plugin data directory.
823
+ * @param {object} [options] - `fs` seam (`readFile`, `writeFile`, `rename`,
824
+ * `mkdir`, `rm`) and `logger`.
825
+ */
826
+ constructor(dataDir, options = {}) {
827
+ if (typeof dataDir !== 'string' || dataDir.trim() === '') {
828
+ throw new TypeError('SessionStore needs a data directory');
829
+ }
830
+ this.dir = dataDir;
831
+ this.path = join(dataDir, SESSIONS_FILE);
832
+ this.fs = options.fs ?? { readFile, writeFile, rename, mkdir, rm };
833
+ this.logger = options.logger ?? null;
834
+ this.records = null;
835
+ this.loading = null;
836
+ this.queue = Promise.resolve();
837
+ this.disposed = false;
838
+ }
839
+
840
+ /**
841
+ * Read the map, newest first.
842
+ * @returns {Promise<object[]>} detached records.
843
+ */
844
+ async list() {
845
+ return (await this.ensureLoaded()).map((record) => ({ ...record }));
846
+ }
847
+
848
+ /**
849
+ * Look up the thread recorded for one task.
850
+ *
851
+ * A legacy row (from a build that keyed the map by directory) is reachable by its
852
+ * task id only when it carries one; a directory-keyed row never answers a task
853
+ * lookup, which is what keeps the migrated rows incapable of an implicit reuse.
854
+ * @param {string} taskId - task id.
855
+ * @returns {Promise<object | null>} detached record, or null.
856
+ */
857
+ async get(taskId) {
858
+ const key = typeof taskId === 'string' ? taskId.trim() : '';
859
+ if (key === '') return null;
860
+ const found = (await this.ensureLoaded()).find((record) => record.taskId === key);
861
+ return found === undefined ? null : { ...found };
862
+ }
863
+
864
+ /**
865
+ * Record the thread one task drove, replacing any earlier row for that task.
866
+ * @param {object} entry - `taskId`, `sourcePath`, `executionPath`, `workspaceId`,
867
+ * `sessionId`, optional `isolation`, `worktreeId`, `worktreeState`.
868
+ * @returns {Promise<object>} the stored record.
869
+ * @throws {TypeError} for an entry that is not a usable identity.
870
+ */
871
+ async put(entry) {
872
+ if (this.disposed) throw new Error('the session map has been disposed');
873
+ const record = projectSessionRecord(entry);
874
+ const run = this.enqueue(async () => {
875
+ const base = await this.ensureLoaded();
876
+ const next = base.filter((item) => item.taskId !== record.taskId);
877
+ next.push(record);
878
+ await this.writeDocument(next);
879
+ this.records = next;
880
+ return { ...record };
881
+ });
882
+ return await run;
883
+ }
884
+
885
+ /**
886
+ * Forget the thread recorded for one task.
887
+ * @param {string} taskId - task id.
888
+ * @returns {Promise<boolean>} whether a record was removed.
889
+ */
890
+ async forget(taskId) {
891
+ if (this.disposed) throw new Error('the session map has been disposed');
892
+ const key = typeof taskId === 'string' ? taskId.trim() : '';
893
+ if (key === '') return false;
894
+ const run = this.enqueue(async () => {
895
+ const base = await this.ensureLoaded();
896
+ const next = base.filter((item) => item.taskId !== key);
897
+ if (next.length === base.length) return false;
898
+ await this.writeDocument(next);
899
+ this.records = next;
900
+ return true;
901
+ });
902
+ return await run;
903
+ }
904
+
905
+ /**
906
+ * Wait for queued writes and stop accepting new ones.
907
+ * @returns {Promise<void>} resolves when settled.
908
+ */
909
+ async dispose() {
910
+ if (this.disposed) return;
911
+ await this.queue;
912
+ this.disposed = true;
913
+ }
914
+
915
+ /**
916
+ * Run one mutation after every earlier one.
917
+ * @param {() => Promise<object>} work - queued mutation.
918
+ * @returns {Promise<object>} its result.
919
+ */
920
+ enqueue(work) {
921
+ const run = this.queue.then(work);
922
+ this.queue = run.then(() => undefined, () => undefined);
923
+ return run;
924
+ }
925
+
926
+ /**
927
+ * Load once, sharing the physical read between concurrent callers.
928
+ * @returns {Promise<object[]>} records, in document order.
929
+ */
930
+ async ensureLoaded() {
931
+ if (this.records !== null) return this.records;
932
+ if (this.loading === null) {
933
+ this.loading = this.readOnce().finally(() => { this.loading = null; });
934
+ }
935
+ return await this.loading;
936
+ }
937
+
938
+ /**
939
+ * Read and normalize the document. A missing file is an empty map; an
940
+ * unreadable or malformed one is reported and treated as empty, because this map
941
+ * is an index for continuing a thread and never an authority over a run.
942
+ * @returns {Promise<object[]>} usable records.
943
+ */
944
+ async readOnce() {
945
+ let raw;
946
+ try {
947
+ raw = await this.fs.readFile(this.path, 'utf8');
948
+ } catch (error) {
949
+ if (error?.code === 'ENOENT') {
950
+ this.records = [];
951
+ return this.records;
952
+ }
953
+ this.logger?.warn?.('dsh-delegate: the session map could not be read', diagnostic(error?.message ?? error, 200));
954
+ this.records = [];
955
+ return this.records;
956
+ }
957
+ let parsed;
958
+ try {
959
+ parsed = JSON.parse(raw);
960
+ } catch {
961
+ this.logger?.warn?.('dsh-delegate: the session map is not valid JSON; starting from an empty map (the file was left as found)');
962
+ this.records = [];
963
+ return this.records;
964
+ }
965
+ const stored = Array.isArray(parsed?.sessions) ? parsed.sessions : [];
966
+ const records = [];
967
+ for (const entry of stored) {
968
+ const migrated = migrateSessionRow(entry);
969
+ if (migrated === null) {
970
+ // A row that is not a usable task identity (including every directory-keyed
971
+ // row from a build that recorded no task id) is dropped, never guessed at:
972
+ // the identity it would carry is what a continuation would act on.
973
+ if (entry !== null && typeof entry === 'object') {
974
+ this.logger?.warn?.('dsh-delegate: one session map row carried no task identity and was ignored');
975
+ }
976
+ continue;
977
+ }
978
+ try {
979
+ records.push(projectSessionRecord(migrated));
980
+ } catch {
981
+ this.logger?.warn?.('dsh-delegate: one session map row was unusable and was ignored');
982
+ }
983
+ }
984
+ this.records = records;
985
+ return this.records;
986
+ }
987
+
988
+ /**
989
+ * Replace the document atomically (temporary sibling, then rename).
990
+ * @param {object[]} records - records to store.
991
+ * @returns {Promise<void>} resolves after the rename.
992
+ */
993
+ async writeDocument(records) {
994
+ const content = `${JSON.stringify({
995
+ schemaVersion: 2,
996
+ updatedAt: new Date().toISOString(),
997
+ sessions: records,
998
+ }, null, 2)}\n`;
999
+ const temp = `${this.path}.${process.pid}.${Date.now()}.tmp`;
1000
+ try {
1001
+ await this.fs.mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
1002
+ await this.fs.writeFile(temp, content, { mode: 0o600 });
1003
+ await this.fs.rename(temp, this.path);
1004
+ } catch (error) {
1005
+ await this.fs.rm?.(temp, { force: true }).catch(() => undefined);
1006
+ throw error;
1007
+ }
1008
+ }
1009
+ }
1010
+
1011
+ /**
1012
+ * Lift one stored row onto the current shape, or refuse it.
1013
+ *
1014
+ * Two stored generations exist:
1015
+ *
1016
+ * * **schema 2** — keyed by task id; this is what this build writes and reads;
1017
+ * * **schema 1** — keyed by canonical execution directory, `{ path, workspaceId,
1018
+ * sessionId, updatedAt }`, written by a build that offered a directory-level
1019
+ * `reuse` mode. It recorded no task id, so it cannot name a task thread and is
1020
+ * therefore *not* usable as a continuation parent. It is ignored on read and
1021
+ * never acts as an implicit source of reuse: the map is keyed by task, and a
1022
+ * legacy row has no task.
1023
+ *
1024
+ * A row that already carries a task id is accepted from either generation, so a
1025
+ * hand-edited or forward-compatible document is read on its own facts.
1026
+ * @param {unknown} entry - one stored row.
1027
+ * @returns {object | null} a row this build can use, or null.
1028
+ */
1029
+ export function migrateSessionRow(entry) {
1030
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return null;
1031
+ const taskId = typeof entry.taskId === 'string' ? entry.taskId.trim() : '';
1032
+ if (taskId === '') return null;
1033
+ return entry;
1034
+ }
1035
+
1036
+ /**
1037
+ * Project one stored row onto the exact field set this module owns.
1038
+ *
1039
+ * Everything omitted here is omitted on purpose: no prompt, no transcript, no model
1040
+ * output, no usage figure and no credential has a field, so a continuation can
1041
+ * carry conversation identity and never conversation content.
1042
+ * @param {unknown} value - candidate row.
1043
+ * @returns {object} bounded record.
1044
+ * @throws {TypeError} when the row is not a usable identity.
1045
+ */
1046
+ function projectSessionRecord(value) {
1047
+ if (value === null || typeof value !== 'object') throw new TypeError('a session map row must be an object');
1048
+ const taskId = typeof value.taskId === 'string' ? value.taskId.trim() : '';
1049
+ const sessionId = typeof value.sessionId === 'string' ? value.sessionId.trim() : '';
1050
+ if (taskId === '') throw new TypeError('a session map row needs a taskId');
1051
+ if (sessionId === '') throw new TypeError('a session map row needs a sessionId');
1052
+ const executionPath = firstPath(value.executionPath, value.path);
1053
+ const sourcePath = firstPath(value.sourcePath, value.executionPath, value.path);
1054
+ const isolation = typeof value.isolation === 'string' && ISOLATION_MODES.includes(value.isolation)
1055
+ ? value.isolation
1056
+ : null;
1057
+ return {
1058
+ taskId,
1059
+ sourcePath,
1060
+ executionPath,
1061
+ workspaceId: typeof value.workspaceId === 'string' ? value.workspaceId.trim() : '',
1062
+ sessionId,
1063
+ isolation,
1064
+ worktreeId: typeof value.worktreeId === 'string' && value.worktreeId.trim() !== '' ? value.worktreeId.trim() : null,
1065
+ worktreeState: typeof value.worktreeState === 'string' && value.worktreeState.trim() !== ''
1066
+ ? value.worktreeState.trim()
1067
+ : null,
1068
+ updatedAt: Number.isFinite(value.updatedAt) ? Math.trunc(value.updatedAt) : Date.now(),
1069
+ };
1070
+ }
1071
+
1072
+ /**
1073
+ * The first usable absolute-looking path among the candidates, or null.
1074
+ * @param {...unknown} candidates - path candidates.
1075
+ * @returns {string | null} chosen path.
1076
+ */
1077
+ function firstPath(...candidates) {
1078
+ for (const candidate of candidates) {
1079
+ if (typeof candidate === 'string' && candidate.trim() !== '') return candidate.trim();
1080
+ }
1081
+ return null;
1082
+ }
1083
+
1084
+ /**
1085
+ * Record the thread a run actually drove.
1086
+ *
1087
+ * Only identity and provenance are written; nothing the model produced and nothing
1088
+ * the harness used to authenticate reaches this call.
1089
+ * @param {object | null | undefined} store - a {@link SessionStore} or null.
1090
+ * @param {object} placement - value returned by {@link placeSession}.
1091
+ * @param {object} entry - `taskId`, `sourcePath`, `executionPath`, optional
1092
+ * `isolation`, `worktreeId`, `worktreeState`.
1093
+ * @returns {Promise<boolean>} whether a record was written.
1094
+ */
1095
+ export async function rememberSession(store, placement, entry) {
1096
+ if (store === null || store === undefined || typeof store.put !== 'function') return false;
1097
+ if (placement === null || typeof placement !== 'object') return false;
1098
+ const sessionId = typeof placement.sessionId === 'string' ? placement.sessionId : '';
1099
+ if (sessionId === '') return false;
1100
+ const target = entry ?? {};
1101
+ const taskId = typeof target.taskId === 'string' ? target.taskId.trim() : '';
1102
+ const executionPath = typeof target.executionPath === 'string' ? target.executionPath.trim() : '';
1103
+ // A row without a task and an execution path names nothing a continuation could
1104
+ // validate, so it is not written at all rather than half-written.
1105
+ if (taskId === '' || executionPath === '') return false;
1106
+ await store.put({
1107
+ taskId,
1108
+ executionPath,
1109
+ sourcePath: typeof target.sourcePath === 'string' && target.sourcePath.trim() !== ''
1110
+ ? target.sourcePath.trim()
1111
+ : executionPath,
1112
+ workspaceId: typeof placement.workspaceId === 'string' ? placement.workspaceId : '',
1113
+ sessionId,
1114
+ isolation: typeof target.isolation === 'string' ? target.isolation : null,
1115
+ worktreeId: typeof target.worktreeId === 'string' ? target.worktreeId : null,
1116
+ worktreeState: typeof target.worktreeState === 'string' ? target.worktreeState : null,
1117
+ });
1118
+ return true;
1119
+ }
1120
+
1121
+ export { RECORD_FIELDS };