dsh-taskbridge 1.4.2 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +34 -2
  2. package/README.md +10 -8
  3. package/bin/dsh-delegate-mcp.d.ts +20 -3
  4. package/bin/dsh-delegate-mcp.js +15 -0
  5. package/codex/dsh-taskbridge.toml +180 -16
  6. package/docs/INTRODUCTION.md +2 -2
  7. package/docs/INTRODUCTION.zh.md +2 -2
  8. package/docs/codex-integration.md +11 -13
  9. package/docs/conversation-placement.md +44 -7
  10. package/docs/plugin-market.md +1 -1
  11. package/docs/redaction-contract.md +47 -4
  12. package/docs/releases/1.5.0-token-benchmark.zh.md +73 -0
  13. package/docs/releases/1.5.0.zh.md +51 -0
  14. package/docs/releases/1.5.1.zh.md +70 -0
  15. package/docs/runtime-compatibility.md +4 -4
  16. package/docs/silent-wait.md +157 -3
  17. package/docs/taskbridge-upgrade.md +1 -1
  18. package/docs/worker-permissions.md +154 -17
  19. package/lib/client.js +298 -103
  20. package/package.json +9 -3
  21. package/src/client/api.js +315 -34
  22. package/src/client/index.jsx +151 -67
  23. package/src/codex/installer.js +251 -11
  24. package/src/config/redact.js +72 -11
  25. package/src/http/execution-plane.js +124 -10
  26. package/src/index.d.ts +347 -0
  27. package/src/index.js +88 -5
  28. package/src/jobs/activity.js +102 -9
  29. package/src/jobs/continuation-identity.js +283 -0
  30. package/src/jobs/engine.js +491 -55
  31. package/src/jobs/history.js +96 -0
  32. package/src/mcp/continuation.js +317 -0
  33. package/src/mcp/metrics.js +366 -0
  34. package/src/mcp/server.js +1203 -53
  35. package/src/mcp/wait.js +338 -73
  36. package/src/review/prompts.js +145 -126
  37. package/src/runtime/agent-runner.js +330 -0
  38. package/src/runtime/permissions.js +192 -2
  39. package/src/runtime/question-call.js +162 -0
  40. package/src/runtime/questions.js +909 -0
  41. package/src/runtime/sandbox.js +363 -358
  42. package/src/runtime/session-placement.js +1207 -1121
  43. package/src/version.js +121 -0
  44. package/src/workspace/worktrees.js +70 -4
@@ -75,8 +75,17 @@ import { resolveRoute } from '../model/routing.js';
75
75
  import { PROVIDER_SET_CODES, managedProvidersOf } from '../model/providers.js';
76
76
  import { RUN_OUTCOMES, RunError, SessionPlacementRefusal, diagnostic, runAgent } from '../runtime/agent-runner.js';
77
77
  import { PermissionBridge, PermissionError, PERMISSION_CODES } from '../runtime/permissions.js';
78
+ import { QuestionBridge, QuestionError, QUESTION_CODES } from '../runtime/questions.js';
78
79
  import { DELEGATE_SANDBOX_MODE } from '../runtime/sandbox.js';
79
80
  import { rememberSession, SESSION_CODES } from '../runtime/session-placement.js';
81
+ import {
82
+ continuationIdentityOf,
83
+ isPathDigest,
84
+ pathDigest,
85
+ recordedDirectoryIs,
86
+ recordedPathIsMasked,
87
+ sameRecordedDirectory,
88
+ } from './continuation-identity.js';
80
89
  import { taskTitle } from './title.js';
81
90
  import { REVIEW_STATES, reviewWork } from '../review/reviewer.js';
82
91
  import { buildReviewPrompt, buildWorkerPrompt } from '../review/prompts.js';
@@ -261,6 +270,10 @@ const HOST_REVIEW_BY = 'host-commander';
261
270
  * new lifecycle.
262
271
  */
263
272
  const PHASE_AWAITING_PERMISSION = 'awaiting-permission';
273
+ // A distinct phase for a waiting QUESTION, because the two waits need different
274
+ // answers and only one of them can grant anything. The task state stays `running`
275
+ // either way, so no existing reader has to learn a new lifecycle value.
276
+ const PHASE_AWAITING_QUESTION = 'awaiting-question';
264
277
  const PHASE_EXECUTE = 'execute';
265
278
 
266
279
  /**
@@ -294,6 +307,10 @@ export const OBSERVE_TASK_REASONS = Object.freeze({
294
307
  heartbeat: 'heartbeat',
295
308
  attention: 'attention',
296
309
  permission: 'permission',
310
+ // The worker asked a human a question through the native question channel. It is a
311
+ // distinct reason from `permission` because answering it grants NOTHING: the
312
+ // commander answers, and any widening still needs its own approval request.
313
+ question: 'question',
297
314
  ready: 'ready',
298
315
  failed: 'failed',
299
316
  cancelled: 'cancelled',
@@ -652,6 +669,12 @@ export class JobEngine {
652
669
  // timer when the request settles, so an approval wait can never be charged
653
670
  // to the execution timeout.
654
671
  permission: { bridge: null, pending: null, evidence: [], pausedAt: null, pausedExecutionMs: 0 },
672
+ // The ordinary-question surface of this run, deliberately SEPARATE from the
673
+ // permission block: a question can never grant access, so it must not be readable
674
+ // as an approval. `pending` is the one question set the worker is waiting on,
675
+ // `evidence` is the bounded settled trail, and `pausedExecutionMs` is the same
676
+ // account the approval wait keeps: time spent waiting for a human is not work.
677
+ question: { bridge: null, pending: null, evidence: [], pausedAt: null, pausedExecutionMs: 0 },
655
678
  // The activity monitor for this run. Created with the task, fed from the
656
679
  // runner's `onEvent` hook, and disposed with the task: its counters describe
657
680
  // THIS run and must not outlive it. It holds metadata only (counts,
@@ -773,10 +796,24 @@ export class JobEngine {
773
796
  // project setting changed after its parent ran, use the parent's isolation
774
797
  // so the follow-up reaches the same checkout or the same managed worktree.
775
798
  overrides.isolation = parentIsolation;
799
+ // The Agent Teams decision follows the same rule as isolation for a CONTINUATION:
800
+ // it is inherited from the parent UNLESS the dispatcher states it explicitly, so a
801
+ // follow-up keeps the chain's team mode instead of silently flipping it. `null`
802
+ // (no choice anywhere) stays `null` and the Session keeps its own mode.
803
+ if (overrides.agentTeams === undefined && typeof task.continuationRecord.agentTeams === 'boolean') {
804
+ overrides.agentTeams = task.continuationRecord.agentTeams;
805
+ }
776
806
  }
777
807
  let effective;
778
808
  try {
779
- effective = resolveEffectiveConfig(settings, { projectPath: sourcePath, overrides });
809
+ // `agentTeams` is a per-run DSH Session choice, not a settings field: it is frozen
810
+ // on the task below and handed to the runner, and the settings validator must
811
+ // never see it.
812
+ const { agentTeams: teamChoice, ...settingsOverrides } = overrides;
813
+ effective = resolveEffectiveConfig(settings, { projectPath: sourcePath, overrides: settingsOverrides });
814
+ // Frozen on the task so the view, the run and a later continuation all state the
815
+ // SAME explicit decision. `null` = the commander made no choice for this task.
816
+ task.agentTeams = typeof teamChoice === 'boolean' ? teamChoice : null;
780
817
  } catch (error) {
781
818
  throw new JobError(JOB_CODES.routingRefused, error?.message ?? 'the effective configuration was refused', {
782
819
  cause: error?.code ?? null,
@@ -1596,6 +1633,10 @@ export class JobEngine {
1596
1633
  state: parent.state,
1597
1634
  sourcePath: parent.sourcePath,
1598
1635
  executionWorkspacePath: parent.executionPath,
1636
+ // A live record keeps its own exact paths and their digests, so the same
1637
+ // proof a durable row carries is available without a projection.
1638
+ sourcePathDigest: pathDigest(parent.sourcePath),
1639
+ executionPathDigest: pathDigest(parent.executionPath),
1599
1640
  isolation: parent.effective?.worker?.isolation ?? null,
1600
1641
  conversation: parent.execution?.conversation ?? null,
1601
1642
  };
@@ -1606,6 +1647,8 @@ export class JobEngine {
1606
1647
  state: durable.state ?? null,
1607
1648
  sourcePath: durable.sourcePath ?? null,
1608
1649
  executionWorkspacePath: durable.executionWorkspacePath ?? null,
1650
+ sourcePathDigest: durable.sourcePathDigest ?? null,
1651
+ executionPathDigest: durable.executionPathDigest ?? null,
1609
1652
  isolation: durable.isolation ?? null,
1610
1653
  conversation: durable.execution?.conversation ?? null,
1611
1654
  };
@@ -1731,17 +1774,23 @@ export class JobEngine {
1731
1774
  SESSION_CODES.continuationState, typeof state === 'string' ? state : 'no recorded end state');
1732
1775
  }
1733
1776
  // Paths are proof, not a hint: a value written through a projection that rewrote it
1734
- // (a mask) cannot say which directory it named, so it is refused exactly like a
1735
- // missing one. No path, connection or isolation value is ever a wildcard.
1736
- for (const [field, session] of [
1737
- ['sourcePath', SESSION_CODES.continuationWorkspaceMismatch],
1738
- ['executionWorkspacePath', SESSION_CODES.continuationUnavailable],
1777
+ // (a mask) can no longer say which directory it named, so it has to be backed by the
1778
+ // digest the same row recorded. Neither a path nor a digest is ever a wildcard, and a
1779
+ // row that proves neither is refused exactly like one with no path at all. This is
1780
+ // only reached for a path that REALLY was shortened: the redaction pattern itself is
1781
+ // narrow (see `config/redact.js`), so an ordinary checkout such as this one keeps its
1782
+ // readable path and is compared directly.
1783
+ for (const [field, digestField, session] of [
1784
+ ['sourcePath', 'sourcePathDigest', SESSION_CODES.continuationWorkspaceMismatch],
1785
+ ['executionWorkspacePath', 'executionPathDigest', SESSION_CODES.continuationUnavailable],
1739
1786
  ]) {
1740
- if (typeof row[field] !== 'string' || row[field].trim() === '' || recordedPathIsMasked(row[field])) {
1787
+ const value = row[field];
1788
+ if (typeof value !== 'string' || value.trim() === ''
1789
+ || (recordedPathIsMasked(value) && !isPathDigest(row[digestField]))) {
1741
1790
  throw refuse('the named task has no reliably recorded path, so its conversation cannot be continued', session, `unusable recorded ${field}`);
1742
1791
  }
1743
1792
  }
1744
- if (!samePath(row.sourcePath, sourcePath)) {
1793
+ if (!recordedDirectoryIs({ path: row.sourcePath, digest: row.sourcePathDigest }, sourcePath)) {
1745
1794
  throw refuse('the named task belongs to another source repository, so its conversation was not continued',
1746
1795
  SESSION_CODES.continuationWorkspaceMismatch, 'different source repository');
1747
1796
  }
@@ -1763,11 +1812,11 @@ export class JobEngine {
1763
1812
  SESSION_CODES.continuationUnavailable, 'no recorded session');
1764
1813
  }
1765
1814
  if (typeof identity.executionPath !== 'string' || identity.executionPath.trim() === ''
1766
- || recordedPathIsMasked(identity.executionPath)) {
1815
+ || (recordedPathIsMasked(identity.executionPath) && !isPathDigest(identity.executionPathDigest))) {
1767
1816
  throw refuse('the named task has no usable execution-path identity, so its conversation cannot be continued',
1768
1817
  SESSION_CODES.continuationUnavailable, 'unusable recorded execution path');
1769
1818
  }
1770
- if (!samePath(identity.sourcePath, sourcePath)) {
1819
+ if (!recordedDirectoryIs({ path: identity.sourcePath, digest: identity.sourcePathDigest }, sourcePath)) {
1771
1820
  throw refuse('the named task belongs to another source repository, so its conversation was not continued',
1772
1821
  SESSION_CODES.continuationWorkspaceMismatch, 'identity source repository differs');
1773
1822
  }
@@ -1780,11 +1829,27 @@ export class JobEngine {
1780
1829
  // is masked cannot say which directory that was, and one that names a different
1781
1830
  // execution directory than the identity resolves is another directory's thread —
1782
1831
  // the Workspace id alone is not proof, so the Session is never resolved for either.
1783
- if (recordedPathIsMasked(conversation.workspacePath) || !samePath(conversation.workspacePath, identity.executionPath)) {
1832
+ //
1833
+ // The conversation lives in the ROW, so the digest it may fall back on is the row's
1834
+ // own execution digest: that digest is the digest of the same directory this path
1835
+ // was written for, so agreement here is a comparison of one fact recorded twice, not
1836
+ // a borrowed proof.
1837
+ const recordedConversation = {
1838
+ path: conversation.workspacePath,
1839
+ digest: row.executionPathDigest,
1840
+ };
1841
+ if (!recordedDirectoryIs(recordedConversation, identity.executionPath)) {
1784
1842
  throw refuse('the recorded conversation path does not match its execution directory',
1785
1843
  SESSION_CODES.continuationUnavailable, 'conversation workspace path differs');
1786
1844
  }
1787
- if (!samePath(identity.executionPath, row.executionWorkspacePath)) {
1845
+ // The identity's execution directory and the snapshot's must be one directory. The
1846
+ // two documents are written from the same live value, so their digests are the
1847
+ // second proof for a path either projection may have shortened — and two digests
1848
+ // that disagree are a real disagreement, refused like two readable paths that differ.
1849
+ if (!sameRecordedDirectory(
1850
+ { path: identity.executionPath, digest: identity.executionPathDigest },
1851
+ { path: row.executionWorkspacePath, digest: row.executionPathDigest },
1852
+ )) {
1788
1853
  throw refuse('the recorded conversation identity does not match the named task',
1789
1854
  SESSION_CODES.continuationUnavailable, 'identity execution path differs');
1790
1855
  }
@@ -1832,8 +1897,8 @@ export class JobEngine {
1832
1897
  *
1833
1898
  * A new tree would hide the parent's uncommitted work and create a different
1834
1899
  * DSH Workspace, so this path never calls `prepare()`. After a plugin restart,
1835
- * or after explicit disposal, the in-memory registry cannot prove ownership and
1836
- * the continuation is refused rather than guessed from a directory name.
1900
+ * recover only the already-authorized identity through Git's live registry.
1901
+ * Missing, replaced or disposed trees are refused, never substituted.
1837
1902
  * @param {object} task - continuation with a stored parent identity.
1838
1903
  * @returns {Promise<object>} the existing tree metadata.
1839
1904
  * @throws {JobError} when the original tree cannot be proven reusable.
@@ -1852,16 +1917,25 @@ export class JobEngine {
1852
1917
  if (manager === null || typeof manager.get !== 'function') {
1853
1918
  throw refuse('the managed worktree service is unavailable, so the original tree cannot be proven reusable', 'no worktree registry');
1854
1919
  }
1920
+ const expectedTreeId = identity.worktreeId ?? identity.taskId;
1855
1921
  let tree;
1856
1922
  try {
1857
1923
  tree = manager.get(identity.executionPath);
1924
+ if (tree === null && typeof manager.recover === 'function') {
1925
+ tree = await manager.recover({
1926
+ taskId: expectedTreeId,
1927
+ sourcePath: identity.sourcePath,
1928
+ workspacePath: identity.executionPath,
1929
+ state: identity.worktreeState,
1930
+ signal: task.controller.signal,
1931
+ });
1932
+ }
1858
1933
  } catch (error) {
1859
1934
  throw refuse('the managed worktree service refused to report the original tree', typeof error?.code === 'string' ? error.code : 'registry read failed');
1860
1935
  }
1861
1936
  if (tree === null || typeof tree !== 'object') {
1862
1937
  throw refuse('the original worktree is no longer registered; a new tree will not be substituted', 'tree not managed here');
1863
1938
  }
1864
- const expectedTreeId = identity.worktreeId ?? identity.taskId;
1865
1939
  if (!samePath(tree.workspacePath, identity.executionPath)
1866
1940
  || !samePath(tree.sourcePath, identity.sourcePath)
1867
1941
  || (typeof expectedTreeId === 'string' && expectedTreeId !== '' && tree.taskId !== expectedTreeId)
@@ -2077,6 +2151,83 @@ export class JobEngine {
2077
2151
  return bridge;
2078
2152
  }
2079
2153
 
2154
+ /**
2155
+ * Create the ordinary-question bridge for one task, or null when the deployment
2156
+ * cannot offer one.
2157
+ *
2158
+ * The factory is the same shape as the permission factory: the engine owns the task
2159
+ * lifecycle, so it hands the bridge the two observer hooks that keep the task view and
2160
+ * the durable record honest. A deployment without the factory simply cannot surface
2161
+ * questions, which is the safe default.
2162
+ * @param {object} task - the running task.
2163
+ * @returns {object | null} a bridge to arm, or null when unavailable.
2164
+ */
2165
+ createQuestionBridge(task) {
2166
+ const factory = this.deps?.questionBridge;
2167
+ if (typeof factory !== 'function') return null;
2168
+ let bridge;
2169
+ try {
2170
+ bridge = factory({
2171
+ taskId: task.taskId,
2172
+ connectionId: task.connectionId,
2173
+ onPending: (view) => this.onQuestionPending(task, view),
2174
+ onSettled: (entry) => this.onQuestionSettled(task, entry),
2175
+ });
2176
+ } catch (error) {
2177
+ this.deps?.logger?.warn?.('dsh-delegate: the question bridge could not be created', String(error?.code ?? ''));
2178
+ return null;
2179
+ }
2180
+ if (bridge === null || bridge === undefined || typeof bridge !== 'object'
2181
+ || typeof bridge.arm !== 'function' || typeof bridge.answer !== 'function') {
2182
+ return null;
2183
+ }
2184
+ return bridge;
2185
+ }
2186
+
2187
+ /**
2188
+ * Record one question set the worker is now waiting on.
2189
+ *
2190
+ * The task stays `running` and only its PHASE changes to `awaiting-question`, so
2191
+ * nothing that reads the state contract learns a new lifecycle value. The reason an
2192
+ * observation reports is `question` — immediately, not after a silence threshold.
2193
+ * @param {object} task - the running task.
2194
+ * @param {object} view - the bridge's bounded pending view.
2195
+ * @returns {void}
2196
+ */
2197
+ onQuestionPending(task, view) {
2198
+ if (TERMINAL.has(task.state)) return;
2199
+ task.question.pending = view;
2200
+ task.question.pausedAt = Date.now();
2201
+ if (task.state === TASK_STATES.running) task.phase = PHASE_AWAITING_QUESTION;
2202
+ this.checkpointHistory(task);
2203
+ }
2204
+
2205
+ /**
2206
+ * Record one settled question set and account for the time spent waiting.
2207
+ * @param {object} task - the task the question belonged to.
2208
+ * @param {object} entry - the bridge's bounded settled view.
2209
+ * @returns {void}
2210
+ */
2211
+ onQuestionSettled(task, entry) {
2212
+ if (task.question.pending !== null && entry?.requestId === task.question.pending.requestId) {
2213
+ task.question.pending = null;
2214
+ }
2215
+ if (task.question.pausedAt !== null) {
2216
+ task.question.pausedExecutionMs += Math.max(0, Date.now() - task.question.pausedAt);
2217
+ task.question.pausedAt = null;
2218
+ }
2219
+ if (entry !== null && entry !== undefined) {
2220
+ task.question.evidence.push(entry);
2221
+ if (task.question.evidence.length > 8) task.question.evidence.shift();
2222
+ }
2223
+ // Back to execution, never to a new state: an answered question and an abandoned one
2224
+ // both leave the task `running` until the run itself reaches an outcome.
2225
+ if (task.state === TASK_STATES.running && task.phase === PHASE_AWAITING_QUESTION) {
2226
+ task.phase = PHASE_EXECUTE;
2227
+ }
2228
+ this.checkpointHistory(task);
2229
+ }
2230
+
2080
2231
  /**
2081
2232
  * Record one request the worker is now waiting on.
2082
2233
  *
@@ -2278,6 +2429,66 @@ export class JobEngine {
2278
2429
  return { task: this.view(task), permission: settled, hostAcceptance: null };
2279
2430
  }
2280
2431
 
2432
+ /**
2433
+ * Answer one pending QUESTION for one task.
2434
+ *
2435
+ * The checks are the permission decision's, in the same order, because the identity
2436
+ * rule is the same: a task this caller cannot prove is answered as absent, a sentinel
2437
+ * task has no pending question, and the authorization is re-checked at the answer so
2438
+ * a switch turned off or a revoked grant cannot be bypassed by answering late.
2439
+ *
2440
+ * What is DIFFERENT is what the answer can do: nothing here grants access. The bridge
2441
+ * validates the batch against the questions the worker actually asked and settles the
2442
+ * paused tool call with the native answer shape. Any widening the worker then wants
2443
+ * still goes through {@link decidePermission}.
2444
+ * @param {object} request - `taskId`, `requestId`, `answers`, and the authenticated
2445
+ * `connectionId` (supplied by the plane, never by the caller's body).
2446
+ * @returns {object} bounded result: `{ task, question, answer: receipt, hostAcceptance: null }`.
2447
+ * @throws {JobError} on any refusal.
2448
+ */
2449
+ decideQuestion(request) {
2450
+ const connectionId = typeof request?.connectionId === 'string' ? request.connectionId : null;
2451
+ if (connectionId === null) {
2452
+ throw new JobError(JOB_CODES.taskNotFound, 'no such task for this connection', {});
2453
+ }
2454
+ const taskId = typeof request?.taskId === 'string' ? request.taskId.trim() : '';
2455
+ if (taskId === '') {
2456
+ throw new JobError(QUESTION_CODES.questionNotFound, 'taskId is required', { field: 'taskId' });
2457
+ }
2458
+ const task = this.tasks.get(taskId);
2459
+ if (task === undefined || task.connectionId !== connectionId) {
2460
+ throw new JobError(JOB_CODES.taskNotFound, 'no such task for this connection', { taskId });
2461
+ }
2462
+ if (TERMINAL.has(task.state)) {
2463
+ throw new JobError(QUESTION_CODES.questionSettled,
2464
+ 'this task has already ended; its pending question is history only', { taskId, state: task.state });
2465
+ }
2466
+ if (this.posture().authorized !== true) {
2467
+ throw new JobError(JOB_CODES.notAuthorized, 'delegation is no longer authorized, so no answer may be applied', {});
2468
+ }
2469
+ this.assertLive(task, 'question-decide');
2470
+ const bridge = task.question?.bridge ?? null;
2471
+ if (bridge === null || bridge === undefined || typeof bridge.decide !== 'function') {
2472
+ throw new JobError(QUESTION_CODES.notPending, 'this task has no pending question', { taskId });
2473
+ }
2474
+ let receipt;
2475
+ try {
2476
+ receipt = bridge.decide({ requestId: request?.requestId, answers: request?.answers });
2477
+ } catch (error) {
2478
+ if (error instanceof QuestionError) {
2479
+ throw new JobError(error.code, error.message, error.details);
2480
+ }
2481
+ throw error;
2482
+ }
2483
+ return {
2484
+ task: this.view(task),
2485
+ question: task.question.pending === null ? this.questionView(task) : redactDeep(task.question.pending),
2486
+ answer: receipt,
2487
+ // Explicit: answering a question is never an approval of anything.
2488
+ hostAcceptance: null,
2489
+ };
2490
+ }
2491
+
2281
2492
  /**
2282
2493
  * Record the commander's delivery review for one finished task.
2283
2494
  *
@@ -2658,6 +2869,53 @@ export class JobEngine {
2658
2869
  if (cause === 'dispose') task.permission.bridge = null;
2659
2870
  }
2660
2871
 
2872
+ /**
2873
+ * Stop every outstanding QUESTION of one task and disarm its bridge.
2874
+ *
2875
+ * Same lifecycle as {@link releasePermissionBridge} and called from the same paths,
2876
+ * for the same reason: a worker paused on a question must be released with a native
2877
+ * refusal when the run is cancelled, switched off, revoked or disposed, instead of
2878
+ * waiting for an answer nobody will give.
2879
+ * @param {object} task - task record.
2880
+ * @param {string} [cause] - `stop` (default) or `dispose`.
2881
+ * @returns {void}
2882
+ */
2883
+ releaseQuestionBridge(task, cause = 'stop') {
2884
+ const bridge = task.question?.bridge ?? null;
2885
+ if (bridge === null || bridge === undefined) return;
2886
+ try {
2887
+ if (cause === 'dispose') bridge.dispose?.();
2888
+ else bridge.stop?.();
2889
+ } catch (error) {
2890
+ this.deps?.logger?.warn?.('dsh-delegate: the question bridge could not be stopped', String(error?.code ?? ''));
2891
+ }
2892
+ if (task.question.pending !== null) task.question.pending = null;
2893
+ task.question.pausedAt = null;
2894
+ if (cause === 'dispose') task.question.bridge = null;
2895
+ }
2896
+
2897
+ /**
2898
+ * The bounded, public QUESTION block of one task.
2899
+ *
2900
+ * It is separate from {@link permissionView} on purpose and says so: `grantsAccess`
2901
+ * is always false, so no reader can mistake an answered question for an authorization.
2902
+ * `pending` carries the questions actually asked — text, options, and whether the
2903
+ * caller declared an intent — and never a reasoning stream or transcript.
2904
+ * @param {object} task - task record.
2905
+ * @returns {object} bounded question view.
2906
+ */
2907
+ questionView(task) {
2908
+ const pending = task.question?.pending ?? null;
2909
+ return {
2910
+ bridged: task.question?.bridge !== null && task.question?.bridge !== undefined,
2911
+ waiting: pending !== null,
2912
+ pending: pending === null ? null : redactDeep(pending),
2913
+ evidence: (task.question?.evidence ?? []).map((entry) => redactDeep(entry)),
2914
+ pausedExecutionMs: task.question?.pausedExecutionMs ?? 0,
2915
+ grantsAccess: false,
2916
+ };
2917
+ }
2918
+
2661
2919
  /**
2662
2920
  * The bounded, public permission block of one task.
2663
2921
  *
@@ -2705,6 +2963,7 @@ export class JobEngine {
2705
2963
  // `releasePermissionBridge(task, 'dispose')` is idempotent, so disposing here
2706
2964
  // does not double-settle.
2707
2965
  this.releasePermissionBridge(task, reason === 'dispose' ? 'dispose' : 'stop');
2966
+ this.releaseQuestionBridge(task, reason === 'dispose' ? 'dispose' : 'stop');
2708
2967
  task.cancelRequested = true;
2709
2968
  task.cancelledBy = task.cancelledBy ?? reason;
2710
2969
  try {
@@ -2761,6 +3020,7 @@ export class JobEngine {
2761
3020
  // Admission never created an executor, so any bridge it did create (it is
2762
3021
  // created just before the runner call, so normally none) is disposed here too.
2763
3022
  this.releasePermissionBridge(task, 'dispose');
3023
+ this.releaseQuestionBridge(task, 'dispose');
2764
3024
  task.endedAt = task.endedAt ?? Date.now();
2765
3025
  // A preflight that ran out of budget is a timeout, not a cancellation: it is
2766
3026
  // the same budget the run itself would have failed on, and reporting it as
@@ -2930,6 +3190,11 @@ export class JobEngine {
2930
3190
  // the run keeps the fail-closed `never` stance and nothing about it changes.
2931
3191
  const bridge = this.createPermissionBridge(task);
2932
3192
  task.permission.bridge = bridge;
3193
+ // The question bridge is its own surface, created the same way and for the same
3194
+ // reason: the runner arms it in the run's setup so the native answerer exists
3195
+ // before the prompt, and the engine records the wait here.
3196
+ const questionBridge = this.createQuestionBridge(task);
3197
+ task.question.bridge = questionBridge;
2933
3198
  // `started` means "this task called the runner", not "the executor is
2934
3199
  // running": placement resolves before the runner sees an Agent, so the task
2935
3200
  // is handed over in `before-create` and only the executor's own events
@@ -2961,6 +3226,10 @@ export class JobEngine {
2961
3226
  // run's setup, scanned by the engine before it is offered here, and
2962
3227
  // disposed when the run ends. `null` keeps the deterministic `never` stance.
2963
3228
  ...(bridge === null ? {} : { permissionBridge: bridge }),
3229
+ // The ordinary-question answerer for THIS task's own Agent. Independent of the
3230
+ // approval bridge: a `never` approval stance still lets the worker ask a
3231
+ // question, and answering one grants nothing.
3232
+ ...(questionBridge === null ? {} : { questionBridge }),
2964
3233
  configureDelegatedSession: this.deps.configureDelegatedSession,
2965
3234
  policyServices: this.deps.policyServices,
2966
3235
  // The engine is the authority for "may this chain be joined": a parent it
@@ -2981,6 +3250,10 @@ export class JobEngine {
2981
3250
  // forwarded — there is no field in the summary they could travel in.
2982
3251
  // This hook is also the only execution evidence the phase trusts.
2983
3252
  onEvent: (event) => { this.onExecutionEvent(task, event); },
3253
+ // The commander's DSH Agent Teams decision for THIS task's own Session. Absent
3254
+ // when the task froze `null` (no choice): the run then keeps the Session's
3255
+ // current mode instead of guessing one.
3256
+ ...(task.agentTeams === null || task.agentTeams === undefined ? {} : { agentTeams: task.agentTeams }),
2984
3257
  });
2985
3258
  task.native.promise = pending;
2986
3259
  let run;
@@ -3010,6 +3283,10 @@ export class JobEngine {
3010
3283
  // armed bridge was the answerer behind it. Recorded per run so "did this
3011
3284
  // task ask, or did it reject without asking" is answerable from the record.
3012
3285
  approval: run.approval ?? null,
3286
+ // The Agent Teams outcome: what the commander asked for and whether DSH's own
3287
+ // service confirmed it on this run's Session. `null` for a task that made no
3288
+ // choice, so "not asked" and "asked but unapplied" stay distinguishable.
3289
+ team: run.team ?? null,
3013
3290
  // Where the conversation landed. Reported per run so an operator can tell a
3014
3291
  // fresh session from a continued one, and which Workspace group it is in.
3015
3292
  conversation: run.conversation ?? null,
@@ -3307,12 +3584,17 @@ export class JobEngine {
3307
3584
  * cancels, restarts or resumes the worker, and never disturbs another
3308
3585
  * observer of the same task.
3309
3586
  * @param {string} taskId - task to observe.
3310
- * @param {object} [options] - `connectionId`, `waitMs` (default 25000, max 25000), `signal`.
3587
+ * @param {object} [options] - `connectionId`, `waitMs` (default 25000, max 25000),
3588
+ * `signal`, `ackFailureEventId` (acknowledge one delivered repeated-failure
3589
+ * reminder by its exact `eventId`).
3311
3590
  * @returns {Promise<{ task: object, reason: string, permission: object | null,
3312
- * failure: object | null, activity: object | null,
3591
+ * failure: object | null, failureAck: object | null, activity: object | null,
3313
3592
  * selfCheck: object | null, wait: { waitMs: number, waitedMs: number, activitySinceWait: boolean } }>} observation.
3314
3593
  * `failure` is present only when `attention` reports a repeated-tool-failure
3315
- * reminder; it carries a tool name, a failure code, an operation digest and counts.
3594
+ * reminder; it carries a stable `eventId`, a tool name, a failure code, an
3595
+ * operation digest and counts, and it is REDELIVERED on later observations until
3596
+ * it is acknowledged — a lost answer does not lose the reminder.
3597
+ * `failureAck` is present only when the caller asked to acknowledge.
3316
3598
  * @throws {JobError} `JOB_TASK_NOT_FOUND` for an unknown or foreign task.
3317
3599
  */
3318
3600
  async observeTask(taskId, options = {}) {
@@ -3320,9 +3602,18 @@ export class JobEngine {
3320
3602
  const waitMs = clampObserveWait(options?.waitMs);
3321
3603
  const signal = options?.signal ?? null;
3322
3604
 
3323
- if (this.aborted) return this.observationOf(task, OBSERVE_TASK_REASONS.interrupted, null, waitMs, 0, false);
3605
+ // Acknowledgment is a write to the MONITOR'S reminder state only — never to the
3606
+ // task, its worker or its deadline — and it is bound to the exact eventId the
3607
+ // caller observed. The result travels back on this observation (`failureAck`),
3608
+ // so the caller learns whether its ack landed even when the observation itself
3609
+ // says nothing new. An unknown id changes nothing: a wrong ack must not
3610
+ // silence a live notification. An EMPTY or non-string id is an explicit
3611
+ // refusal (`event-id-required`), never a silent no-op.
3612
+ const failureAck = this.ackObservedFailure(task, options?.ackFailureEventId);
3613
+
3614
+ if (this.aborted) return this.observationOf(task, OBSERVE_TASK_REASONS.interrupted, null, waitMs, 0, false, null, failureAck);
3324
3615
  if (signal !== null && signal.aborted === true) {
3325
- return this.observationOf(task, OBSERVE_TASK_REASONS.interrupted, null, waitMs, 0, false);
3616
+ return this.observationOf(task, OBSERVE_TASK_REASONS.interrupted, null, waitMs, 0, false, null, failureAck);
3326
3617
  }
3327
3618
 
3328
3619
  // Exactly one monitor per task, created at most once (see `ensureMonitor`).
@@ -3339,9 +3630,9 @@ export class JobEngine {
3339
3630
  // timed-out review learn the outcome here, instead of re-sending a decision (or
3340
3631
  // believing the review vanished). The wait is bounded and the report is honest
3341
3632
  // either way; nothing about the task's state is touched.
3342
- const settledObservation = await this.awaitReviewSettlement(task, waitMs, signal);
3633
+ const settledObservation = await this.awaitReviewSettlement(task, waitMs, signal, failureAck);
3343
3634
  if (settledObservation !== null) return settledObservation;
3344
- return this.observationOf(task, immediate, monitor, waitMs, 0, false);
3635
+ return this.observationOf(task, immediate, monitor, waitMs, 0, false, null, failureAck);
3345
3636
  }
3346
3637
 
3347
3638
  // ONE bounded wait, and nothing more. `waitMs` is the caller's promise: a
@@ -3362,7 +3653,7 @@ export class JobEngine {
3362
3653
  // those outrank it, and a failure report must not describe a task that now needs a
3363
3654
  // different decision.
3364
3655
  const failure = reason === OBSERVE_TASK_REASONS.attention ? (outcome.failure ?? null) : null;
3365
- return this.observationOf(task, reason, monitor, waitMs, outcome.waitedMs, outcome.activitySinceWait, failure);
3656
+ return this.observationOf(task, reason, monitor, waitMs, outcome.waitedMs, outcome.activitySinceWait, failure, failureAck);
3366
3657
  }
3367
3658
 
3368
3659
  /**
@@ -3377,7 +3668,47 @@ export class JobEngine {
3377
3668
  * @param {AbortSignal | null} signal - the caller's cancellation.
3378
3669
  * @returns {Promise<object | null>} an observation when the wait changed the answer, else null.
3379
3670
  */
3380
- async awaitReviewSettlement(task, waitMs, signal) {
3671
+ /**
3672
+ * Apply (or refuse) one caller acknowledgment and return the fact the observation
3673
+ * must publish.
3674
+ *
3675
+ * `null` means the caller did not acknowledge anything (`ackFailureEventId`
3676
+ * absent), in which case NO ack block appears on the observation at all — the
3677
+ * published shape an old caller receives is unchanged. A non-empty string is
3678
+ * forwarded to the monitor; an EMPTY string is an explicit refusal
3679
+ * (`event-id-required`), not a silent no-op, so both surfaces answer with the
3680
+ * same clear fact.
3681
+ * @param {object} task - task record.
3682
+ * @param {unknown} ackFailureEventId - the ack the caller carried, if any.
3683
+ * @returns {object | null} the ack result to publish, or null.
3684
+ */
3685
+ ackObservedFailure(task, ackFailureEventId) {
3686
+ if (ackFailureEventId === undefined || ackFailureEventId === null) return null;
3687
+ if (typeof ackFailureEventId !== 'string' || ackFailureEventId === '') {
3688
+ return { acknowledged: false, eventId: typeof ackFailureEventId === 'string' ? ackFailureEventId : null, reason: 'event-id-required' };
3689
+ }
3690
+ const monitorForAck = this.ensureMonitor(task);
3691
+ try {
3692
+ return monitorForAck.ackFailureReport(ackFailureEventId);
3693
+ } catch {
3694
+ return { acknowledged: false, eventId: ackFailureEventId, reason: 'ack-failed' };
3695
+ }
3696
+ }
3697
+
3698
+ /**
3699
+ * The ack result of THIS observeTask call, passed explicitly into the settlement
3700
+ * branch. The receipt belongs to the CALL, not to the monitor: a shared store on
3701
+ * the monitor would let concurrent observations overwrite each other's verdicts
3702
+ * (a later refusal replacing an earlier success) and answer a caller that never
3703
+ * acked with another caller's receipt. Each settle wait therefore carries its own
3704
+ * ack result through its own argument.
3705
+ * @param {object} task - task record.
3706
+ * @param {number} waitMs - the caller's own wait bound.
3707
+ * @param {AbortSignal | null} signal - the caller's cancellation.
3708
+ * @param {object | null} failureAck - the ack result of THIS observation, or null.
3709
+ * @returns {Promise<object | null>} an observation when the wait changed the answer, else null.
3710
+ */
3711
+ async awaitReviewSettlement(task, waitMs, signal, failureAck = null) {
3381
3712
  const entry = this.reviewState.get(task.taskId) ?? null;
3382
3713
  if (entry === null) return null;
3383
3714
  if (entry.state !== REVIEW_PERSISTENCE_STATES.saving && entry.state !== REVIEW_PERSISTENCE_STATES.timedOut) return null;
@@ -3389,10 +3720,12 @@ export class JobEngine {
3389
3720
  if (outcome === REVIEW_OUTCOME_TIMEOUT) return null;
3390
3721
  if (signal !== null && signal.aborted === true) return null;
3391
3722
  // The write settled inside the wait: report the resulting fact (confirmed or failed)
3392
- // together with how long it took, without re-deriving the task's state.
3723
+ // together with how long it took, without re-deriving the task's state. The ack
3724
+ // result is THIS call's own (passed in as an argument, never read from shared
3725
+ // state), so concurrent observations cannot cross their receipts.
3393
3726
  const reason = this.settleReason(task) ?? OBSERVE_TASK_REASONS.attention;
3394
3727
  const waitedMs = Math.max(0, this.clock() - started);
3395
- return this.observationOf(task, reason, this.ensureMonitor(task), waitMs, waitedMs, true, null);
3728
+ return this.observationOf(task, reason, this.ensureMonitor(task), waitMs, waitedMs, true, null, failureAck);
3396
3729
  }
3397
3730
 
3398
3731
  /**
@@ -3444,6 +3777,13 @@ export class JobEngine {
3444
3777
  settleReason(task) {
3445
3778
  const terminal = terminalReason(task);
3446
3779
  if (terminal !== null) return terminal;
3780
+ // A QUESTION outranks silence for the same reason a permission does, and it is the
3781
+ // defect this reason exists to remove: a worker waiting for a human answer used to
3782
+ // be reported only when the ten-minute silence threshold fired, so the commander
3783
+ // learned about the question long after the worker had asked it.
3784
+ if (task?.question?.pending !== null && task?.question?.pending !== undefined) {
3785
+ return OBSERVE_TASK_REASONS.question;
3786
+ }
3447
3787
  if (task?.permission?.pending !== null && task?.permission?.pending !== undefined) {
3448
3788
  return OBSERVE_TASK_REASONS.permission;
3449
3789
  }
@@ -3489,9 +3829,11 @@ export class JobEngine {
3489
3829
  * @param {boolean} activitySinceWait - whether activity arrived during the wait.
3490
3830
  * @param {object | null} [failure] - the repeated-failure diagnostic, when that is
3491
3831
  * what ended the wait.
3832
+ * @param {object | null} [failureAck] - the acknowledgment result, present only when
3833
+ * the caller asked to acknowledge one delivered reminder by its `eventId`.
3492
3834
  * @returns {object} observation result.
3493
3835
  */
3494
- observationOf(task, reason, monitor, waitMs, waitedMs, activitySinceWait, failure = null) {
3836
+ observationOf(task, reason, monitor, waitMs, waitedMs, activitySinceWait, failure = null, failureAck = null) {
3495
3837
  const at = this.clock();
3496
3838
  const summary = this.observationSummary(task, at);
3497
3839
  const pending = task?.permission?.pending ?? null;
@@ -3502,10 +3844,25 @@ export class JobEngine {
3502
3844
  reason,
3503
3845
  // The full, unshortened redacted request on the ONE reason that needs it.
3504
3846
  permission: reason === OBSERVE_TASK_REASONS.permission ? pending : null,
3847
+ // The questions the worker actually asked, on the one reason that needs them.
3848
+ // Carried here rather than only inside the task summary so a waiting host gets the
3849
+ // question, its options and its detail in ONE answer — the same shape the
3850
+ // permission reason uses, and for the same reason: a commander that had to read
3851
+ // the task first would spend a round trip before it could answer.
3852
+ question: reason === OBSERVE_TASK_REASONS.question
3853
+ ? (task?.question?.pending === null || task?.question?.pending === undefined
3854
+ ? null
3855
+ : redactDeep(task.question.pending))
3856
+ : null,
3505
3857
  // The typed, bounded diagnostic for a repeated-failure reminder. It is the only
3506
3858
  // thing that distinguishes that reminder from an ordinary silence report, whose
3507
- // own diagnostic is `selfCheck`.
3859
+ // own diagnostic is `selfCheck`. Its `eventId` is the identity the receiver
3860
+ // acknowledges; the reminder is redelivered until that ack lands.
3508
3861
  failure: reason === OBSERVE_TASK_REASONS.attention && failure !== null ? failure : null,
3862
+ // The acknowledgment result. Present (possibly with `acknowledged: false`) only
3863
+ // when the caller asked to acknowledge; absent otherwise, so an old caller's
3864
+ // observation shape is byte-for-byte unchanged.
3865
+ ...(failureAck === null ? {} : { failureAck }),
3509
3866
  activity: summary.activity,
3510
3867
  selfCheck,
3511
3868
  wait: { waitMs, waitedMs: Math.max(0, Math.trunc(waitedMs)), activitySinceWait: activitySinceWait === true },
@@ -3563,6 +3920,11 @@ export class JobEngine {
3563
3920
  // Where that decision is in its durable write, so a waiting host can tell "not
3564
3921
  // reviewed" from "the review is being written right now" and does not resubmit one.
3565
3922
  reviewPersistence: this.reviewPersistenceView(task),
3923
+ // The Agent Teams decision and outcome, short enough for a wait: `agentTeams` is the
3924
+ // frozen request (or null), `team` the verified result (`applied`/`enabled`) or the
3925
+ // reason it could not be applied. No team reasoning or task-board content travels.
3926
+ agentTeams: task.agentTeams ?? null,
3927
+ team: summarizedTeam(task.execution?.team ?? null),
3566
3928
  };
3567
3929
  }
3568
3930
 
@@ -3605,6 +3967,7 @@ export class JobEngine {
3605
3967
  // (the worker's paused tool call resumes `unavailable`) and the bridge can never
3606
3968
  // answer a request that outlived the run it belonged to.
3607
3969
  this.releasePermissionBridge(task, 'dispose');
3970
+ this.releaseQuestionBridge(task, 'dispose');
3608
3971
  // The monitor is stopped BEFORE the record is persisted, so no observation can
3609
3972
  // still be waiting on a run that has already ended. The summary survives on the
3610
3973
  // task, so the stored view still says how much activity there was.
@@ -3696,6 +4059,7 @@ export class JobEngine {
3696
4059
  let timer = null;
3697
4060
  try {
3698
4061
  const view = this.view(task);
4062
+ this.attachContinuationProof(view, task);
3699
4063
  const bounded = new Promise((resolvePromise, rejectPromise) => {
3700
4064
  timer = setTimeout(() => {
3701
4065
  rejectPromise(new JobError(JOB_CODES.historyFailed, 'the job history write exceeded its time budget', {
@@ -3724,6 +4088,38 @@ export class JobEngine {
3724
4088
  }
3725
4089
  }
3726
4090
 
4091
+ /**
4092
+ * Put the verifiable continuation identity beside the two display paths.
4093
+ *
4094
+ * The stored record needs BOTH: the readable path an operator recognises, and a
4095
+ * proof that survives the projection it is written through. The digests are opaque
4096
+ * to redaction, so a row whose path was shortened still proves which directory it
4097
+ * named — and a row whose digest is absent proves nothing, which is what a follow-up
4098
+ * must refuse.
4099
+ *
4100
+ * The digests are taken from the identity {@link rememberConversation} actually
4101
+ * wrote when that ran for the same placement, so the two durable documents cannot
4102
+ * record two different identities for one task. Otherwise they are derived from the
4103
+ * task's own live paths.
4104
+ * @param {object} view - the public view about to be stored.
4105
+ * @param {object} task - terminal task record.
4106
+ * @returns {void}
4107
+ */
4108
+ attachContinuationProof(view, task) {
4109
+ if (view === null || typeof view !== 'object') return;
4110
+ const placement = task.execution?.conversation ?? null;
4111
+ const written = task.continuationIdentityWritten ?? null;
4112
+ const usable = written !== null && placement !== null
4113
+ && written.workspaceId === (placement.workspaceId ?? '')
4114
+ && written.sessionId === (placement.sessionId ?? '');
4115
+ const identity = usable ? written : continuationIdentityOf(task, placement, task.effective?.worker?.isolation ?? null);
4116
+ if (identity === null) return;
4117
+ view.sourcePathDigest = identity.sourcePathDigest;
4118
+ view.executionPathDigest = identity.executionPathDigest;
4119
+ view.workspaceId = identity.workspaceId;
4120
+ view.sessionId = identity.sessionId;
4121
+ }
4122
+
3727
4123
  /**
3728
4124
  * Build the public view one review write should store.
3729
4125
  *
@@ -4056,6 +4452,12 @@ export class JobEngine {
4056
4452
  const placement = task.execution?.conversation ?? null;
4057
4453
  if (store === null || store === undefined || placement === null) return;
4058
4454
  const worktree = task.worktree === null || task.worktree === undefined ? null : task.worktree;
4455
+ // The canonical identity, computed once here and reused by the durable history row
4456
+ // (see {@link persistHistory}): the paths as one canonical spelling plus the digest
4457
+ // of each, so a later follow-up compares a verifiable identity instead of relying on
4458
+ // a display string that a projection may have shortened.
4459
+ const identity = continuationIdentityOf(task, placement, task.effective?.worker?.isolation ?? null);
4460
+ task.continuationIdentityWritten = identity;
4059
4461
  try {
4060
4462
  const saved = await rememberSession(store, {
4061
4463
  workspaceId: placement.workspaceId,
@@ -4073,6 +4475,10 @@ export class JobEngine {
4073
4475
  ? worktree.worktreeId
4074
4476
  : (typeof worktree.taskId === 'string' ? worktree.taskId : task.taskId)),
4075
4477
  worktreeState: worktree === null ? null : (typeof worktree.state === 'string' ? worktree.state : null),
4478
+ // The chain's Agent Teams decision, so a follow-up in a later process inherits the
4479
+ // mode its parent ran with. `null` (no decision) is stored as "no decision", which
4480
+ // is how an old row written before this field reads back too.
4481
+ agentTeams: task.agentTeams ?? null,
4076
4482
  });
4077
4483
  task.conversationSaved = saved;
4078
4484
  task.conversationError = null;
@@ -4277,6 +4683,11 @@ export class JobEngine {
4277
4683
  sourcePath: task.sourcePath,
4278
4684
  workspacePath: task.executionPath ?? task.sourcePath,
4279
4685
  executionWorkspacePath: task.executionPath,
4686
+ // The verifiable half of the same identity (a digest of each canonical path, plus
4687
+ // the DSH Workspace/Session the run drove) is attached by
4688
+ // {@link attachContinuationProof} when the view is STORED. It is not part of the
4689
+ // live projection: a reader of a running task does not need it, and one place
4690
+ // that decides it cannot disagree with another.
4280
4691
  isolation: effective === null ? null : effective.worker.isolation,
4281
4692
  connectionId: task.connectionId,
4282
4693
  grantId: task.grantId,
@@ -4318,6 +4729,9 @@ export class JobEngine {
4318
4729
  conversation: task.execution.conversation ?? null,
4319
4730
  cancelCause: task.execution.cancelCause,
4320
4731
  error: task.execution.error,
4732
+ // The Agent Teams outcome this run verified (or refuses to claim). Reported inside
4733
+ // `execution` because it is a fact about THIS run, not about the task's intent.
4734
+ team: task.execution.team ?? null,
4321
4735
  },
4322
4736
  // Where the run's conversation was placed in DSH. `workspaceId` is the group an
4323
4737
  // operator sees; `kind` is `new` or `continuation`, and `continuedFromTaskId`
@@ -4336,9 +4750,20 @@ export class JobEngine {
4336
4750
  // the standing mode the decision did NOT change. Present on every task, so a
4337
4751
  // reader never has to infer "no bridge" from a missing field.
4338
4752
  permission: this.permissionView(task),
4753
+ // The ordinary-question surface: the questions the worker is actually waiting on,
4754
+ // the settled trail, and how much of the execution budget went to waiting. It is
4755
+ // a separate block because answering a question grants nothing — `grantsAccess`
4756
+ // is stated as `false` rather than left to be inferred.
4757
+ question: this.questionView(task),
4339
4758
  // The approval stance the run installed and read back (`never` without a
4340
4759
  // bridge, `ask` with an armed one), recorded from the run itself.
4341
4760
  approval: task.execution?.approval ?? null,
4761
+ // The Agent Teams decision: `requested` is what the dispatcher froze on the task
4762
+ // (`null` when they made no choice) and `applied` is what DSH's own service
4763
+ // confirmed on this run's Session. Kept as one block so "asked for teams" and
4764
+ // "teams actually on for this run" are never conflated.
4765
+ agentTeams: task.agentTeams ?? null,
4766
+ team: task.execution?.team ?? null,
4342
4767
  // A bounded progress summary: counts, timestamps and the tool in flight. It
4343
4768
  // carries no model text, no reasoning, no tool arguments and no diff, so the
4344
4769
  // ordinary task view can show "still working, last activity 12s ago" without
@@ -4403,12 +4828,14 @@ export class JobEngine {
4403
4828
  // A terminal task may still hold a bridge if its own teardown has not run
4404
4829
  // yet; disposing is idempotent and cannot answer anything after this point.
4405
4830
  this.releasePermissionBridge(task, 'dispose');
4831
+ this.releaseQuestionBridge(task, 'dispose');
4406
4832
  continue;
4407
4833
  }
4408
4834
  this.abortTask(task, 'dispose');
4409
4835
  // Teardown is not a cancel: the answerer goes away, so the worker's paused
4410
4836
  // call must be told the channel is gone rather than that it was withdrawn.
4411
4837
  this.releasePermissionBridge(task, 'dispose');
4838
+ this.releaseQuestionBridge(task, 'dispose');
4412
4839
  count += 1;
4413
4840
  }
4414
4841
  await Promise.race([
@@ -4484,31 +4911,6 @@ function samePath(a, b) {
4484
4911
  return normalize(a) === normalize(b);
4485
4912
  }
4486
4913
 
4487
- /**
4488
- * The placeholder a redacted path segment is rewritten to.
4489
- */
4490
- const PATH_MASK_SEGMENT = 'masks-user-profile-segment';
4491
-
4492
- /**
4493
- * Whether a persisted path cannot prove which directory it names.
4494
- *
4495
- * Durable documents are projected through redaction, which replaces an
4496
- * account-identifying directory name with the placeholder above. A path carrying that
4497
- * placeholder is a shortened spelling: nothing can prove which directory stood there,
4498
- * so it is never compared into a match and is treated exactly like a missing path — the
4499
- * mask only ever causes a refusal, it never stands for equality. A real directory whose
4500
- * name merely *starts with* the placeholder is still its own directory, which is why the
4501
- * test is for the whole segment.
4502
- * @param {unknown} value - candidate path.
4503
- * @returns {boolean} true when the path was rewritten and can only be refused.
4504
- */
4505
- function recordedPathIsMasked(value) {
4506
- if (typeof value !== 'string') return false;
4507
- return value
4508
- .split(/[\\/]+/)
4509
- .some((part) => part.trim() === PATH_MASK_SEGMENT);
4510
- }
4511
-
4512
4914
  /**
4513
4915
  * Review selection projection for a review that never ran.
4514
4916
  * @param {object} review - effective review block.
@@ -4534,11 +4936,25 @@ export function sanitizeOverrides(value) {
4534
4936
  if (typeof value !== 'object' || Array.isArray(value)) {
4535
4937
  throw new JobError(JOB_CODES.overrideInvalid, 'overrides must be an object', {});
4536
4938
  }
4537
- const allowed = ['providerId', 'model', 'reasoningEffort', 'timeoutSeconds', 'isolation'];
4939
+ // `agentTeams` is NOT part of the frozen worker configuration (it is not a settings
4940
+ // field and never reaches the settings validator); it is carried on the overrides
4941
+ // object only because that is the existing channel a dispatcher uses for per-task
4942
+ // choices. It selects DSH Agent Teams for THIS run's own Session; `undefined` means
4943
+ // the commander made no choice and the Session keeps its current mode.
4944
+ const workerKeys = ['providerId', 'model', 'reasoningEffort', 'timeoutSeconds', 'isolation'];
4538
4945
  const out = {};
4539
- for (const key of allowed) {
4946
+ for (const key of workerKeys) {
4540
4947
  if (value[key] !== undefined) out[key] = value[key];
4541
4948
  }
4949
+ if (value.agentTeams !== undefined) {
4950
+ if (typeof value.agentTeams !== 'boolean') {
4951
+ throw new JobError(JOB_CODES.overrideInvalid, 'overrides.agentTeams must be a boolean', {
4952
+ field: 'agentTeams',
4953
+ requestedType: typeof value.agentTeams,
4954
+ });
4955
+ }
4956
+ out.agentTeams = value.agentTeams;
4957
+ }
4542
4958
  return out;
4543
4959
  }
4544
4960
 
@@ -4629,3 +5045,23 @@ function summarizedAcceptance(acceptance) {
4629
5045
  noteOmitted: true,
4630
5046
  };
4631
5047
  }
5048
+
5049
+ /**
5050
+ * The Agent Teams outcome as a WAIT reports it: four booleans and one bounded reason.
5051
+ *
5052
+ * A waiting host must be able to answer "are teams on for this run, and if not why"
5053
+ * without reading the full result. Nothing else from the team machinery (task board,
5054
+ * members, messages) belongs on a wait, and its reason is a code or a one-line diagnostic.
5055
+ * @param {object | null} team - the run's `team` fact.
5056
+ * @returns {object | null} the short fact.
5057
+ */
5058
+ function summarizedTeam(team) {
5059
+ if (team === null || typeof team !== 'object') return null;
5060
+ return {
5061
+ requested: typeof team.requested === 'boolean' ? team.requested : null,
5062
+ supported: team.supported === true,
5063
+ applied: team.applied === true,
5064
+ enabled: typeof team.enabled === 'boolean' ? team.enabled : null,
5065
+ reason: typeof team.reason === 'string' ? diagnostic(team.reason, 200) : null,
5066
+ };
5067
+ }