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,3614 @@
1
+ // Job engine: the only component that can turn a request into model work.
2
+ //
3
+ // Authorization order is fixed and every step can refuse:
4
+ // 1. the caller presents a connection identity and a grant; the grant is
5
+ // consumed (or, for a session, checked by its exact id) before anything is
6
+ // read from disk;
7
+ // 2. an immutable effective configuration snapshot is resolved and validated;
8
+ // 3. the concurrency slot is checked, then the source workspace is locked;
9
+ // 4. isolation is honoured (a real worktree) or refused — never downgraded;
10
+ // 5. the execution workspace is locked, audited and baselined;
11
+ // 6. worker and review routes are confirmed and frozen against one provider
12
+ // registry snapshot;
13
+ // 7. only then does an agent exist.
14
+ //
15
+ // A job that completes is NOT accepted. It becomes `awaiting-host-review`, and
16
+ // the host decides. Nothing in this module can mark a job approved.
17
+ //
18
+ // Race discipline. A start is not atomic: it awaits path resolution, settings,
19
+ // the provider registry, worktree creation, the audit and routing. Two rules
20
+ // apply to every one of those awaits.
21
+ //
22
+ // 1. They are *guarded*: raced against the task's own abort signal and against
23
+ // its deadline, so a native service that never settles cannot hold a start,
24
+ // its concurrency slot or its leases forever.
25
+ // 2. They are followed by `assertLive`, which re-checks three independent
26
+ // facts: the plugin is not disposed, the task's controller is not aborted,
27
+ // and the authorization still covers exactly this task and this source
28
+ // workspace.
29
+ //
30
+ // The task record (with its controller and its creation sequence) exists before
31
+ // the first await and counts towards `maxParallelism` from that moment. The slot
32
+ // decision is ordered by that sequence, so two concurrent starts cannot both
33
+ // believe they hold the free slot: the older one is admitted, the newer one is
34
+ // refused. Any failure releases the slot and the leases, marks a prepared tree
35
+ // complete (never deleted), and nothing else: a consumed grant is never restored.
36
+ //
37
+ // A task can also stop from the outside: the authorization registry's
38
+ // invalidation subscription aborts matching pending and running tasks
39
+ // immediately, and an internal sweep timer makes expiry effective even when no
40
+ // request arrives to trigger a sweep.
41
+ //
42
+ // Terminal states. Exactly one terminal state is recorded per task, and the first
43
+ // one wins: {@link markTerminal} is the only writer, so a late promise, a late
44
+ // review result or a second failure can never revive or overwrite a task that has
45
+ // already ended. Cancellation is checked before a deadline for the same reason —
46
+ // an operator who cancelled did ask to stop, and reporting a timeout instead
47
+ // would misattribute the outcome.
48
+ //
49
+ // Cleanup. Release of a lease, release of the concurrency slot and completion of a
50
+ // prepared tree all happen in {@link finalize}, which is idempotent and runs on
51
+ // every exit path — successful completion, cancellation, timeout, failure and an
52
+ // admission refusal alike. The one thing it refuses to do is release the workspace
53
+ // (or the slot) of a task whose native executor has not yet confirmed that it
54
+ // stopped: freeing a workspace that is still being mutated would hand it to the
55
+ // next job while the previous one is writing. When that happens the leases stay
56
+ // held, the slot stays occupied and the refusal is recorded as `cleanupError` on
57
+ // the task record, so it is visible rather than silent. The task's settlement
58
+ // promise resolves only once finalize has finished, so `cancel()` returning means
59
+ // the capacity it described has actually been returned (or the refusal has been
60
+ // recorded), not merely that the state was written.
61
+
62
+ import { randomUUID } from 'node:crypto';
63
+ import { defaultSettings, LIMITS, MONITORING_DEFAULTS } from '../config/defaults.js';
64
+ import { redactDeep, redactText } from '../config/redact.js';
65
+ import { resolveEffectiveConfig } from '../config/settings.js';
66
+ import { AUTH_CODES, AuthError } from '../auth/grants.js';
67
+ import { TaskMonitor, isPublicReason, terminalReason } from './activity.js';
68
+ import { resolveRoute } from '../model/routing.js';
69
+ import { PROVIDER_SET_CODES, managedProvidersOf } from '../model/providers.js';
70
+ import { RUN_OUTCOMES, RunError, SessionPlacementRefusal, diagnostic, runAgent } from '../runtime/agent-runner.js';
71
+ import { PermissionBridge, PermissionError, PERMISSION_CODES } from '../runtime/permissions.js';
72
+ import { DELEGATE_SANDBOX_MODE } from '../runtime/sandbox.js';
73
+ import { rememberSession, SESSION_CODES } from '../runtime/session-placement.js';
74
+ import { taskTitle } from './title.js';
75
+ import { REVIEW_STATES, reviewWork } from '../review/reviewer.js';
76
+ import { buildReviewPrompt, buildWorkerPrompt } from '../review/prompts.js';
77
+ import { captureBaseline, captureDiff } from '../workspace/audit.js';
78
+ import { LOCK_CODES, WorkspaceError, resolveWorkspacePath } from '../workspace/locks.js';
79
+
80
+ /** Task lifecycle states. `awaiting-host-review` is terminal for this plugin. */
81
+ export const TASK_STATES = Object.freeze({
82
+ pending: 'pending',
83
+ running: 'running',
84
+ awaitingHostReview: 'awaiting-host-review',
85
+ failed: 'failed',
86
+ cancelled: 'cancelled',
87
+ });
88
+
89
+ /** Terminal states: a task in one of these may not be driven again. */
90
+ const TERMINAL = new Set([TASK_STATES.awaitingHostReview, TASK_STATES.failed, TASK_STATES.cancelled]);
91
+
92
+ /** States that occupy a concurrency slot. */
93
+ const LIVE = new Set([TASK_STATES.pending, TASK_STATES.running]);
94
+
95
+ /** Job-level refusal codes. */
96
+ export const JOB_CODES = Object.freeze({
97
+ notAuthorized: 'JOB_NOT_AUTHORIZED',
98
+ taskNotFound: 'JOB_TASK_NOT_FOUND',
99
+ taskTerminal: 'JOB_TASK_TERMINAL',
100
+ promptRequired: 'JOB_PROMPT_REQUIRED',
101
+ promptTooLarge: 'JOB_PROMPT_TOO_LARGE',
102
+ workspaceRequired: 'JOB_WORKSPACE_REQUIRED',
103
+ noProviders: 'JOB_NO_PROVIDERS',
104
+ providerRegistry: 'JOB_PROVIDER_REGISTRY_REQUIRED',
105
+ isolationRefused: 'JOB_ISOLATION_REFUSED',
106
+ auditUnavailable: 'JOB_AUDIT_UNAVAILABLE',
107
+ routingRefused: 'JOB_ROUTING_REFUSED',
108
+ busy: 'JOB_WORKSPACE_BUSY',
109
+ concurrency: 'JOB_CONCURRENCY_LIMIT',
110
+ cancelled: 'JOB_CANCELLED',
111
+ disposed: 'JOB_DISPOSED',
112
+ startFailed: 'JOB_START_FAILED',
113
+ overrideInvalid: 'JOB_OVERRIDE_INVALID',
114
+ internal: 'JOB_INTERNAL',
115
+ timeout: 'JOB_TIMEOUT',
116
+ executionFailed: 'JOB_EXECUTION_FAILED',
117
+ noOutput: 'JOB_NO_OUTPUT',
118
+ // Distinct from `noOutput`: the model was asked and stopped because it ran out
119
+ // of its own output budget. The task may still have produced a change, so the
120
+ // budget is reported instead of being dressed up as a provider error.
121
+ outputTruncated: 'JOB_OUTPUT_TRUNCATED',
122
+ failed: 'JOB_FAILED',
123
+ nativeNotStopped: 'JOB_NATIVE_NOT_STOPPED',
124
+ historyFailed: 'JOB_HISTORY_FAILED',
125
+ // Session placement refused: this harness cannot group the run into a DSH
126
+ // Workspace, or could not create/resume the Workspace's session. A specific
127
+ // `SESSION_*` code is carried in `details.session`.
128
+ conversationUnavailable: 'JOB_CONVERSATION_UNAVAILABLE',
129
+ // A `continueFromTaskId` follow-up was requested and cannot be honoured. Always
130
+ // fail-closed: the run is refused rather than turned into a new conversation the
131
+ // caller did not ask for. `details.session` carries the specific `SESSION_*` code.
132
+ continuationRefused: 'JOB_CONTINUATION_REFUSED',
133
+ // A pending per-call permission request the worker is waiting on. The task is
134
+ // still `running`; the PHASE says it is waiting for the commander's decision.
135
+ // `waitingForPermission` is not a terminal state and is not a failure.
136
+ permissionPending: 'JOB_PERMISSION_PENDING',
137
+ });
138
+
139
+ /** Default interval of the internal authorization sweep. */
140
+ const DEFAULT_SWEEP_INTERVAL_MS = 1000;
141
+
142
+ /**
143
+ * Bound on preflight before the operator's own timeout is known.
144
+ *
145
+ * The worker timeout lives in the settings document, which is read *during*
146
+ * preflight, so the first steps need a bound of their own or a hung native
147
+ * service could hold a slot forever. Once the effective snapshot is resolved the
148
+ * deadline is re-armed from `worker.timeoutSeconds`, measured from task creation,
149
+ * so preflight time is charged to the same budget as the run itself.
150
+ */
151
+ const DEFAULT_PREFLIGHT_TIMEOUT_MS = defaultSettings().worker.timeoutSeconds * 1000;
152
+
153
+ /** Ceiling on the additional review's own time budget. */
154
+ const REVIEW_TIMEOUT_CAP_MS = 1800 * 1000;
155
+
156
+ /** How long cancel/dispose wait for a task to observe its cancellation. */
157
+ const SETTLE_TIMEOUT_MS = 5000;
158
+
159
+ /**
160
+ * Bound on waiting for a native executor to confirm that it stopped.
161
+ *
162
+ * {@link finalize} will not hand back a concurrency slot or a workspace lease
163
+ * while the executor this task started may still be writing, so the wait has to
164
+ * be bounded: an executor that never settles must cost a recorded refusal
165
+ * (`cleanupError`), not a slot retained forever with no evidence. The bound
166
+ * matches the window `cancel()` and `dispose()` use, so a caller that observed
167
+ * either of those already waited at least as long as this gate can take.
168
+ */
169
+ const NATIVE_SETTLE_TIMEOUT_MS = SETTLE_TIMEOUT_MS;
170
+
171
+ /**
172
+ * Bound on one durable history write.
173
+ *
174
+ * The history document is written atomically, but it is still file I/O on a
175
+ * borrowed directory: a wedged filesystem must not keep a terminal task's
176
+ * cleanup (and therefore its workspace lease) pending forever. Exceeding this
177
+ * bound is recorded on the task as `historyError` rather than silently dropped.
178
+ */
179
+ const HISTORY_WRITE_TIMEOUT_MS = 5000;
180
+
181
+ /** Upper bound on retained task records; oldest terminal records go first. */
182
+ const MAX_RETAINED_TASKS = 256;
183
+
184
+ /**
185
+ * The phase a running task reports while a permission request is outstanding.
186
+ *
187
+ * It is a PHASE, not a state, on purpose: the worker is still running and its
188
+ * workspace slot, lock and execution budget are still its own. Reporting a new
189
+ * `waiting` state would have changed every state contract downstream (terminal
190
+ * sets, cancel rules, history rehydration) to describe something that is not a
191
+ * new lifecycle.
192
+ */
193
+ const PHASE_AWAITING_PERMISSION = 'awaiting-permission';
194
+ const PHASE_EXECUTE = 'execute';
195
+
196
+ /**
197
+ * The closed vocabulary of reasons one observation may report to a caller.
198
+ *
199
+ * `heartbeat` is in it because the adapter contract names it, but
200
+ * {@link JobEngine#observeTask} never RETURNS it: it means "the internal wait
201
+ * expired with nothing to say", and the documented behaviour is to re-wait once
202
+ * rather than hand the caller a report that carries no information.
203
+ */
204
+ export const OBSERVE_TASK_REASONS = Object.freeze({
205
+ heartbeat: 'heartbeat',
206
+ attention: 'attention',
207
+ permission: 'permission',
208
+ ready: 'ready',
209
+ failed: 'failed',
210
+ cancelled: 'cancelled',
211
+ interrupted: 'interrupted',
212
+ });
213
+
214
+ /**
215
+ * How long one observation may wait inside the engine, and the internal slice it
216
+ * polls on. The outer bound is a hard part of the contract (an adapter must never
217
+ * hold a request open indefinitely); the slice is an implementation detail that a
218
+ * test narrows to simulate time.
219
+ */
220
+ const OBSERVE_WAIT_MS = 25_000;
221
+ const OBSERVE_SLICE_MS = 1000;
222
+
223
+ /** Raised for job-level refusals. */
224
+ export class JobError extends Error {
225
+ /**
226
+ * @param {string} code - stable machine code.
227
+ * @param {string} message - human-readable explanation.
228
+ * @param {object} [details] - bounded, redacted details.
229
+ */
230
+ constructor(code, message, details = {}) {
231
+ super(message);
232
+ this.name = 'JobError';
233
+ this.code = code;
234
+ this.details = details;
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Task engine. Holds at most a bounded number of live tasks in memory. Terminal
240
+ * records are persisted to an optional `HistoryStore`; nothing is read back to
241
+ * decide anything, so a restart begins with no tasks and no authorization.
242
+ */
243
+ export class JobEngine {
244
+ /**
245
+ * @param {object} deps - native services and plugin components:
246
+ * `agents`, `agentPresets`, `sessions`, `llm`, `settings`, `auth`, `locks`,
247
+ * `runGit`, optional `ensureRoutes` (the entry point's full-snapshot seam:
248
+ * `(settings) => Promise<Map<publicId, nativeRoute>>`, which publishes the
249
+ * adapter snapshot *and* registers the native routes in one transaction),
250
+ * optional `providerRegistry` (`{ ensure(providers) }`, the route-only
251
+ * registration used as the fallback seam), optional `worktrees` (a
252
+ * `WorktreeManager`), optional `history` (a `HistoryStore`), optional
253
+ * `sweepIntervalMs`, optional `preflightTimeoutMs` (a bound for preflight
254
+ * steps that run before the worker timeout is known),
255
+ * `allowLegacyProviderRoutes` (tests only: use the profile id as the native
256
+ * route when neither seam is present), and the optional observation seams
257
+ * `now` (a clock returning epoch milliseconds) and `wait(ms, { signal })`
258
+ * (a bounded sleep), plus `observeSliceMs` (test-only polling slice).
259
+ */
260
+ constructor(deps) {
261
+ this.deps = deps;
262
+ this.settings = deps.settings;
263
+ this.auth = deps.auth;
264
+ this.locks = deps.locks;
265
+ // Durable job history. Optional injection: the engine persists the public
266
+ // view it already computed for a terminal task and never reads history back
267
+ // to decide anything. Startup history belongs to whoever constructs the
268
+ // store, so a restart reports its own `interrupted` records instead of this
269
+ // engine resurrecting tasks it never admitted.
270
+ this.history = deps?.history ?? null;
271
+ this.tasks = new Map();
272
+ this.aborted = false;
273
+ this.sweepTimer = null;
274
+ this.unsubscribe = null;
275
+ this.sequence = 0;
276
+ // The new control plane uses one persisted switch. Legacy grant mode stays
277
+ // available when this is false so existing clients can be upgraded safely.
278
+ this.delegationEnabled = deps?.delegationEnabled === true;
279
+ this.authorizationMode = deps?.authorizationMode === 'switch' ? 'switch' : 'grants';
280
+ const configuredPreflight = Number(deps?.preflightTimeoutMs);
281
+ this.preflightTimeoutMs = Number.isFinite(configuredPreflight) && configuredPreflight > 0
282
+ ? configuredPreflight
283
+ : DEFAULT_PREFLIGHT_TIMEOUT_MS;
284
+ // Observation seams. Production leaves both absent and gets the real clock and
285
+ // a real unref'd wait; a test injects a clock and a wait it can advance, so
286
+ // "twenty minutes of silent waiting" costs no wall time and cannot flake. They
287
+ // live on the engine, not on the monitor, because every monitor of every task
288
+ // must read the same time source.
289
+ this.clock = typeof deps?.now === 'function' ? deps.now : Date.now;
290
+ this.observationWait = typeof deps?.wait === 'function' ? deps.wait : undefined;
291
+ const slice = Number(deps?.observeSliceMs);
292
+ this.observeSliceMs = Number.isFinite(slice) && slice > 0 ? Math.trunc(slice) : OBSERVE_SLICE_MS;
293
+ // Observers currently waiting, so disposal can release them without touching
294
+ // the workers they were only watching.
295
+ this.observers = new Set();
296
+ this.listen();
297
+ }
298
+
299
+ /**
300
+ * Subscribe to authorization invalidation and start the internal sweep.
301
+ *
302
+ * Two mechanisms, because they answer different questions. The subscription is
303
+ * what makes an operator's revoke an actual cancellation; the timer is what
304
+ * makes an expiry effective when no authenticated request arrives to trigger a
305
+ * sweep. Both are idempotent and both are removed on dispose.
306
+ * @returns {void}
307
+ */
308
+ listen() {
309
+ if (this.unsubscribe === null && typeof this.auth?.subscribe === 'function') {
310
+ try {
311
+ this.unsubscribe = this.auth.subscribe((event) => this.onAuthorizationInvalidated(event));
312
+ } catch {
313
+ // An authorization registry that refuses subscribers leaves the engine
314
+ // with one fewer notification path; the per-phase rechecks still hold.
315
+ this.unsubscribe = null;
316
+ }
317
+ }
318
+ if (this.sweepTimer === null && typeof this.auth?.sweep === 'function') {
319
+ const configured = Number(this.deps?.sweepIntervalMs);
320
+ const interval = Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_SWEEP_INTERVAL_MS;
321
+ this.sweepTimer = setInterval(() => {
322
+ try {
323
+ this.auth.sweep();
324
+ } catch {
325
+ // A sweep failure must not kill the timer; the next tick retries.
326
+ }
327
+ }, interval);
328
+ this.sweepTimer.unref?.();
329
+ }
330
+ }
331
+
332
+ /**
333
+ * Stop the subscription and the sweep timer. Called from {@link dispose}.
334
+ * @returns {void}
335
+ */
336
+ stopListening() {
337
+ if (this.sweepTimer !== null) {
338
+ clearInterval(this.sweepTimer);
339
+ this.sweepTimer = null;
340
+ }
341
+ if (this.unsubscribe !== null) {
342
+ try {
343
+ this.unsubscribe();
344
+ } catch {
345
+ // Unsubscribe is idempotent by contract; a throw is not actionable.
346
+ }
347
+ this.unsubscribe = null;
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Report whether delegation may run at all right now.
353
+ * @returns {{ authorized: boolean, reason: string | null }} current posture.
354
+ */
355
+ posture() {
356
+ if (this.aborted) return { authorized: false, reason: 'the plugin has been disposed' };
357
+ if (this.authorizationMode === 'switch') {
358
+ return this.delegationEnabled === true
359
+ ? { authorized: true, reason: null, mode: 'switch' }
360
+ : { authorized: false, reason: 'delegation is disabled', mode: 'switch' };
361
+ }
362
+ if (this.auth.isDelegationAuthorized() !== true) {
363
+ return { authorized: false, reason: 'no live delegation authorization exists' };
364
+ }
365
+ return { authorized: true, reason: null };
366
+ }
367
+
368
+ /** Toggle the DSH-side master switch and stop live work when it is disabled. */
369
+ setDelegationEnabled(enabled) {
370
+ const next = enabled === true;
371
+ const changed = this.delegationEnabled !== next;
372
+ this.delegationEnabled = next;
373
+ if (changed && next === false) {
374
+ for (const task of this.tasks.values()) {
375
+ if (!TERMINAL.has(task.state)) this.abortTask(task, 'delegation-disabled');
376
+ }
377
+ }
378
+ return this.posture();
379
+ }
380
+
381
+ /**
382
+ * Start one delegated task.
383
+ *
384
+ * The task record (and its controller) is created before the first await, so
385
+ * the request occupies a concurrency slot from the moment it is accepted and a
386
+ * cancellation or revocation can reach it while it is still resolving paths.
387
+ * A preflight deadline is armed at the same moment and cleared on every exit,
388
+ * so a native service that never settles costs a bounded wait instead of a
389
+ * permanent slot.
390
+ *
391
+ * The authorization is consumed before any other side effect, so a failure
392
+ * later in the pipeline still costs the caller its grant. That is deliberate:
393
+ * a grant authorizes one attempt at one task, not a free retry loop. A retry is
394
+ * a new `start` with a new grant; a consumed grant is never restored.
395
+ * @param {object} request - `connectionId`, `grantId`, `workspacePath`, `prompt`, `overrides`,
396
+ * `authorization` (`'task'` consumes a single-use grant, `'session'` checks the named live session grant),
397
+ * and optional `continueFromTaskId` (this submission is a follow-up to that named
398
+ * delegated task and must continue exactly its DSH thread).
399
+ * @returns {Promise<object>} the created task view.
400
+ */
401
+ async start(request) {
402
+ const posture = this.posture();
403
+ if (!posture.authorized) {
404
+ throw new JobError(JOB_CODES.notAuthorized, posture.reason ?? 'delegation is not authorized', {});
405
+ }
406
+
407
+ const prompt = typeof request?.prompt === 'string' ? request.prompt.trim() : '';
408
+ if (prompt === '') throw new JobError(JOB_CODES.promptRequired, 'a task prompt is required', {});
409
+ if (prompt.length > LIMITS.promptChars) {
410
+ throw new JobError(JOB_CODES.promptTooLarge, `the task prompt exceeds ${LIMITS.promptChars} characters`, {
411
+ limit: LIMITS.promptChars,
412
+ });
413
+ }
414
+ // A continuation identity that is not a string is a caller bug, refused here
415
+ // rather than coerced: coercing would either name some other task (`String(42)`)
416
+ // or silently drop the request and start a new conversation.
417
+ const rawContinuation = request?.continueFromTaskId;
418
+ if (rawContinuation !== undefined && rawContinuation !== null && typeof rawContinuation !== 'string') {
419
+ throw new JobError(JOB_CODES.continuationRefused, 'continueFromTaskId must be a task id string', {
420
+ requestedType: typeof rawContinuation,
421
+ });
422
+ }
423
+ const continueFromTaskId = typeof rawContinuation === 'string' ? rawContinuation.trim() : '';
424
+
425
+ const authorization = this.authorizationMode === 'switch'
426
+ ? 'switch'
427
+ : (request?.authorization === 'session' ? 'session' : 'task');
428
+ const task = this.createTask(prompt, authorization);
429
+ task.title = taskTitle(request?.title, prompt);
430
+ // Frozen before the first await so the task record states, from the moment it
431
+ // exists, whether it starts a conversation or continues one.
432
+ task.continueFromTaskId = continueFromTaskId === '' ? null : continueFromTaskId;
433
+ this.tasks.set(task.taskId, task);
434
+ this.prune();
435
+
436
+ try {
437
+ this.armPreflightDeadline(task, this.preflightTimeoutMs);
438
+ await this.admit(task, request);
439
+ } catch (error) {
440
+ await this.failAdmission(task, error);
441
+ throw this.admissionError(error);
442
+ } finally {
443
+ this.clearPreflightDeadline(task);
444
+ }
445
+
446
+ this.drive(task);
447
+ return this.view(task, { includePrompt: true });
448
+ }
449
+
450
+ /**
451
+ * Build the pending record. Synchronous on purpose: nothing may await between
452
+ * the caller's request and the existence of a cancellation target.
453
+ * @param {string} prompt - validated prompt text.
454
+ * @param {'task'|'session'} authorization - which grant kind was presented.
455
+ * @returns {object} task record.
456
+ */
457
+ createTask(prompt, authorization) {
458
+ const taskId = `task-${randomUUID()}`;
459
+ let settle;
460
+ const settled = new Promise((resolvePromise) => { settle = resolvePromise; });
461
+ this.sequence += 1;
462
+ return {
463
+ taskId,
464
+ // Admission order. The concurrency slot is decided by this number, not by
465
+ // whichever start happens to finish its awaits first.
466
+ sequence: this.sequence,
467
+ state: TASK_STATES.pending,
468
+ phase: 'created',
469
+ createdAt: Date.now(),
470
+ startedAt: null,
471
+ endedAt: null,
472
+ prompt,
473
+ authorization,
474
+ // The task whose DSH thread this submission continues, or null for a new
475
+ // conversation. Frozen at creation: it is what the run does with its session,
476
+ // and it must not be re-read after the first await.
477
+ continueFromTaskId: null,
478
+ connectionId: null,
479
+ grantId: null,
480
+ grantKind: null,
481
+ sourcePath: null,
482
+ executionPath: null,
483
+ effective: null,
484
+ routes: null,
485
+ route: null,
486
+ reviewRoute: null,
487
+ reviewRouteError: null,
488
+ baseline: null,
489
+ worktree: null,
490
+ leases: [],
491
+ // The process-local provider-definition lease this task holds, taken before
492
+ // it awaited the route ensure and given back only by {@link finalize}: it is
493
+ // what keeps the served provider set identical for every native model
494
+ // operation of this task, not only the first one.
495
+ providerLease: null,
496
+ providerLeaseReleased: false,
497
+ // Whether this task currently owns a concurrency slot. Set synchronously
498
+ // during admission and cleared only once the slot may legally be reused.
499
+ slotHeld: false,
500
+ diff: null,
501
+ execution: null,
502
+ // Session placement facts for this task: which DSH Workspace group it ran in,
503
+ // whether it started a new conversation or continued the task it named, and
504
+ // whether the identity was saved so a later follow-up can continue it.
505
+ // `conversationError` is recorded rather than thrown, because failing to save
506
+ // a continuation handle must not change the run's outcome.
507
+ conversation: null,
508
+ conversationSaved: null,
509
+ conversationError: null,
510
+ // A continuation may reuse the parent task's managed worktree. These are
511
+ // admission-only facts; the public task view exposes the resulting
512
+ // execution path and conversation, never the internal parent object.
513
+ continuationParent: null,
514
+ continuationRecord: null,
515
+ // The identity map row, read exactly once, and the single durable snapshot the
516
+ // continuation is judged by. Both are admission-only facts; the public task view
517
+ // exposes the resulting execution path and conversation, never the internals.
518
+ continuationIdentity: null,
519
+ reusedWorktree: false,
520
+ review: { state: REVIEW_STATES.notRun, verdict: null, text: '', error: null },
521
+ error: null,
522
+ cancelRequested: false,
523
+ cancelledBy: null,
524
+ // The preflight deadline: set before the first await so a hung native
525
+ // service cannot retain this task, and re-armed from the effective
526
+ // worker timeout once that is known.
527
+ preflightTimer: null,
528
+ preflightTimedOut: false,
529
+ controller: new AbortController(),
530
+ // Native execution bookkeeping. `started` flips immediately before the
531
+ // runner is called; `settled` flips when the runner's promise resolves,
532
+ // which is where the runner has disposed the handle it knew about. The
533
+ // promise is what {@link finalize} waits on, boundedly, before it releases
534
+ // the leases: a workspace must not be handed to the next job while the
535
+ // previous executor may still be writing to it.
536
+ native: { started: false, settled: false, promise: null },
537
+ // The per-call permission surface of this run. `bridge` is the answerer the
538
+ // runner arms for this task's own Agent (null when the run was not offered
539
+ // one), `pending` is the one request the worker is waiting on (null when
540
+ // nothing is outstanding), and `evidence` is the bounded settled trail the
541
+ // task view and the durable history carry. `pausedExecutionMs` is how much
542
+ // of the execution budget was spent WAITING: it is given back to the run's
543
+ // timer when the request settles, so an approval wait can never be charged
544
+ // to the execution timeout.
545
+ permission: { bridge: null, pending: null, evidence: [], pausedAt: null, pausedExecutionMs: 0 },
546
+ // The activity monitor for this run. Created with the task, fed from the
547
+ // runner's `onEvent` hook, and disposed with the task: its counters describe
548
+ // THIS run and must not outlive it. It holds metadata only (counts,
549
+ // timestamps, a tool name and call id), never model text or tool arguments.
550
+ monitor: null,
551
+ // Idempotence latch for {@link finalize}: one promise per task, ever.
552
+ finalizing: null,
553
+ finalizedAt: null,
554
+ // Cleanup that could not be performed, and durable-history outcomes. Both
555
+ // are recorded on the task so a failure is visible instead of swallowed.
556
+ cleanupError: null,
557
+ historyError: null,
558
+ historySavedAt: null,
559
+ // Host acceptance is never granted here; it is the host's own record.
560
+ hostAcceptance: null,
561
+ settled,
562
+ settle: () => { settle(); },
563
+ };
564
+ }
565
+
566
+ /**
567
+ * Admit one task: every preflight step, in the fixed order, with a liveness and
568
+ * authorization recheck after each await.
569
+ *
570
+ * Every await goes through {@link guardPreflight}, which races the native call
571
+ * against the task's own cancellation and preflight deadline. That is what
572
+ * makes a hung `settings.read()`, `providerRegistry.ensure()` or
573
+ * `worktrees.prepare()` cost a bounded wait instead of a permanent slot, a
574
+ * permanent lease, or a start that never returns.
575
+ * @param {object} task - pending record.
576
+ * @param {object} request - the start request.
577
+ * @returns {Promise<void>} resolves when the task is fully prepared.
578
+ */
579
+ async admit(task, request) {
580
+ // ---- 1. source workspace -------------------------------------------------
581
+ task.phase = 'workspace';
582
+ const sourcePath = await this.guardPreflight(task, 'workspace', () => resolveWorkspacePath(request?.workspacePath))
583
+ .catch((error) => {
584
+ if (error instanceof WorkspaceError) {
585
+ throw new JobError(JOB_CODES.workspaceRequired, error.message, redactDeep(error.details ?? {}));
586
+ }
587
+ throw error;
588
+ });
589
+ task.sourcePath = sourcePath;
590
+ task.executionPath = sourcePath;
591
+ this.assertLive(task, 'workspace');
592
+
593
+ // ---- 2. authorization, bound to the source workspace ---------------------
594
+ // A task grant is consumed exactly once; a session grant is checked by the
595
+ // exact id the caller named and the resulting id is frozen on the task. The
596
+ // engine never widens a named lookup to "some other live session grant".
597
+ task.phase = 'authorization';
598
+ let grant = { grantId: null, kind: 'switch', overrides: null };
599
+ if (task.authorization === 'switch') {
600
+ task.connectionId = 'local-mcp';
601
+ task.grantId = null;
602
+ task.grantKind = 'switch';
603
+ this.assertLive(task, 'authorization');
604
+ } else {
605
+ grant = task.authorization === 'session'
606
+ ? this.auth.requireSessionGrant({
607
+ connectionId: request?.connectionId,
608
+ grantId: request?.grantId,
609
+ workspacePath: sourcePath,
610
+ })
611
+ : this.auth.consumeTaskGrant({
612
+ connectionId: request?.connectionId,
613
+ grantId: request?.grantId,
614
+ taskId: task.taskId,
615
+ workspacePath: sourcePath,
616
+ });
617
+ // The public grant projection carries no connectionId; the caller's verified
618
+ // identity is the connection the registry just checked against the grant.
619
+ task.connectionId = request?.connectionId;
620
+ task.grantId = grant.grantId;
621
+ task.grantKind = grant.kind;
622
+ this.assertLive(task, 'authorization');
623
+ }
624
+
625
+ // ---- 2b. a follow-up must be owned by this caller, fail-closed -----------
626
+ // Proven here, where the caller's verified connection identity is known, and
627
+ // before anything about the parent can be described. One call decides the whole
628
+ // chain — ownership, outcome, paths, isolation and the identity map — from a
629
+ // single durable snapshot, so nothing about the parent can reach a caller who has
630
+ // not proven ownership and no later step reads history or the identity map again.
631
+ // Running it here, before settings and the concurrency slot, is what makes a
632
+ // refusal stable: a still-running parent is refused for its own state rather than
633
+ // for a slot it was never entitled to, and the parent's isolation mode is known
634
+ // before any mode is resolved.
635
+ if (task.continueFromTaskId !== null) {
636
+ task.phase = 'continuation';
637
+ await this.assertContinuation(task, sourcePath);
638
+ this.assertLive(task, 'continuation');
639
+ }
640
+
641
+ // ---- 3. one immutable settings snapshot ----------------------------------
642
+ task.phase = 'settings';
643
+ const settings = await this.guardPreflight(task, 'settings', () => this.settings.read());
644
+ this.assertLive(task, 'settings');
645
+ if (!Array.isArray(settings?.providers) || settings.providers.length === 0) {
646
+ throw new JobError(JOB_CODES.noProviders, 'no provider profile is configured', {});
647
+ }
648
+
649
+ // ---- 4. effective configuration and the concurrency slot -----------------
650
+ task.phase = 'effective';
651
+ const overrides = sanitizeOverrides(grant.overrides ?? request?.overrides);
652
+ if (task.continuationRecord !== null) {
653
+ const parentIsolation = task.continuationRecord.isolation;
654
+ if (overrides.isolation !== undefined && overrides.isolation !== parentIsolation) {
655
+ throw this.continuationRefusal('a follow-up must keep the isolation mode of the task it continues', {
656
+ continueFromTaskId: task.continueFromTaskId,
657
+ requestedIsolation: overrides.isolation,
658
+ parentIsolation,
659
+ session: SESSION_CODES.continuationUnavailable,
660
+ });
661
+ }
662
+ // A continuation belongs to the original task chain. If the global or
663
+ // project setting changed after its parent ran, use the parent's isolation
664
+ // so the follow-up reaches the same checkout or the same managed worktree.
665
+ overrides.isolation = parentIsolation;
666
+ }
667
+ let effective;
668
+ try {
669
+ effective = resolveEffectiveConfig(settings, { projectPath: sourcePath, overrides });
670
+ } catch (error) {
671
+ throw new JobError(JOB_CODES.routingRefused, error?.message ?? 'the effective configuration was refused', {
672
+ cause: error?.code ?? null,
673
+ details: redactDeep(error?.details ?? null),
674
+ });
675
+ }
676
+ task.effective = effective;
677
+ // The worker timeout is a budget for the whole task, preflight included, so
678
+ // the deadline is re-armed from creation time rather than from this point.
679
+ task.deadlineAt = task.createdAt + effective.worker.timeoutSeconds * 1000;
680
+ this.armPreflightDeadline(task, task.deadlineAt - Date.now());
681
+ this.assertLive(task, 'effective');
682
+ // The slot claim and the count happen in one synchronous step, ordered by
683
+ // admission sequence, so two concurrent starts cannot both take the slot.
684
+ // From here the slot is held until {@link finalize} returns it, and finalize
685
+ // does that only after the native executor is confirmed stopped.
686
+ this.reserveSlot(task, effective.worker.maxParallelism);
687
+
688
+ // ---- 5. provider routes for worker and review, from one snapshot ---------
689
+ task.phase = 'providers';
690
+ // The provider-definition lease is taken *before* the first await of this
691
+ // step, in this same synchronous section. The native adapter serves the latest
692
+ // generation the registry committed for every model operation, so without a
693
+ // hold a settings edit (or another job's catalog read) could swap the served
694
+ // definition between two turns of this task while `task.effective` still names
695
+ // the old one. The hold is released only by {@link finalize}, after the native
696
+ // executor has confirmed it stopped.
697
+ this.leaseProviders(task, settings);
698
+ task.routes = await this.guardPreflight(task, 'providers', () => this.ensureRoutes(settings));
699
+ this.assertLive(task, 'providers');
700
+ const workerRouteId = this.routeFor(task.routes, effective.worker.providerId, 'worker');
701
+
702
+ // ---- 6. lock the source workspace before anything is audited or created --
703
+ task.phase = 'source-lock';
704
+ this.acquireSourceLock(task);
705
+
706
+ // ---- 7. isolation: a real worktree, or explicitly shared -----------------
707
+ if (effective.worker.isolation === 'worktree') {
708
+ task.phase = 'worktree';
709
+ const prepared = task.continuationRecord === null
710
+ ? await this.guardPreflight(task, 'worktree', () => this.prepareWorktree(task), {
711
+ // A tree that finished after this start was abandoned still exists on
712
+ // disk. It is recorded and marked complete, never deleted or merged: it
713
+ // is evidence, and the host decides what happens to it.
714
+ onLateSettle: (value) => this.adoptLateWorktree(task, value),
715
+ })
716
+ : await this.guardPreflight(task, 'continuation-worktree', () => this.reuseContinuationWorktree(task));
717
+ task.worktree = prepared;
718
+ task.executionPath = prepared.workspacePath;
719
+ task.reusedWorktree = task.continuationRecord !== null;
720
+ this.assertLive(task, 'worktree');
721
+ this.acquireExecutionLock(task);
722
+ } else if (effective.worker.isolation !== 'shared') {
723
+ // Unreachable for a validated snapshot; refusing is still the only honest
724
+ // answer to a mode this build cannot honour.
725
+ throw new JobError(JOB_CODES.isolationRefused, `isolation ${String(effective.worker.isolation)} is not implemented`, {
726
+ requested: effective.worker.isolation ?? null,
727
+ });
728
+ }
729
+
730
+ // ---- 8. baseline in the workspace the run will actually mutate -----------
731
+ task.phase = 'baseline';
732
+ let baseline;
733
+ try {
734
+ baseline = await this.guardPreflight(task, 'baseline', () => captureBaseline(this.deps, task.executionPath));
735
+ } catch (error) {
736
+ if (error instanceof JobError) throw error;
737
+ throw new JobError(JOB_CODES.auditUnavailable, error?.message ?? 'the workspace could not be audited', {
738
+ cause: error?.code ?? null,
739
+ });
740
+ }
741
+ this.assertLive(task, 'baseline');
742
+ if (task.worktree !== null && baseline.head !== task.worktree.baseHead) {
743
+ // The tree is a detached checkout of one commit; a baseline that disagrees
744
+ // means something else wrote to it before the run started.
745
+ throw new JobError(JOB_CODES.auditUnavailable, 'the isolated workspace does not start at the pinned commit', {
746
+ cause: 'BASELINE_HEAD_MISMATCH',
747
+ });
748
+ }
749
+ task.baseline = baseline;
750
+
751
+ // ---- 9. worker route, frozen on the task ---------------------------------
752
+ task.phase = 'worker-route';
753
+ let route;
754
+ try {
755
+ route = await this.guardPreflight(task, 'worker-route', () => resolveRoute(this.deps, {
756
+ providerId: effective.worker.providerId,
757
+ providerRoute: workerRouteId,
758
+ model: effective.worker.model,
759
+ reasoningEffort: effective.worker.reasoningEffort,
760
+ }, { signal: task.controller.signal }));
761
+ } catch (error) {
762
+ if (error instanceof JobError) throw error;
763
+ throw new JobError(JOB_CODES.routingRefused, error?.message ?? 'the route could not be confirmed', {
764
+ cause: error?.code ?? null,
765
+ details: redactDeep(error?.details ?? null),
766
+ });
767
+ }
768
+ this.assertLive(task, 'worker-route');
769
+ task.route = route;
770
+
771
+ // ---- 10. review route, frozen BEFORE the worker runs ---------------------
772
+ // A review that resolved its route after execution would judge the work with
773
+ // whatever configuration existed later, or with an ambient route. A review
774
+ // routing failure is recorded on the review record and never refuses the
775
+ // task, and it never turns into approval.
776
+ if (effective.review.enabled === true) {
777
+ task.phase = 'review-route';
778
+ try {
779
+ const reviewRouteId = this.routeFor(task.routes, effective.review.providerId, 'review');
780
+ task.reviewRoute = await this.guardPreflight(task, 'review-route', () => resolveRoute(this.deps, {
781
+ providerId: effective.review.providerId,
782
+ providerRoute: reviewRouteId,
783
+ model: effective.review.model,
784
+ reasoningEffort: effective.review.reasoningEffort,
785
+ }, { signal: task.controller.signal }));
786
+ } catch (error) {
787
+ if (error instanceof JobError) throw error;
788
+ task.reviewRoute = null;
789
+ task.reviewRouteError = {
790
+ code: 'REVIEW_ROUTING_REFUSED',
791
+ message: diagnostic(error?.message ?? 'the review route could not be confirmed', 400),
792
+ cause: typeof error?.code === 'string' ? error.code : null,
793
+ };
794
+ }
795
+ this.assertLive(task, 'review-route');
796
+ }
797
+
798
+ // ---- 11. last preflight gate before any native create --------------------
799
+ task.phase = 'admitted';
800
+ this.assertLive(task, 'admitted');
801
+ }
802
+
803
+ /**
804
+ * Await one preflight step under cancellation and the preflight deadline.
805
+ *
806
+ * The await is what a native service can hang on, so it is the await that gets
807
+ * a bound. When the race loses, the underlying promise is *not* cancelled — it
808
+ * cannot be — so `onLateSettle` is given the chance to account for whatever it
809
+ * eventually produced (a worktree, in practice) instead of leaking it.
810
+ * @param {object} task - pending record.
811
+ * @param {string} phase - the step being awaited.
812
+ * @param {() => Promise<unknown>} start - thunk producing the native call.
813
+ * @param {object} [options] - `onLateSettle(value)` for work that lands late.
814
+ * @returns {Promise<unknown>} the native call's value.
815
+ */
816
+ async guardPreflight(task, phase, start, options = {}) {
817
+ const signal = task.controller.signal;
818
+ if (signal.aborted) throw this.preflightAbort(task, phase);
819
+
820
+ const promise = Promise.resolve().then(start);
821
+ let onAbort;
822
+ const aborted = new Promise((resolvePromise) => {
823
+ onAbort = () => resolvePromise({ kind: 'aborted' });
824
+ signal.addEventListener('abort', onAbort, { once: true });
825
+ });
826
+
827
+ try {
828
+ const raced = await Promise.race([
829
+ promise.then((value) => ({ kind: 'ok', value }), (error) => ({ kind: 'error', error })),
830
+ aborted,
831
+ ]);
832
+ if (raced.kind === 'aborted') {
833
+ if (typeof options.onLateSettle === 'function') {
834
+ void promise.then(
835
+ (value) => { options.onLateSettle(value); },
836
+ () => {},
837
+ );
838
+ }
839
+ throw this.preflightAbort(task, phase);
840
+ }
841
+ if (raced.kind === 'error') throw raced.error;
842
+ return raced.value;
843
+ } finally {
844
+ signal.removeEventListener?.('abort', onAbort);
845
+ }
846
+ }
847
+
848
+ /**
849
+ * Map a preflight race loss onto the reason it was lost.
850
+ * @param {object} task - pending record.
851
+ * @param {string} phase - the step that was abandoned.
852
+ * @returns {JobError} refusal to throw.
853
+ */
854
+ preflightAbort(task, phase) {
855
+ if (this.aborted) {
856
+ return new JobError(JOB_CODES.disposed, 'the plugin was disposed while the task was starting', { phase });
857
+ }
858
+ if (task.preflightTimedOut === true) {
859
+ return new JobError(JOB_CODES.timeout, `the task exceeded its time budget during ${phase}`, { phase });
860
+ }
861
+ return new JobError(JOB_CODES.cancelled, `the task was cancelled during ${phase}`, {
862
+ phase,
863
+ reason: task.cancelledBy ?? 'request',
864
+ });
865
+ }
866
+
867
+ /**
868
+ * Arm (or re-arm) the preflight deadline that bounds a pending start.
869
+ * @param {object} task - pending record.
870
+ * @param {number} remainingMs - milliseconds left in the task's budget.
871
+ * @returns {void}
872
+ */
873
+ armPreflightDeadline(task, remainingMs) {
874
+ this.clearPreflightDeadline(task);
875
+ const delay = Number.isFinite(remainingMs)
876
+ ? Math.max(0, remainingMs)
877
+ : this.preflightTimeoutMs;
878
+ if (delay === 0) {
879
+ // The budget was already spent before this step began.
880
+ task.preflightTimedOut = true;
881
+ try {
882
+ task.controller.abort();
883
+ } catch {
884
+ // AbortController.abort() does not throw; kept for defence in depth.
885
+ }
886
+ return;
887
+ }
888
+ const timer = setTimeout(() => {
889
+ task.preflightTimer = null;
890
+ task.preflightTimedOut = true;
891
+ try {
892
+ task.controller.abort();
893
+ } catch {
894
+ // As above: abort is not expected to throw.
895
+ }
896
+ }, delay);
897
+ timer.unref?.();
898
+ task.preflightTimer = timer;
899
+ }
900
+
901
+ /**
902
+ * Disarm the preflight deadline. Idempotent, and safe after it already fired.
903
+ * @param {object} task - task record.
904
+ * @returns {void}
905
+ */
906
+ clearPreflightDeadline(task) {
907
+ if (task.preflightTimer !== null && task.preflightTimer !== undefined) {
908
+ clearTimeout(task.preflightTimer);
909
+ task.preflightTimer = null;
910
+ }
911
+ }
912
+
913
+ /**
914
+ * Record and finish a worktree that was prepared after its start was abandoned.
915
+ * @param {object} task - task record.
916
+ * @param {unknown} prepared - the late value, if it is usable.
917
+ * @returns {void}
918
+ */
919
+ adoptLateWorktree(task, prepared) {
920
+ if (prepared === null || typeof prepared !== 'object' || typeof prepared.workspacePath !== 'string') return;
921
+ if (task.worktree === null) {
922
+ task.worktree = prepared;
923
+ task.executionPath = prepared.workspacePath;
924
+ }
925
+ this.completeWorktree(task);
926
+ }
927
+
928
+ /**
929
+ * Whether a task still occupies a concurrency slot.
930
+ *
931
+ * Two independent reasons, and a task may have both: it is live, or it is
932
+ * terminal but its native executor has not been confirmed stopped and its
933
+ * leases therefore have not been released. The second case is what stops a
934
+ * finished-but-still-cleaning task from being counted as free capacity — the
935
+ * next job would then admit against a workspace that is still being written to.
936
+ * @param {object} task - task record.
937
+ * @returns {boolean} true when the slot is still taken.
938
+ */
939
+ occupiesSlot(task) {
940
+ if (task.slotHeld === true) return true;
941
+ return LIVE.has(task.state);
942
+ }
943
+
944
+ /**
945
+ * Record the one terminal state a task may have. The first writer wins, so a
946
+ * late promise, a late review result or a second failure can never revive or
947
+ * overwrite a task that has already ended.
948
+ * @param {object} task - task record.
949
+ * @param {string} state - terminal state to record.
950
+ * @returns {boolean} true when this call recorded the state.
951
+ */
952
+ markTerminal(task, state) {
953
+ if (TERMINAL.has(task.state)) return false;
954
+ task.state = state;
955
+ task.endedAt = task.endedAt ?? Date.now();
956
+ return true;
957
+ }
958
+
959
+ /**
960
+ * Claim the concurrency slot for one task, or refuse.
961
+ *
962
+ * The count and the claim happen in one synchronous step, so two concurrent
963
+ * starts cannot both observe the same free slot: whichever claims second sees
964
+ * the first claim. Ordering is by admission sequence, so a pending start
965
+ * competes only with the requests accepted before it. A later request is behind
966
+ * it in the queue and counting it would refuse both starts of a
967
+ * `maxParallelism: 1` pair, dropping work the operator asked for instead of
968
+ * admitting exactly one.
969
+ * @param {object} task - the pending task asking for a slot.
970
+ * @param {number} limit - `worker.maxParallelism`.
971
+ * @returns {void}
972
+ * @throws {JobError} when every slot is already taken.
973
+ */
974
+ reserveSlot(task, limit) {
975
+ if (task.slotHeld === true) return;
976
+ let ahead = 0;
977
+ for (const other of this.tasks.values()) {
978
+ if (other === task) continue;
979
+ if (other.sequence >= task.sequence) continue;
980
+ if (!this.occupiesSlot(other)) continue;
981
+ ahead += 1;
982
+ }
983
+ if (ahead >= limit) {
984
+ throw new JobError(JOB_CODES.concurrency, `at most ${limit} task(s) may run at once`, {
985
+ limit,
986
+ active: ahead,
987
+ });
988
+ }
989
+ // Claimed, not merely counted: from this statement the slot is this task's
990
+ // until {@link releaseSlot} returns it inside {@link finalize}.
991
+ task.slotHeld = true;
992
+ }
993
+
994
+ /**
995
+ * Return the concurrency slot. Idempotent, and never called before the native
996
+ * executor is confirmed stopped.
997
+ * @param {object} task - task record.
998
+ * @returns {void}
999
+ */
1000
+ releaseSlot(task) {
1001
+ task.slotHeld = false;
1002
+ }
1003
+
1004
+ /**
1005
+ * Return this task's capacity exactly once: the concurrency slot, every
1006
+ * workspace lease, and the provider-definition lease.
1007
+ *
1008
+ * Idempotent by latch. A task keeps its record after it is terminal, so every
1009
+ * terminal path — success, failure, cancellation, timeout, admission refusal,
1010
+ * dispose — has to come through here, and a second path that races the first
1011
+ * (a late review refusal, `cancel()` after `dispose()`) awaits the same
1012
+ * promise instead of releasing twice.
1013
+ *
1014
+ * It refuses to hand anything back while the native executor this task started
1015
+ * may still be writing. The wait for that executor is bounded (see
1016
+ * {@link NATIVE_SETTLE_TIMEOUT_MS}); when the bound is exceeded the release is
1017
+ * declined and recorded as `cleanupError`, so an executor that never confirms
1018
+ * it stopped costs a visible refusal rather than a silent double-write. A
1019
+ * declined release is not latched as final: a later caller retries it, and
1020
+ * succeeds if the executor has settled by then. Only a *completed* release is
1021
+ * terminal, and only one attempt runs at a time.
1022
+ * @param {object} task - task record.
1023
+ * @returns {Promise<boolean>} true when the capacity was actually returned.
1024
+ */
1025
+ finalize(task) {
1026
+ if (task.finalizedAt !== null) return Promise.resolve(true);
1027
+ if (task.finalizing !== null) return task.finalizing;
1028
+ const attempt = this.releaseCapacity(task).then(
1029
+ (released) => {
1030
+ // A refusal stays retryable; the next terminal path may find the
1031
+ // executor stopped. A release that happened is never repeated.
1032
+ if (released !== true && task.finalizing === attempt) task.finalizing = null;
1033
+ return released;
1034
+ },
1035
+ (error) => {
1036
+ if (task.finalizing === attempt) task.finalizing = null;
1037
+ throw error;
1038
+ },
1039
+ );
1040
+ task.finalizing = attempt;
1041
+ return attempt;
1042
+ }
1043
+
1044
+ /**
1045
+ * Take the process-local provider-definition lease for one task.
1046
+ *
1047
+ * This is the second half of the immutability of `task.effective`. The effective
1048
+ * configuration snapshot freezes what the task *asked for*; the native adapter,
1049
+ * however, serves whatever generation the registry committed last, and every
1050
+ * model operation re-reads it. A multi-turn run would therefore follow a settings
1051
+ * change onto its next turn, on a route whose endpoint and models the task never
1052
+ * agreed to. Holding the provider set for the task's whole life — from the step
1053
+ * before the route ensure runs until {@link finalize} confirms the native
1054
+ * executor stopped — makes the served set a fact the task controls, and makes a
1055
+ * different set a refusal the other caller can see (see `PROVIDER_SET_CODES`).
1056
+ *
1057
+ * Called synchronously, before the ensure await, so the hold exists before any
1058
+ * other start can observe a window without it. Idempotent: a task takes at most
1059
+ * one lease.
1060
+ *
1061
+ * The lease covers the *plugin-managed* providers only — the same subset
1062
+ * `ensureRoutes` registers — so the two are two readings of one list rather than
1063
+ * two filters that can disagree. Native DSH profiles are references to routes
1064
+ * this plugin never registers: leasing them used to fingerprint the settings list
1065
+ * (`[workbuddy]`) while the route ensure registered the custom subset (`[]`), and
1066
+ * the task's own ensure was then refused, unanswered by any second task, with
1067
+ * `PROVIDER_SET_BUSY` and `routeCount` 0.
1068
+ *
1069
+ * The lease is best-effort by design, and its absence is never silent: an
1070
+ * injected registry that predates this contract (no `lease`) is used exactly as
1071
+ * before, and a registry whose `lease` throws is treated as "no hold" rather than
1072
+ * as an admission failure — the engine cannot invent a lease a registry does not
1073
+ * implement, and refusing every job on an older seam would be worse than the
1074
+ * status quo. The one exception is the registry's own busy refusal: a caller that
1075
+ * asked for a different provider set while another is pinned must be told, and
1076
+ * the refusal carries `PROVIDER_SET_CODES.busy` straight through to the job.
1077
+ * @param {object} task - pending record with `effective` resolved.
1078
+ * @param {object} settings - the validated settings snapshot the task read.
1079
+ * @returns {void}
1080
+ * @throws {JobError} `PROVIDER_SET_BUSY` when another provider set is pinned.
1081
+ */
1082
+ leaseProviders(task, settings) {
1083
+ if (task.providerLease !== null || task.providerLeaseReleased === true) return;
1084
+ const registry = this.deps?.providerRegistry;
1085
+ if (registry === undefined || registry === null || typeof registry.lease !== 'function') return;
1086
+ // The canonical set, shared with `ensureRoutes` by construction. A native-only
1087
+ // configuration therefore leases the empty set, which is exactly what its route
1088
+ // registration applies — the two agree, and the refusal only ever comes from a
1089
+ // genuinely different custom set.
1090
+ const managed = managedProvidersOf(settings?.providers);
1091
+ try {
1092
+ task.providerLease = registry.lease(managed, task.taskId);
1093
+ return;
1094
+ } catch (error) {
1095
+ if (error?.code === PROVIDER_SET_CODES.busy) {
1096
+ throw new JobError(PROVIDER_SET_CODES.busy, diagnostic(error?.message ?? 'the provider configuration is pinned', 300)
1097
+ ?? 'the provider configuration is pinned', { phase: 'providers', ...redactDeep(error?.details ?? {}) });
1098
+ }
1099
+ task.providerLease = null;
1100
+ }
1101
+ }
1102
+
1103
+ /**
1104
+ * Give back the provider-definition lease, if this task holds one.
1105
+ *
1106
+ * Idempotent by latch, and never called before the native executor is confirmed
1107
+ * stopped: the executor is the only party that performs native model operations
1108
+ * after preflight, so releasing any earlier would reopen the window this lease
1109
+ * exists to close. A refusal thrown by the registry is swallowed: the lease is
1110
+ * process-local, the task is already terminal, and the next task's release would
1111
+ * hit the same registry state. The latch is still set, so a late cleanup can
1112
+ * never release twice.
1113
+ * @param {object} task - task record.
1114
+ * @returns {void}
1115
+ */
1116
+ releaseProviderLease(task) {
1117
+ if (task.providerLeaseReleased === true) return;
1118
+ task.providerLeaseReleased = true;
1119
+ const held = task.providerLease;
1120
+ task.providerLease = null;
1121
+ if (held === null || held === undefined) return;
1122
+ try {
1123
+ this.deps?.providerRegistry?.release?.(held);
1124
+ } catch {
1125
+ // A registry that cannot release is a registry defect, not a task outcome;
1126
+ // the task is terminal and this cannot be reported anywhere useful.
1127
+ }
1128
+ }
1129
+
1130
+ /**
1131
+ * Perform one release attempt, gated on the native executor's settlement.
1132
+ * @param {object} task - task record.
1133
+ * @returns {Promise<boolean>} true when the slot and the leases were returned.
1134
+ */
1135
+ async releaseCapacity(task) {
1136
+ this.clearPreflightDeadline(task);
1137
+ if (task.native.started === true && task.native.settled !== true) {
1138
+ await this.awaitNativeSettlement(task);
1139
+ }
1140
+ if (task.native.started === true && task.native.settled !== true) {
1141
+ task.cleanupError = {
1142
+ code: JOB_CODES.nativeNotStopped,
1143
+ message: 'the native executor did not confirm that it stopped; the workspace lease and slot stay held',
1144
+ };
1145
+ return false;
1146
+ }
1147
+ task.cleanupError = null;
1148
+ this.releaseLeases(task);
1149
+ // The provider set is given back on the same terms as the workspace: only
1150
+ // once the executor that reads it has confirmed it stopped. After this line a
1151
+ // saved, different configuration applies to the next task.
1152
+ this.releaseProviderLease(task);
1153
+ // A tree prepared before the task ended is evidence, not garbage: it is kept
1154
+ // and marked complete so the host can inspect or dispose it explicitly.
1155
+ this.completeWorktree(task);
1156
+ this.releaseSlot(task);
1157
+ task.finalizedAt = task.finalizedAt ?? Date.now();
1158
+ return true;
1159
+ }
1160
+
1161
+ /**
1162
+ * Wait, boundedly, for the native executor's own promise to settle.
1163
+ * @param {object} task - task record holding a started executor.
1164
+ * @returns {Promise<void>} resolves when it settled, or when the bound expires.
1165
+ */
1166
+ async awaitNativeSettlement(task) {
1167
+ const pending = task.native.promise;
1168
+ if (pending === null || typeof pending.then !== 'function') return;
1169
+ await Promise.race([
1170
+ pending.then(() => {}, () => {}),
1171
+ new Promise((resolvePromise) => { setTimeout(resolvePromise, NATIVE_SETTLE_TIMEOUT_MS).unref?.(); }),
1172
+ ]);
1173
+ }
1174
+
1175
+ /**
1176
+ * Ensure the native provider routes for one settings snapshot.
1177
+ *
1178
+ * One call per snapshot, before either the worker or the review route is
1179
+ * resolved, so both selections come from the same mapping. Previously ensured
1180
+ * routes stay with the registry until plugin dispose; the engine never narrows
1181
+ * the set it passes in.
1182
+ *
1183
+ * Which seam is used matters, and is not an implementation detail. Native route
1184
+ * registration has two halves that must move together: the adapter's served
1185
+ * snapshot (which is what `LlmRuntime.registerAdapter()` reads synchronously
1186
+ * through `providerInfo(route)`) and the core's route table. The entry point's
1187
+ * `deps.ensureRoutes(settings)` seam performs both in one synchronous,
1188
+ * rollback-protected transaction, and every other caller (`/models`,
1189
+ * `/catalog`, connectivity) already goes through it.
1190
+ *
1191
+ * Registering through `providerRegistry.ensure()` alone only touches the core's
1192
+ * route table: the adapter keeps serving whatever generation it was last given
1193
+ * — often the empty one — and the first job on a freshly loaded plugin then
1194
+ * fails with `ROUTING_MODEL_UNRESOLVED` for a model that is configured and
1195
+ * plain resolvable. So the full-snapshot seam is preferred whenever it was
1196
+ * injected, and the registry is only the fallback when it was not.
1197
+ * @param {object} settings - immutable settings snapshot.
1198
+ * @returns {Promise<Map<string, string> | null>} public provider id -> native route, or null on the legacy test path.
1199
+ */
1200
+ async ensureRoutes(settings) {
1201
+ const seam = this.deps?.ensureRoutes;
1202
+ if (seam !== undefined && seam !== null && typeof seam === 'function') {
1203
+ return await this.ensureRoutesThroughSeam(seam, settings);
1204
+ }
1205
+ const registry = this.deps?.providerRegistry;
1206
+ if (registry === undefined || registry === null) {
1207
+ // Production entry points always inject one of the two seams (src/index.js
1208
+ // injects both). The profile-id fallback exists only for tests that fake the
1209
+ // native routes directly, and must be requested explicitly.
1210
+ if (this.deps?.allowLegacyProviderRoutes === true) return null;
1211
+ throw new JobError(
1212
+ JOB_CODES.providerRegistry,
1213
+ 'the native provider registry is required to route a delegated run',
1214
+ {},
1215
+ );
1216
+ }
1217
+ if (typeof registry.ensure !== 'function') {
1218
+ throw new JobError(JOB_CODES.providerRegistry, 'the injected provider registry cannot ensure routes', {});
1219
+ }
1220
+ let ensured;
1221
+ try {
1222
+ ensured = await registry.ensure(settings.providers);
1223
+ } catch (error) {
1224
+ throw this.routeEnsureRefusal(error);
1225
+ }
1226
+ return this.readRouteMapping(ensured, 'the provider registry');
1227
+ }
1228
+
1229
+ /**
1230
+ * Ensure routes through the entry point's full-snapshot seam.
1231
+ *
1232
+ * The seam is handed the *whole* settings snapshot rather than a provider list,
1233
+ * because publishing the adapter snapshot needs the provider profiles (display
1234
+ * names, models, effort axes) and not only the ids the core registers. It
1235
+ * returns the mapping directly; the shape is validated here anyway so a seam
1236
+ * that changes shape is a refusal instead of a `undefined.get()` later.
1237
+ * @param {Function} seam - `deps.ensureRoutes(settings) -> Promise<Map|{routes}>`.
1238
+ * @param {object} settings - immutable settings snapshot.
1239
+ * @returns {Promise<Map<string, string>>} public provider id -> native route.
1240
+ */
1241
+ async ensureRoutesThroughSeam(seam, settings) {
1242
+ let ensured;
1243
+ try {
1244
+ ensured = await seam(settings);
1245
+ } catch (error) {
1246
+ throw this.routeEnsureRefusal(error);
1247
+ }
1248
+ return this.readRouteMapping(ensured, 'the provider route seam');
1249
+ }
1250
+
1251
+ /**
1252
+ * Turn a failed route ensure into a bounded job refusal.
1253
+ * @param {unknown} error - thrown by the registry or the seam.
1254
+ * @returns {JobError} routing refusal.
1255
+ */
1256
+ routeEnsureRefusal(error) {
1257
+ if (error instanceof JobError) return error;
1258
+ return new JobError(JOB_CODES.routingRefused, 'the provider routes could not be ensured', {
1259
+ cause: typeof error?.code === 'string' ? error.code : null,
1260
+ detail: diagnostic(error?.message ?? error, 200),
1261
+ });
1262
+ }
1263
+
1264
+ /**
1265
+ * Accept either shape a route ensure produces: a `Map` of public id -> native
1266
+ * route, or a record carrying one as `routes`.
1267
+ * @param {unknown} ensured - value returned by a route ensure seam.
1268
+ * @param {string} source - seam name for diagnostics.
1269
+ * @returns {Map<string, string>} the route mapping.
1270
+ */
1271
+ readRouteMapping(ensured, source) {
1272
+ if (ensured === null || typeof ensured !== 'object') {
1273
+ throw new JobError(JOB_CODES.routingRefused, `${source} returned no route mapping`, {});
1274
+ }
1275
+ const routes = ensured instanceof Map ? ensured : ensured.routes;
1276
+ if (routes instanceof Map) {
1277
+ if (routes.size > 0) return routes;
1278
+ } else if (routes !== null && typeof routes === 'object') {
1279
+ const mapped = new Map();
1280
+ for (const [key, value] of Object.entries(routes)) {
1281
+ const id = nativeRouteId(value);
1282
+ if (id !== null) mapped.set(key, id);
1283
+ }
1284
+ if (mapped.size > 0) return mapped;
1285
+ }
1286
+ throw new JobError(JOB_CODES.routingRefused, `${source} returned no usable route mapping`, {});
1287
+ }
1288
+
1289
+ /**
1290
+ * Resolve the native route for one public provider profile id.
1291
+ *
1292
+ * A mapping that exists but does not cover the selected provider is a refusal,
1293
+ * never a fallback to the profile id: the profile id is not a native route, and
1294
+ * resolving one produced the field failure this module exists to prevent.
1295
+ * @param {Map<string, string> | null} routes - route mapping, or null for the legacy path.
1296
+ * @param {string | null} providerId - operator-facing profile id.
1297
+ * @param {string} role - `worker` or `review`, for diagnostics.
1298
+ * @returns {string} native route id.
1299
+ */
1300
+ routeFor(routes, providerId, role) {
1301
+ if (routes === null) return providerId;
1302
+ if (typeof providerId !== 'string' || providerId === '') {
1303
+ throw new JobError(JOB_CODES.routingRefused, 'no provider was selected', { role });
1304
+ }
1305
+ if (!(routes instanceof Map)) {
1306
+ throw new JobError(JOB_CODES.routingRefused, 'the provider route mapping is unusable', { role });
1307
+ }
1308
+ if (!routes.has(providerId)) {
1309
+ throw new JobError(JOB_CODES.routingRefused, `provider ${providerId} was not registered with the harness`, {
1310
+ role,
1311
+ providerId,
1312
+ registered: [...routes.keys()].slice(0, 32),
1313
+ });
1314
+ }
1315
+ const route = routes.get(providerId);
1316
+ const id = nativeRouteId(route);
1317
+ if (id === null) {
1318
+ throw new JobError(JOB_CODES.routingRefused, `provider ${providerId} has no native route`, {
1319
+ role,
1320
+ providerId,
1321
+ });
1322
+ }
1323
+ return id;
1324
+ }
1325
+
1326
+ /**
1327
+ * Acquire the lease on the source workspace.
1328
+ * @param {object} task - pending record.
1329
+ * @returns {void}
1330
+ */
1331
+ acquireSourceLock(task) {
1332
+ try {
1333
+ const lease = this.locks.acquire(task.sourcePath, { taskId: task.taskId });
1334
+ task.leases.push({ path: task.sourcePath, nonce: lease.nonce });
1335
+ } catch (error) {
1336
+ if (error instanceof WorkspaceError && error.code === LOCK_CODES.busy) {
1337
+ throw new JobError(JOB_CODES.busy, error.message, redactDeep(error.details ?? {}));
1338
+ }
1339
+ throw error;
1340
+ }
1341
+ }
1342
+
1343
+ /**
1344
+ * Acquire the lease on the execution workspace (the worktree), after the
1345
+ * source lease. A shared run reuses the source lease instead of double-locking
1346
+ * one path.
1347
+ * @param {object} task - pending record with a prepared execution path.
1348
+ * @returns {void}
1349
+ */
1350
+ acquireExecutionLock(task) {
1351
+ if (task.executionPath === null || samePath(task.executionPath, task.sourcePath)) return;
1352
+ if (task.leases.some((lease) => samePath(lease.path, task.executionPath))) return;
1353
+ try {
1354
+ const lease = this.locks.acquire(task.executionPath, { taskId: task.taskId });
1355
+ task.leases.push({ path: task.executionPath, nonce: lease.nonce });
1356
+ } catch (error) {
1357
+ if (error instanceof WorkspaceError && error.code === LOCK_CODES.busy) {
1358
+ throw new JobError(JOB_CODES.busy, 'another job is already running in the isolated workspace', {
1359
+ ...redactDeep(error.details ?? {}),
1360
+ });
1361
+ }
1362
+ throw error;
1363
+ }
1364
+ }
1365
+
1366
+ /**
1367
+ * Prepare an isolated worktree, or refuse. There is no fallback to shared
1368
+ * execution: a missing service is a refusal, not a downgrade.
1369
+ * @param {object} task - pending record with a locked source path.
1370
+ * @returns {Promise<object>} prepared worktree metadata.
1371
+ */
1372
+ async prepareWorktree(task) {
1373
+ const manager = this.deps?.worktrees;
1374
+ if (manager === undefined || manager === null || typeof manager.prepare !== 'function') {
1375
+ throw new JobError(
1376
+ JOB_CODES.isolationRefused,
1377
+ 'worktree isolation is configured but no worktree service is available; select shared isolation explicitly',
1378
+ { requested: 'worktree', cause: 'WORKTREE_SERVICE_UNAVAILABLE' },
1379
+ );
1380
+ }
1381
+ let prepared;
1382
+ try {
1383
+ prepared = await manager.prepare({
1384
+ taskId: task.taskId,
1385
+ sourcePath: task.sourcePath,
1386
+ signal: task.controller.signal,
1387
+ });
1388
+ } catch (error) {
1389
+ if (error?.code === 'WORKTREE_CANCELLED') {
1390
+ throw new JobError(JOB_CODES.cancelled, error?.message ?? 'the worktree was cancelled', {
1391
+ cause: error.code,
1392
+ });
1393
+ }
1394
+ throw new JobError(JOB_CODES.isolationRefused, error?.message ?? 'the isolated workspace could not be prepared', {
1395
+ requested: 'worktree',
1396
+ cause: typeof error?.code === 'string' ? error.code : null,
1397
+ details: redactDeep(error?.details ?? null),
1398
+ });
1399
+ }
1400
+ if (prepared === null || typeof prepared !== 'object'
1401
+ || typeof prepared.workspacePath !== 'string' || prepared.workspacePath === '') {
1402
+ throw new JobError(JOB_CODES.isolationRefused, 'the worktree service returned no usable workspace', {
1403
+ requested: 'worktree',
1404
+ cause: 'WORKTREE_NO_PATH',
1405
+ });
1406
+ }
1407
+ if (prepared.isolated !== true) {
1408
+ throw new JobError(JOB_CODES.isolationRefused, 'the worktree service did not report an isolated checkout', {
1409
+ requested: 'worktree',
1410
+ cause: 'WORKTREE_NOT_ISOLATED',
1411
+ workspacePath: prepared.workspacePath,
1412
+ });
1413
+ }
1414
+ if (samePath(prepared.workspacePath, task.sourcePath)) {
1415
+ throw new JobError(JOB_CODES.isolationRefused, 'the worktree service returned the source workspace', {
1416
+ requested: 'worktree',
1417
+ cause: 'WORKTREE_SAME_PATH',
1418
+ });
1419
+ }
1420
+ return prepared;
1421
+ }
1422
+
1423
+ /**
1424
+ * Shape a continuation refusal as the job error that carries its `SESSION_*` cause.
1425
+ *
1426
+ * The specific placement code travels in `details.session` so a caller can tell a
1427
+ * stale identity from a live one from an unreadable store, exactly as a
1428
+ * conversation-placement refusal does.
1429
+ * @param {string} message - operator-readable explanation.
1430
+ * @param {object} [details] - bounded context; never a credential or a transcript.
1431
+ * @returns {JobError} refusal to throw.
1432
+ */
1433
+ continuationRefusal(message, details = {}) {
1434
+ return new JobError(JOB_CODES.continuationRefused, message, redactDeep(details));
1435
+ }
1436
+
1437
+ /**
1438
+ * Prove that this caller owns the named parent thread, then judge whether the chain
1439
+ * may be joined — in one method, from one snapshot, with no branch that skips a check.
1440
+ *
1441
+ * Admission calls this once, before settings are read and before a concurrency slot
1442
+ * is claimed, so everything a continuation needs is decided in one order:
1443
+ *
1444
+ * 1. **Ownership.** The caller must state a verified connection id (the empty side is
1445
+ * never a wildcard). A live parent record is proven by its own exact
1446
+ * `connectionId`; a record that states none is unprovable rather than ownerless.
1447
+ * A parent this process does not hold is proven by its durable history row, whose
1448
+ * exact `connectionId` must equal the caller's. A deployment without durable
1449
+ * history, an unreadable or malformed document, a pruned or missing record, a
1450
+ * truncated record and a record with no owner all fail closed the same way, because
1451
+ * each of them would otherwise confirm that some task exists. Every ownership
1452
+ * failure is the same `JOB_TASK_NOT_FOUND`, reported as absent rather than
1453
+ * forbidden, so the answer cannot enumerate another connection's tasks.
1454
+ * 2. **The durable snapshot.** History is read exactly once here and the row is
1455
+ * reduced to one standard shape: `state`, `sourcePath`, `executionWorkspacePath`,
1456
+ * `isolation` and `conversation`. A parent that is live in this process supplies
1457
+ * that shape from its own record; a parent from a previous process supplies it from
1458
+ * the durable row, with `conversation` taken from `row.execution?.conversation`.
1459
+ * There is no "row was null, so skip the checks" path: a failed read is a refusal,
1460
+ * never a pass.
1461
+ * 3. **The identity map**, read exactly once, and **the outcome**: {@link admitContinuation}
1462
+ * judges state, paths, isolation and Session from that snapshot and this identity.
1463
+ *
1464
+ * The verified result is recorded on the task, because steps 4 and 7 of admission
1465
+ * (effective isolation, and reusing the parent's tree instead of preparing a new one)
1466
+ * read `task.continuationRecord`. Nothing below re-reads history or the identity map.
1467
+ * @param {object} task - pending record with `continueFromTaskId` and a verified `connectionId`.
1468
+ * @param {string} sourcePath - this submission's resolved source workspace.
1469
+ * @returns {Promise<void>} resolves once the chain is proven continuable.
1470
+ * @throws {JobError} `JOB_TASK_NOT_FOUND` when ownership is unprovable, a `SESSION_*`
1471
+ * refusal when a proven parent cannot be joined.
1472
+ */
1473
+ async assertContinuation(task, sourcePath) {
1474
+ const parentId = task.continueFromTaskId;
1475
+ const caller = typeof task.connectionId === 'string' && task.connectionId !== '' ? task.connectionId : null;
1476
+ if (caller === null) throw this.absentContinuation(parentId);
1477
+
1478
+ // One snapshot of the parent, in one standard shape. A live record is authoritative
1479
+ // for its own outcome and paths; otherwise the durable row must supply them, and a
1480
+ // row that cannot be found or read is a refusal, never a skip.
1481
+ const parent = this.tasks.get(parentId) ?? null;
1482
+ let row;
1483
+ if (parent !== null) {
1484
+ if (parent.connectionId !== caller) throw this.absentContinuation(parentId);
1485
+ row = {
1486
+ state: parent.state,
1487
+ sourcePath: parent.sourcePath,
1488
+ executionWorkspacePath: parent.executionPath,
1489
+ isolation: parent.effective?.worker?.isolation ?? null,
1490
+ conversation: parent.execution?.conversation ?? null,
1491
+ };
1492
+ } else {
1493
+ const durable = await this.durableParent(task, parentId, caller);
1494
+ if (durable === null) throw this.absentContinuation(parentId);
1495
+ row = {
1496
+ state: durable.state ?? null,
1497
+ sourcePath: durable.sourcePath ?? null,
1498
+ executionWorkspacePath: durable.executionWorkspacePath ?? null,
1499
+ isolation: durable.isolation ?? null,
1500
+ conversation: durable.execution?.conversation ?? null,
1501
+ };
1502
+ }
1503
+
1504
+ // The identity map is the only document carrying the exact execution directory and
1505
+ // the Session; it is read once, here, and judged together with the snapshot above.
1506
+ task.continuationIdentity = await this.readContinuationIdentity(task);
1507
+ this.admitContinuation(task, row, sourcePath);
1508
+
1509
+ // Recorded only after every check passed: these two facts are what admission's
1510
+ // isolation and worktree steps read to resume the parent instead of starting over.
1511
+ task.continuationParent = parent;
1512
+ task.continuationRecord = task.continuationIdentity;
1513
+ }
1514
+
1515
+ /**
1516
+ * The one refusal an unprovable owner gets.
1517
+ *
1518
+ * Unknown, ownerless and another connection's parent are indistinguishable on
1519
+ * purpose: the details carry the id the caller itself supplied and nothing else,
1520
+ * so the answer cannot confirm that any other task exists.
1521
+ * @param {string} parentTaskId - the id the caller named.
1522
+ * @returns {JobError} refusal to throw.
1523
+ */
1524
+ absentContinuation(parentTaskId) {
1525
+ return new JobError(JOB_CODES.taskNotFound, 'no such task for this connection', { continueFromTaskId: parentTaskId });
1526
+ }
1527
+
1528
+ /**
1529
+ * Read the durable record of a parent this process does not hold, and decide
1530
+ * whether it proves this caller's ownership.
1531
+ *
1532
+ * Fail-closed by construction: a deployment without durable history, an
1533
+ * unreadable or malformed document, a missing (pruned, never written) record, a
1534
+ * truncated record and a record that states no owner all answer `null`, which the
1535
+ * caller turns into the same `JOB_TASK_NOT_FOUND` an unknown id gets.
1536
+ * @param {object} task - pending record (for the guarded await).
1537
+ * @param {string} parentTaskId - the id the caller named.
1538
+ * @param {string} caller - this submission's verified connection id.
1539
+ * @returns {Promise<object | null>} the proven row, or null.
1540
+ */
1541
+ async durableParent(task, parentTaskId, caller) {
1542
+ const history = this.history;
1543
+ if (history === null || history === undefined || typeof history.load !== 'function') return null;
1544
+ let rows;
1545
+ try {
1546
+ rows = await this.guardPreflight(task, 'continuation-history', () => history.load());
1547
+ } catch (error) {
1548
+ if (error instanceof JobError) throw error;
1549
+ return null;
1550
+ }
1551
+ // Read once. The document is newest-first, so the first match is recent.
1552
+ const row = Array.isArray(rows)
1553
+ ? rows.find((entry) => entry !== null && typeof entry === 'object' && entry.taskId === parentTaskId) ?? null
1554
+ : null;
1555
+ if (row === null) return null;
1556
+ // A record that had to be cut to fit its byte budget is not complete evidence of
1557
+ // either ownership or outcome.
1558
+ if (row.truncation !== undefined && row.truncation !== null) return null;
1559
+ if (typeof row.connectionId !== 'string' || row.connectionId === '' || row.connectionId !== caller) return null;
1560
+ return row;
1561
+ }
1562
+
1563
+ /**
1564
+ * Decide whether a proven parent may be joined, and record what joining it needs.
1565
+ *
1566
+ * Ownership is already proven, so every refusal here may name its reason. They are
1567
+ * all `SESSION_*` codes carried in `details.session`, and none of them falls back to
1568
+ * a new conversation.
1569
+ *
1570
+ * 1. **The snapshot decides the outcome.** It must be terminal — `pending`,
1571
+ * `running`, `interrupted` (live when a previous process stopped) and anything
1572
+ * this build does not know are refused — and it must name a conversation that
1573
+ * really drove a Session: a placement of kind `new` or `continuation` with a
1574
+ * non-empty Workspace id and Workspace path. A run that failed before it reached
1575
+ * one has no thread, and continuing it would silently start a new one.
1576
+ * 2. **Its paths must be usable proof.** Both the source repository and the
1577
+ * execution directory must be stated, unmasked and non-empty. A masked path was
1578
+ * rewritten by redaction and cannot prove which directory it names, so it is
1579
+ * refused exactly like a missing one — a mask is never a wildcard and never equals
1580
+ * anything.
1581
+ * 3. **The identity map supplies the thread and must agree.** It is the only
1582
+ * document carrying the exact execution directory and Session, so it must state
1583
+ * one, its source repository must be this submission's, and its Workspace id,
1584
+ * execution directory and isolation must be the ones the snapshot names. The
1585
+ * native Session and its Agent are then verified by placement.
1586
+ * @param {object} task - pending record carrying the once-read `continuationIdentity`.
1587
+ * @param {object} row - the single parent snapshot, already in the standard shape.
1588
+ * @param {string} sourcePath - this submission's resolved source workspace.
1589
+ * @returns {void}
1590
+ * @throws {JobError} a `SESSION_*` refusal naming the reason.
1591
+ */
1592
+ admitContinuation(task, row, sourcePath) {
1593
+ const parentId = task.continueFromTaskId;
1594
+ const refuse = (message, session, reason, extra = {}) => this.continuationRefusal(message, {
1595
+ continueFromTaskId: parentId,
1596
+ session,
1597
+ reason,
1598
+ ...extra,
1599
+ });
1600
+ const state = row.state;
1601
+ if (!TERMINAL.has(state)) {
1602
+ // A parent that is merely unfinished (`pending`/`running`) is the one refusal an
1603
+ // operator retries, and says so in the same words the live re-check uses. A run
1604
+ // that stopped without ending (`interrupted`, or a state this build does not
1605
+ // know) is not "still running" and keeps the message that does not promise a retry.
1606
+ const message = state === TASK_STATES.pending || state === TASK_STATES.running
1607
+ ? 'the named task is still running, so its conversation cannot be continued yet'
1608
+ : 'the named task did not end, so its conversation cannot be continued';
1609
+ throw refuse(message, SESSION_CODES.continuationState,
1610
+ typeof state === 'string' ? state : 'no recorded end state');
1611
+ }
1612
+ const conversation = row.conversation;
1613
+ // A conversation is proof only when it names a placement that reached a Session in a
1614
+ // named Workspace. An absent one, an unknown kind or an empty Workspace id is a run
1615
+ // that never drove a thread, whichever terminal state it ended in.
1616
+ if (conversation === null || typeof conversation !== 'object'
1617
+ || !['new', 'continuation'].includes(conversation.kind)
1618
+ || typeof conversation.workspaceId !== 'string' || conversation.workspaceId.trim() === ''
1619
+ || typeof conversation.workspacePath !== 'string' || conversation.workspacePath.trim() === '') {
1620
+ throw refuse('the named task ended without driving a conversation, so there is nothing to continue',
1621
+ SESSION_CODES.continuationState, typeof state === 'string' ? state : 'no recorded end state');
1622
+ }
1623
+ // Paths are proof, not a hint: a value written through a projection that rewrote it
1624
+ // (a mask) cannot say which directory it named, so it is refused exactly like a
1625
+ // missing one. No path, connection or isolation value is ever a wildcard.
1626
+ for (const [field, session] of [
1627
+ ['sourcePath', SESSION_CODES.continuationWorkspaceMismatch],
1628
+ ['executionWorkspacePath', SESSION_CODES.continuationUnavailable],
1629
+ ]) {
1630
+ if (typeof row[field] !== 'string' || row[field].trim() === '' || recordedPathIsMasked(row[field])) {
1631
+ throw refuse('the named task has no reliably recorded path, so its conversation cannot be continued', session, `unusable recorded ${field}`);
1632
+ }
1633
+ }
1634
+ if (!samePath(row.sourcePath, sourcePath)) {
1635
+ throw refuse('the named task belongs to another source repository, so its conversation was not continued',
1636
+ SESSION_CODES.continuationWorkspaceMismatch, 'different source repository');
1637
+ }
1638
+ if (!['shared', 'worktree'].includes(row.isolation)) {
1639
+ throw refuse('the named task has no recorded isolation, so its conversation cannot be continued',
1640
+ SESSION_CODES.continuationUnavailable, 'no recorded isolation');
1641
+ }
1642
+
1643
+ // The identity map supplies the thread itself, and must agree with the snapshot it
1644
+ // belongs to. It is the only document that carries the exact execution directory and
1645
+ // the Session, so a missing one is refused like a missing path.
1646
+ const identity = task.continuationIdentity;
1647
+ if (identity === null || typeof identity !== 'object') {
1648
+ throw refuse('no conversation identity is recorded for the named task, so it cannot be continued',
1649
+ SESSION_CODES.continuationUnknown, 'unknown, pruned or started by another deployment');
1650
+ }
1651
+ if (typeof identity.sessionId !== 'string' || identity.sessionId.trim() === '') {
1652
+ throw refuse('the recorded conversation identity names no Session, so it cannot be continued',
1653
+ SESSION_CODES.continuationUnavailable, 'no recorded session');
1654
+ }
1655
+ if (typeof identity.executionPath !== 'string' || identity.executionPath.trim() === ''
1656
+ || recordedPathIsMasked(identity.executionPath)) {
1657
+ throw refuse('the named task has no usable execution-path identity, so its conversation cannot be continued',
1658
+ SESSION_CODES.continuationUnavailable, 'unusable recorded execution path');
1659
+ }
1660
+ if (!samePath(identity.sourcePath, sourcePath)) {
1661
+ throw refuse('the named task belongs to another source repository, so its conversation was not continued',
1662
+ SESSION_CODES.continuationWorkspaceMismatch, 'identity source repository differs');
1663
+ }
1664
+ if (typeof identity.workspaceId !== 'string' || identity.workspaceId.trim() === ''
1665
+ || identity.workspaceId !== conversation.workspaceId) {
1666
+ throw refuse('the recorded conversation identity does not match the named task',
1667
+ SESSION_CODES.continuationUnavailable, 'identity workspace differs');
1668
+ }
1669
+ // The conversation names the directory it was recorded against. A record whose path
1670
+ // is masked cannot say which directory that was, and one that names a different
1671
+ // execution directory than the identity resolves is another directory's thread —
1672
+ // the Workspace id alone is not proof, so the Session is never resolved for either.
1673
+ if (recordedPathIsMasked(conversation.workspacePath) || !samePath(conversation.workspacePath, identity.executionPath)) {
1674
+ throw refuse('the recorded conversation path does not match its execution directory',
1675
+ SESSION_CODES.continuationUnavailable, 'conversation workspace path differs');
1676
+ }
1677
+ if (!samePath(identity.executionPath, row.executionWorkspacePath)) {
1678
+ throw refuse('the recorded conversation identity does not match the named task',
1679
+ SESSION_CODES.continuationUnavailable, 'identity execution path differs');
1680
+ }
1681
+ if (!['shared', 'worktree'].includes(identity.isolation) || identity.isolation !== row.isolation) {
1682
+ throw refuse('the recorded conversation identity does not match the named task',
1683
+ SESSION_CODES.continuationUnavailable, 'identity isolation differs');
1684
+ }
1685
+ }
1686
+
1687
+ /**
1688
+ * Read the persisted identity of the named parent task, or refuse.
1689
+ *
1690
+ * This is the only read of the identity map in a submission. A missing store, an
1691
+ * unreadable document and a document with no row for the task are each a refusal,
1692
+ * because without them no Session can be reached and the follow-up would silently
1693
+ * become a new conversation. The row's own facts are judged in
1694
+ * {@link admitContinuation}, once ownership and outcome are known.
1695
+ * @param {object} task - pending record with `continueFromTaskId`.
1696
+ * @returns {Promise<object | null>} the stored row, or null when there is none.
1697
+ * @throws {JobError} when the map cannot be read at all.
1698
+ */
1699
+ async readContinuationIdentity(task) {
1700
+ const store = this.deps?.sessionStore ?? null;
1701
+ if (store === null || typeof store.get !== 'function') {
1702
+ throw this.continuationRefusal('this deployment keeps no task-to-conversation identity, so the named task cannot be continued', {
1703
+ continueFromTaskId: task.continueFromTaskId,
1704
+ session: SESSION_CODES.continuationUnavailable,
1705
+ reason: 'no session identity store',
1706
+ });
1707
+ }
1708
+ try {
1709
+ return await this.guardPreflight(task, 'continuation-identity', () => store.get(task.continueFromTaskId));
1710
+ } catch (error) {
1711
+ if (error instanceof JobError) throw error;
1712
+ throw this.continuationRefusal('the stored task-to-conversation identity could not be read, so the named task cannot be continued', {
1713
+ continueFromTaskId: task.continueFromTaskId,
1714
+ session: SESSION_CODES.continuationUnavailable,
1715
+ cause: typeof error?.code === 'string' ? error.code : null,
1716
+ });
1717
+ }
1718
+ }
1719
+
1720
+ /**
1721
+ * Resolve and validate the existing managed tree for a continuation.
1722
+ *
1723
+ * A new tree would hide the parent's uncommitted work and create a different
1724
+ * DSH Workspace, so this path never calls `prepare()`. After a plugin restart,
1725
+ * or after explicit disposal, the in-memory registry cannot prove ownership and
1726
+ * the continuation is refused rather than guessed from a directory name.
1727
+ * @param {object} task - continuation with a stored parent identity.
1728
+ * @returns {Promise<object>} the existing tree metadata.
1729
+ * @throws {JobError} when the original tree cannot be proven reusable.
1730
+ */
1731
+ async reuseContinuationWorktree(task) {
1732
+ const identity = task.continuationRecord;
1733
+ const manager = this.deps?.worktrees ?? null;
1734
+ const refuse = (message, reason) => this.continuationRefusal(message, {
1735
+ continueFromTaskId: task.continueFromTaskId,
1736
+ session: SESSION_CODES.continuationUnavailable,
1737
+ reason,
1738
+ });
1739
+ if (identity?.isolation !== 'worktree') {
1740
+ throw refuse('the named task did not use a managed worktree', 'parent was not isolated');
1741
+ }
1742
+ if (manager === null || typeof manager.get !== 'function') {
1743
+ throw refuse('the managed worktree service is unavailable, so the original tree cannot be proven reusable', 'no worktree registry');
1744
+ }
1745
+ let tree;
1746
+ try {
1747
+ tree = manager.get(identity.executionPath);
1748
+ } catch (error) {
1749
+ throw refuse('the managed worktree service refused to report the original tree', typeof error?.code === 'string' ? error.code : 'registry read failed');
1750
+ }
1751
+ if (tree === null || typeof tree !== 'object') {
1752
+ throw refuse('the original worktree is no longer registered; a new tree will not be substituted', 'tree not managed here');
1753
+ }
1754
+ const expectedTreeId = identity.worktreeId ?? identity.taskId;
1755
+ if (!samePath(tree.workspacePath, identity.executionPath)
1756
+ || !samePath(tree.sourcePath, identity.sourcePath)
1757
+ || (typeof expectedTreeId === 'string' && expectedTreeId !== '' && tree.taskId !== expectedTreeId)
1758
+ || tree.state === 'disposed'
1759
+ || tree.isolated !== true
1760
+ || tree.detached !== true) {
1761
+ throw refuse('the registered worktree does not match the task being continued', 'worktree identity mismatch');
1762
+ }
1763
+ let workspacePath;
1764
+ try {
1765
+ workspacePath = await resolveWorkspacePath(identity.executionPath);
1766
+ } catch {
1767
+ throw refuse('the original worktree path is no longer available', 'worktree path unavailable');
1768
+ }
1769
+ if (!samePath(workspacePath, identity.executionPath)) {
1770
+ throw refuse('the original worktree path resolves to a different directory', 'worktree path mismatch');
1771
+ }
1772
+ return { ...tree, workspacePath, reused: true };
1773
+ }
1774
+
1775
+ /**
1776
+ * Decide whether a named task thread may be joined, from the live facts of one parent.
1777
+ *
1778
+ * This is the engine's own answer for a parent still in memory, used by placement
1779
+ * (`deps.assertAdmissible`) as a synchronous re-check of a chain admission has already
1780
+ * proven; a parent this process does not hold is not its business and answers
1781
+ * `undefined`, because {@link assertContinuation} already judged such a parent from its
1782
+ * durable snapshot. It is purely synchronous and never reads history or the identity
1783
+ * map back.
1784
+ *
1785
+ * The ownership, terminal-state, conversation and path rules are the same ones
1786
+ * {@link admitContinuation} applies to a snapshot, expressed for a live record: a
1787
+ * caller with no verified connection identity and a parent record that states no owner
1788
+ * are both unprovable, a parent that has not ended, or ended without a conversation,
1789
+ * is refused with the `SESSION_*` code that says why, and a parent that ran in another
1790
+ * directory (or records a masked one) cannot be joined merely because its Workspace id
1791
+ * looks familiar.
1792
+ * @param {string} parentTaskId - the task id the caller named.
1793
+ * @param {object} facts - `sourcePath` (this submission's source workspace),
1794
+ * `executionPath` (the directory this submission runs in — the parent's tree when it
1795
+ * continues an isolated chain), optional `connectionId` (this submission's verified
1796
+ * connection, or null), and optional `selfTaskId` (the submitting task, for the
1797
+ * self-continuation guard). A missing or masked path on either side is never a
1798
+ * wildcard.
1799
+ * @returns {object | undefined} the live parent record when this process has one.
1800
+ * @throws {JobError} when the chain cannot be joined.
1801
+ */
1802
+ assertAdmissible(parentTaskId, facts = {}) {
1803
+ const parent = this.tasks.get(parentTaskId);
1804
+ if (parent === undefined) return undefined;
1805
+ if (facts.selfTaskId !== undefined && parent.taskId === facts.selfTaskId) {
1806
+ throw this.continuationRefusal('a task cannot continue its own conversation', {
1807
+ continueFromTaskId: parentTaskId,
1808
+ session: SESSION_CODES.continuationState,
1809
+ });
1810
+ }
1811
+ // An id is proven by comparing two ids, so a caller that states nothing and a
1812
+ // parent record that states no owner are both unprovable: the empty side is
1813
+ // never a wildcard. Reported as absent rather than forbidden, the same way a
1814
+ // cross-connection task read is — a distinct code would confirm the id exists.
1815
+ const owner = typeof parent.connectionId === 'string' && parent.connectionId !== '' ? parent.connectionId : null;
1816
+ const caller = typeof facts.connectionId === 'string' && facts.connectionId !== '' ? facts.connectionId : null;
1817
+ if (owner === null || caller === null || owner !== caller) throw this.absentContinuation(parentTaskId);
1818
+ if (!TERMINAL.has(parent.state)) {
1819
+ throw this.continuationRefusal('the named task is still running, so its conversation cannot be continued yet', {
1820
+ continueFromTaskId: parentTaskId,
1821
+ state: typeof parent.state === 'string' ? parent.state : 'no recorded end state',
1822
+ session: SESSION_CODES.continuationState,
1823
+ });
1824
+ }
1825
+ const conversation = parent.execution?.conversation ?? null;
1826
+ if (conversation === null || typeof conversation !== 'object') {
1827
+ // A run that ended without ever driving a session (an admission refusal, a
1828
+ // policy failure) has no thread; continuing it would silently start a new one.
1829
+ throw this.continuationRefusal('the named task ended without driving a conversation, so there is nothing to continue', {
1830
+ continueFromTaskId: parentTaskId,
1831
+ state: parent.state,
1832
+ session: SESSION_CODES.continuationState,
1833
+ });
1834
+ }
1835
+ if (typeof parent.sourcePath !== 'string' || parent.sourcePath === ''
1836
+ || typeof facts.sourcePath !== 'string' || facts.sourcePath === ''
1837
+ || !samePath(parent.sourcePath, facts.sourcePath)) {
1838
+ throw this.continuationRefusal('the named task belongs to another source repository, so its conversation was not continued', {
1839
+ continueFromTaskId: parentTaskId,
1840
+ reason: 'different source repository',
1841
+ session: SESSION_CODES.continuationWorkspaceMismatch,
1842
+ });
1843
+ }
1844
+ // The execution directory is the other half of a chain's identity: the parent's
1845
+ // conversation lives in the Workspace of the directory it ran in, and a live parent
1846
+ // keeps its exact directory even when it drove a managed worktree. Equal Workspace
1847
+ // ids are not enough — the same id two coordinates apart is a workspace the
1848
+ // follow-up did not inherit — and a masked directory cannot prove which one it names.
1849
+ const recordedExecution = parent.executionPath;
1850
+ const execution = facts.executionPath;
1851
+ if (recordedExecution !== undefined && recordedExecution !== null) {
1852
+ if (typeof recordedExecution !== 'string' || recordedExecution.trim() === ''
1853
+ || typeof execution !== 'string' || execution.trim() === ''
1854
+ || recordedPathIsMasked(recordedExecution) || recordedPathIsMasked(execution)) {
1855
+ throw this.continuationRefusal('the named task has no reliably recorded execution path, so its conversation cannot be continued', {
1856
+ continueFromTaskId: parentTaskId,
1857
+ reason: 'unusable recorded execution path',
1858
+ session: SESSION_CODES.continuationUnavailable,
1859
+ });
1860
+ }
1861
+ if (!samePath(recordedExecution, execution)) {
1862
+ throw this.continuationRefusal('the named task ran in another execution directory, so its conversation was not continued', {
1863
+ continueFromTaskId: parentTaskId,
1864
+ reason: 'different execution directory',
1865
+ session: SESSION_CODES.continuationPathMismatch,
1866
+ });
1867
+ }
1868
+ }
1869
+ return parent;
1870
+ }
1871
+
1872
+ /**
1873
+ * Re-check the three facts that make a preflight step legal: not disposed, not
1874
+ * cancelled, and still authorized for exactly this task and source workspace.
1875
+ * @param {object} task - pending record.
1876
+ * @param {string} phase - the step that just completed.
1877
+ * @returns {void}
1878
+ */
1879
+ assertLive(task, phase) {
1880
+ if (this.aborted) {
1881
+ throw new JobError(JOB_CODES.disposed, 'the plugin was disposed while the task was starting', { phase });
1882
+ }
1883
+ if (task.cancelRequested || task.controller.signal.aborted) {
1884
+ throw new JobError(JOB_CODES.cancelled, `the task was cancelled during ${phase}`, {
1885
+ phase,
1886
+ reason: task.cancelledBy ?? 'request',
1887
+ });
1888
+ }
1889
+ if (task.authorization === 'switch' && this.delegationEnabled !== true) {
1890
+ throw new JobError(JOB_CODES.notAuthorized, 'delegation is disabled', { phase });
1891
+ }
1892
+ if (task.connectionId === null || task.grantId === null || task.sourcePath === null) return;
1893
+ try {
1894
+ this.auth.assertTaskAuthorized({
1895
+ connectionId: task.connectionId,
1896
+ grantId: task.grantId,
1897
+ taskId: task.taskId,
1898
+ workspacePath: task.sourcePath,
1899
+ });
1900
+ } catch (error) {
1901
+ throw new JobError(
1902
+ typeof error?.code === 'string' ? error.code : JOB_CODES.notAuthorized,
1903
+ diagnostic(error?.message ?? 'the authorization is no longer valid', 300) ?? 'the authorization is no longer valid',
1904
+ { phase, ...redactDeep(error?.details ?? {}) },
1905
+ );
1906
+ }
1907
+ }
1908
+
1909
+ /**
1910
+ * Whether the task has been asked to stop.
1911
+ * @param {object} task - task record.
1912
+ * @returns {boolean} true when cancellation was requested.
1913
+ */
1914
+ isCancelled(task) {
1915
+ return task.cancelRequested === true || task.controller.signal.aborted === true;
1916
+ }
1917
+
1918
+ /**
1919
+ * Whether a delegated run may be offered a per-call permission bridge.
1920
+ *
1921
+ * The question is capability, not configuration, and it is answered by the
1922
+ * deployment: a bridge is offered only when the entry point says it can surface
1923
+ * pending requests and accept a decision from a commander (`deps.permissionBridge`
1924
+ * is a function returning a bridge). A deployment without that seam keeps the
1925
+ * original fail-closed behaviour for every run, and nothing in this module
1926
+ * invents a second way to grant anything.
1927
+ * @returns {boolean} true when a bridge may be created for a run.
1928
+ */
1929
+ permissionBridgeAvailable() {
1930
+ return typeof this.deps?.permissionBridge === 'function' && this.aborted !== true;
1931
+ }
1932
+
1933
+ /**
1934
+ * Create the permission bridge for one task, or `null`.
1935
+ *
1936
+ * The bridge belongs to the task and to the run inside it. Its observers are
1937
+ * wired here rather than in the runtime so the task record — not the runner —
1938
+ * owns the phase, the execution-time accounting and the evidence trail: those
1939
+ * are task lifecycle facts, and the runner has no authority over the budget.
1940
+ *
1941
+ * The factory is called with the exact facts the commander is later asked to
1942
+ * recognise: the task and the connection that owns it.
1943
+ * @param {object} task - the running task.
1944
+ * @returns {object | null} a bridge to arm, or null when unavailable.
1945
+ */
1946
+ createPermissionBridge(task) {
1947
+ if (!this.permissionBridgeAvailable()) return null;
1948
+ let bridge;
1949
+ try {
1950
+ bridge = this.deps.permissionBridge({
1951
+ taskId: task.taskId,
1952
+ connectionId: task.connectionId,
1953
+ onPending: (view) => this.onPermissionPending(task, view),
1954
+ onSettled: (entry) => this.onPermissionSettled(task, entry),
1955
+ });
1956
+ } catch (error) {
1957
+ // A factory that cannot produce a bridge is the same operator situation as a
1958
+ // deployment without the seam: the run keeps `never` and is not failed for
1959
+ // it. The refusal is logged rather than surfaced as a task error, because
1960
+ // "approvals are not bridged here" is a property of the deployment.
1961
+ this.deps?.logger?.warn?.('dsh-delegate: the per-call permission bridge could not be created', String(error?.code ?? ''));
1962
+ return null;
1963
+ }
1964
+ if (bridge === null || bridge === undefined || typeof bridge !== 'object' || typeof bridge.arm !== 'function') {
1965
+ return null;
1966
+ }
1967
+ return bridge;
1968
+ }
1969
+
1970
+ /**
1971
+ * Record one request the worker is now waiting on.
1972
+ *
1973
+ * The task state stays `running` and only its PHASE changes, so nothing that
1974
+ * reads the state contract has to learn a new lifecycle value: a task waiting for
1975
+ * a decision is neither failed nor execution-complete, and its workspace lock,
1976
+ * concurrency slot and provider lease remain its own.
1977
+ *
1978
+ * The wait is NOT charged to the execution budget. The runner's own timer does
1979
+ * not observe it (the native tool call is paused, not the run), and the request
1980
+ * carries a separate bounded deadline of its own, so a paused call can never
1981
+ * turn into a timeout of the work.
1982
+ * @param {object} task - the running task.
1983
+ * @param {object} view - the bridge's redacted request view.
1984
+ * @returns {void}
1985
+ */
1986
+ onPermissionPending(task, view) {
1987
+ if (TERMINAL.has(task.state)) return;
1988
+ task.permission.pending = view;
1989
+ task.permission.pausedAt = Date.now();
1990
+ if (task.state === TASK_STATES.running) task.phase = PHASE_AWAITING_PERMISSION;
1991
+ // Durable checkpoint: a crash while the worker is PAUSED is exactly the case the
1992
+ // in-memory record cannot describe after a restart, so the pending request is
1993
+ // written now rather than only at terminal time.
1994
+ this.checkpointHistory(task);
1995
+ }
1996
+
1997
+ /**
1998
+ * Record one settled request and account for the time spent waiting.
1999
+ * @param {object} task - the task the request belonged to.
2000
+ * @param {object} entry - the bridge's redacted settled view.
2001
+ * @returns {void}
2002
+ */
2003
+ onPermissionSettled(task, entry) {
2004
+ if (task.permission.pending !== null && entry?.requestId === task.permission.pending.requestId) {
2005
+ task.permission.pending = null;
2006
+ }
2007
+ if (task.permission.pausedAt !== null) {
2008
+ task.permission.pausedExecutionMs += Math.max(0, Date.now() - task.permission.pausedAt);
2009
+ task.permission.pausedAt = null;
2010
+ }
2011
+ if (entry !== null && entry !== undefined) {
2012
+ task.permission.evidence.push(entry);
2013
+ if (task.permission.evidence.length > 8) task.permission.evidence.shift();
2014
+ }
2015
+ // Back to the execution phase, never to a new state: a settled request that was
2016
+ // allowed and one that was rejected both leave the task `running` until the run
2017
+ // itself reaches an outcome.
2018
+ if (task.state === TASK_STATES.running && task.phase === PHASE_AWAITING_PERMISSION) {
2019
+ task.phase = PHASE_EXECUTE;
2020
+ }
2021
+ this.checkpointHistory(task);
2022
+ }
2023
+
2024
+ /**
2025
+ * Write a bounded, fire-and-forget history checkpoint for a LIVE task.
2026
+ *
2027
+ * Three deliberate properties:
2028
+ *
2029
+ * * it is **serialized by the store**, so a pending checkpoint cannot interleave
2030
+ * with the terminal write — the documents are whole-file atomic writes and one
2031
+ * save runs at a time;
2032
+ * * it **cannot resurrect a terminal task**: `HistoryStore` refuses to overwrite a
2033
+ * terminal record with a live one, and this method re-checks the task's own state
2034
+ * before the write lands, so a slow checkpoint that finishes after the run ended
2035
+ * is dropped instead of rolling the record back to `running`;
2036
+ * * it is **bounded and silent**. It shares `HISTORY_WRITE_TIMEOUT_MS`, records a
2037
+ * failure as `historyError` and never rejects upward: a checkpoint is evidence,
2038
+ * not a step the run depends on.
2039
+ * @param {object} task - live task record.
2040
+ * @returns {void}
2041
+ */
2042
+ checkpointHistory(task) {
2043
+ const history = this.history;
2044
+ if (history === null || history === undefined || typeof history.save !== 'function') return;
2045
+ if (TERMINAL.has(task.state)) return;
2046
+ let view;
2047
+ try {
2048
+ view = this.view(task);
2049
+ } catch {
2050
+ return;
2051
+ }
2052
+ // A save that is already queued for a NEWER snapshot wins; an older one is
2053
+ // discarded rather than allowed to publish a stale phase.
2054
+ this.historyCheckpointSeq = (this.historyCheckpointSeq ?? 0) + 1;
2055
+ task.historyCheckpointSeq = this.historyCheckpointSeq;
2056
+ const seq = this.historyCheckpointSeq;
2057
+ let timer = null;
2058
+ const bounded = new Promise((resolvePromise, rejectPromise) => {
2059
+ timer = setTimeout(() => {
2060
+ rejectPromise(new JobError(JOB_CODES.historyFailed, 'the history checkpoint exceeded its time budget', {
2061
+ code: 'HISTORY_WRITE_TIMEOUT',
2062
+ timeoutMs: HISTORY_WRITE_TIMEOUT_MS,
2063
+ }));
2064
+ }, HISTORY_WRITE_TIMEOUT_MS);
2065
+ timer.unref?.();
2066
+ Promise.resolve(history.save(view)).then(resolvePromise, rejectPromise);
2067
+ });
2068
+ void bounded
2069
+ .then(() => {
2070
+ // A LATER snapshot OF THIS SAME TASK has superseded this one. The counter is
2071
+ // global, so `this.historyCheckpointSeq` would let a concurrent task's
2072
+ // checkpoint discard this task's own successful write (and leave the
2073
+ // bookkeeping fields stale); the comparison is per task, against the
2074
+ // sequence this task last claimed.
2075
+ if (task.historyCheckpointSeq !== seq) return;
2076
+ // The run ended while this write was in flight: the terminal record is the
2077
+ // truth, and a live snapshot must never overwrite it.
2078
+ if (TERMINAL.has(task.state)) return;
2079
+ task.historyError = null;
2080
+ task.historySavedAt = Date.now();
2081
+ })
2082
+ .catch((error) => {
2083
+ task.historyError = {
2084
+ code: typeof error?.code === 'string' ? error.code : JOB_CODES.historyFailed,
2085
+ message: diagnostic(error?.message ?? error, 300),
2086
+ };
2087
+ })
2088
+ .finally(() => {
2089
+ if (timer !== null) clearTimeout(timer);
2090
+ });
2091
+ }
2092
+
2093
+ /**
2094
+ * Decide one pending permission request for one task.
2095
+ *
2096
+ * This is the commander's only way to answer, and it is shaped like every other
2097
+ * refusal in this class: the identity comes from the authenticated caller, the
2098
+ * task owner is checked before anything is read, and an id this deployment cannot
2099
+ * prove belongs to the caller is answered as absent so the reply cannot be used
2100
+ * to discover other tasks.
2101
+ *
2102
+ * The chain of checks, all refusals:
2103
+ *
2104
+ * 1. the task exists and belongs to the deciding connection (a foreign task is
2105
+ * `JOB_TASK_NOT_FOUND`, identical to an unknown one);
2106
+ * 2. delegation is still authorized and this task's own authorization is still
2107
+ * valid (a switch turned off or a revoked grant stops the decision);
2108
+ * 3. the task is live and has a bridge with an outstanding request;
2109
+ * 4. the bridge decides the request — still pending, not past its deadline, and
2110
+ * the fingerprint (when supplied) matching the bound operation exactly;
2111
+ * 5. only then does the outcome travel to the paused native tool call.
2112
+ *
2113
+ * The decision is NOT acceptance and NOT a standing grant: the task keeps
2114
+ * running afterwards, `selfApproved` stays false, and the Session's sandbox mode
2115
+ * is untouched.
2116
+ * @param {object} request - `taskId`, `requestId`, `decision`, optional `reason`,
2117
+ * optional `fingerprint`, and the authenticated `connectionId` (supplied by the
2118
+ * plane, never by the caller's body).
2119
+ * @returns {object} bounded result: `{ task, permission, hostAcceptance: null }`.
2120
+ * @throws {JobError} on any refusal.
2121
+ */
2122
+ decidePermission(request) {
2123
+ const connectionId = typeof request?.connectionId === 'string' ? request.connectionId : null;
2124
+ if (connectionId === null) {
2125
+ // No verified identity means no ownership proof, which is the same answer an
2126
+ // unknown task gets — never a discovery oracle.
2127
+ throw new JobError(JOB_CODES.taskNotFound, 'no such task for this connection', {});
2128
+ }
2129
+ const taskId = typeof request?.taskId === 'string' ? request.taskId.trim() : '';
2130
+ if (taskId === '') {
2131
+ throw new JobError(PERMISSION_CODES.invalid, 'taskId is required', { field: 'taskId' });
2132
+ }
2133
+ const task = this.tasks.get(taskId);
2134
+ if (task === undefined || task.connectionId !== connectionId) {
2135
+ throw new JobError(JOB_CODES.taskNotFound, 'no such task for this connection', { taskId });
2136
+ }
2137
+ if (TERMINAL.has(task.state)) {
2138
+ throw new JobError(PERMISSION_CODES.notPending, 'this task has already ended; its pending request is history only', {
2139
+ taskId,
2140
+ state: task.state,
2141
+ });
2142
+ }
2143
+ // The authorization is re-checked at the decision, not only at submission: an
2144
+ // operator who closed the switch or revoked the authorization between the ask
2145
+ // and the decision must not have a live decision applied afterwards.
2146
+ if (this.posture().authorized !== true) {
2147
+ throw new JobError(JOB_CODES.notAuthorized, 'delegation is no longer authorized, so no decision may be applied', {});
2148
+ }
2149
+ this.assertLive(task, 'permission-decide');
2150
+ const bridge = task.permission.bridge;
2151
+ if (bridge === null || bridge === undefined || typeof bridge.decide !== 'function') {
2152
+ throw new JobError(PERMISSION_CODES.notFound, 'this task has no pending permission request', { taskId });
2153
+ }
2154
+ let settled;
2155
+ try {
2156
+ settled = bridge.decide({
2157
+ requestId: request?.requestId,
2158
+ decision: request?.decision,
2159
+ reason: request?.reason,
2160
+ ...(request?.fingerprint === undefined ? {} : { fingerprint: request.fingerprint }),
2161
+ });
2162
+ } catch (error) {
2163
+ if (error instanceof PermissionError) {
2164
+ throw new JobError(error.code, error.message, error.details);
2165
+ }
2166
+ throw error;
2167
+ }
2168
+ return { task: this.view(task), permission: settled, hostAcceptance: null };
2169
+ }
2170
+
2171
+ /**
2172
+ * Stop every outstanding request of one task and disarm its bridge.
2173
+ *
2174
+ * Called from every path that ends a run — a terminal state, cancellation,
2175
+ * switch-off, revocation, disposal — so a paused native tool call is released
2176
+ * instead of outliving the reason it was paused. The bridge is disposed LAST, so
2177
+ * the outstanding request is first settled with the right cause (`cancelled` for
2178
+ * a stop, `unavailable` for a disposal) and only then does the answerer go away.
2179
+ * @param {object} task - task record.
2180
+ * @param {string} [cause] - `stop` (default) or `dispose`.
2181
+ * @returns {void}
2182
+ */
2183
+ releasePermissionBridge(task, cause = 'stop') {
2184
+ const bridge = task.permission?.bridge ?? null;
2185
+ if (bridge === null || bridge === undefined) return;
2186
+ try {
2187
+ if (cause === 'dispose') bridge.dispose?.();
2188
+ else bridge.stop?.();
2189
+ } catch (error) {
2190
+ this.deps?.logger?.warn?.('dsh-delegate: the permission bridge could not be stopped', String(error?.code ?? ''));
2191
+ }
2192
+ if (task.permission.pending !== null) task.permission.pending = null;
2193
+ task.permission.pausedAt = null;
2194
+ if (cause === 'dispose') task.permission.bridge = null;
2195
+ }
2196
+
2197
+ /**
2198
+ * The bounded, public permission block of one task.
2199
+ *
2200
+ * `pending` is the request the commander has to decide (or `null`), `evidence` is
2201
+ * the settled trail, and `bridged`/`waiting` are stated so a client never has to
2202
+ * infer them from a phase string. `pausedExecutionMs` is reported because it is
2203
+ * the time that was NOT charged to the execution budget — an operator reading a
2204
+ * long run should be able to see how much of it was spent waiting for a decision.
2205
+ * @param {object} task - task record.
2206
+ * @returns {object} redacted permission view.
2207
+ */
2208
+ permissionView(task) {
2209
+ const pending = task.permission?.pending ?? null;
2210
+ return {
2211
+ bridged: task.permission?.bridge !== null && task.permission?.bridge !== undefined,
2212
+ waiting: pending !== null,
2213
+ pending,
2214
+ evidence: Array.isArray(task.permission?.evidence) ? task.permission.evidence : [],
2215
+ pausedExecutionMs: task.permission?.pausedExecutionMs ?? 0,
2216
+ // Stated on every view, because it is the property the whole feature turns
2217
+ // on: a decision applies to one call and never to the standing policy.
2218
+ standingSandboxMode: DELEGATE_SANDBOX_MODE,
2219
+ grantScope: 'single-call',
2220
+ };
2221
+ }
2222
+
2223
+ /**
2224
+ * Request cancellation of one live task and record why.
2225
+ *
2226
+ * The task's outstanding permission request is withdrawn FIRST (if it has one),
2227
+ * so the paused native tool call observes a cancelled question instead of a
2228
+ * controller abort it would learn about only after the tool returned. The
2229
+ * workspace lock, the concurrency slot and the provider lease are untouched here:
2230
+ * they are released by {@link finalize}, and only once the executor confirms it
2231
+ * stopped — a wait that was interrupted by a cancel is still a live executor.
2232
+ * @param {object} task - task record.
2233
+ * @param {string} reason - recorded provenance.
2234
+ * @returns {void}
2235
+ */
2236
+ abortTask(task, reason) {
2237
+ if (TERMINAL.has(task.state)) return;
2238
+ // The CAUSE decides how the outstanding request is settled, and only the
2239
+ // dispose path reports the channel as unusable: a plugin teardown must not be
2240
+ // dressed up as "the operator withdrew the question". A later explicit
2241
+ // `releasePermissionBridge(task, 'dispose')` is idempotent, so disposing here
2242
+ // does not double-settle.
2243
+ this.releasePermissionBridge(task, reason === 'dispose' ? 'dispose' : 'stop');
2244
+ task.cancelRequested = true;
2245
+ task.cancelledBy = task.cancelledBy ?? reason;
2246
+ try {
2247
+ task.controller.abort();
2248
+ } catch {
2249
+ // AbortController.abort() does not throw; kept for defence in depth.
2250
+ }
2251
+ }
2252
+
2253
+ /**
2254
+ * Handle one authorization invalidation event.
2255
+ * @param {object} event - `kind`, optional `grantId`/`connectionId`, `reason`.
2256
+ * @returns {void}
2257
+ */
2258
+ onAuthorizationInvalidated(event) {
2259
+ if (this.aborted) return;
2260
+ const reason = `authorization:${typeof event?.reason === 'string' ? event.reason : 'revoked'}`;
2261
+ for (const task of this.tasks.values()) {
2262
+ if (TERMINAL.has(task.state)) continue;
2263
+ if (!matchesInvalidation(task, event)) continue;
2264
+ this.abortTask(task, reason);
2265
+ }
2266
+ }
2267
+
2268
+ /**
2269
+ * Drive one admitted task to a terminal state.
2270
+ * @param {object} task - admitted task.
2271
+ * @returns {void}
2272
+ */
2273
+ drive(task) {
2274
+ void this.execute(task)
2275
+ .catch((error) => {
2276
+ // execute() already records failures; this guards against a programming
2277
+ // error escaping an already-settled task.
2278
+ if (task.state === TASK_STATES.running || task.state === TASK_STATES.pending) {
2279
+ task.state = TASK_STATES.failed;
2280
+ task.error = task.error ?? { code: JOB_CODES.internal, message: diagnostic(error?.message ?? error) };
2281
+ task.endedAt = Date.now();
2282
+ }
2283
+ })
2284
+ .finally(() => task.settle());
2285
+ }
2286
+
2287
+ /**
2288
+ * Record a failed admission: the slot and every lease are released, the record
2289
+ * becomes terminal, and nothing is created. A consumed grant stays consumed,
2290
+ * and a tree that was created before the refusal is marked complete and kept.
2291
+ * @param {object} task - pending record.
2292
+ * @param {unknown} error - the refusal that ended admission.
2293
+ * @returns {Promise<void>} resolves once the refused task's capacity is returned.
2294
+ */
2295
+ async failAdmission(task, error) {
2296
+ this.clearPreflightDeadline(task);
2297
+ // Admission never created an executor, so any bridge it did create (it is
2298
+ // created just before the runner call, so normally none) is disposed here too.
2299
+ this.releasePermissionBridge(task, 'dispose');
2300
+ task.endedAt = task.endedAt ?? Date.now();
2301
+ // A preflight that ran out of budget is a timeout, not a cancellation: it is
2302
+ // the same budget the run itself would have failed on, and reporting it as
2303
+ // "cancelled" would hide that nobody asked to stop it.
2304
+ const timedOut = error?.code === JOB_CODES.timeout || (task.preflightTimedOut === true && this.isCancelled(task));
2305
+ const cancelled = !timedOut
2306
+ && (this.aborted || this.isCancelled(task)
2307
+ || error?.code === JOB_CODES.cancelled || error?.code === JOB_CODES.disposed);
2308
+ if (!TERMINAL.has(task.state)) {
2309
+ task.state = cancelled ? TASK_STATES.cancelled : TASK_STATES.failed;
2310
+ if (cancelled) {
2311
+ task.cancelledBy = task.cancelledBy ?? (this.aborted ? 'dispose' : 'request');
2312
+ task.error = null;
2313
+ } else {
2314
+ task.error = this.errorOf(error, task);
2315
+ }
2316
+ }
2317
+ // A tree prepared before the refusal is evidence, not garbage: it is kept and
2318
+ // marked complete so the host can inspect or dispose it explicitly. Both that
2319
+ // and the lease release are done by {@link finalize}, which is the single
2320
+ // release path for every exit. Admission failed before any native executor
2321
+ // existed, so the slot is returned immediately rather than staying occupied by
2322
+ // a record that will never run.
2323
+ await this.finalize(task);
2324
+ // A refused task is a failed task: the history document records it on the same
2325
+ // terms as a failed run, so an operator can see that a grant was spent and no
2326
+ // work was produced.
2327
+ await this.persistHistory(task);
2328
+ task.settle();
2329
+ }
2330
+
2331
+ /**
2332
+ * Project a thrown refusal into a bounded task error.
2333
+ *
2334
+ * A session-placement refusal is also handled here, not only in the execution
2335
+ * path: `start()` raises these during admission, and reporting one as a generic
2336
+ * `JOB_START_FAILED` would hide the one code an operator can act on. A
2337
+ * continuation refusal keeps its `SESSION_*` cause in `details.session`.
2338
+ * @param {unknown} error - thrown value.
2339
+ * @param {object} [task] - the task record, when the error belongs to one.
2340
+ * @returns {object} error record.
2341
+ */
2342
+ errorOf(error, task = null) {
2343
+ if (error instanceof SessionPlacementRefusal && task !== null) {
2344
+ return this.conversationErrorOf(error, task);
2345
+ }
2346
+ return {
2347
+ code: typeof error?.code === 'string' ? error.code : JOB_CODES.failed,
2348
+ message: diagnostic(error?.message ?? String(error), 400) ?? 'the task could not start',
2349
+ details: redactDeep(error?.details ?? {}),
2350
+ };
2351
+ }
2352
+
2353
+ /**
2354
+ * Shape one session-placement refusal into the task error an operator reads.
2355
+ * @param {object} error - placement refusal.
2356
+ * @param {object} task - the task the refusal belongs to.
2357
+ * @returns {{ code: string, message: string, details: object }} bounded error.
2358
+ */
2359
+ conversationErrorOf(error, task) {
2360
+ const continuation = task?.continueFromTaskId ?? null;
2361
+ return {
2362
+ code: continuation === null ? JOB_CODES.conversationUnavailable : JOB_CODES.continuationRefused,
2363
+ message: error.message,
2364
+ details: {
2365
+ session: error.code,
2366
+ ...(continuation === null ? {} : { continueFromTaskId: continuation }),
2367
+ ...redactDeep(error.details ?? {}),
2368
+ },
2369
+ };
2370
+ }
2371
+
2372
+ /**
2373
+ * Map any admission refusal onto a job refusal for the caller.
2374
+ * @param {unknown} error - thrown value.
2375
+ * @returns {JobError} refusal to throw.
2376
+ */
2377
+ admissionError(error) {
2378
+ if (error instanceof JobError) return error;
2379
+ const code = typeof error?.code === 'string' ? error.code : null;
2380
+ if (error instanceof AuthError || (code !== null && code.startsWith('GRANT_'))) {
2381
+ return new JobError(code ?? JOB_CODES.notAuthorized, diagnostic(error?.message ?? 'authorization refused', 300)
2382
+ ?? 'authorization refused', redactDeep(error?.details ?? {}));
2383
+ }
2384
+ if (code !== null) {
2385
+ return new JobError(code, diagnostic(error?.message ?? 'the task could not start', 300)
2386
+ ?? 'the task could not start', redactDeep(error?.details ?? {}));
2387
+ }
2388
+ return new JobError(JOB_CODES.startFailed, diagnostic(error?.message ?? 'the task could not start', 300)
2389
+ ?? 'the task could not start', {});
2390
+ }
2391
+
2392
+ /**
2393
+ * Release every lease this task holds, newest first.
2394
+ * @param {object} task - task record.
2395
+ * @returns {void}
2396
+ */
2397
+ releaseLeases(task) {
2398
+ while (task.leases.length > 0) {
2399
+ const lease = task.leases.pop();
2400
+ try {
2401
+ this.locks.release(lease.path, lease.nonce);
2402
+ } catch {
2403
+ // Releasing a lease we no longer hold is a no-op by design.
2404
+ }
2405
+ }
2406
+ }
2407
+
2408
+ /**
2409
+ * Execute one admitted task end to end. Records failures on the task; never throws.
2410
+ * @param {object} task - task record.
2411
+ * @returns {Promise<void>} resolves when the task reaches a terminal state.
2412
+ */
2413
+ async execute(task) {
2414
+ // A task cancelled or revoked while it was being handed over is never
2415
+ // published as `running`: the operator asked for it to stop, so it must not
2416
+ // appear to have started afterwards.
2417
+ if (!this.isCancelled(task)) {
2418
+ task.state = TASK_STATES.running;
2419
+ task.phase = 'execute';
2420
+ task.startedAt = Date.now();
2421
+ }
2422
+ // The monitor exists from the moment the run is driven, so an executor that
2423
+ // produces nothing at all is still measured from its own state time instead of
2424
+ // being invisible. Its thresholds come from the snapshot this task froze at
2425
+ // admission, never from live settings: an edit mid-run must not retime a task
2426
+ // that is already in flight.
2427
+ //
2428
+ // `ensureMonitor` never REPLACES one: an observation started before this call
2429
+ // (against `startedAt`, i.e. while the task was still `pending`) already holds a
2430
+ // reference to the monitor, and swapping it here would leave that observer
2431
+ // watching an object that never receives another event.
2432
+ this.ensureMonitor(task);
2433
+ try {
2434
+ const workerSelection = {
2435
+ // The public profile id stays the operator-facing identity; the native
2436
+ // route is a separate fact the registry produced.
2437
+ providerId: task.effective.worker.providerId,
2438
+ providerRoute: task.route.providerRoute,
2439
+ model: task.route.model,
2440
+ reasoningEffort: task.route.reasoningEffort,
2441
+ };
2442
+ const prompt = buildWorkerPrompt({
2443
+ taskId: task.taskId,
2444
+ prompt: task.prompt,
2445
+ workspacePath: task.executionPath,
2446
+ isolation: task.effective.worker.isolation,
2447
+ baseline: task.baseline,
2448
+ });
2449
+
2450
+ // The last gate before a native agent exists. Everything above awaited at
2451
+ // least once; this re-check runs in the same step as the creation call.
2452
+ task.phase = 'before-create';
2453
+ this.assertLive(task, 'before-create');
2454
+
2455
+ // The native executor comes into existence here. `started` is recorded
2456
+ // before the call and `settled` only once its promise has settled, on
2457
+ // success and on failure alike, so {@link finalize} can tell "no executor
2458
+ // was ever created" from "an executor may still be writing to the
2459
+ // workspace". Nothing below may release a lease or the slot before the
2460
+ // matching `settled` is true.
2461
+ //
2462
+ // The permission bridge is created BEFORE the executor exists (it is bound
2463
+ // in the run's setup, so the runtime also sees it) and is the answerer the
2464
+ // policy stance is installed for. A bridge is offered only when this
2465
+ // deployment can surface its requests to a commander at all; when it cannot,
2466
+ // the run keeps the fail-closed `never` stance and nothing about it changes.
2467
+ const bridge = this.createPermissionBridge(task);
2468
+ task.permission.bridge = bridge;
2469
+ task.native.started = true;
2470
+ const pending = runAgent(this.deps, {
2471
+ prompt,
2472
+ title: task.title,
2473
+ cwd: task.executionPath,
2474
+ selection: workerSelection,
2475
+ timeoutMs: task.effective.worker.timeoutSeconds * 1000,
2476
+ signal: task.controller.signal,
2477
+ // What this run does with its DSH conversation, frozen on the task at
2478
+ // creation: omitted means a new conversation, present means continue exactly
2479
+ // that task's thread. There is no directory-level mode to consult, so a
2480
+ // settings edit (or a legacy `reuse` value) cannot change it mid-run.
2481
+ ...(task.continueFromTaskId === null ? {} : { continueFromTaskId: task.continueFromTaskId }),
2482
+ // The task/connection/source facts a continuation identity must match.
2483
+ taskId: task.taskId,
2484
+ connectionId: task.connectionId,
2485
+ sourcePath: task.sourcePath,
2486
+ // Worker sessions are writable only inside their current DSH workspace.
2487
+ // Wider sandbox requests are refused when no bridge is armed, and decided
2488
+ // per call by the commander when one is. The services that own both facts
2489
+ // are read live through `deps.policyServices`, so the runner verifies the
2490
+ // resolved policy before it prompts.
2491
+ delegated: true,
2492
+ // The per-call approval answerer for THIS task's own Agent: armed in the
2493
+ // run's setup, scanned by the engine before it is offered here, and
2494
+ // disposed when the run ends. `null` keeps the deterministic `never` stance.
2495
+ ...(bridge === null ? {} : { permissionBridge: bridge }),
2496
+ configureDelegatedSession: this.deps.configureDelegatedSession,
2497
+ policyServices: this.deps.policyServices,
2498
+ // The engine is the authority for "may this chain be joined": a parent it
2499
+ // still holds is judged live here, and a parent recovered from the persisted
2500
+ // map is judged by the same rule through this hook.
2501
+ assertAdmissible: (parentTaskId) => this.assertAdmissible(parentTaskId, {
2502
+ sourcePath: task.sourcePath,
2503
+ // The directory this run actually executes in: the parent's own managed tree
2504
+ // when this task continues an isolated chain, the source checkout otherwise.
2505
+ executionPath: task.executionPath,
2506
+ connectionId: task.connectionId,
2507
+ selfTaskId: task.taskId,
2508
+ }),
2509
+ // The activity feed. `runAgent` already dispatches every native session
2510
+ // event here, and the monitor reads only the parts it classifies: whether
2511
+ // the event was progress, and (for a tool event) its name and call id.
2512
+ // Reasoning text, assistant text and tool arguments are never retained or
2513
+ // forwarded — there is no field in the summary they could travel in.
2514
+ onEvent: (event) => { task.monitor?.onEvent(event, this.clock()); },
2515
+ });
2516
+ task.native.promise = pending;
2517
+ let run;
2518
+ try {
2519
+ run = await pending;
2520
+ } finally {
2521
+ task.native.settled = true;
2522
+ }
2523
+
2524
+ task.execution = {
2525
+ workspacePath: task.executionPath,
2526
+ outcome: run.outcome,
2527
+ text: run.text,
2528
+ reasoningOnly: run.reasoningOnly,
2529
+ usage: run.usage,
2530
+ turnEnd: run.turnEnd,
2531
+ agentId: run.agentId,
2532
+ sessionId: run.sessionId,
2533
+ // The provider/model/effort the run actually installed on the agent it
2534
+ // drove, plus the output budget it requested. Reported because a placed
2535
+ // run does not create its agent through `agents.create`, so `agentOptions`
2536
+ // is not observable for it — and "which model did this run on" must still
2537
+ // be answerable from the task record.
2538
+ selection: run.selection ?? null,
2539
+ maxTokens: run.maxTokens ?? null,
2540
+ // The approval stance this run installed and read back, plus whether an
2541
+ // armed bridge was the answerer behind it. Recorded per run so "did this
2542
+ // task ask, or did it reject without asking" is answerable from the record.
2543
+ approval: run.approval ?? null,
2544
+ // Where the conversation landed. Reported per run so an operator can tell a
2545
+ // fresh session from a continued one, and which Workspace group it is in.
2546
+ conversation: run.conversation ?? null,
2547
+ cancelCause: run.cancelCause,
2548
+ error: run.error,
2549
+ };
2550
+
2551
+ // Remember the thread this run drove, keyed by THIS task, so a later explicit
2552
+ // `continueFromTaskId` follow-up can continue exactly that conversation in
2553
+ // exactly this execution path. Only identity and provenance are stored; the
2554
+ // transcript stays in the native session log. A failure here is recorded and
2555
+ // never changes the run's outcome.
2556
+ await this.rememberConversation(task);
2557
+
2558
+ // Evidence is captured even for a failed or cancelled run: a partial
2559
+ // change still needs to be visible to the host.
2560
+ task.diff = await captureDiff(this.deps, task.executionPath, task.baseline).catch((error) => ({
2561
+ error: {
2562
+ code: error?.code ?? 'AUDIT_FAILED',
2563
+ message: diagnostic(error?.message ?? error, 300),
2564
+ },
2565
+ files: [],
2566
+ fileCount: 0,
2567
+ patchText: '',
2568
+ patchTruncated: false,
2569
+ }));
2570
+
2571
+ if (run.outcome === RUN_OUTCOMES.cancelled || this.isCancelled(task)) {
2572
+ this.finishCancelled(task);
2573
+ return;
2574
+ }
2575
+ if (run.outcome === RUN_OUTCOMES.timedOut) {
2576
+ task.state = TASK_STATES.failed;
2577
+ task.error = { code: JOB_CODES.timeout, message: 'the task exceeded its time budget' };
2578
+ task.endedAt = Date.now();
2579
+ return;
2580
+ }
2581
+ if (run.outcome !== RUN_OUTCOMES.completed) {
2582
+ task.state = TASK_STATES.failed;
2583
+ // Three endings that are not completion, kept apart because they need
2584
+ // different fixes:
2585
+ // * the model was stopped by its own output budget (`max-tokens`) — raise
2586
+ // the budget;
2587
+ // * an agent-reported error — investigate the provider;
2588
+ // * silence — investigate the run.
2589
+ // The budget ending is tested by the turn record, not by the runner's
2590
+ // message: the runner states a diagnostic for that case too, and reading the
2591
+ // message first would turn a settings change into a provider investigation.
2592
+ // A reasoning-only run never reaches this branch at all — the runner counts
2593
+ // reasoning as output, so it completes.
2594
+ const budgetExhausted = run.turnEnd?.reason === 'max-tokens';
2595
+ const reported = run.error !== null && run.error !== undefined;
2596
+ const code = budgetExhausted
2597
+ ? JOB_CODES.outputTruncated
2598
+ : (reported ? JOB_CODES.executionFailed : JOB_CODES.noOutput);
2599
+ task.error = {
2600
+ code,
2601
+ message: budgetExhausted
2602
+ ? 'the delegated run stopped at its output token budget before producing an answer'
2603
+ : (reported ? run.error : 'the delegated run produced no output'),
2604
+ ...(budgetExhausted
2605
+ ? { details: { turnEnd: run.turnEnd ?? null, usage: run.usage ?? null } }
2606
+ : {}),
2607
+ };
2608
+ task.endedAt = Date.now();
2609
+ return;
2610
+ }
2611
+
2612
+ // Review runs only for a completed execution, and only when enabled. Its
2613
+ // route was frozen during preflight; nothing here re-reads settings.
2614
+ task.phase = 'review';
2615
+ task.review = await this.runReview(task);
2616
+
2617
+ // A cancellation or revocation during the review makes the task terminal
2618
+ // cancelled. It must never be reported as awaiting host review, because
2619
+ // nothing was reviewed to completion.
2620
+ if (this.isCancelled(task) || task.review.state === REVIEW_STATES.cancelled) {
2621
+ this.finishCancelled(task, task.review.state === REVIEW_STATES.cancelled ? 'review-cancelled' : null);
2622
+ return;
2623
+ }
2624
+
2625
+ task.state = TASK_STATES.awaitingHostReview;
2626
+ task.phase = 'awaiting-host-review';
2627
+ task.endedAt = Date.now();
2628
+ } catch (error) {
2629
+ if (this.isCancelled(task)) {
2630
+ this.finishCancelled(task);
2631
+ return;
2632
+ }
2633
+ task.state = TASK_STATES.failed;
2634
+ task.phase = 'failed';
2635
+ task.error = this.runErrorOf(error, task);
2636
+ task.endedAt = Date.now();
2637
+ } finally {
2638
+ await this.finishTask(task);
2639
+ }
2640
+ }
2641
+
2642
+ /**
2643
+ * Shape any thrown value from the EXECUTION path into the bounded error record.
2644
+ *
2645
+ * A session-placement refusal keeps its own `SESSION_*` code as a detail and is
2646
+ * reported as the job-level `JOB_CONVERSATION_UNAVAILABLE` — or, when the run was
2647
+ * a `continueFromTaskId` follow-up, `JOB_CONTINUATION_REFUSED` — because the cause
2648
+ * an operator needs is "this harness cannot place the run in a Workspace" or "this
2649
+ * thread cannot be continued", not the name of the missing service. It is never
2650
+ * mapped onto a generic execution failure: the run did not fail, it never started.
2651
+ * @param {unknown} error - thrown value.
2652
+ * @param {object} [task] - the task record, when the error belongs to one.
2653
+ * @returns {{ code: string, message: string, details?: object }} bounded error.
2654
+ */
2655
+ runErrorOf(error, task = null) {
2656
+ if (error instanceof SessionPlacementRefusal) return this.conversationErrorOf(error, task ?? {});
2657
+ if (error instanceof RunError) {
2658
+ return { code: error.code, message: error.message, details: redactDeep(error.details ?? null) };
2659
+ }
2660
+ return {
2661
+ code: typeof error?.code === 'string' ? error.code : JOB_CODES.internal,
2662
+ message: diagnostic(error?.message ?? error, 300),
2663
+ };
2664
+ }
2665
+
2666
+ /**
2667
+ * Make a cancelled task terminal and preserve its provenance.
2668
+ * @param {object} task - task record.
2669
+ * @param {string | null} [fallback] - provenance to record when nothing else did.
2670
+ * @returns {void}
2671
+ */
2672
+ finishCancelled(task, fallback = null) {
2673
+ task.state = TASK_STATES.cancelled;
2674
+ task.phase = 'cancelled';
2675
+ task.cancelledBy = task.cancelledBy ?? fallback ?? (task.cancelRequested ? 'request' : 'agent');
2676
+ task.endedAt = Date.now();
2677
+ }
2678
+
2679
+ /**
2680
+ * Build the activity monitor for one task.
2681
+ *
2682
+ * Thresholds come from the task's own frozen effective snapshot. They are
2683
+ * therefore immutable for the life of the run: `setMonitoring` affects the next
2684
+ * admission, never one already executing. The engine's clock and wait seams are
2685
+ * handed to every monitor so all of them observe one time source.
2686
+ * @param {object} task - admitted task record with `effective`.
2687
+ * @returns {object} the task's monitor.
2688
+ */
2689
+ createMonitor(task) {
2690
+ const monitoring = task.effective?.monitoring ?? null;
2691
+ return new TaskMonitor(task, {
2692
+ now: () => this.clock(),
2693
+ ...(this.observationWait === undefined ? {} : { wait: this.observationWait }),
2694
+ waitSliceMs: this.observeSliceMs,
2695
+ selfCheckSeconds: monitoring?.selfCheckSeconds ?? MONITORING_DEFAULTS.selfCheckSeconds,
2696
+ attentionSeconds: monitoring?.attentionSeconds ?? MONITORING_DEFAULTS.attentionSeconds,
2697
+ log: (message, detail) => this.deps?.logger?.warn?.(message, detail),
2698
+ });
2699
+ }
2700
+
2701
+ /**
2702
+ * Return this task's monitor, creating it only when there is none.
2703
+ *
2704
+ * There is exactly ONE monitor per task. A task may be observed before `execute`
2705
+ * creates its monitor (the task is `pending` but already admitted, so its frozen
2706
+ * thresholds are known), and the observation holds a reference to whatever it
2707
+ * got. Replacing the monitor later — which an unconditional assignment would do —
2708
+ * would leave that observer watching an object that never receives another event,
2709
+ * so it would stay silent forever. Creation therefore happens at most once, and
2710
+ * the threshold source is the frozen snapshot either way.
2711
+ * @param {object} task - task record (admitted, so `effective` is resolved).
2712
+ * @returns {object} the task's single monitor.
2713
+ */
2714
+ ensureMonitor(task) {
2715
+ if (task.monitor === null || task.monitor === undefined) task.monitor = this.createMonitor(task);
2716
+ return task.monitor;
2717
+ }
2718
+
2719
+ /**
2720
+ * Stop one task's monitor and release any observation waiting on it.
2721
+ *
2722
+ * Idempotent, and never touches the worker: an observation that ends is a reader
2723
+ * leaving, not a run being stopped. The activity is finalized at the task's own
2724
+ * end so a later view or a stored record cannot report an idle (or tool-elapsed)
2725
+ * span that keeps growing after the run stopped.
2726
+ * @param {object} task - task record.
2727
+ * @returns {void}
2728
+ */
2729
+ releaseMonitor(task) {
2730
+ const monitor = task?.monitor ?? null;
2731
+ if (monitor === null || monitor === undefined) return;
2732
+ try {
2733
+ monitor.dispose(Number.isFinite(task.endedAt) ? task.endedAt : this.clock());
2734
+ } catch {
2735
+ // A monitor that refuses to dispose is a defect, not a reason to leave a
2736
+ // task unsettled; the observer set is cleared below regardless.
2737
+ }
2738
+ }
2739
+
2740
+ /**
2741
+ * Whether a task currently has a native tool call outstanding.
2742
+ *
2743
+ * The monitor keeps the last tool span it was told about. What that means is the
2744
+ * ENGINE's judgement, not the monitor's: a run in its permission wait is not
2745
+ * "waiting on a tool" (the request carries its own reason), and a settled run is
2746
+ * not waiting on anything. So the monitor is asked for a duration, and the answer
2747
+ * about meaning is decided here.
2748
+ * @param {object} task - task record.
2749
+ * @returns {boolean} true when the summary should describe a running tool.
2750
+ */
2751
+ toolActive(task) {
2752
+ const monitor = task?.monitor ?? null;
2753
+ if (monitor === null || monitor === undefined || monitor.disposed === true) return false;
2754
+ if (task.permission?.pending !== null && task.permission?.pending !== undefined) return false;
2755
+ return LIVE.has(task.state) && monitor.activity.tool !== null;
2756
+ }
2757
+
2758
+ /**
2759
+ * The bounded, publishable activity block of one task view.
2760
+ *
2761
+ * Safe by construction: counts, timestamps and identifiers only. No transcript,
2762
+ * no reasoning, no tool arguments and no diff has a field here, so every existing
2763
+ * view (`get`, `list`, history, MCP) inherits a progress summary without
2764
+ * inheriting content.
2765
+ * @param {object} task - task record.
2766
+ * @returns {object | null} activity summary, or null for a task that never ran.
2767
+ */
2768
+ activityView(task) {
2769
+ const monitor = task?.monitor ?? null;
2770
+ if (monitor === null || monitor === undefined) return null;
2771
+ const at = this.clock();
2772
+ try {
2773
+ return monitor.snapshot({ at, toolActive: this.toolActive(task) });
2774
+ } catch {
2775
+ return null;
2776
+ }
2777
+ }
2778
+
2779
+ /**
2780
+ * Await one bounded observation of a task.
2781
+ *
2782
+ * This is the documented seam the HTTP adapter (a later work unit) turns into an
2783
+ * endpoint. It answers ONE question — "is there anything the commander should
2784
+ * know right now, or should this request simply wait?" — and reports why it
2785
+ * returned.
2786
+ *
2787
+ * Contract:
2788
+ *
2789
+ * * `waitMs` defaults to 25 s and is clamped to `[1, 25000]`. The wait is
2790
+ * BOUNDED BY ONE WAIT: when it expires with nothing to report the reason is
2791
+ * `heartbeat` and the caller re-issues. There is no internal re-wait, so the
2792
+ * documented bound is the real upper bound of one call.
2793
+ * * Reasons, in precedence order: `interrupted` (caller aborted, or the engine
2794
+ * was disposed — the WORKER keeps running), then any terminal state
2795
+ * (`ready`/`failed`/`cancelled`, which wins even over an `interrupted` caused
2796
+ * by engine teardown, because the run really did reach that outcome), then
2797
+ * `permission` (a per-call decision is outstanding), then `attention` (the
2798
+ * silence reached `attentionSeconds`, claimed by exactly one observer), then
2799
+ * `heartbeat`. Genuine progress never produces `attention`: it resets the
2800
+ * silence instead.
2801
+ * * The permission reason carries the FULL existing redacted request view,
2802
+ * including its exact fingerprint and completeness facts. A shortened
2803
+ * operation is not decidable, and an undecidable request is the one thing this
2804
+ * feature must never produce.
2805
+ * * An unknown task and another connection's task are the SAME refusal
2806
+ * (`JOB_TASK_NOT_FOUND`, same message, same details), so the answer cannot be
2807
+ * used to discover that an id exists.
2808
+ * * The checks are re-run after the wait, before the summary is built, and the
2809
+ * summary is built from the SAME task record the checks read. A permission
2810
+ * request or a finish that lands while the caller is waiting is therefore
2811
+ * reported, not lost.
2812
+ * * Aborting an observation releases only its own listener and timer. It never
2813
+ * cancels, restarts or resumes the worker, and never disturbs another
2814
+ * observer of the same task.
2815
+ * @param {string} taskId - task to observe.
2816
+ * @param {object} [options] - `connectionId`, `waitMs` (default 25000, max 25000), `signal`.
2817
+ * @returns {Promise<{ task: object, reason: string, permission: object | null, activity: object | null,
2818
+ * selfCheck: object | null, wait: { waitMs: number, waitedMs: number, activitySinceWait: boolean } }>} observation.
2819
+ * @throws {JobError} `JOB_TASK_NOT_FOUND` for an unknown or foreign task.
2820
+ */
2821
+ async observeTask(taskId, options = {}) {
2822
+ const task = this.taskForObservation(taskId, options?.connectionId);
2823
+ const waitMs = clampObserveWait(options?.waitMs);
2824
+ const signal = options?.signal ?? null;
2825
+
2826
+ if (this.aborted) return this.observationOf(task, OBSERVE_TASK_REASONS.interrupted, null, waitMs, 0, false);
2827
+ if (signal !== null && signal.aborted === true) {
2828
+ return this.observationOf(task, OBSERVE_TASK_REASONS.interrupted, null, waitMs, 0, false);
2829
+ }
2830
+
2831
+ // Exactly one monitor per task, created at most once (see `ensureMonitor`).
2832
+ const monitor = this.ensureMonitor(task);
2833
+
2834
+ // A task that has already ended owes the caller its outcome immediately: there
2835
+ // is nothing to wait for, and a `heartbeat` here would invite a pointless
2836
+ // re-request for a run that will never change again. The same is true of an
2837
+ // outstanding permission request, which is decidable right now.
2838
+ const immediate = this.settleReason(task);
2839
+ if (immediate !== null) {
2840
+ return this.observationOf(task, immediate, monitor, waitMs, 0, false);
2841
+ }
2842
+
2843
+ // ONE bounded wait, and nothing more. `waitMs` is the caller's promise: a
2844
+ // documented `<= 25 s` observation must never become two waits back to back,
2845
+ // which would double it and blow an adapter's own request timeout. Re-issuing
2846
+ // is the caller's loop (the MCP tool in the next unit), not this method's.
2847
+ const outcome = await this.waitForTaskReport(monitor, { waitMs, signal });
2848
+ let reason = isPublicReason(outcome.reason) ? outcome.reason : OBSERVE_TASK_REASONS.heartbeat;
2849
+
2850
+ // Late-event delivery: the summary is rebuilt from the record AFTER the wait,
2851
+ // and the checks below read the SAME `task` object the monitor loop examined.
2852
+ // A terminal state always wins — including over an `interrupted` produced by an
2853
+ // engine dispose, because the run really did reach an outcome — and a pending
2854
+ // request beats a silence report. `heartbeat` is the only reason that yields.
2855
+ const settled = this.settleReason(task);
2856
+ if (settled !== null) reason = settled;
2857
+ return this.observationOf(task, reason, monitor, waitMs, outcome.waitedMs, outcome.activitySinceWait);
2858
+ }
2859
+
2860
+ /**
2861
+ * Run one bounded internal wait against a task's monitor.
2862
+ *
2863
+ * The monitor's loop reads the task's own fields through the SAME record, so no
2864
+ * step here re-reads a stale copy. This method owns only the registration that
2865
+ * lets {@link dispose} release the waiter; it never touches the run.
2866
+ * @param {object} monitor - task monitor.
2867
+ * @param {object} input - `waitMs` and `signal`.
2868
+ * @returns {Promise<{ reason: string, waitedMs: number, activitySinceWait: boolean, selfCheck: object | null }>} outcome.
2869
+ */
2870
+ async waitForTaskReport(monitor, { waitMs, signal }) {
2871
+ const registration = { controller: new AbortController() };
2872
+ this.observers.add(registration);
2873
+ const forwarded = new AbortController();
2874
+ const forward = () => {
2875
+ try {
2876
+ forwarded.abort();
2877
+ registration.controller.abort();
2878
+ } catch {
2879
+ // Abort is idempotent.
2880
+ }
2881
+ };
2882
+ if (signal !== null) signal.addEventListener?.('abort', forward, { once: true });
2883
+ try {
2884
+ return await monitor.observe({ waitMs, signal: forwarded.signal });
2885
+ } finally {
2886
+ this.observers.delete(registration);
2887
+ if (signal !== null) signal.removeEventListener?.('abort', forward);
2888
+ }
2889
+ }
2890
+
2891
+ /**
2892
+ * The reason a task's current record implies right now, or null while it is
2893
+ * still running with nothing outstanding.
2894
+ *
2895
+ * Shared by the wait loop and the post-wait re-check, so the two can never
2896
+ * disagree about precedence.
2897
+ *
2898
+ * A terminal state comes FIRST. A task that has ended may still carry a stale
2899
+ * `permission.pending` block (a run stopped while a request was outstanding), and
2900
+ * reporting that as `permission` would offer a decision for a call that no longer
2901
+ * exists — and would keep offering it forever, because nothing will ever settle
2902
+ * it. A settled run is reported as settled, and the stored request is history.
2903
+ * @param {object} task - task record.
2904
+ * @returns {string | null} reason key, or null.
2905
+ */
2906
+ settleReason(task) {
2907
+ const terminal = terminalReason(task);
2908
+ if (terminal !== null) return terminal;
2909
+ if (task?.permission?.pending !== null && task?.permission?.pending !== undefined) {
2910
+ return OBSERVE_TASK_REASONS.permission;
2911
+ }
2912
+ return null;
2913
+ }
2914
+
2915
+ /**
2916
+ * Resolve the task one observation may read, refusing identically for every
2917
+ * task this caller cannot prove.
2918
+ * @param {unknown} taskId - caller-supplied id.
2919
+ * @param {unknown} connectionId - the caller's verified connection identity.
2920
+ * @returns {object} the task record.
2921
+ * @throws {JobError} `JOB_TASK_NOT_FOUND`, indistinguishable across causes.
2922
+ */
2923
+ taskForObservation(taskId, connectionId) {
2924
+ const requested = typeof taskId === 'string' ? taskId.trim() : '';
2925
+ const caller = typeof connectionId === 'string' && connectionId !== '' ? connectionId : null;
2926
+ const task = requested === '' || caller === null ? undefined : this.tasks.get(requested);
2927
+ const owner = task !== null && task !== undefined && typeof task.connectionId === 'string' && task.connectionId !== ''
2928
+ ? task.connectionId
2929
+ : null;
2930
+ // Unknown id, blank id, no verified caller, a task with no recorded owner and
2931
+ // another connection's task are one answer with one shape. The details carry
2932
+ // only what the caller itself supplied.
2933
+ if (task === undefined || owner === null || owner !== caller) {
2934
+ throw new JobError(JOB_CODES.taskNotFound, 'no such task for this connection', { taskId: requested });
2935
+ }
2936
+ return task;
2937
+ }
2938
+
2939
+ /**
2940
+ * Build the documented observation result.
2941
+ *
2942
+ * The permission reason carries the WHOLE redacted pending view — request id,
2943
+ * exact fingerprint, completeness, bounds, redacted arguments — because a
2944
+ * commander cannot decide a shortened operation. Everything else is the compact
2945
+ * task summary: no transcript, no execution text, no diff.
2946
+ * @param {object} task - task record.
2947
+ * @param {string} reason - reported reason.
2948
+ * @param {object | null} monitor - task monitor, for the self-check diagnostic.
2949
+ * @param {number} waitMs - the bound that applied.
2950
+ * @param {number} waitedMs - how long the wait actually took.
2951
+ * @param {boolean} activitySinceWait - whether activity arrived during the wait.
2952
+ * @returns {object} observation result.
2953
+ */
2954
+ observationOf(task, reason, monitor, waitMs, waitedMs, activitySinceWait) {
2955
+ const at = this.clock();
2956
+ const summary = this.observationSummary(task, at);
2957
+ const pending = task?.permission?.pending ?? null;
2958
+ const live = monitor ?? task?.monitor ?? null;
2959
+ const selfCheck = live === null || live === undefined ? null : live.snapshot({ at }).selfCheck;
2960
+ return {
2961
+ task: summary,
2962
+ reason,
2963
+ // The full, unshortened redacted request on the ONE reason that needs it.
2964
+ permission: reason === OBSERVE_TASK_REASONS.permission ? pending : null,
2965
+ activity: summary.activity,
2966
+ selfCheck,
2967
+ wait: { waitMs, waitedMs: Math.max(0, Math.trunc(waitedMs)), activitySinceWait: activitySinceWait === true },
2968
+ };
2969
+ }
2970
+
2971
+ /**
2972
+ * The compact task summary an observation returns.
2973
+ *
2974
+ * Deliberately narrower than {@link view}: it carries the facts a waiting caller
2975
+ * needs (identity, phase, timing, silence, the tool in flight, the frozen route)
2976
+ * and NONE of the evidence a reviewer reads (diff, execution text, review text).
2977
+ * @param {object} task - task record.
2978
+ * @param {number} at - reference time.
2979
+ * @returns {object} compact summary.
2980
+ */
2981
+ observationSummary(task, at) {
2982
+ const monitor = task?.monitor ?? null;
2983
+ const activity = monitor === null || monitor === undefined
2984
+ ? null
2985
+ : monitor.snapshot({ at, toolActive: this.toolActive(task) });
2986
+ const startedAt = Number.isFinite(task.startedAt) ? task.startedAt : task.createdAt;
2987
+ const endedAt = Number.isFinite(task.endedAt) ? task.endedAt : null;
2988
+ return {
2989
+ taskId: task.taskId,
2990
+ state: task.state,
2991
+ title: task.title ?? taskTitle(null, task.prompt),
2992
+ phase: task.phase,
2993
+ createdAt: task.createdAt ?? null,
2994
+ startedAt: task.startedAt ?? null,
2995
+ endedAt,
2996
+ elapsedMs: Math.max(0, (endedAt ?? at) - (Number.isFinite(startedAt) ? startedAt : at)),
2997
+ lastActivityAt: activity === null ? null : activity.lastActivityAt,
2998
+ currentTool: activity === null ? null : activity.currentTool,
2999
+ idleForMs: activity === null ? null : activity.idleForMs,
3000
+ waitingOn: activity === null ? null : activity.waitingOn,
3001
+ activity,
3002
+ selfCheck: monitor === null || monitor === undefined
3003
+ ? null
3004
+ : { episode: monitor.selfCheck.episode, checkedAt: monitor.selfCheck.checkedAt, verdict: monitor.selfCheck.verdict },
3005
+ // The route this task froze at admission. Reported as the frozen triple, not
3006
+ // re-resolved: a settings edit during the wait must not change what a
3007
+ // finished run is described as having used.
3008
+ route: this.observationRoute(task),
3009
+ connectionId: task.connectionId ?? null,
3010
+ // Stated so no consumer reads `awaiting-host-review` as acceptance.
3011
+ selfApproved: false,
3012
+ hostAcceptance: null,
3013
+ };
3014
+ }
3015
+
3016
+ /**
3017
+ * The frozen worker route of one task, for an observation summary.
3018
+ * @param {object} task - task record.
3019
+ * @returns {object | null} route.
3020
+ */
3021
+ observationRoute(task) {
3022
+ if (task?.effective === null || task?.effective === undefined) return null;
3023
+ return {
3024
+ providerId: task.effective.worker?.providerId ?? null,
3025
+ providerRoute: task.route?.providerRoute ?? null,
3026
+ model: task.route?.model ?? task.effective.worker?.model ?? null,
3027
+ reasoningEffort: task.route?.reasoningEffort ?? task.effective.worker?.reasoningEffort ?? null,
3028
+ isolation: task.effective.worker?.isolation ?? null,
3029
+ monitoring: {
3030
+ selfCheckSeconds: task.effective.monitoring?.selfCheckSeconds ?? null,
3031
+ attentionSeconds: task.effective.monitoring?.attentionSeconds ?? null,
3032
+ },
3033
+ };
3034
+ }
3035
+
3036
+ /**
3037
+ * Settle a terminal task: release its capacity (slot and leases) through the
3038
+ * single idempotent {@link finalize} path, then resolve its settlement promise.
3039
+ *
3040
+ * `finalize` is what decides whether the release is legal: it declines while a
3041
+ * native executor may still be writing, and records that refusal on the task.
3042
+ * @param {object} task - terminal task.
3043
+ * @returns {Promise<void>} resolves after bookkeeping.
3044
+ */
3045
+ async finishTask(task) {
3046
+ task.hostAcceptance = null;
3047
+ this.clearPreflightDeadline(task);
3048
+ // The run is over, so its answerer must go: an outstanding request is released
3049
+ // (the worker's paused tool call resumes `unavailable`) and the bridge can never
3050
+ // answer a request that outlived the run it belonged to.
3051
+ this.releasePermissionBridge(task, 'dispose');
3052
+ // The monitor is stopped BEFORE the record is persisted, so no observation can
3053
+ // still be waiting on a run that has already ended. The summary survives on the
3054
+ // task, so the stored view still says how much activity there was.
3055
+ this.releaseMonitor(task);
3056
+ await this.finalize(task);
3057
+ await this.persistHistory(task);
3058
+ task.settle();
3059
+ }
3060
+
3061
+ /**
3062
+ * Persist one terminal task's public view to the durable history store.
3063
+ *
3064
+ * Three deliberate properties:
3065
+ *
3066
+ * * The *view* is what is stored, so the history document inherits every
3067
+ * redaction the projection already applies — there is no second
3068
+ * serializer that could forget one.
3069
+ * * The write is bounded. A wedged data directory must not keep a terminal
3070
+ * task's cleanup pending, so exceeding the bound is recorded on the task as
3071
+ * `historyError` instead of being swallowed or retried forever.
3072
+ * * A missing store is not an error. Running without durable history is a
3073
+ * supported posture (the engine never reads history back to decide
3074
+ * anything), so `history === null` is silent while a *failing* store is loud.
3075
+ * @param {object} task - terminal task record.
3076
+ * @returns {Promise<void>} resolves after the attempt, never rejects.
3077
+ */
3078
+ async persistHistory(task) {
3079
+ const history = this.history;
3080
+ if (history === null || history === undefined || typeof history.save !== 'function') return;
3081
+ let timer = null;
3082
+ try {
3083
+ const view = this.view(task);
3084
+ const bounded = new Promise((resolvePromise, rejectPromise) => {
3085
+ timer = setTimeout(() => {
3086
+ rejectPromise(new JobError(JOB_CODES.historyFailed, 'the job history write exceeded its time budget', {
3087
+ code: 'HISTORY_WRITE_TIMEOUT',
3088
+ timeoutMs: HISTORY_WRITE_TIMEOUT_MS,
3089
+ }));
3090
+ }, HISTORY_WRITE_TIMEOUT_MS);
3091
+ timer.unref?.();
3092
+ Promise.resolve(history.save(view)).then(resolvePromise, rejectPromise);
3093
+ });
3094
+ await bounded;
3095
+ task.historyError = null;
3096
+ task.historySavedAt = Date.now();
3097
+ } catch (error) {
3098
+ // Recorded, not thrown: a history failure must not turn a completed task
3099
+ // into a failed one, and it must not escape into the release path.
3100
+ task.historyError = {
3101
+ code: typeof error?.code === 'string' ? error.code : JOB_CODES.historyFailed,
3102
+ message: diagnostic(error?.message ?? error, 300),
3103
+ };
3104
+ task.historySavedAt = null;
3105
+ } finally {
3106
+ if (timer !== null) clearTimeout(timer);
3107
+ }
3108
+ }
3109
+
3110
+ /**
3111
+ * Persist the minimal task-thread identity a later `continueFromTaskId` needs.
3112
+ *
3113
+ * Four deliberate properties, mirroring {@link persistHistory}:
3114
+ *
3115
+ * * the row is keyed by TASK, and holds only what a continuation is validated
3116
+ * against — the two paths, the DSH Workspace/Session ids, the isolation that
3117
+ * was used and (for a managed tree) that tree's ownership facts. No prompt,
3118
+ * transcript, output, usage figure or credential has a field;
3119
+ * * a failure is recorded on the task (`conversationError`) instead of thrown,
3120
+ * because losing the ability to *continue* this thread later is not a reason
3121
+ * to fail or un-finish the run that just succeeded;
3122
+ * * a missing store is silent: an engine constructed without one simply cannot
3123
+ * offer continuation, which is the safe default;
3124
+ * * an unplaced run (the additional review) records nothing, because it is not
3125
+ * part of the worker thread and must not become continuable.
3126
+ * @param {object} task - task record with a completed `task.execution`.
3127
+ * @returns {Promise<void>} resolves after the attempt, never rejects.
3128
+ */
3129
+ async rememberConversation(task) {
3130
+ const store = this.deps?.sessionStore ?? null;
3131
+ const placement = task.execution?.conversation ?? null;
3132
+ if (store === null || store === undefined || placement === null) return;
3133
+ const worktree = task.worktree === null || task.worktree === undefined ? null : task.worktree;
3134
+ try {
3135
+ const saved = await rememberSession(store, {
3136
+ workspaceId: placement.workspaceId,
3137
+ sessionId: placement.sessionId,
3138
+ }, {
3139
+ taskId: task.taskId,
3140
+ sourcePath: task.sourcePath,
3141
+ executionPath: task.executionPath,
3142
+ isolation: task.effective?.worker?.isolation ?? null,
3143
+ // A worktree row carries the tree's identity so a follow-up can prove it is
3144
+ // reusing the same tree instead of a fresh one.
3145
+ worktreeId: worktree === null
3146
+ ? null
3147
+ : (typeof worktree.worktreeId === 'string' && worktree.worktreeId !== ''
3148
+ ? worktree.worktreeId
3149
+ : (typeof worktree.taskId === 'string' ? worktree.taskId : task.taskId)),
3150
+ worktreeState: worktree === null ? null : (typeof worktree.state === 'string' ? worktree.state : null),
3151
+ });
3152
+ task.conversationSaved = saved;
3153
+ task.conversationError = null;
3154
+ } catch (error) {
3155
+ task.conversationSaved = false;
3156
+ task.conversationError = {
3157
+ code: typeof error?.code === 'string' ? error.code : 'CONVERSATION_SAVE_FAILED',
3158
+ message: diagnostic(error?.message ?? error, 300),
3159
+ };
3160
+ }
3161
+ }
3162
+
3163
+ /**
3164
+ * Mark a prepared tree complete and record its final metadata.
3165
+ *
3166
+ * The tree is kept, never deleted and never merged: it is the evidence a host
3167
+ * reviews, and an unreviewed deletion would destroy the only proof of what the
3168
+ * run changed. A tree that cannot be marked stays recorded with the reason, so
3169
+ * the host can still review or dispose of it explicitly.
3170
+ * @param {object} task - task record holding a prepared tree.
3171
+ * @returns {void}
3172
+ */
3173
+ completeWorktree(task) {
3174
+ if (task.worktree === null || task.executionPath === null) return;
3175
+ if (task.worktreeCompleted === true) return;
3176
+ task.worktreeCompleted = true;
3177
+ const manager = this.deps?.worktrees;
3178
+ if (typeof manager?.markComplete !== 'function') return;
3179
+ try {
3180
+ const metadata = manager.markComplete(task.executionPath);
3181
+ if (metadata !== null && typeof metadata === 'object') {
3182
+ task.worktree = { ...task.worktree, ...metadata };
3183
+ }
3184
+ } catch (error) {
3185
+ task.worktree = {
3186
+ ...task.worktree,
3187
+ markCompleteError: {
3188
+ code: typeof error?.code === 'string' ? error.code : 'WORKTREE_MARK_FAILED',
3189
+ message: diagnostic(error?.message ?? error, 300),
3190
+ },
3191
+ };
3192
+ }
3193
+ }
3194
+
3195
+ /**
3196
+ * Run the optional independent review against the frozen review route.
3197
+ * @param {object} task - completed-execution task.
3198
+ * @returns {Promise<object>} review record.
3199
+ */
3200
+ async runReview(task) {
3201
+ if (task.effective.review.enabled !== true) {
3202
+ return { state: REVIEW_STATES.disabled, verdict: null, text: '', error: null };
3203
+ }
3204
+ if (task.reviewRouteError !== null) {
3205
+ // A review routing failure is a review failure, not a task failure, and it
3206
+ // is never an approval.
3207
+ return {
3208
+ state: REVIEW_STATES.failed,
3209
+ verdict: null,
3210
+ text: '',
3211
+ error: task.reviewRouteError,
3212
+ denials: [],
3213
+ selection: reviewSelection(task.effective.review, null),
3214
+ };
3215
+ }
3216
+ const route = task.reviewRoute;
3217
+ if (route === null) {
3218
+ return {
3219
+ state: REVIEW_STATES.failed,
3220
+ verdict: null,
3221
+ text: '',
3222
+ error: {
3223
+ code: 'REVIEW_ROUTING_REFUSED',
3224
+ message: 'the review route was not confirmed before execution',
3225
+ cause: null,
3226
+ },
3227
+ denials: [],
3228
+ selection: reviewSelection(task.effective.review, null),
3229
+ };
3230
+ }
3231
+ if (this.isCancelled(task)) {
3232
+ return {
3233
+ state: REVIEW_STATES.cancelled,
3234
+ verdict: null,
3235
+ text: '',
3236
+ error: { code: 'REVIEW_CANCELLED', message: 'the additional review was cancelled before it started' },
3237
+ denials: [],
3238
+ selection: reviewSelection(task.effective.review, route),
3239
+ };
3240
+ }
3241
+ const prompt = buildReviewPrompt({
3242
+ taskId: task.taskId,
3243
+ taskPrompt: task.prompt,
3244
+ workerSummary: task.execution?.text ?? '',
3245
+ evidence: task.diff,
3246
+ });
3247
+ const result = await reviewWork(this.deps, {
3248
+ taskId: task.taskId,
3249
+ cwd: task.executionPath,
3250
+ selection: {
3251
+ // The public id is what an operator recognises; the native route is
3252
+ // carried alongside it and is not disguised as a profile id.
3253
+ providerId: task.effective.review.providerId,
3254
+ providerRoute: route.providerRoute,
3255
+ model: route.model,
3256
+ reasoningEffort: route.reasoningEffort,
3257
+ },
3258
+ prompt,
3259
+ evidence: task.diff,
3260
+ timeoutMs: Math.min(task.effective.worker.timeoutSeconds, 1800) * 1000,
3261
+ // Cancellation and revocation reach the reviewer through the same signal.
3262
+ signal: task.controller.signal,
3263
+ });
3264
+ return {
3265
+ state: result.state,
3266
+ verdict: result.verdict,
3267
+ text: result.text ?? '',
3268
+ error: result.error ?? null,
3269
+ denials: result.denials ?? [],
3270
+ denialsDelivered: (result.denials ?? []).length,
3271
+ selection: result.selection ?? reviewSelection(task.effective.review, route),
3272
+ };
3273
+ }
3274
+
3275
+ /**
3276
+ * Request cancellation of one task.
3277
+ * @param {string} taskId - task to cancel.
3278
+ * @param {string} reason - recorded provenance.
3279
+ * @returns {Promise<object>} the task view.
3280
+ */
3281
+ async cancel(taskId, reason = 'request') {
3282
+ const task = this.tasks.get(taskId);
3283
+ if (task === undefined) throw new JobError(JOB_CODES.taskNotFound, 'no such task', { taskId });
3284
+ if (TERMINAL.has(task.state)) return this.view(task);
3285
+ this.abortTask(task, reason);
3286
+ // Give the run a bounded window to observe the cancellation and clean up.
3287
+ await Promise.race([
3288
+ task.settled ?? Promise.resolve(),
3289
+ new Promise((resolvePromise) => { setTimeout(resolvePromise, SETTLE_TIMEOUT_MS).unref?.(); }),
3290
+ ]);
3291
+ return this.view(task);
3292
+ }
3293
+
3294
+ /**
3295
+ * Read one task.
3296
+ * @param {string} taskId - task id.
3297
+ * @param {object} [options] - `includePrompt` adds the prompt text.
3298
+ * @returns {object} task view.
3299
+ */
3300
+ get(taskId, options = {}) {
3301
+ const task = this.tasks.get(taskId);
3302
+ if (task === undefined) throw new JobError(JOB_CODES.taskNotFound, 'no such task', { taskId });
3303
+ return this.view(task, options);
3304
+ }
3305
+
3306
+ /**
3307
+ * List tasks, optionally filtered by connection.
3308
+ * @param {object} [options] - `connectionId`.
3309
+ * @returns {object[]} task views, newest first.
3310
+ */
3311
+ list(options = {}) {
3312
+ const out = [];
3313
+ for (const task of this.tasks.values()) {
3314
+ if (options.connectionId !== undefined && task.connectionId !== options.connectionId) continue;
3315
+ out.push(this.view(task));
3316
+ }
3317
+ return out.sort((a, b) => b.createdAt - a.createdAt);
3318
+ }
3319
+
3320
+ /**
3321
+ * Public projection of one task.
3322
+ *
3323
+ * The projection is structural, not incidental: no credential, no provider
3324
+ * endpoint, and no un-redacted text leaves this method. `workspacePath` is the
3325
+ * path the work actually ran in; `sourcePath` is the authorized repository.
3326
+ * @param {object} task - task record.
3327
+ * @param {object} [options] - `includePrompt`.
3328
+ * @returns {object} redacted view.
3329
+ */
3330
+ view(task, options = {}) {
3331
+ const effective = task.effective === null ? null : {
3332
+ worker: { ...task.effective.worker },
3333
+ review: { ...task.effective.review },
3334
+ // The conversation policy this task ran under. It is a rule, not a stored
3335
+ // setting: a new submission starts a new DSH conversation, and a follow-up
3336
+ // continues the thread named by `continueFromTaskId`.
3337
+ conversation: { ...task.effective.conversation },
3338
+ // The silence thresholds this task froze at admission. Published so a reader
3339
+ // can interpret the activity block without consulting a settings document
3340
+ // that may have changed since.
3341
+ monitoring: { ...(task.effective.monitoring ?? MONITORING_DEFAULTS) },
3342
+ provenance: task.effective.provenance,
3343
+ };
3344
+ const view = {
3345
+ taskId: task.taskId,
3346
+ state: task.state,
3347
+ title: task.title ?? taskTitle(null, task.prompt),
3348
+ phase: task.phase,
3349
+ createdAt: task.createdAt,
3350
+ startedAt: task.startedAt,
3351
+ endedAt: task.endedAt,
3352
+ sourcePath: task.sourcePath,
3353
+ workspacePath: task.executionPath ?? task.sourcePath,
3354
+ executionWorkspacePath: task.executionPath,
3355
+ isolation: effective === null ? null : effective.worker.isolation,
3356
+ connectionId: task.connectionId,
3357
+ grantId: task.grantId,
3358
+ authorization: task.authorization,
3359
+ effective,
3360
+ // The public id is the operator's profile id; the native route is a
3361
+ // separate field and never replaces it.
3362
+ route: task.route === null ? null : {
3363
+ providerId: effective === null ? null : effective.worker.providerId,
3364
+ providerRoute: task.route.providerRoute,
3365
+ model: task.route.model,
3366
+ reasoningEffort: task.route.reasoningEffort,
3367
+ },
3368
+ // Frozen during preflight: a later settings edit does not change it.
3369
+ reviewRoute: task.reviewRoute === null ? null : {
3370
+ providerId: effective === null ? null : effective.review.providerId,
3371
+ providerRoute: task.reviewRoute.providerRoute,
3372
+ model: task.reviewRoute.model,
3373
+ reasoningEffort: task.reviewRoute.reasoningEffort,
3374
+ },
3375
+ reviewRouteError: task.reviewRouteError,
3376
+ worktree: task.worktree,
3377
+ baseline: task.baseline,
3378
+ diff: task.diff,
3379
+ execution: task.execution === null ? null : {
3380
+ workspacePath: task.execution.workspacePath ?? task.executionPath,
3381
+ outcome: task.execution.outcome,
3382
+ text: task.execution.text,
3383
+ reasoningOnly: task.execution.reasoningOnly,
3384
+ usage: task.execution.usage,
3385
+ turnEnd: task.execution.turnEnd,
3386
+ agentId: task.execution.agentId,
3387
+ sessionId: task.execution.sessionId,
3388
+ // The provider/model/effort actually installed on the agent this run
3389
+ // drove, and the request budget. Observable for BOTH paths: a placed run
3390
+ // drives a resolved Agent, so `agents.create` options cannot be read.
3391
+ selection: task.execution.selection ?? null,
3392
+ maxTokens: task.execution.maxTokens ?? null,
3393
+ conversation: task.execution.conversation ?? null,
3394
+ cancelCause: task.execution.cancelCause,
3395
+ error: task.execution.error,
3396
+ },
3397
+ // Where the run's conversation was placed in DSH. `workspaceId` is the group an
3398
+ // operator sees; `kind` is `new` or `continuation`, and `continuedFromTaskId`
3399
+ // names the task whose thread this run continued (null for a new one).
3400
+ conversation: task.execution?.conversation ?? null,
3401
+ // Frozen on the task at creation, so the record states the intent even when
3402
+ // the run never got as far as driving a conversation.
3403
+ continueFromTaskId: task.continueFromTaskId ?? null,
3404
+ conversationSaved: task.conversationSaved,
3405
+ conversationError: task.conversationError,
3406
+ review: task.review,
3407
+ error: task.error,
3408
+ cancelledBy: task.cancelledBy,
3409
+ // The per-call permission surface of this run: whether it was bridged, the
3410
+ // request the commander may still decide (redacted), the settled trail, and
3411
+ // the standing mode the decision did NOT change. Present on every task, so a
3412
+ // reader never has to infer "no bridge" from a missing field.
3413
+ permission: this.permissionView(task),
3414
+ // The approval stance the run installed and read back (`never` without a
3415
+ // bridge, `ask` with an armed one), recorded from the run itself.
3416
+ approval: task.execution?.approval ?? null,
3417
+ // A bounded progress summary: counts, timestamps and the tool in flight. It
3418
+ // carries no model text, no reasoning, no tool arguments and no diff, so the
3419
+ // ordinary task view can show "still working, last activity 12s ago" without
3420
+ // becoming a second transcript.
3421
+ activity: this.activityView(task),
3422
+ hostAcceptance: task.hostAcceptance,
3423
+ // Stated explicitly so no consumer can read `awaiting-host-review` as
3424
+ // "done and approved".
3425
+ selfApproved: false,
3426
+ };
3427
+ if (options.includePrompt === true) view.prompt = redactText(task.prompt);
3428
+ return redactDeep(view);
3429
+ }
3430
+
3431
+ /**
3432
+ * Bound the in-memory task map: oldest terminal records are dropped first, and
3433
+ * a live task is never dropped.
3434
+ * @returns {void}
3435
+ */
3436
+ prune() {
3437
+ if (this.tasks.size <= MAX_RETAINED_TASKS) return;
3438
+ const terminal = [...this.tasks.values()]
3439
+ .filter((task) => TERMINAL.has(task.state))
3440
+ .sort((a, b) => (a.endedAt ?? a.createdAt) - (b.endedAt ?? b.createdAt));
3441
+ for (const task of terminal) {
3442
+ if (this.tasks.size <= MAX_RETAINED_TASKS) break;
3443
+ this.tasks.delete(task.taskId);
3444
+ }
3445
+ }
3446
+
3447
+ /**
3448
+ * Abort every live task, stop the timers, and release every lease. Called on
3449
+ * dispose. Prepared worktrees are not deleted: a finished tree is evidence.
3450
+ * @returns {Promise<number>} number of tasks asked to stop.
3451
+ */
3452
+ async dispose() {
3453
+ this.aborted = true;
3454
+ this.stopListening();
3455
+ // Every observation still waiting is released, and nothing else: an observer
3456
+ // is a reader, so ending it must not be mistaken for ending the run. The
3457
+ // monitors are disposed with their tasks below.
3458
+ for (const registration of [...this.observers]) {
3459
+ try {
3460
+ registration.controller.abort();
3461
+ } catch {
3462
+ // Abort is idempotent.
3463
+ }
3464
+ }
3465
+ this.observers.clear();
3466
+ let count = 0;
3467
+ for (const task of this.tasks.values()) {
3468
+ // Every task's monitor is stopped, terminal or not: a monitor outliving the
3469
+ // engine would keep a waiter alive against a task nobody may read again.
3470
+ this.releaseMonitor(task);
3471
+ if (TERMINAL.has(task.state)) {
3472
+ // A terminal task may still hold a bridge if its own teardown has not run
3473
+ // yet; disposing is idempotent and cannot answer anything after this point.
3474
+ this.releasePermissionBridge(task, 'dispose');
3475
+ continue;
3476
+ }
3477
+ this.abortTask(task, 'dispose');
3478
+ // Teardown is not a cancel: the answerer goes away, so the worker's paused
3479
+ // call must be told the channel is gone rather than that it was withdrawn.
3480
+ this.releasePermissionBridge(task, 'dispose');
3481
+ count += 1;
3482
+ }
3483
+ await Promise.race([
3484
+ Promise.allSettled([...this.tasks.values()].map((task) => task.settled ?? Promise.resolve())),
3485
+ new Promise((resolvePromise) => { setTimeout(resolvePromise, SETTLE_TIMEOUT_MS).unref?.(); }),
3486
+ ]);
3487
+ this.locks.releaseAll();
3488
+ this.aborted = true;
3489
+ return count;
3490
+ }
3491
+ }
3492
+
3493
+ /**
3494
+ * Clamp one caller-requested observation wait to the documented bound.
3495
+ *
3496
+ * The ceiling is part of the contract, not a courtesy: an adapter must be able to
3497
+ * promise that a request returns within 25 seconds. A missing, negative or
3498
+ * non-finite request takes the default rather than a wild value.
3499
+ * @param {unknown} waitMs - requested wait in milliseconds.
3500
+ * @returns {number} a whole number of milliseconds within `[1, OBSERVE_WAIT_MS]`.
3501
+ */
3502
+ function clampObserveWait(waitMs) {
3503
+ if (typeof waitMs !== 'number' || !Number.isFinite(waitMs) || waitMs <= 0) return OBSERVE_WAIT_MS;
3504
+ return Math.min(OBSERVE_WAIT_MS, Math.max(1, Math.trunc(waitMs)));
3505
+ }
3506
+
3507
+ /**
3508
+ * Whether an invalidation event concerns one task.
3509
+ * @param {object} task - task record.
3510
+ * @param {object} event - invalidation event.
3511
+ * @returns {boolean} true when the task's authorization is gone.
3512
+ */
3513
+ function matchesInvalidation(task, event) {
3514
+ if (event === null || typeof event !== 'object') return false;
3515
+ if (event.kind === 'all') return true;
3516
+ if (event.kind === 'connection') {
3517
+ return task.connectionId !== null && task.connectionId === event.connectionId;
3518
+ }
3519
+ if (event.kind === 'grant') {
3520
+ if (task.grantId === null || event.grantId !== task.grantId) return false;
3521
+ return event.connectionId === undefined || task.connectionId === event.connectionId;
3522
+ }
3523
+ return false;
3524
+ }
3525
+
3526
+ /**
3527
+ * Extract a native route id from a value the provider registry produced.
3528
+ * @param {unknown} value - string, `{ id }`, `{ route }` or `{ providerRoute }`.
3529
+ * @returns {string | null} route id.
3530
+ */
3531
+ function nativeRouteId(value) {
3532
+ if (typeof value === 'string' && value !== '') return value;
3533
+ if (value === null || typeof value !== 'object') return null;
3534
+ for (const key of ['id', 'route', 'providerRoute']) {
3535
+ const candidate = value[key];
3536
+ if (typeof candidate === 'string' && candidate !== '') return candidate;
3537
+ }
3538
+ return null;
3539
+ }
3540
+
3541
+ /**
3542
+ * Compare two workspace paths the way the lock registry keys them.
3543
+ * @param {string} a - first path.
3544
+ * @param {string} b - second path.
3545
+ * @returns {boolean} true when they name the same directory.
3546
+ */
3547
+ function samePath(a, b) {
3548
+ if (typeof a !== 'string' || typeof b !== 'string') return false;
3549
+ const normalize = (value) => {
3550
+ const trimmed = value.replace(/[\\/]+$/, '');
3551
+ return process.platform === 'win32' ? trimmed.toLowerCase() : trimmed;
3552
+ };
3553
+ return normalize(a) === normalize(b);
3554
+ }
3555
+
3556
+ /**
3557
+ * The placeholder a redacted path segment is rewritten to.
3558
+ */
3559
+ const PATH_MASK_SEGMENT = 'masks-user-profile-segment';
3560
+
3561
+ /**
3562
+ * Whether a persisted path cannot prove which directory it names.
3563
+ *
3564
+ * Durable documents are projected through redaction, which replaces an
3565
+ * account-identifying directory name with the placeholder above. A path carrying that
3566
+ * placeholder is a shortened spelling: nothing can prove which directory stood there,
3567
+ * so it is never compared into a match and is treated exactly like a missing path — the
3568
+ * mask only ever causes a refusal, it never stands for equality. A real directory whose
3569
+ * name merely *starts with* the placeholder is still its own directory, which is why the
3570
+ * test is for the whole segment.
3571
+ * @param {unknown} value - candidate path.
3572
+ * @returns {boolean} true when the path was rewritten and can only be refused.
3573
+ */
3574
+ function recordedPathIsMasked(value) {
3575
+ if (typeof value !== 'string') return false;
3576
+ return value
3577
+ .split(/[\\/]+/)
3578
+ .some((part) => part.trim() === PATH_MASK_SEGMENT);
3579
+ }
3580
+
3581
+ /**
3582
+ * Review selection projection for a review that never ran.
3583
+ * @param {object} review - effective review block.
3584
+ * @param {object | null} route - frozen route, if any.
3585
+ * @returns {object} selection summary.
3586
+ */
3587
+ function reviewSelection(review, route) {
3588
+ return {
3589
+ providerId: review?.providerId ?? null,
3590
+ model: route?.model ?? review?.model ?? null,
3591
+ reasoningEffort: route?.reasoningEffort ?? review?.reasoningEffort ?? null,
3592
+ };
3593
+ }
3594
+
3595
+ /**
3596
+ * Validate the shape a caller-supplied override may take before it reaches the
3597
+ * settings validator. Kept here so the engine never trusts a raw object.
3598
+ * @param {unknown} value - raw override object.
3599
+ * @returns {object} shallow copy with only known keys.
3600
+ */
3601
+ export function sanitizeOverrides(value) {
3602
+ if (value === null || value === undefined) return {};
3603
+ if (typeof value !== 'object' || Array.isArray(value)) {
3604
+ throw new JobError(JOB_CODES.overrideInvalid, 'overrides must be an object', {});
3605
+ }
3606
+ const allowed = ['providerId', 'model', 'reasoningEffort', 'timeoutSeconds', 'isolation'];
3607
+ const out = {};
3608
+ for (const key of allowed) {
3609
+ if (value[key] !== undefined) out[key] = value[key];
3610
+ }
3611
+ return out;
3612
+ }
3613
+
3614
+ export { AuthError, AUTH_CODES, defaultSettings };