dsh-taskbridge 1.6.0 → 1.7.0

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 (66) hide show
  1. package/CHANGELOG.md +10 -1
  2. package/README.md +41 -41
  3. package/THIRD_PARTY_NOTICES.txt +23 -0
  4. package/codex/dsh-taskbridge.toml +140 -71
  5. package/docs/INTRODUCTION.md +44 -22
  6. package/docs/INTRODUCTION.zh.md +32 -26
  7. package/docs/codex-integration.md +90 -10
  8. package/docs/contracts-stage-b.md +4 -4
  9. package/docs/conversation-placement.md +25 -7
  10. package/docs/plugin-market.md +1 -1
  11. package/docs/releases/1.7.0.zh.md +11 -0
  12. package/docs/runtime-compatibility.md +4 -11
  13. package/docs/silent-wait.md +69 -31
  14. package/docs/taskbridge-upgrade.md +1 -1
  15. package/docs/worker-permissions.md +4 -14
  16. package/docs/workspace-grouping.md +126 -0
  17. package/lib/client.d.ts +365 -3
  18. package/lib/client.js +260 -5
  19. package/locale/en.json +1 -1
  20. package/locale/zh.json +1 -1
  21. package/package.json +7 -19
  22. package/src/client/api.js +550 -90
  23. package/src/client/index.jsx +699 -307
  24. package/src/client/sidebar.jsx +6 -5
  25. package/src/client/styles.js +251 -0
  26. package/src/client/task-cleanup.js +304 -0
  27. package/src/client/task-records-table.jsx +217 -0
  28. package/src/client/task-view.js +226 -10
  29. package/src/client/workspace-groups.js +482 -0
  30. package/src/client/workspaces-browser.jsx +770 -0
  31. package/src/codex/agent-ownership.js +270 -0
  32. package/src/codex/installer.js +525 -35
  33. package/src/codex/seam.js +5 -0
  34. package/src/config/defaults.js +63 -17
  35. package/src/config/settings.js +60 -62
  36. package/src/config/validate.js +126 -71
  37. package/src/http/respond.js +8 -0
  38. package/src/http/user-plane.js +197 -2
  39. package/src/index.js +50 -42
  40. package/src/jobs/activity.js +968 -78
  41. package/src/jobs/engine.js +784 -230
  42. package/src/jobs/history.js +188 -12
  43. package/src/jobs/plan-store.js +5 -0
  44. package/src/jobs/record-cleanup.js +196 -0
  45. package/src/jobs/task-tree.js +5 -3
  46. package/src/jobs/title.js +129 -12
  47. package/src/mcp/server.js +16 -8
  48. package/src/mcp/wait.js +64 -5
  49. package/src/runtime/agent-runner.js +53 -15
  50. package/src/runtime/worker-prompt.js +53 -0
  51. package/src/workspace/locks.js +288 -167
  52. package/docs/releases/1.4.0-token-benchmark.zh.md +0 -40
  53. package/docs/releases/1.4.0.zh.md +0 -54
  54. package/docs/releases/1.4.1.zh.md +0 -59
  55. package/docs/releases/1.4.2.zh.md +0 -23
  56. package/docs/releases/1.5.0-token-benchmark.zh.md +0 -73
  57. package/docs/releases/1.5.0.zh.md +0 -51
  58. package/docs/releases/1.5.1.zh.md +0 -70
  59. package/docs/releases/1.5.2.zh.md +0 -30
  60. package/docs/releases/1.5.3-test.1.zh.md +0 -28
  61. package/docs/releases/1.5.3-test.2.zh.md +0 -24
  62. package/docs/releases/1.5.3.zh.md +0 -33
  63. package/docs/releases/1.5.4.zh.md +0 -25
  64. package/src/review/preset.js +0 -868
  65. package/src/review/prompts.js +0 -145
  66. package/src/review/reviewer.js +0 -933
@@ -8,7 +8,7 @@
8
8
  // 3. the concurrency slot is checked, then the source workspace is locked;
9
9
  // 4. isolation is honoured (a real worktree) or refused — never downgraded;
10
10
  // 5. the execution workspace is locked, audited and baselined;
11
- // 6. worker and review routes are confirmed and frozen against one provider
11
+ // 6. the worker route is confirmed and frozen against one provider
12
12
  // registry snapshot;
13
13
  // 7. only then does an agent exist.
14
14
  //
@@ -66,11 +66,11 @@
66
66
  // recorded), not merely that the state was written.
67
67
 
68
68
  import { randomUUID } from 'node:crypto';
69
- import { defaultSettings, LIMITS, MONITORING_DEFAULTS } from '../config/defaults.js';
69
+ import { DEFAULT_AGENT_TEAMS_FOR_NEW_TASKS, defaultSettings, LIMITS, MONITORING_DEFAULTS } from '../config/defaults.js';
70
70
  import { redactDeep, redactText } from '../config/redact.js';
71
71
  import { resolveEffectiveConfig } from '../config/settings.js';
72
72
  import { AUTH_CODES, AuthError } from '../auth/grants.js';
73
- import { TaskMonitor, isPublicReason, terminalReason } from './activity.js';
73
+ import { CHECKPOINTS, TaskMonitor, isPublicReason, terminalReason } from './activity.js';
74
74
  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';
@@ -88,10 +88,9 @@ import {
88
88
  } from './continuation-identity.js';
89
89
  import { taskTitle } from './title.js';
90
90
  import { MAX_PLAN_DEPTH } from './plan-store.js';
91
- import { REVIEW_STATES, reviewWork } from '../review/reviewer.js';
92
- import { buildReviewPrompt, buildWorkerPrompt } from '../review/prompts.js';
91
+ import { buildWorkerPrompt } from '../runtime/worker-prompt.js';
93
92
  import { captureBaseline, captureDiff } from '../workspace/audit.js';
94
- import { LOCK_CODES, WorkspaceError, resolveWorkspacePath } from '../workspace/locks.js';
93
+ import { LOCK_CODES, LOCK_MODES, WorkspaceError, resolveWorkspacePath } from '../workspace/locks.js';
95
94
  import {
96
95
  REVIEW_NOTE_MAX_CHARS,
97
96
  normalizeReviewNote,
@@ -128,6 +127,13 @@ export const JOB_CODES = Object.freeze({
128
127
  isolationRefused: 'JOB_ISOLATION_REFUSED',
129
128
  auditUnavailable: 'JOB_AUDIT_UNAVAILABLE',
130
129
  routingRefused: 'JOB_ROUTING_REFUSED',
130
+ // The directory a job needs is already held by another job. Reported in exactly
131
+ // two situations, both of which mean "this submission would have changed bytes the
132
+ // other job owns": another job is running in the SAME directory (shared
133
+ // isolation, or the same managed tree for a continuation), or another job is
134
+ // writing to the source checkout this submission wanted to write to as well.
135
+ // Two ISOLATED runs of one source are NOT one of them: they prepare their trees
136
+ // one at a time and then run in separate checkouts (see {@link JobEngine#admit}).
131
137
  busy: 'JOB_WORKSPACE_BUSY',
132
138
  concurrency: 'JOB_CONCURRENCY_LIMIT',
133
139
  cancelled: 'JOB_CANCELLED',
@@ -183,22 +189,34 @@ export const JOB_CODES = Object.freeze({
183
189
  const DEFAULT_SWEEP_INTERVAL_MS = 1000;
184
190
 
185
191
  /**
186
- * Bound on preflight before the operator's own timeout is known.
192
+ * Bound on preflight before a task's own execution budget is known.
187
193
  *
188
- * The worker timeout lives in the settings document, which is read *during*
189
- * preflight, so the first steps need a bound of their own or a hung native
190
- * service could hold a slot forever. Once the effective snapshot is resolved the
191
- * deadline is re-armed from `worker.timeoutSeconds`, measured from task creation,
192
- * so preflight time is charged to the same budget as the run itself.
194
+ * Preflight is admission work — path resolution, routing, the source lock, a
195
+ * worktree, provider leases — and it must be bounded by SOMETHING, or a hung native
196
+ * service would hold a concurrency slot and a workspace lease forever. This is a
197
+ * FIXED internal bound and deliberately not the operator's old `worker.timeoutSeconds`:
198
+ * that field no longer limits a run, so it must not quietly limit admission either.
199
+ *
200
+ * Once the effective snapshot is resolved, {@link JobEngine#start} re-arms the
201
+ * deadline from `executionTimeoutSeconds` — `null` by default, in which case there is
202
+ * NO deadline at all for the run itself. An admission that never reaches that point
203
+ * keeps this bound.
193
204
  */
194
- const DEFAULT_PREFLIGHT_TIMEOUT_MS = defaultSettings().worker.timeoutSeconds * 1000;
195
-
196
- /** Ceiling on the additional review's own time budget. */
197
- const REVIEW_TIMEOUT_CAP_MS = 1800 * 1000;
205
+ const DEFAULT_PREFLIGHT_TIMEOUT_MS = 30 * 60 * 1000;
198
206
 
199
207
  /** How long cancel/dispose wait for a task to observe its cancellation. */
200
208
  const SETTLE_TIMEOUT_MS = 5000;
201
209
 
210
+ /**
211
+ * How far a task's recorded start may be from the engine's own clock and still be used.
212
+ *
213
+ * A task record can come from a different time base than the engine's `now` seam (a
214
+ * restored record, or a test with an injected clock). Beyond this distance the recorded
215
+ * start is not an elapsed time but two clocks that disagree, so the engine stamps its
216
+ * OWN instant when the run really starts — the same rule the monitor applies to silence.
217
+ */
218
+ const MAX_PLAUSIBLE_START_SKEW_MS = 24 * 60 * 60 * 1000;
219
+
202
220
  /**
203
221
  * Bound on waiting for a native executor to confirm that it stopped.
204
222
  *
@@ -211,6 +229,18 @@ const SETTLE_TIMEOUT_MS = 5000;
211
229
  */
212
230
  const NATIVE_SETTLE_TIMEOUT_MS = SETTLE_TIMEOUT_MS;
213
231
 
232
+ /**
233
+ * How long an ISOLATED submission waits for its turn to prepare a Git worktree.
234
+ *
235
+ * Two isolated runs of one source repository share only Git's administrative area,
236
+ * so the creation step is serialised while the runs themselves are not. That wait
237
+ * is charged to the same preflight budget every admission step already has
238
+ * (`preflightTimeoutMs`, and the task's own execution budget once known), so this
239
+ * value only bounds a queue entry whose wait has no other bound: a caller that
240
+ * abandons its start must not leave its place in the queue held forever.
241
+ */
242
+ const PREPARATION_QUEUE_LIMIT_MS = DEFAULT_PREFLIGHT_TIMEOUT_MS;
243
+
214
244
  /**
215
245
  * Bound on one durable history write.
216
246
  *
@@ -399,6 +429,7 @@ export class JobEngine {
399
429
  this.history = deps?.history ?? null;
400
430
  this.plans = deps?.plans ?? null;
401
431
  this.tasks = new Map();
432
+ this.cleanupIds = new Set();
402
433
  this.aborted = false;
403
434
  this.sweepTimer = null;
404
435
  this.unsubscribe = null;
@@ -418,6 +449,21 @@ export class JobEngine {
418
449
  // must read the same time source.
419
450
  this.clock = typeof deps?.now === 'function' ? deps.now : Date.now;
420
451
  this.observationWait = typeof deps?.wait === 'function' ? deps.wait : undefined;
452
+ // The scheduler seam for the monitors' own self-check timer. Absent in production
453
+ // (the monitor uses the real, unref'd `setTimeout`); a test injects one so the
454
+ // scheduled inspection can be fired deterministically.
455
+ const timers = deps?.timers;
456
+ this.timerSeam = timers !== null && typeof timers === 'object'
457
+ && (typeof timers.setTimeout === 'function' || typeof timers.clearTimeout === 'function')
458
+ ? {
459
+ // EACH seam is passed only when it is a function. A host that injects the scheduler
460
+ // for its own bookkeeping (a recording `setTimeout` with the platform's own
461
+ // `clearTimeout`, or the reverse) must never make one of the two `undefined`: the
462
+ // monitor would then call `undefined` and silently lose the inspection.
463
+ ...(typeof timers.setTimeout === 'function' ? { setTimeout: timers.setTimeout } : {}),
464
+ ...(typeof timers.clearTimeout === 'function' ? { clearTimeout: timers.clearTimeout } : {}),
465
+ }
466
+ : undefined;
421
467
  const slice = Number(deps?.observeSliceMs);
422
468
  this.observeSliceMs = Number.isFinite(slice) && slice > 0 ? Math.trunc(slice) : OBSERVE_SLICE_MS;
423
469
  // Observers currently waiting, so disposal can release them without touching
@@ -432,6 +478,11 @@ export class JobEngine {
432
478
  // entry it belongs to, so a global counter is enough and cannot wrap into confusion
433
479
  // with a task's own numbering.
434
480
  this.reviewSeq = 0;
481
+ // Git preparation turns, keyed by source repository. Isolated runs of one source
482
+ // share Git's administrative area, so their creation step is serialised while the
483
+ // runs are not; see {@link withPreparationTurn}. Live entries only: an abandoned
484
+ // waiter is removed from the queue when it gives up.
485
+ this.preparationTurns = new Map();
435
486
  this.listen();
436
487
  }
437
488
 
@@ -577,6 +628,8 @@ export class JobEngine {
577
628
  });
578
629
  }
579
630
  const parentNodeId = typeof rawParentNodeId === 'string' ? rawParentNodeId.trim() : '';
631
+ this.assertRecordNotBeingRemoved(continueFromTaskId);
632
+ this.assertRecordNotBeingRemoved(parentNodeId);
580
633
  const goal = canonicalTaskDescription(request?.goalDescription, TASK_DESCRIPTION_FIELDS.goal, redactText);
581
634
  if (goal.ok === false) {
582
635
  throw new JobError(JOB_CODES.descriptionInvalid, goal.refusal.message, {
@@ -654,10 +707,12 @@ export class JobEngine {
654
707
  effective: null,
655
708
  routes: null,
656
709
  route: null,
657
- reviewRoute: null,
658
- reviewRouteError: null,
659
710
  baseline: null,
660
711
  worktree: null,
712
+ // What this task actually holds in the workspace lock registry. Each entry is
713
+ // `{ path, nonce, mode, purpose }`: `exclusive` holds name the directory the run
714
+ // writes to, `preparation` holds are the short shared ones taken while a Git tree
715
+ // is created. Both are released by {@link releaseLeases}, newest first.
661
716
  leases: [],
662
717
  // The process-local provider-definition lease this task holds, taken before
663
718
  // it awaited the route ensure and given back only by {@link finalize}: it is
@@ -683,12 +738,25 @@ export class JobEngine {
683
738
  // execution path and conversation, never the internal parent object.
684
739
  continuationParent: null,
685
740
  continuationRecord: null,
741
+ // The parent's Agent Teams facts (`teamFactsOf`), read once during continuation
742
+ // admission from the same documents whose ownership was just proven. Admission's
743
+ // effective step decides what may be inherited from them; nothing re-reads history
744
+ // for it. `null` for a task that is not a continuation.
745
+ continuationTeam: null,
746
+ // The frozen Agent Teams decision (`null` when none is applied), WHERE it came from
747
+ // (`request` / `continuation` / `settings-default`) and whether it is the operator's
748
+ // DEFAULT filling an absent choice. The three are kept apart so a record never
749
+ // presents a default as a request, and so the runner can refuse an explicit or
750
+ // inherited choice it cannot apply while still letting the documented OFF default
751
+ // through on an older host.
752
+ agentTeams: null,
753
+ agentTeamsOrigin: null,
754
+ agentTeamsFromDefault: false,
686
755
  // The identity map row, read exactly once, and the single durable snapshot the
687
756
  // continuation is judged by. Both are admission-only facts; the public task view
688
757
  // exposes the resulting execution path and conversation, never the internals.
689
758
  continuationIdentity: null,
690
759
  reusedWorktree: false,
691
- review: { state: REVIEW_STATES.notRun, verdict: null, text: '', error: null },
692
760
  error: null,
693
761
  cancelRequested: false,
694
762
  cancelledBy: null,
@@ -737,7 +805,11 @@ export class JobEngine {
737
805
  // published only once the durable write has CONFIRMED it (see `recordHostReview`).
738
806
  hostAcceptance: null,
739
807
  settled,
740
- settle: () => { settle(); },
808
+ cleanupSettled: false,
809
+ settle() {
810
+ this.cleanupSettled = true;
811
+ settle();
812
+ },
741
813
  };
742
814
  }
743
815
 
@@ -831,6 +903,15 @@ export class JobEngine {
831
903
  // ---- 4. effective configuration and the concurrency slot -----------------
832
904
  task.phase = 'effective';
833
905
  const overrides = sanitizeOverrides(grant.overrides ?? request?.overrides);
906
+ // WHERE the frozen team choice came from: the dispatcher's own per-task value, the
907
+ // chain a follow-up continues, or the operator's new-task default. Recorded so a
908
+ // reader can tell "you asked for this" from "the setting decided this".
909
+ let teamChoiceOrigin = typeof overrides.agentTeams === 'boolean' ? 'request' : null;
910
+ // Whether the frozen choice is the OPERATOR'S DEFAULT filling an absent one. Only that
911
+ // kind may proceed when the host has no agent-teams service: an explicit choice — and
912
+ // a choice inherited from a chain, which the dispatcher did make at some point — is
913
+ // refused instead of silently running under the Session's own mode.
914
+ let teamChoiceFromDefault = false;
834
915
  if (task.continuationRecord !== null) {
835
916
  const parentIsolation = task.continuationRecord.isolation;
836
917
  if (overrides.isolation !== undefined && overrides.isolation !== parentIsolation) {
@@ -847,12 +928,40 @@ export class JobEngine {
847
928
  overrides.isolation = parentIsolation;
848
929
  // The Agent Teams decision follows the same rule as isolation for a CONTINUATION:
849
930
  // it is inherited from the parent UNLESS the dispatcher states it explicitly, so a
850
- // follow-up keeps the chain's team mode instead of silently flipping it. `null`
851
- // (no choice anywhere) stays `null` and the Session keeps its own mode.
852
- if (overrides.agentTeams === undefined && typeof task.continuationRecord.agentTeams === 'boolean') {
853
- overrides.agentTeams = task.continuationRecord.agentTeams;
931
+ // follow-up keeps the chain's team mode instead of silently flipping it.
932
+ //
933
+ // What may be inherited is a value that actually reached a native Session. A parent
934
+ // whose decision was the operator's default, asked for OFF, and was answered by a
935
+ // host with no agent-teams service never wrote anything (`teamFactsOf` says so), so
936
+ // there is nothing to carry forward: this follow-up sends no choice and keeps its
937
+ // Session's own mode. It also deliberately does NOT fall back to today's new-task
938
+ // default — that setting is about new tasks, not about a live conversation.
939
+ //
940
+ // Everything else is inherited exactly as before, including a real explicit
941
+ // `true`/`false`, a value inherited earlier in the chain, and an older record that
942
+ // stored `false` with no receipt (that run really did write it).
943
+ const inheritedTeam = task.continuationTeam ?? teamFactsOf(
944
+ task.continuationRecord.agentTeams, null, null,
945
+ );
946
+ if (overrides.agentTeams === undefined && inheritedTeam.inheritable === true) {
947
+ overrides.agentTeams = inheritedTeam.value;
948
+ teamChoiceOrigin = 'continuation';
854
949
  }
855
950
  }
951
+ // The operator's NEW-TASK default fills an absent choice for a NEW task only.
952
+ //
953
+ // It deliberately does NOT fill a continuation: a follow-up belongs to an existing
954
+ // conversation whose mode the operator may have set in DSH itself, and inventing a
955
+ // choice there would overwrite a live Session's selection with a setting that was
956
+ // never about it. So a continuation with no provable parent decision and no explicit
957
+ // choice stays ABSENT (`null`): no `agentTeams` is sent, the native Session keeps its
958
+ // current value, and the record says the mode was not decided here rather than
959
+ // claiming it was turned off.
960
+ if (typeof overrides.agentTeams !== 'boolean' && task.continuationRecord === null) {
961
+ overrides.agentTeams = operatorTeamDefault(settings);
962
+ teamChoiceOrigin = 'settings-default';
963
+ teamChoiceFromDefault = true;
964
+ }
856
965
  let effective;
857
966
  try {
858
967
  // `agentTeams` is a per-run DSH Session choice, not a settings field: it is frozen
@@ -861,8 +970,15 @@ export class JobEngine {
861
970
  const { agentTeams: teamChoice, ...settingsOverrides } = overrides;
862
971
  effective = resolveEffectiveConfig(settings, { projectPath: sourcePath, overrides: settingsOverrides });
863
972
  // Frozen on the task so the view, the run and a later continuation all state the
864
- // SAME explicit decision. `null` = the commander made no choice for this task.
973
+ // SAME explicit decision. `null` = no choice applied, which the runner reports as
974
+ // "no choice" rather than guessing one.
865
975
  task.agentTeams = typeof teamChoice === 'boolean' ? teamChoice : null;
976
+ task.agentTeamsOrigin = task.agentTeams === null ? null : teamChoiceOrigin;
977
+ // Whether that frozen choice is the operator's default rather than something a
978
+ // person decided. The runner needs it to tell "the setting asked for this" (which
979
+ // may proceed unpublished on an older host) from "somebody asked for this" (which
980
+ // must be refused rather than silently ignored).
981
+ task.agentTeamsFromDefault = task.agentTeams !== null && teamChoiceFromDefault === true;
866
982
  } catch (error) {
867
983
  throw new JobError(JOB_CODES.routingRefused, error?.message ?? 'the effective configuration was refused', {
868
984
  cause: error?.code ?? null,
@@ -870,10 +986,24 @@ export class JobEngine {
870
986
  });
871
987
  }
872
988
  task.effective = effective;
873
- // The worker timeout is a budget for the whole task, preflight included, so
874
- // the deadline is re-armed from creation time rather than from this point.
875
- task.deadlineAt = task.createdAt + effective.worker.timeoutSeconds * 1000;
876
- this.armPreflightDeadline(task, task.deadlineAt - Date.now());
989
+ // The execution budget the RUN gets. `executionTimeoutSeconds === null` is the
990
+ // documented default: an ordinary delegated task has NO total execution
991
+ // deadline, so silence is reported by the monitoring block and never turned
992
+ // into a failure. A number here means the dispatcher explicitly asked for a
993
+ // per-job cap (`overrides.timeoutSeconds`) — the one retained compatibility
994
+ // path — and it is measured from creation, preflight included, exactly as
995
+ // before. `deadlineAt: null` is the explicit "no deadline" fact the view and
996
+ // the preflight gate both read.
997
+ const executionSeconds = effective.worker.executionTimeoutSeconds;
998
+ if (Number.isFinite(executionSeconds) && executionSeconds > 0) {
999
+ task.deadlineAt = task.createdAt + executionSeconds * 1000;
1000
+ this.armPreflightDeadline(task, task.deadlineAt - Date.now());
1001
+ } else {
1002
+ task.deadlineAt = null;
1003
+ // Admission still needs a bound of its own (see DEFAULT_PREFLIGHT_TIMEOUT_MS);
1004
+ // it bounds STARTUP only and is cleared on every exit from admission.
1005
+ this.armPreflightDeadline(task, this.preflightTimeoutMs);
1006
+ }
877
1007
  this.assertLive(task, 'effective');
878
1008
  // The slot claim and the count happen in one synchronous step, ordered by
879
1009
  // admission sequence, so two concurrent starts cannot both take the slot.
@@ -881,7 +1011,7 @@ export class JobEngine {
881
1011
  // does that only after the native executor is confirmed stopped.
882
1012
  this.reserveSlot(task, effective.worker.maxParallelism);
883
1013
 
884
- // ---- 5. provider routes for worker and review, from one snapshot ---------
1014
+ // ---- 5. provider routes for the worker, from one snapshot ---------
885
1015
  task.phase = 'providers';
886
1016
  // The provider-definition lease is taken *before* the first await of this
887
1017
  // step, in this same synchronous section. The native adapter serves the latest
@@ -895,32 +1025,87 @@ export class JobEngine {
895
1025
  this.assertLive(task, 'providers');
896
1026
  const workerRouteId = this.routeFor(task.routes, effective.worker.providerId, 'worker');
897
1027
 
898
- // ---- 6. lock the source workspace before anything is audited or created --
899
- task.phase = 'source-lock';
900
- this.acquireSourceLock(task);
1028
+ // ---- 6 and 7. isolation, and the directory this run owns -----------------
1029
+ //
1030
+ // Which directory a run writes to decides what it has to hold, so the two are
1031
+ // decided together rather than "lock the source, then prepare the tree":
1032
+ //
1033
+ // - **shared**: the run writes to the source checkout itself. The source is
1034
+ // held EXCLUSIVELY for the whole run, exactly as before, so two shared runs
1035
+ // of one repository still refuse each other with `JOB_WORKSPACE_BUSY`.
1036
+ // - **worktree**: the run writes to its own checkout. The source is held only
1037
+ // for PREPARATION — the Git worktree creation, and the commit it is pinned
1038
+ // to — and released as soon as the tree exists, then the tree is held
1039
+ // exclusively. Two isolated runs of one source prepare one at a time (the
1040
+ // turn below) and then run at the same time in separate directories, which
1041
+ // is the whole point of the mode. They no longer refuse each other merely
1042
+ // for sharing a source repository.
1043
+ //
1044
+ // The turn and the preparation lease answer two different hazards and neither
1045
+ // replaces the other: the turn keeps two `git worktree add` calls out of each
1046
+ // other's way in one administrative area, and the preparation lease makes a
1047
+ // shared run (which holds the source exclusively) exclude preparation while it
1048
+ // writes, in both orders. Preparation is over before the run exists, so
1049
+ // preparation cannot deadlock against anything a run holds.
1050
+ const isolation = effective.worker.isolation;
1051
+ if (isolation !== 'worktree' && isolation !== 'shared') {
1052
+ // Unreachable for a validated snapshot; refusing is still the only honest
1053
+ // answer to a mode this build cannot honour.
1054
+ throw new JobError(JOB_CODES.isolationRefused, `isolation ${String(isolation)} is not implemented`, {
1055
+ requested: isolation ?? null,
1056
+ });
1057
+ }
901
1058
 
902
- // ---- 7. isolation: a real worktree, or explicitly shared -----------------
903
- if (effective.worker.isolation === 'worktree') {
904
- task.phase = 'worktree';
905
- const prepared = task.continuationRecord === null
906
- ? await this.guardPreflight(task, 'worktree', () => this.prepareWorktree(task), {
1059
+ if (isolation === 'shared') {
1060
+ // ---- 6. lock the source workspace before anything is audited or created --
1061
+ task.phase = 'source-lock';
1062
+ this.acquireSourceLock(task);
1063
+ } else {
1064
+ // ---- 7. isolation: a real worktree, or an adopted one for a follow-up ----
1065
+ //
1066
+ // Two isolated runs of one source write to different checkouts, so they must RUN
1067
+ // together; only the Git preparation is serialised, because `git worktree add` and
1068
+ // the status read share the source's administrative area. A shared run holds the
1069
+ // source exclusively while it writes, so preparation and a shared run exclude each
1070
+ // other in both orders.
1071
+ //
1072
+ // The GUARD wraps the whole queue turn, not just the Git call inside it: the queue
1073
+ // wait is a native-service-shaped await like any other, so it needs the same
1074
+ // cancellation and deadline bound, and `onLateSettle` still collects a tree that
1075
+ // finished after this start was abandoned.
1076
+ task.phase = 'worktree-queue';
1077
+ const prepared = await this.guardPreflight(
1078
+ task,
1079
+ 'worktree',
1080
+ () => this.withPreparationTurn(task, () => (task.continuationRecord === null
1081
+ ? this.prepareWorktree(task)
1082
+ : this.reuseContinuationWorktree(task))),
1083
+ {
907
1084
  // A tree that finished after this start was abandoned still exists on
908
1085
  // disk. It is recorded and marked complete, never deleted or merged: it
909
1086
  // is evidence, and the host decides what happens to it.
910
1087
  onLateSettle: (value) => this.adoptLateWorktree(task, value),
911
- })
912
- : await this.guardPreflight(task, 'continuation-worktree', () => this.reuseContinuationWorktree(task));
1088
+ },
1089
+ );
913
1090
  task.worktree = prepared;
914
1091
  task.executionPath = prepared.workspacePath;
915
1092
  task.reusedWorktree = task.continuationRecord !== null;
916
1093
  this.assertLive(task, 'worktree');
917
- this.acquireExecutionLock(task);
918
- } else if (effective.worker.isolation !== 'shared') {
919
- // Unreachable for a validated snapshot; refusing is still the only honest
920
- // answer to a mode this build cannot honour.
921
- throw new JobError(JOB_CODES.isolationRefused, `isolation ${String(effective.worker.isolation)} is not implemented`, {
922
- requested: effective.worker.isolation ?? null,
923
- });
1094
+ if (!task.leases.some((lease) => lease.mode === LOCK_MODES.exclusive && samePath(lease.path, task.executionPath))) {
1095
+ // A follow-up drives the directory its parent ran in, so this keeps two
1096
+ // continuations of one chain from writing to one checkout. The refusal is the
1097
+ // same one a busy shared run produces, so a caller can tell the two apart by
1098
+ // `details.purpose`.
1099
+ const treeBusy = this.locks.isLocked(task.executionPath, { mode: LOCK_MODES.exclusive });
1100
+ if (treeBusy && !this.holdsLease(task, task.executionPath)) {
1101
+ throw new JobError(JOB_CODES.busy, 'another job is already running in the isolated workspace', {
1102
+ purpose: 'execution',
1103
+ phase: 'worktree',
1104
+ path: task.executionPath,
1105
+ });
1106
+ }
1107
+ this.acquireExecutionLock(task);
1108
+ }
924
1109
  }
925
1110
 
926
1111
  // ---- 8. baseline in the workspace the run will actually mutate -----------
@@ -964,34 +1149,7 @@ export class JobEngine {
964
1149
  this.assertLive(task, 'worker-route');
965
1150
  task.route = route;
966
1151
 
967
- // ---- 10. review route, frozen BEFORE the worker runs ---------------------
968
- // A review that resolved its route after execution would judge the work with
969
- // whatever configuration existed later, or with an ambient route. A review
970
- // routing failure is recorded on the review record and never refuses the
971
- // task, and it never turns into approval.
972
- if (effective.review.enabled === true) {
973
- task.phase = 'review-route';
974
- try {
975
- const reviewRouteId = this.routeFor(task.routes, effective.review.providerId, 'review');
976
- task.reviewRoute = await this.guardPreflight(task, 'review-route', () => resolveRoute(this.deps, {
977
- providerId: effective.review.providerId,
978
- providerRoute: reviewRouteId,
979
- model: effective.review.model,
980
- reasoningEffort: effective.review.reasoningEffort,
981
- }, { signal: task.controller.signal }));
982
- } catch (error) {
983
- if (error instanceof JobError) throw error;
984
- task.reviewRoute = null;
985
- task.reviewRouteError = {
986
- code: 'REVIEW_ROUTING_REFUSED',
987
- message: diagnostic(error?.message ?? 'the review route could not be confirmed', 400),
988
- cause: typeof error?.code === 'string' ? error.code : null,
989
- };
990
- }
991
- this.assertLive(task, 'review-route');
992
- }
993
-
994
- // ---- 11. last preflight gate before any native create --------------------
1152
+ // ---- 10. last preflight gate before any native create --------------------
995
1153
  task.phase = 'admitted';
996
1154
  this.assertLive(task, 'admitted');
997
1155
  }
@@ -1108,6 +1266,12 @@ export class JobEngine {
1108
1266
 
1109
1267
  /**
1110
1268
  * Record and finish a worktree that was prepared after its start was abandoned.
1269
+ *
1270
+ * The Git call finished after the submission gave up (cancel, or the admission
1271
+ * deadline). The queue released the source lease on that settlement, so nothing is
1272
+ * left to return; what remains is the TREE, which is evidence: it is recorded on the
1273
+ * task and marked complete, never merged and never deleted. The host reviews or
1274
+ * disposes it explicitly.
1111
1275
  * @param {object} task - task record.
1112
1276
  * @param {unknown} prepared - the late value, if it is usable.
1113
1277
  * @returns {void}
@@ -1139,7 +1303,7 @@ export class JobEngine {
1139
1303
 
1140
1304
  /**
1141
1305
  * Record the one terminal state a task may have. The first writer wins, so a
1142
- * late promise, a late review result or a second failure can never revive or
1306
+ * late promise or a second failure can never revive or
1143
1307
  * overwrite a task that has already ended.
1144
1308
  * @param {object} task - task record.
1145
1309
  * @param {string} state - terminal state to record.
@@ -1204,7 +1368,7 @@ export class JobEngine {
1204
1368
  * Idempotent by latch. A task keeps its record after it is terminal, so every
1205
1369
  * terminal path — success, failure, cancellation, timeout, admission refusal,
1206
1370
  * dispose — has to come through here, and a second path that races the first
1207
- * (a late review refusal, `cancel()` after `dispose()`) awaits the same
1371
+ * (`cancel()` after `dispose()`) awaits the same
1208
1372
  * promise instead of releasing twice.
1209
1373
  *
1210
1374
  * It refuses to hand anything back while the native executor this task started
@@ -1371,7 +1535,7 @@ export class JobEngine {
1371
1535
  /**
1372
1536
  * Ensure the native provider routes for one settings snapshot.
1373
1537
  *
1374
- * One call per snapshot, before either the worker or the review route is
1538
+ * One call per snapshot, before the worker route is
1375
1539
  * resolved, so both selections come from the same mapping. Previously ensured
1376
1540
  * routes stay with the registry until plugin dispose; the engine never narrows
1377
1541
  * the set it passes in.
@@ -1490,7 +1654,7 @@ export class JobEngine {
1490
1654
  * resolving one produced the field failure this module exists to prevent.
1491
1655
  * @param {Map<string, string> | null} routes - route mapping, or null for the legacy path.
1492
1656
  * @param {string | null} providerId - operator-facing profile id.
1493
- * @param {string} role - `worker` or `review`, for diagnostics.
1657
+ * @param {string} role - route role for diagnostics.
1494
1658
  * @returns {string} native route id.
1495
1659
  */
1496
1660
  routeFor(routes, providerId, role) {
@@ -1520,38 +1684,253 @@ export class JobEngine {
1520
1684
  }
1521
1685
 
1522
1686
  /**
1523
- * Acquire the lease on the source workspace.
1687
+ * Acquire the EXCLUSIVE lease on the source workspace.
1688
+ *
1689
+ * This is the shared-isolation case: the run writes to the source checkout, so
1690
+ * nothing else — another shared run, or another run's Git preparation — may
1691
+ * touch it for as long as the run lives.
1524
1692
  * @param {object} task - pending record.
1525
1693
  * @returns {void}
1526
1694
  */
1527
1695
  acquireSourceLock(task) {
1528
1696
  try {
1529
- const lease = this.locks.acquire(task.sourcePath, { taskId: task.taskId });
1530
- task.leases.push({ path: task.sourcePath, nonce: lease.nonce });
1697
+ // `explicitRelease`: a shared run may legitimately last hours (a delegated run
1698
+ // has no total time limit by default), so the sourcestays this run's until
1699
+ // {@link finalize} returns it — never until a wall-clock bound expires.
1700
+ const lease = this.locks.acquire(task.sourcePath, {
1701
+ taskId: task.taskId,
1702
+ mode: LOCK_MODES.exclusive,
1703
+ explicitRelease: true,
1704
+ });
1705
+ task.leases.push({ path: task.sourcePath, nonce: lease.nonce, mode: LOCK_MODES.exclusive, purpose: 'source' });
1531
1706
  } catch (error) {
1532
1707
  if (error instanceof WorkspaceError && error.code === LOCK_CODES.busy) {
1533
- throw new JobError(JOB_CODES.busy, error.message, redactDeep(error.details ?? {}));
1708
+ throw new JobError(JOB_CODES.busy, error.message, { purpose: 'source', ...redactDeep(error.details ?? {}) });
1534
1709
  }
1535
1710
  throw error;
1536
1711
  }
1537
1712
  }
1538
1713
 
1539
1714
  /**
1540
- * Acquire the lease on the execution workspace (the worktree), after the
1541
- * source lease. A shared run reuses the source lease instead of double-locking
1542
- * one path.
1715
+ * Run one Git preparation under the per-source FIFO, and nothing else.
1716
+ *
1717
+ * ## Why a queue exists
1718
+ *
1719
+ * Two isolated runs of one source write to two DIFFERENT checkouts, so they must RUN
1720
+ * at the same time. What they share is Git's administrative area: `worktree add`, the
1721
+ * pinned-commit read, `status` and `prune` all touch the same `.git/worktrees` index,
1722
+ * and `git status` there can see the source checkout. So only the PREPARATION step is
1723
+ * serialised per source, never the run.
1724
+ *
1725
+ * ## How the exclusion is actually enforced
1726
+ *
1727
+ * Two independent mechanisms, and both must hold:
1728
+ *
1729
+ * - **The FIFO** — arrivals queue by resolved source path and only the head runs
1730
+ * its Git work. A waiter that gives up while queued leaves and hands the place on,
1731
+ * so the queue never jams.
1732
+ * - **A hard exclusive lease on the source**, taken by the head in a LOCAL variable
1733
+ * and released in the same `finally` that ends its Git work. It is deliberately
1734
+ * NOT recorded in `task.leases`: an admission that is cancelled would otherwise
1735
+ * let the ordinary `finalize` release it while `git worktree add` was still
1736
+ * writing, which is exactly how a second preparation could begin beside the first
1737
+ * (`peak: 2`).
1738
+ *
1739
+ * The lease is what makes the guarantee survive a cancellation. The outer
1740
+ * {@link JobEngine#guardPreflight} may return to `start()` — and `cancel()` may
1741
+ * complete — while this async operation is still running; the operation keeps the
1742
+ * lease until Git really answers, so the next head cannot start Git until then. This
1743
+ * method therefore never has to "step aside" early: its `finally` runs when the work
1744
+ * it awaits is truly over.
1745
+ * @param {object} task - pending run with a resolved source path.
1746
+ * @param {() => Promise<object>} work - the Git preparation to run as the head.
1747
+ * @returns {Promise<object>} the preparation's result.
1748
+ */
1749
+ async withPreparationTurn(task, work) {
1750
+ const key = lockKeyOf(task.sourcePath);
1751
+ let queue = this.preparationTurns.get(key);
1752
+ if (queue === undefined) {
1753
+ queue = [];
1754
+ this.preparationTurns.set(key, queue);
1755
+ }
1756
+ const entry = { key, queue, signal: task.controller.signal, wake: null, granted: null, left: false };
1757
+ entry.granted = new Promise((resolvePromise) => { entry.wake = () => resolvePromise(); });
1758
+ queue.push(entry);
1759
+ // The FIRST arrival takes the turn at once: there is no predecessor to hand it over.
1760
+ // A later arrival waits for the hand-over in `finally`, which happens only after the
1761
+ // head's Git work is finished and its lease is back — never before.
1762
+ if (queue.length === 1) entry.wake();
1763
+
1764
+ let release = null;
1765
+ try {
1766
+ // A waiter that is not the head subscribes FIRST, so a hand-over that happens
1767
+ // between these two steps cannot be missed.
1768
+ const queued = this.awaitPreparationTurn(task, entry);
1769
+ await queued;
1770
+ // Refusals after the wait must be seen here, in the same step that starts Git.
1771
+ this.assertLive(task, 'worktree-queue');
1772
+ // An EXCLUSIVE lease, held locally. A shared run holds the source the same way
1773
+ // while it writes, so the two exclude each other in both orders.
1774
+ release = this.acquirePreparationLease(task);
1775
+ return await work();
1776
+ } finally {
1777
+ // Order is deliberate: the lease goes back BEFORE the place is handed on, so the
1778
+ // next head can never observe a lease this turn is about to drop. The place is
1779
+ // released only once this Git work has really finished — the whole point of the
1780
+ // local lease is that the outer guard may have already returned to `start()`.
1781
+ release?.();
1782
+ this.leavePreparationQueue(entry);
1783
+ }
1784
+ }
1785
+
1786
+ /**
1787
+ * Wait until this submission is the head of its source's preparation queue.
1788
+ *
1789
+ * Ends in one of three ways: the turn is granted, the task is cancelled or disposed,
1790
+ * or {@link PREPARATION_QUEUE_LIMIT_MS} expires. Only the first may start Git; the
1791
+ * others leave the queue (handing the place on) and are refused, so a cancelled
1792
+ * submission can never create a tree.
1793
+ * @param {object} task - pending run with a resolved source path.
1794
+ * @param {object} entry - this submission's queue entry.
1795
+ * @returns {Promise<void>} resolves when this submission is the head.
1796
+ */
1797
+ async awaitPreparationTurn(task, entry) {
1798
+ const limit = Number.isFinite(this.preparationQueueLimitMs) && this.preparationQueueLimitMs > 0
1799
+ ? this.preparationQueueLimitMs
1800
+ : PREPARATION_QUEUE_LIMIT_MS;
1801
+ let stopWatching = null;
1802
+ const abandoned = new Promise((resolvePromise) => {
1803
+ // A signal that is ALREADY aborted never fires its listener, so it is checked
1804
+ // rather than awaited.
1805
+ if (entry.signal?.aborted === true) {
1806
+ resolvePromise('aborted');
1807
+ return;
1808
+ }
1809
+ const onAbort = () => resolvePromise('aborted');
1810
+ entry.signal?.addEventListener?.('abort', onAbort, { once: true });
1811
+ const timer = setTimeout(() => resolvePromise('timeout'), limit);
1812
+ timer?.unref?.();
1813
+ stopWatching = () => {
1814
+ entry.signal?.removeEventListener?.('abort', onAbort);
1815
+ clearTimeout(timer);
1816
+ };
1817
+ });
1818
+ let outcome;
1819
+ try {
1820
+ outcome = await Promise.race([entry.granted, abandoned]);
1821
+ } finally {
1822
+ stopWatching?.();
1823
+ }
1824
+ if (outcome === undefined) return;
1825
+ // Refused while queued: leave now, hand the place on, and never start Git.
1826
+ this.leavePreparationQueue(entry);
1827
+ if (outcome === 'timeout') {
1828
+ throw new JobError(JOB_CODES.timeout, 'the task could not prepare an isolated workspace in time', {
1829
+ phase: 'worktree-queue',
1830
+ queued: true,
1831
+ });
1832
+ }
1833
+ throw this.preflightAbort(task, 'worktree-queue');
1834
+ }
1835
+
1836
+ /**
1837
+ * Remove one entry from its queue and pass the turn on. Idempotent.
1838
+ * @param {object} entry - the queue entry to remove.
1839
+ * @returns {void}
1840
+ */
1841
+ leavePreparationQueue(entry) {
1842
+ if (entry.left === true) return;
1843
+ entry.left = true;
1844
+ const index = entry.queue.indexOf(entry);
1845
+ if (index >= 0) entry.queue.splice(index, 1);
1846
+ // A woken waiter that is itself abandoned drops out on its own turn and hands the
1847
+ // place on again, so the place is never lost.
1848
+ entry.queue[0]?.wake?.();
1849
+ if (entry.queue.length === 0 && this.preparationTurns.get(entry.key) === entry.queue) {
1850
+ this.preparationTurns.delete(entry.key);
1851
+ }
1852
+ }
1853
+
1854
+ /**
1855
+ * Take the head's hard exclusive lease on the source, locally.
1856
+ *
1857
+ * Returned as a releaser rather than recorded on the task: the task's `leases` list
1858
+ * is cleared by ordinary `finalize`, which may run while this Git call is still
1859
+ * writing — releasing here would let a second preparation start beside it.
1860
+ * @param {object} task - pending run with a resolved source path.
1861
+ * @returns {() => void} idempotent releaser for exactly this nonce.
1862
+ */
1863
+ acquirePreparationLease(task) {
1864
+ let lease;
1865
+ try {
1866
+ lease = this.locks.acquire(task.sourcePath, {
1867
+ taskId: task.taskId,
1868
+ mode: LOCK_MODES.exclusive,
1869
+ explicitRelease: true,
1870
+ });
1871
+ } catch (error) {
1872
+ if (error instanceof WorkspaceError && error.code === LOCK_CODES.busy) {
1873
+ throw new JobError(JOB_CODES.busy, error.message, {
1874
+ purpose: 'source',
1875
+ ...redactDeep(error.details ?? {}),
1876
+ });
1877
+ }
1878
+ throw error;
1879
+ }
1880
+ let released = false;
1881
+ // The lease names its directory `workspacePath`; `path` is the name this module uses
1882
+ // for the same value on a task's own lease records. Reading the wrong one would make
1883
+ // every release a silent no-op keyed on `undefined`.
1884
+ const heldPath = lease.workspacePath ?? task.sourcePath;
1885
+ return () => {
1886
+ if (released) return;
1887
+ released = true;
1888
+ try {
1889
+ this.locks.release(heldPath, lease.nonce);
1890
+ } catch {
1891
+ // Releasing a lease we no longer hold is a no-op by design.
1892
+ }
1893
+ };
1894
+ }
1895
+
1896
+ /**
1897
+ * Whether this task already holds a lease on one path.
1898
+ * @param {object} task - task record.
1899
+ * @param {string} path - workspace path.
1900
+ * @returns {boolean} true when a lease on that path is held.
1901
+ */
1902
+ holdsLease(task, path) {
1903
+ return task.leases.some((lease) => samePath(lease.path, path));
1904
+ }
1905
+
1906
+ /**
1907
+ * Acquire the EXCLUSIVE lease on the execution workspace (the worktree), once it
1908
+ * exists. A shared run already holds the source exclusively, so one path is never
1909
+ * double-locked.
1543
1910
  * @param {object} task - pending record with a prepared execution path.
1544
1911
  * @returns {void}
1545
1912
  */
1546
1913
  acquireExecutionLock(task) {
1547
1914
  if (task.executionPath === null || samePath(task.executionPath, task.sourcePath)) return;
1548
- if (task.leases.some((lease) => samePath(lease.path, task.executionPath))) return;
1915
+ if (this.holdsLease(task, task.executionPath)) return;
1549
1916
  try {
1550
- const lease = this.locks.acquire(task.executionPath, { taskId: task.taskId });
1551
- task.leases.push({ path: task.executionPath, nonce: lease.nonce });
1917
+ // `explicitRelease`: an isolated run is a real execution whose length nobody
1918
+ // bounded, so its checkout stays its own until {@link finalize} returns it.
1919
+ const lease = this.locks.acquire(task.executionPath, {
1920
+ taskId: task.taskId,
1921
+ mode: LOCK_MODES.exclusive,
1922
+ explicitRelease: true,
1923
+ });
1924
+ task.leases.push({
1925
+ path: task.executionPath,
1926
+ nonce: lease.nonce,
1927
+ mode: LOCK_MODES.exclusive,
1928
+ purpose: 'execution',
1929
+ });
1552
1930
  } catch (error) {
1553
1931
  if (error instanceof WorkspaceError && error.code === LOCK_CODES.busy) {
1554
1932
  throw new JobError(JOB_CODES.busy, 'another job is already running in the isolated workspace', {
1933
+ purpose: 'execution',
1555
1934
  ...redactDeep(error.details ?? {}),
1556
1935
  });
1557
1936
  }
@@ -1562,7 +1941,13 @@ export class JobEngine {
1562
1941
  /**
1563
1942
  * Prepare an isolated worktree, or refuse. There is no fallback to shared
1564
1943
  * execution: a missing service is a refusal, not a downgrade.
1565
- * @param {object} task - pending record with a locked source path.
1944
+ *
1945
+ * Called only as the head of its source's preparation queue, so the preparation
1946
+ * lease on the source is already held (see {@link JobEngine#withPreparationTurn})
1947
+ * and no sibling can be inside Git at the same time. This method therefore owns no
1948
+ * lease of its own: whatever happens to the caller, the queue releases the one it
1949
+ * took when this promise settles.
1950
+ * @param {object} task - pending record with a resolved source path.
1566
1951
  * @returns {Promise<object>} prepared worktree metadata.
1567
1952
  */
1568
1953
  async prepareWorktree(task) {
@@ -1575,6 +1960,9 @@ export class JobEngine {
1575
1960
  );
1576
1961
  }
1577
1962
  let prepared;
1963
+ // The Git call is awaited directly: the queue's `finally` releases the head's
1964
+ // exclusive lease only after this promise settles, so an abandoned caller cannot
1965
+ // let a second preparation start beside a running `git worktree add`.
1578
1966
  try {
1579
1967
  prepared = await manager.prepare({
1580
1968
  taskId: task.taskId,
@@ -1613,6 +2001,9 @@ export class JobEngine {
1613
2001
  cause: 'WORKTREE_SAME_PATH',
1614
2002
  });
1615
2003
  }
2004
+ // A fresh worktree may be the first to create the root. Workspace registration
2005
+ // only affects the sidebar and is independent of the task's own placement.
2006
+ void this.deps.registerWorktreeWorkspace?.();
1616
2007
  return prepared;
1617
2008
  }
1618
2009
 
@@ -1676,6 +2067,12 @@ export class JobEngine {
1676
2067
  // row that cannot be found or read is a refusal, never a skip.
1677
2068
  const parent = this.tasks.get(parentId) ?? null;
1678
2069
  let row;
2070
+ // The parent's recorded team receipt, kept beside the snapshot so the decision below
2071
+ // reads facts from the SAME documents that were just proven rather than re-reading
2072
+ // history later. A live record is authoritative; a row from a previous process
2073
+ // supplies its stored `team`/`agentTeamsOrigin`, and the identity map (read once,
2074
+ // below) supplies the chain's decision when an older row predates those fields.
2075
+ let durableTeamRecord = {};
1679
2076
  if (parent !== null) {
1680
2077
  if (parent.connectionId !== caller) throw this.absentContinuation(parentId);
1681
2078
  row = {
@@ -1705,6 +2102,11 @@ export class JobEngine {
1705
2102
  planNodeId: durable.planNodeId ?? null,
1706
2103
  parentNodeId: durable.parentNodeId ?? null,
1707
2104
  };
2105
+ durableTeamRecord = {
2106
+ agentTeams: durable.agentTeams,
2107
+ agentTeamsOrigin: durable.agentTeamsOrigin,
2108
+ team: durable.team,
2109
+ };
1708
2110
  }
1709
2111
 
1710
2112
  // The identity map is the only document carrying the exact execution directory and
@@ -1745,6 +2147,12 @@ export class JobEngine {
1745
2147
  // isolation and worktree steps read to resume the parent instead of starting over.
1746
2148
  task.continuationParent = parent;
1747
2149
  task.continuationRecord = task.continuationIdentity;
2150
+ // The parent's Agent Teams facts, taken from the same two documents that were just
2151
+ // proven. Admission reads them once here, so a later step never re-reads history or
2152
+ // the identity map for a decision it must not re-derive.
2153
+ task.continuationTeam = parent !== null
2154
+ ? teamFactsOf(parent.agentTeams, parent.agentTeamsOrigin, parent.execution?.team)
2155
+ : teamFactsOf(durableTeamRecord.agentTeams, durableTeamRecord.agentTeamsOrigin, durableTeamRecord.team);
1748
2156
  }
1749
2157
 
1750
2158
  async assertPlanHierarchy(task, sourcePath) {
@@ -2819,6 +3227,7 @@ export class JobEngine {
2819
3227
  * @throws {JobError} when a different conclusion is recorded or already in flight.
2820
3228
  */
2821
3229
  beginReviewWrite(task, decision, note, completionSummary = null) {
3230
+ this.assertRecordNotBeingRemoved(task.taskId);
2822
3231
  if (this.history === null || this.history === undefined || typeof this.history.save !== 'function') {
2823
3232
  // `persistHistory` answers success for the missing-store posture, which would let a
2824
3233
  // review be claimed as saved when nothing was written, so this is refused up front.
@@ -3359,7 +3768,12 @@ export class JobEngine {
3359
3768
  }
3360
3769
 
3361
3770
  /**
3362
- * Release every lease this task holds, newest first.
3771
+ * Release every lease this task still holds, newest first.
3772
+ *
3773
+ * Only EXECUTION leases are recorded on a task. The head's Git-preparation lease is
3774
+ * held in a local variable by {@link JobEngine#withPreparationTurn} and never enters
3775
+ * this list, precisely so an admission that is cancelled while `git worktree add` is
3776
+ * still running cannot have its source returned from here.
3363
3777
  * @param {object} task - task record.
3364
3778
  * @returns {void}
3365
3779
  */
@@ -3387,6 +3801,18 @@ export class JobEngine {
3387
3801
  task.state = TASK_STATES.running;
3388
3802
  task.phase = 'execute';
3389
3803
  task.startedAt = Date.now();
3804
+ // The instant DSH really STARTED running this task, as the engine's own clock reads
3805
+ // it. `startedAt` stays the wall-clock fact the view and the history report; this is
3806
+ // the same moment expressed in the clock the monitors use, and it is what BOTH
3807
+ // reminders measure from: the ten-minute inspection (always, busy or quiet) and the
3808
+ // forty-minute delivery clock (until TaskBridge hands a new result to the commander).
3809
+ // A recorded start that disagrees wildly with that clock is not an elapsed time, so
3810
+ // the engine stamps its own instant instead of inheriting a foreign time base.
3811
+ const clockNow = this.clock();
3812
+ const plausible = Number.isFinite(task.startedAt) && task.startedAt > 0
3813
+ && task.startedAt <= clockNow
3814
+ && clockNow - task.startedAt <= MAX_PLAUSIBLE_START_SKEW_MS;
3815
+ task.runStartedAt = plausible ? task.startedAt : clockNow;
3390
3816
  }
3391
3817
  // The monitor exists from the moment the run is driven, so an executor that
3392
3818
  // produces nothing at all is still measured from its own state time instead of
@@ -3398,7 +3824,18 @@ export class JobEngine {
3398
3824
  // (against `startedAt`, i.e. while the task was still `pending`) already holds a
3399
3825
  // reference to the monitor, and swapping it here would leave that observer
3400
3826
  // watching an object that never receives another event.
3401
- this.ensureMonitor(task);
3827
+ const monitor = this.ensureMonitor(task);
3828
+ // Arm the run's ON-DEMAND self-check timer. It is the one scheduler the monitor owns:
3829
+ // a run is inspected ONCE when it has really been running for `selfCheckSeconds`,
3830
+ // even when no host is waiting on it — and even while its model and tools stay busy.
3831
+ // The instant is the run's real start + `selfCheckSeconds` (the stamp set just above), so
3832
+ // queueing, admission and Session creation never arm it. finalize/cancel/dispose clear it
3833
+ // (see `releaseMonitor`).
3834
+ try {
3835
+ monitor.scheduleSelfCheck?.();
3836
+ } catch {
3837
+ // Scheduling can never block a run from starting.
3838
+ }
3402
3839
  try {
3403
3840
  const workerSelection = {
3404
3841
  // The public profile id stays the operator-facing identity; the native
@@ -3450,7 +3887,13 @@ export class JobEngine {
3450
3887
  title: task.title,
3451
3888
  cwd: task.executionPath,
3452
3889
  selection: workerSelection,
3453
- timeoutMs: task.effective.worker.timeoutSeconds * 1000,
3890
+ // The RUN's own budget, or `null` for "no total deadline" (the default).
3891
+ // An absent execution budget must not be sent as `undefined`: the runner
3892
+ // treats a non-positive/non-integer value the same way, but stating `null`
3893
+ // keeps the intent explicit in the request it receives.
3894
+ timeoutMs: Number.isFinite(task.effective.worker.executionTimeoutSeconds)
3895
+ ? task.effective.worker.executionTimeoutSeconds * 1000
3896
+ : null,
3454
3897
  signal: task.controller.signal,
3455
3898
  // What this run does with its DSH conversation, frozen on the task at
3456
3899
  // creation: omitted means a new conversation, present means continue exactly
@@ -3495,10 +3938,18 @@ export class JobEngine {
3495
3938
  // forwarded — there is no field in the summary they could travel in.
3496
3939
  // This hook is also the only execution evidence the phase trusts.
3497
3940
  onEvent: (event) => { this.onExecutionEvent(task, event); },
3498
- // The commander's DSH Agent Teams decision for THIS task's own Session. Absent
3499
- // when the task froze `null` (no choice): the run then keeps the Session's
3500
- // current mode instead of guessing one.
3501
- ...(task.agentTeams === null || task.agentTeams === undefined ? {} : { agentTeams: task.agentTeams }),
3941
+ // The DSH Agent Teams decision for THIS task's own Session. ABSENT when the task
3942
+ // froze none — a continuation whose chain recorded no decision, so the native
3943
+ // Session keeps whatever mode it already has instead of being overwritten by a
3944
+ // setting that was never about it.
3945
+ ...(task.agentTeams === null || task.agentTeams === undefined ? {} : {
3946
+ agentTeams: task.agentTeams,
3947
+ // A NARROW, strictly-boolean fact: is this the operator's default, or did a
3948
+ // person decide it? The runner uses it to refuse explicit/inherited choices on a
3949
+ // host with no agent-teams service, while the documented OFF default may proceed
3950
+ // unpublished. Always a boolean, never the freeze's own tri-state.
3951
+ agentTeamsImplicit: task.agentTeamsFromDefault === true,
3952
+ }),
3502
3953
  });
3503
3954
  task.native.promise = pending;
3504
3955
  let run;
@@ -3604,19 +4055,6 @@ export class JobEngine {
3604
4055
  return;
3605
4056
  }
3606
4057
 
3607
- // Review runs only for a completed execution, and only when enabled. Its
3608
- // route was frozen during preflight; nothing here re-reads settings.
3609
- task.phase = 'review';
3610
- task.review = await this.runReview(task);
3611
-
3612
- // A cancellation or revocation during the review makes the task terminal
3613
- // cancelled. It must never be reported as awaiting host review, because
3614
- // nothing was reviewed to completion.
3615
- if (this.isCancelled(task) || task.review.state === REVIEW_STATES.cancelled) {
3616
- this.finishCancelled(task, task.review.state === REVIEW_STATES.cancelled ? 'review-cancelled' : null);
3617
- return;
3618
- }
3619
-
3620
4058
  task.state = TASK_STATES.awaitingHostReview;
3621
4059
  task.phase = 'awaiting-host-review';
3622
4060
  task.endedAt = Date.now();
@@ -3687,7 +4125,14 @@ export class JobEngine {
3687
4125
  now: () => this.clock(),
3688
4126
  ...(this.observationWait === undefined ? {} : { wait: this.observationWait }),
3689
4127
  waitSliceMs: this.observeSliceMs,
4128
+ // The scheduler seam. Production leaves it absent and gets the real (unref'd)
4129
+ // timer; a test injects its own so the scheduled self-check is driven at the
4130
+ // instant it was armed for instead of waiting ten minutes of wall time.
4131
+ ...(this.timerSeam === undefined ? {} : { setTimeout: this.timerSeam.setTimeout, clearTimeout: this.timerSeam.clearTimeout }),
3690
4132
  selfCheckSeconds: monitoring?.selfCheckSeconds ?? MONITORING_DEFAULTS.selfCheckSeconds,
4133
+ // The ONE notification interval this product measures: consecutive time without
4134
+ // real progress, reported as a run progress check asking the commander to look.
4135
+ // `0` means the operator switched it off for this run.
3691
4136
  attentionSeconds: monitoring?.attentionSeconds ?? MONITORING_DEFAULTS.attentionSeconds,
3692
4137
  repeatFailureThreshold: monitoring?.repeatFailureThreshold ?? MONITORING_DEFAULTS.repeatFailureThreshold,
3693
4138
  log: (message, detail) => this.deps?.logger?.warn?.(message, detail),
@@ -3726,6 +4171,8 @@ export class JobEngine {
3726
4171
  const monitor = task?.monitor ?? null;
3727
4172
  if (monitor === null || monitor === undefined) return;
3728
4173
  try {
4174
+ // `dispose` both finalizes the activity and clears the scheduled self-check, so a
4175
+ // finished, failed, cancelled or torn-down run leaves NO timer behind.
3729
4176
  monitor.dispose(Number.isFinite(task.endedAt) ? task.endedAt : this.clock());
3730
4177
  } catch {
3731
4178
  // A monitor that refuses to dispose is a defect, not a reason to leave a
@@ -3784,8 +4231,15 @@ export class JobEngine {
3784
4231
  activityView(task) {
3785
4232
  const monitor = task?.monitor ?? null;
3786
4233
  if (monitor === null || monitor === undefined) return null;
3787
- const at = this.clock();
4234
+ let at;
3788
4235
  try {
4236
+ // A settled record is described at its OWN recorded end (`finalize` writes it onto the
4237
+ // activity), so every elapsed value — including the delivery interval — is the span
4238
+ // the run really had. A live run is described at the engine's clock.
4239
+ const finalizedAt = monitor.activity?.final;
4240
+ at = finalizedAt !== null && finalizedAt !== undefined && Number.isFinite(finalizedAt.endedAt)
4241
+ ? finalizedAt.endedAt
4242
+ : this.clock();
3789
4243
  return monitor.snapshot({ at, toolActive: this.toolActive(task) });
3790
4244
  } catch {
3791
4245
  return null;
@@ -3896,9 +4350,23 @@ export class JobEngine {
3896
4350
  if (settled !== null) reason = settled;
3897
4351
  // A reminder superseded by a terminal state or a pending request above is dropped:
3898
4352
  // those outrank it, and a failure report must not describe a task that now needs a
3899
- // different decision.
4353
+ // different decision. The same rule covers the `checkpoint` classification: it is
4354
+ // carried only when the reason actually is `attention`.
3900
4355
  const failure = reason === OBSERVE_TASK_REASONS.attention ? (outcome.failure ?? null) : null;
3901
- return this.observationOf(task, reason, monitor, waitMs, outcome.waitedMs, outcome.activitySinceWait, failure, failureAck);
4356
+ const reminder = reason === OBSERVE_TASK_REASONS.attention
4357
+ ? { checkpoint: outcome.checkpoint ?? null, progress: outcome.progress ?? null }
4358
+ : null;
4359
+ return this.observationOf(
4360
+ task,
4361
+ reason,
4362
+ monitor,
4363
+ waitMs,
4364
+ outcome.waitedMs,
4365
+ outcome.activitySinceWait,
4366
+ failure,
4367
+ failureAck,
4368
+ reminder,
4369
+ );
3902
4370
  }
3903
4371
 
3904
4372
  /**
@@ -4076,14 +4544,56 @@ export class JobEngine {
4076
4544
  * what ended the wait.
4077
4545
  * @param {object | null} [failureAck] - the acknowledgment result, present only when
4078
4546
  * the caller asked to acknowledge one delivered reminder by its `eventId`.
4547
+ * @param {object | null} [reminder] - the reminder an `attention` observation
4548
+ * reported: `{ checkpoint, progress }`. `checkpoint` distinguishes a scheduled
4549
+ * progress check from the silence reminder and from the failure reminder;
4550
+ * `progress` is its bounded diagnostic. Absent for every other reason, so the
4551
+ * previous answer shape is unchanged for a caller that never sees one.
4079
4552
  * @returns {object} observation result.
4080
4553
  */
4081
- observationOf(task, reason, monitor, waitMs, waitedMs, activitySinceWait, failure = null, failureAck = null) {
4554
+ observationOf(task, reason, monitor, waitMs, waitedMs, activitySinceWait, failure = null, failureAck = null, reminder = null) {
4082
4555
  const at = this.clock();
4083
4556
  const summary = this.observationSummary(task, at);
4084
4557
  const pending = task?.permission?.pending ?? null;
4085
4558
  const live = monitor ?? task?.monitor ?? null;
4086
- const selfCheck = live === null || live === undefined ? null : live.snapshot({ at }).selfCheck;
4559
+ const selfCheckView = live === null || live === undefined ? null : live.snapshot({ at }).selfCheck;
4560
+ const selfCheck = selfCheckView;
4561
+ const isAttention = reason === OBSERVE_TASK_REASONS.attention;
4562
+ // A reminder superseded by a more urgent reason (a pending request, or a terminal
4563
+ // state) is DROPPED rather than carried: it would describe a task that now needs a
4564
+ // different decision, and the next observation re-derives it from the monitor.
4565
+ const checkpoint = isAttention && typeof reminder?.checkpoint === 'string' ? reminder.checkpoint : null;
4566
+ const progress = checkpoint === CHECKPOINTS.progress && reminder?.progress !== null
4567
+ && typeof reminder?.progress === 'object'
4568
+ ? reminder.progress
4569
+ : null;
4570
+ // THE DELIVERY. This observation is the answer this process is about to hand to the
4571
+ // commander, and the ONLY thing that advances the run's 40-minute clock is a new result
4572
+ // the commander did not have before — which, in THIS wait protocol, means the run's
4573
+ // terminal outcome. There is no mid-run stage result: the wait channel delivers the
4574
+ // result when the task ends, and nothing else.
4575
+ //
4576
+ // So none of these is a delivery:
4577
+ // * a LOCAL self-check diagnostic, on any answer — including a plain heartbeat. Reading
4578
+ // the diagnostic is a read of local facts the plugin already holds; it is not work
4579
+ // returned to anyone, and if it reset the clock the run's own inspection would hide the
4580
+ // very stall that inspection exists to notice;
4581
+ // * DSH-internal model steps, reasoning, text deltas and tool activity;
4582
+ // * a heartbeat, an empty poll or a `wait-limit`;
4583
+ // * a permission or question wait, a repeated-failure reminder, the progress check itself;
4584
+ // * the run's START, which opens the FIRST interval rather than counting as one delivery.
4585
+ //
4586
+ // A genuine stage result reaches the monitor through the reserved, event-deduplicated
4587
+ // {@link TaskMonitor#noteStageResult}; nothing in this engine calls it, because nothing in
4588
+ // this protocol produces such a result yet. A test drives it directly.
4589
+ let delivery = null;
4590
+ try {
4591
+ delivery = live === null || live === undefined || typeof live.delivery !== 'function'
4592
+ ? null
4593
+ : live.delivery({ at, delivered: terminalReason(task) !== null });
4594
+ } catch {
4595
+ delivery = null;
4596
+ }
4087
4597
  return {
4088
4598
  task: summary,
4089
4599
  reason,
@@ -4103,13 +4613,29 @@ export class JobEngine {
4103
4613
  // thing that distinguishes that reminder from an ordinary silence report, whose
4104
4614
  // own diagnostic is `selfCheck`. Its `eventId` is the identity the receiver
4105
4615
  // acknowledges; the reminder is redelivered until that ack lands.
4106
- failure: reason === OBSERVE_TASK_REASONS.attention && failure !== null ? failure : null,
4616
+ failure: isAttention && failure !== null ? failure : null,
4617
+ // WHICH attention reminder this is, and — for a scheduled progress check — its
4618
+ // bounded diagnostic. Present only on an `attention` observation, so the
4619
+ // shape of every other reason is unchanged.
4620
+ ...(checkpoint === null ? {} : { checkpoint }),
4621
+ ...(progress === null ? {} : { progress }),
4107
4622
  // The acknowledgment result. Present (possibly with `acknowledged: false`) only
4108
4623
  // when the caller asked to acknowledge; absent otherwise, so an old caller's
4109
4624
  // observation shape is byte-for-byte unchanged.
4110
4625
  ...(failureAck === null ? {} : { failureAck }),
4111
4626
  activity: summary.activity,
4112
4627
  selfCheck,
4628
+ // The delivery state, as two INDEPENDENT facts (present only when the monitor could
4629
+ // state them, so an injected fixture's shape is unchanged): how long nothing was
4630
+ // returned to the commander, and what DSH is doing right now. `returned` states
4631
+ // whether THIS answer is what advanced the clock, so a caller never has to infer it.
4632
+ ...(delivery === null ? {} : {
4633
+ returnState: {
4634
+ ...delivery,
4635
+ returned: delivery.counted === true,
4636
+ returnedReason: delivery.counted === true ? reason : null,
4637
+ },
4638
+ }),
4113
4639
  wait: { waitMs, waitedMs: Math.max(0, Math.trunc(waitedMs)), activitySinceWait: activitySinceWait === true },
4114
4640
  };
4115
4641
  }
@@ -4117,8 +4643,7 @@ export class JobEngine {
4117
4643
  /**
4118
4644
  * The compact task summary an observation returns.
4119
4645
  *
4120
- * Deliberately narrower than {@link view}: it carries the facts a waiting caller
4121
- * needs (identity, phase, timing, silence, the tool in flight, the frozen route)
4646
+ * Deliberately narrower than {@link view}: it carries the facts a waiting caller * needs (identity, phase, timing, silence, the tool in flight, the frozen route)
4122
4647
  * and NONE of the evidence a reviewer reads (diff, execution text, review text).
4123
4648
  * @param {object} task - task record.
4124
4649
  * @param {number} at - reference time.
@@ -4148,6 +4673,18 @@ export class JobEngine {
4148
4673
  selfCheck: monitor === null || monitor === undefined
4149
4674
  ? null
4150
4675
  : { episode: monitor.selfCheck.episode, checkedAt: monitor.selfCheck.checkedAt, verdict: monitor.selfCheck.verdict },
4676
+ // The two independent facts a reminder must keep apart, in the compact summary a
4677
+ // waiting caller reads: how long nothing has been returned to the commander, and
4678
+ // what DSH is doing right now. Both are bounded reads of the monitor's own state.
4679
+ returnState: monitor === null || monitor === undefined || typeof monitor.delivery !== 'function'
4680
+ ? null
4681
+ : (() => {
4682
+ try {
4683
+ return monitor.delivery({ at });
4684
+ } catch {
4685
+ return null;
4686
+ }
4687
+ })(),
4151
4688
  // The route this task froze at admission. Reported as the frozen triple, not
4152
4689
  // re-resolved: a settings edit during the wait must not change what a
4153
4690
  // finished run is described as having used.
@@ -4166,9 +4703,11 @@ export class JobEngine {
4166
4703
  // reviewed" from "the review is being written right now" and does not resubmit one.
4167
4704
  reviewPersistence: this.reviewPersistenceView(task),
4168
4705
  // The Agent Teams decision and outcome, short enough for a wait: `agentTeams` is the
4169
- // frozen request (or null), `team` the verified result (`applied`/`enabled`) or the
4170
- // reason it could not be applied. No team reasoning or task-board content travels.
4706
+ // frozen request (or null), `agentTeamsOrigin` is where it came from, `team` the
4707
+ // verified result (`applied`/`enabled`) or the reason it could not be applied. No
4708
+ // team reasoning or task-board content travels.
4171
4709
  agentTeams: task.agentTeams ?? null,
4710
+ agentTeamsOrigin: teamOriginOf(task),
4172
4711
  team: summarizedTeam(task.execution?.team ?? null),
4173
4712
  };
4174
4713
  }
@@ -4188,6 +4727,8 @@ export class JobEngine {
4188
4727
  isolation: task.effective.worker?.isolation ?? null,
4189
4728
  monitoring: {
4190
4729
  selfCheckSeconds: task.effective.monitoring?.selfCheckSeconds ?? null,
4730
+ // The notification interval, stated so a wait answer explains the run progress
4731
+ // check without the host having to infer a cadence.
4191
4732
  attentionSeconds: task.effective.monitoring?.attentionSeconds ?? null,
4192
4733
  repeatFailureThreshold: task.effective.monitoring?.repeatFailureThreshold ?? null,
4193
4734
  },
@@ -4532,6 +5073,7 @@ export class JobEngine {
4532
5073
  * @throws {JobError} on a recorded or in-flight conflict.
4533
5074
  */
4534
5075
  beginHistoryReviewWrite(row, decision, note, completionSummary = null) {
5076
+ this.assertRecordNotBeingRemoved(row.taskId);
4535
5077
  const history = this.history;
4536
5078
  if (history === null || history === undefined || typeof history.update !== 'function') {
4537
5079
  throw new JobError(JOB_CODES.reviewNotPersisted,
@@ -4702,8 +5244,7 @@ export class JobEngine {
4702
5244
  * to fail or un-finish the run that just succeeded;
4703
5245
  * * a missing store is silent: an engine constructed without one simply cannot
4704
5246
  * offer continuation, which is the safe default;
4705
- * * an unplaced run (the additional review) records nothing, because it is not
4706
- * part of the worker thread and must not become continuable.
5247
+ * * a run without a native conversation records no continuation identity.
4707
5248
  * @param {object} task - task record with a completed `task.execution`.
4708
5249
  * @returns {Promise<void>} resolves after the attempt, never rejects.
4709
5250
  */
@@ -4783,86 +5324,6 @@ export class JobEngine {
4783
5324
  }
4784
5325
  }
4785
5326
 
4786
- /**
4787
- * Run the optional independent review against the frozen review route.
4788
- * @param {object} task - completed-execution task.
4789
- * @returns {Promise<object>} review record.
4790
- */
4791
- async runReview(task) {
4792
- if (task.effective.review.enabled !== true) {
4793
- return { state: REVIEW_STATES.disabled, verdict: null, text: '', error: null };
4794
- }
4795
- if (task.reviewRouteError !== null) {
4796
- // A review routing failure is a review failure, not a task failure, and it
4797
- // is never an approval.
4798
- return {
4799
- state: REVIEW_STATES.failed,
4800
- verdict: null,
4801
- text: '',
4802
- error: task.reviewRouteError,
4803
- denials: [],
4804
- selection: reviewSelection(task.effective.review, null),
4805
- };
4806
- }
4807
- const route = task.reviewRoute;
4808
- if (route === null) {
4809
- return {
4810
- state: REVIEW_STATES.failed,
4811
- verdict: null,
4812
- text: '',
4813
- error: {
4814
- code: 'REVIEW_ROUTING_REFUSED',
4815
- message: 'the review route was not confirmed before execution',
4816
- cause: null,
4817
- },
4818
- denials: [],
4819
- selection: reviewSelection(task.effective.review, null),
4820
- };
4821
- }
4822
- if (this.isCancelled(task)) {
4823
- return {
4824
- state: REVIEW_STATES.cancelled,
4825
- verdict: null,
4826
- text: '',
4827
- error: { code: 'REVIEW_CANCELLED', message: 'the additional review was cancelled before it started' },
4828
- denials: [],
4829
- selection: reviewSelection(task.effective.review, route),
4830
- };
4831
- }
4832
- const prompt = buildReviewPrompt({
4833
- taskId: task.taskId,
4834
- taskPrompt: task.prompt,
4835
- workerSummary: task.execution?.text ?? '',
4836
- evidence: task.diff,
4837
- });
4838
- const result = await reviewWork(this.deps, {
4839
- taskId: task.taskId,
4840
- cwd: task.executionPath,
4841
- selection: {
4842
- // The public id is what an operator recognises; the native route is
4843
- // carried alongside it and is not disguised as a profile id.
4844
- providerId: task.effective.review.providerId,
4845
- providerRoute: route.providerRoute,
4846
- model: route.model,
4847
- reasoningEffort: route.reasoningEffort,
4848
- },
4849
- prompt,
4850
- evidence: task.diff,
4851
- timeoutMs: Math.min(task.effective.worker.timeoutSeconds, 1800) * 1000,
4852
- // Cancellation and revocation reach the reviewer through the same signal.
4853
- signal: task.controller.signal,
4854
- });
4855
- return {
4856
- state: result.state,
4857
- verdict: result.verdict,
4858
- text: result.text ?? '',
4859
- error: result.error ?? null,
4860
- denials: result.denials ?? [],
4861
- denialsDelivered: (result.denials ?? []).length,
4862
- selection: result.selection ?? reviewSelection(task.effective.review, route),
4863
- };
4864
- }
4865
-
4866
5327
  /**
4867
5328
  * Request cancellation of one task.
4868
5329
  * @param {string} taskId - task to cancel.
@@ -4882,6 +5343,31 @@ export class JobEngine {
4882
5343
  return this.view(task);
4883
5344
  }
4884
5345
 
5346
+ assertRecordNotBeingRemoved(taskId) {
5347
+ if (this.cleanupIds.has(taskId)) {
5348
+ throw new JobError(JOB_CODES.taskNotFound, 'task record is being removed; refresh and retry', { taskId });
5349
+ }
5350
+ }
5351
+
5352
+ isTaskSettledForCleanup(taskId) {
5353
+ return this.tasks.get(taskId)?.cleanupSettled === true;
5354
+ }
5355
+
5356
+ // Hold these ids between the final check and the removal from disk and memory.
5357
+ reserveCleanupIds(taskIds) {
5358
+ for (const id of taskIds) this.cleanupIds.add(id);
5359
+ return () => {
5360
+ for (const id of taskIds) this.cleanupIds.delete(id);
5361
+ };
5362
+ }
5363
+
5364
+ forgetCleanedRecords(taskIds) {
5365
+ for (const id of taskIds) {
5366
+ this.tasks.delete(id);
5367
+ this.reviewState.delete(id);
5368
+ }
5369
+ }
5370
+
4885
5371
  /**
4886
5372
  * Read one task.
4887
5373
  * @param {string} taskId - task id.
@@ -4921,7 +5407,6 @@ export class JobEngine {
4921
5407
  view(task, options = {}) {
4922
5408
  const effective = task.effective === null ? null : {
4923
5409
  worker: { ...task.effective.worker },
4924
- review: { ...task.effective.review },
4925
5410
  // The conversation policy this task ran under. It is a rule, not a stored
4926
5411
  // setting: a new submission starts a new DSH conversation, and a follow-up
4927
5412
  // continues the thread named by `continueFromTaskId`.
@@ -4929,8 +5414,7 @@ export class JobEngine {
4929
5414
  // The silence thresholds this task froze at admission. Published so a reader
4930
5415
  // can interpret the activity block without consulting a settings document
4931
5416
  // that may have changed since.
4932
- monitoring: { ...(task.effective.monitoring ?? MONITORING_DEFAULTS) },
4933
- provenance: task.effective.provenance,
5417
+ monitoring: { ...(task.effective.monitoring ?? MONITORING_DEFAULTS) }, provenance: task.effective.provenance,
4934
5418
  };
4935
5419
  const view = {
4936
5420
  taskId: task.taskId,
@@ -4961,14 +5445,6 @@ export class JobEngine {
4961
5445
  model: task.route.model,
4962
5446
  reasoningEffort: task.route.reasoningEffort,
4963
5447
  },
4964
- // Frozen during preflight: a later settings edit does not change it.
4965
- reviewRoute: task.reviewRoute === null ? null : {
4966
- providerId: effective === null ? null : effective.review.providerId,
4967
- providerRoute: task.reviewRoute.providerRoute,
4968
- model: task.reviewRoute.model,
4969
- reasoningEffort: task.reviewRoute.reasoningEffort,
4970
- },
4971
- reviewRouteError: task.reviewRouteError,
4972
5448
  worktree: task.worktree,
4973
5449
  baseline: task.baseline,
4974
5450
  diff: task.diff,
@@ -5011,7 +5487,6 @@ export class JobEngine {
5011
5487
  : {}),
5012
5488
  conversationSaved: task.conversationSaved,
5013
5489
  conversationError: task.conversationError,
5014
- review: task.review,
5015
5490
  error: task.error,
5016
5491
  cancelledBy: task.cancelledBy,
5017
5492
  // The per-call permission surface of this run: whether it was bridged, the
@@ -5032,6 +5507,10 @@ export class JobEngine {
5032
5507
  // confirmed on this run's Session. Kept as one block so "asked for teams" and
5033
5508
  // "teams actually on for this run" are never conflated.
5034
5509
  agentTeams: task.agentTeams ?? null,
5510
+ // WHERE that frozen decision came from: `request` (the dispatcher stated it for this
5511
+ // task), `continuation` (inherited from the chain this follow-up continues) or
5512
+ // `settings-default` (the operator's new-task default filled an absent choice).
5513
+ agentTeamsOrigin: teamOriginOf(task),
5035
5514
  team: task.execution?.team ?? null,
5036
5515
  // A bounded progress summary: counts, timestamps and the tool in flight. It
5037
5516
  // carries no model text, no reasoning, no tool arguments and no diff, so the
@@ -5061,7 +5540,7 @@ export class JobEngine {
5061
5540
  prune() {
5062
5541
  if (this.tasks.size <= MAX_RETAINED_TASKS) return;
5063
5542
  const terminal = [...this.tasks.values()]
5064
- .filter((task) => TERMINAL.has(task.state))
5543
+ .filter((task) => TERMINAL.has(task.state) && task.cleanupSettled)
5065
5544
  .sort((a, b) => (a.endedAt ?? a.createdAt) - (b.endedAt ?? b.createdAt));
5066
5545
  for (const task of terminal) {
5067
5546
  if (this.tasks.size <= MAX_RETAINED_TASKS) break;
@@ -5173,25 +5652,18 @@ function nativeRouteId(value) {
5173
5652
  */
5174
5653
  function samePath(a, b) {
5175
5654
  if (typeof a !== 'string' || typeof b !== 'string') return false;
5176
- const normalize = (value) => {
5177
- const trimmed = value.replace(/[\\/]+$/, '');
5178
- return process.platform === 'win32' ? trimmed.toLowerCase() : trimmed;
5179
- };
5180
- return normalize(a) === normalize(b);
5655
+ return lockKeyOf(a) === lockKeyOf(b);
5181
5656
  }
5182
5657
 
5183
5658
  /**
5184
- * Review selection projection for a review that never ran.
5185
- * @param {object} review - effective review block.
5186
- * @param {object | null} route - frozen route, if any.
5187
- * @returns {object} selection summary.
5659
+ * One directory's key for the in-process tables, folded the way the lock registry
5660
+ * folds it so two spellings of one source share one preparation queue.
5661
+ * @param {string} path - workspace path.
5662
+ * @returns {string} normalized key.
5188
5663
  */
5189
- function reviewSelection(review, route) {
5190
- return {
5191
- providerId: review?.providerId ?? null,
5192
- model: route?.model ?? review?.model ?? null,
5193
- reasoningEffort: route?.reasoningEffort ?? review?.reasoningEffort ?? null,
5194
- };
5664
+ function lockKeyOf(path) {
5665
+ const trimmed = String(path).replace(/[\\/]+$/, '');
5666
+ return process.platform === 'win32' ? trimmed.toLowerCase() : trimmed;
5195
5667
  }
5196
5668
 
5197
5669
  /**
@@ -5227,6 +5699,88 @@ export function sanitizeOverrides(value) {
5227
5699
  return out;
5228
5700
  }
5229
5701
 
5702
+ /**
5703
+ * The Agent Teams facts a parent recorded, as one conservative verdict for a follow-up.
5704
+ *
5705
+ * A continuation may only INHERIT a switch value that actually reached the native
5706
+ * Session. One case must not be inherited: the operator's default filled an absent
5707
+ * choice (`settings-default`), asked for OFF, and the host answered that it has no
5708
+ * agent-teams service at all (`supported: false`, `applied: false`). Nothing was ever
5709
+ * written in that run, so there is no native value to carry forward — and re-sending
5710
+ * `false` as though somebody had chosen it would make a capable-no-more host refuse a run
5711
+ * that previously worked, while a host without the service would be told a mode it never
5712
+ * had. Such a chain keeps its Session's current mode instead.
5713
+ *
5714
+ * Every other shape is inheritable, deliberately INCLUDING a bug of an earlier build that
5715
+ * recorded `false` for an implicit default with NO receipt at all (`team: null`): that
5716
+ * run really did write `false` to its Session, and the follow-up must keep it.
5717
+ *
5718
+ * The test for "never applied" is deliberately strict — all of `origin ===
5719
+ * 'settings-default'`, `value === false`, `team.supported === false` and
5720
+ * `team.applied === false` must hold. Anything else (an explicit request, an inherited
5721
+ * chain value, a receipt that claims support, an unknown origin, a missing receipt) is a
5722
+ * real decision and is inherited exactly as before.
5723
+ * @param {unknown} value - the parent's frozen `agentTeams` (boolean or null).
5724
+ * @param {unknown} origin - the parent's `agentTeamsOrigin`.
5725
+ * @param {unknown} team - the parent's run receipt (`team` block or its summary).
5726
+ * @returns {{ value: boolean | null, inheritable: boolean, neverAppliedDefault: boolean,
5727
+ * origin: string | null, applied: boolean | null, supported: boolean | null }} facts.
5728
+ */
5729
+ function teamFactsOf(value, origin, team) {
5730
+ const decision = typeof value === 'boolean' ? value : null;
5731
+ const kind = origin === 'request' || origin === 'continuation' || origin === 'settings-default'
5732
+ ? origin
5733
+ : null;
5734
+ const receipt = team !== null && typeof team === 'object' && !Array.isArray(team) ? team : null;
5735
+ const applied = receipt !== null && typeof receipt.applied === 'boolean' ? receipt.applied : null;
5736
+ const supported = receipt !== null && typeof receipt.supported === 'boolean' ? receipt.supported : null;
5737
+ const neverAppliedDefault = decision === false
5738
+ && kind === 'settings-default'
5739
+ && supported === false
5740
+ && applied === false;
5741
+ return {
5742
+ value: decision,
5743
+ // Only a recorded boolean can be carried forward; `null` means the parent recorded
5744
+ // nothing, which is the existing "keep the Session's own mode" case.
5745
+ inheritable: decision !== null && !neverAppliedDefault,
5746
+ neverAppliedDefault,
5747
+ origin: kind,
5748
+ applied,
5749
+ supported,
5750
+ };
5751
+ }
5752
+
5753
+ /**
5754
+ * The operator's Agent Teams default for a NEW task, read from one settings snapshot.
5755
+ *
5756
+ * Absent or unreadable means the documented OFF default — never "on" and never
5757
+ * "no choice": an upgraded document that predates the setting, and a settings
5758
+ * snapshot a deployment served without one, both resolve to `false`, which is what
5759
+ * a fresh install stores. The value is only ever a boolean, so a hand-edited
5760
+ * document that slipped a string in cannot become a truthy selection.
5761
+ * @param {object | null} settings - the settings snapshot admission froze.
5762
+ * @returns {boolean} the default for a new task with no per-task choice.
5763
+ */
5764
+ function operatorTeamDefault(settings) {
5765
+ const value = settings?.execution?.agentTeamsDefault;
5766
+ return typeof value === 'boolean' ? value : DEFAULT_AGENT_TEAMS_FOR_NEW_TASKS;
5767
+ }
5768
+
5769
+ /**
5770
+ * WHERE a task's frozen Agent Teams decision came from, as a closed vocabulary.
5771
+ *
5772
+ * `null` when no decision is frozen (no choice applied at all). A value outside
5773
+ * the three documented origins is reported as `null` rather than echoed, so a
5774
+ * restored record cannot introduce a fourth word.
5775
+ * @param {object} task - task record.
5776
+ * @returns {'request' | 'continuation' | 'settings-default' | null} the origin.
5777
+ */
5778
+ function teamOriginOf(task) {
5779
+ if (typeof task?.agentTeams !== 'boolean') return null;
5780
+ const origin = task.agentTeamsOrigin;
5781
+ return origin === 'request' || origin === 'continuation' || origin === 'settings-default' ? origin : null;
5782
+ }
5783
+
5230
5784
  export { AuthError, AUTH_CODES, defaultSettings };
5231
5785
 
5232
5786
  /**