dsh-taskbridge 1.5.4 → 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 (74) hide show
  1. package/CHANGELOG.md +80 -59
  2. package/README.md +51 -50
  3. package/THIRD_PARTY_NOTICES.txt +23 -0
  4. package/bin/dsh-delegate-mcp.d.ts +1 -0
  5. package/bin/dsh-delegate-mcp.js +1 -0
  6. package/codex/dsh-taskbridge.toml +148 -71
  7. package/docs/INTRODUCTION.md +44 -22
  8. package/docs/INTRODUCTION.zh.md +32 -26
  9. package/docs/codex-integration.md +99 -19
  10. package/docs/contracts-stage-b.md +4 -4
  11. package/docs/conversation-placement.md +25 -7
  12. package/docs/plugin-market.md +1 -1
  13. package/docs/releases/1.6.0.zh.md +11 -0
  14. package/docs/releases/1.7.0.zh.md +11 -0
  15. package/docs/runtime-compatibility.md +10 -11
  16. package/docs/silent-wait.md +69 -31
  17. package/docs/taskbridge-upgrade.md +1 -1
  18. package/docs/worker-permissions.md +11 -21
  19. package/docs/workspace-grouping.md +126 -0
  20. package/lib/client.d.ts +581 -0
  21. package/lib/client.js +332 -3461
  22. package/locale/en.json +1 -1
  23. package/locale/zh.json +1 -1
  24. package/package.json +7 -19
  25. package/src/client/api.js +895 -90
  26. package/src/client/index.jsx +1363 -296
  27. package/src/client/sidebar.jsx +862 -0
  28. package/src/client/styles.js +340 -0
  29. package/src/client/task-cleanup.js +304 -0
  30. package/src/client/task-records-table.jsx +217 -0
  31. package/src/client/task-view.js +307 -0
  32. package/src/client/workspace-groups.js +482 -0
  33. package/src/client/workspaces-browser.jsx +770 -0
  34. package/src/codex/agent-ownership.js +270 -0
  35. package/src/codex/installer.js +528 -35
  36. package/src/codex/seam.js +5 -0
  37. package/src/config/defaults.js +63 -17
  38. package/src/config/settings.js +60 -62
  39. package/src/config/validate.js +126 -71
  40. package/src/http/execution-plane.js +200 -1
  41. package/src/http/respond.js +26 -2
  42. package/src/http/user-plane.js +566 -2
  43. package/src/index.d.ts +55 -0
  44. package/src/index.js +58 -42
  45. package/src/jobs/activity.js +968 -78
  46. package/src/jobs/engine.js +1010 -230
  47. package/src/jobs/history.js +224 -12
  48. package/src/jobs/plan-store.js +1020 -0
  49. package/src/jobs/record-cleanup.js +196 -0
  50. package/src/jobs/task-display.js +73 -0
  51. package/src/jobs/task-tree.js +786 -0
  52. package/src/jobs/title.js +129 -12
  53. package/src/mcp/server.js +206 -10
  54. package/src/mcp/wait.js +64 -5
  55. package/src/runtime/agent-runner.js +101 -15
  56. package/src/runtime/worker-prompt.js +53 -0
  57. package/src/workspace/locks.js +288 -167
  58. package/docs/assets/taskbridge-workflow.en.png +0 -0
  59. package/docs/assets/taskbridge-workflow.zh.png +0 -0
  60. package/docs/releases/1.4.0-token-benchmark.zh.md +0 -40
  61. package/docs/releases/1.4.0.zh.md +0 -54
  62. package/docs/releases/1.4.1.zh.md +0 -59
  63. package/docs/releases/1.4.2.zh.md +0 -23
  64. package/docs/releases/1.5.0-token-benchmark.zh.md +0 -73
  65. package/docs/releases/1.5.0.zh.md +0 -51
  66. package/docs/releases/1.5.1.zh.md +0 -70
  67. package/docs/releases/1.5.2.zh.md +0 -30
  68. package/docs/releases/1.5.3-test.1.zh.md +0 -28
  69. package/docs/releases/1.5.3-test.2.zh.md +0 -24
  70. package/docs/releases/1.5.3.zh.md +0 -33
  71. package/docs/releases/1.5.4.zh.md +0 -25
  72. package/src/review/preset.js +0 -868
  73. package/src/review/prompts.js +0 -145
  74. package/src/review/reviewer.js +0 -933
@@ -68,6 +68,14 @@ const MAX_IDENTIFIER_CHARS = 200;
68
68
  /** Settled call ids remembered so a completion can be matched to its start. */
69
69
  const MAX_TRACKED_CALL_IDS = 64;
70
70
 
71
+ /**
72
+ * Stage-result identities remembered for per-event deduplication.
73
+ *
74
+ * An id is remembered only after a stage result really advanced the clock, so the bound costs
75
+ * nothing but memory: past it, the oldest identity is forgotten and would count once more.
76
+ */
77
+ const MAX_TRACKED_STAGE_EVENTS = 64;
78
+
71
79
  /**
72
80
  * Session event types that are PROGRESS, keyed to the evidence they carry.
73
81
  *
@@ -765,6 +773,22 @@ function randomHex16() {
765
773
  /** Why one observation wait ended. */
766
774
  export const OBSERVE_REASONS = Object.freeze({
767
775
  heartbeat: 'heartbeat',
776
+ /**
777
+ * The run needs the commander.
778
+ *
779
+ * Two DIFFERENT reminders share this reason because they all mean "look at it".
780
+ * `checkpoint` says which one it is:
781
+ * * `checkpoint: 'progress'` — the run has produced no real progress for the
782
+ * configured interval (default 40 minutes) while its executor is still alive. The
783
+ * host is asked to check the run's progress, and the default answer is to keep
784
+ * waiting on the same task.
785
+ * * `checkpoint: 'failure'` — the repeated-tool-failure reminder (`failure` block;
786
+ * older hosts read only that block, so they keep working unchanged).
787
+ *
788
+ * Both are measured on ONE clock for the progress report: consecutive time WITHOUT
789
+ * real progress, reset only by real progress. Total runtime is never a reminder.
790
+ * Nothing is ever cancelled, restarted, resubmitted or re-queued by one.
791
+ */
768
792
  attention: 'attention',
769
793
  permission: 'permission',
770
794
  // The worker asked a human an ordinary question. It is its own reason because answering
@@ -776,6 +800,25 @@ export const OBSERVE_REASONS = Object.freeze({
776
800
  interrupted: 'interrupted',
777
801
  });
778
802
 
803
+ /**
804
+ * The closed vocabulary of `attention` checkpoints.
805
+ *
806
+ * A host that reads only `reason` keeps the previous behaviour; a host that reads
807
+ * `checkpoint` can tell "the run made no real progress for the interval" from "the
808
+ * worker kept failing the same call" without parsing prose.
809
+ *
810
+ * There are exactly TWO reminders: `progress` (the run progress check on the one
811
+ * no-progress clock) and `failure` (the repeated-tool-failure reminder). `stall` is
812
+ * accepted ONLY as a legacy label — a host or a fixture written by the earlier candidate
813
+ * may still send it — and this monitor never emits it: there is no second duration to
814
+ * report a shorter threshold under.
815
+ */
816
+ export const CHECKPOINTS = Object.freeze({
817
+ progress: 'progress',
818
+ stall: 'stall',
819
+ failure: 'failure',
820
+ });
821
+
779
822
  /**
780
823
  * Reasons no caller may ever receive from {@link TaskMonitor#observe}.
781
824
  *
@@ -819,7 +862,8 @@ const PHASE_AWAITING_PERMISSION = 'awaiting-permission';
819
862
  *
820
863
  * What it must never do, and does not: run an LLM, read a diff or a workspace
821
864
  * file, mutate the task, restart/cancel/resubmit a run, or extend a deadline. The
822
- * self-check is a read of facts the engine already holds.
865
+ * self-check and the progress checkpoint are reads of facts the engine already
866
+ * holds; a checkpoint is a report to the commander, never a control action.
823
867
  */
824
868
  export class TaskMonitor {
825
869
  /**
@@ -827,8 +871,11 @@ export class TaskMonitor {
827
871
  * @param {object} [options] - seams and thresholds.
828
872
  * @param {() => number} [options.now] - clock.
829
873
  * @param {(ms: number) => Promise<void>} [options.wait] - bounded sleep.
830
- * @param {number} [options.selfCheckSeconds] - idle span for the self-check.
831
- * @param {number} [options.attentionSeconds] - idle span for `attention`.
874
+ * @param {number} [options.selfCheckSeconds] - no-progress span for the self-check, or 0 to disable it.
875
+ * @param {number} [options.attentionSeconds] - no-progress span for the run progress
876
+ * check (default 40 minutes), or 0 to disable it. This is the ONLY notification
877
+ * clock: a run that keeps producing real progress never reaches it, whatever its
878
+ * total duration.
832
879
  * @param {number} [options.repeatFailureThreshold] - consecutive identical tool
833
880
  * failures reported once, or 0 to disable that reminder.
834
881
  * @param {number} [options.waitSliceMs] - internal polling slice.
@@ -838,12 +885,27 @@ export class TaskMonitor {
838
885
  this.task = task;
839
886
  this.now = typeof options.now === 'function' ? options.now : Date.now;
840
887
  this.wait = typeof options.wait === 'function' ? options.wait : sleep;
841
- this.selfCheckMs = secondsToMs(options.selfCheckSeconds, 300);
842
- this.attentionMs = secondsToMs(options.attentionSeconds, 600);
888
+ // `0` is a DECISION ("this reminder is off"), not a missing value. Only a value
889
+ // that is not a usable threshold at all falls back to the documented default.
890
+ //
891
+ // TWO independent clocks, which is the whole difference between the two:
892
+ // * the self-check is armed from the moment DSH actually STARTED running this task
893
+ // (see {@link TaskMonitor#runOrigin}) — a run whose model keeps streaming and
894
+ // whose tools keep answering is still inspected once at ten minutes, because the
895
+ // product asks for that one local look rather than for "time without progress";
896
+ // * the run progress check is armed from the last genuine DELIVERY back to the
897
+ // commander (see {@link TaskMonitor#progressOrigin}) — internal model steps,
898
+ // text deltas, tool activity, heartbeats and the check itself never move it.
899
+ this.selfCheckMs = thresholdToMs(options.selfCheckSeconds, 10 * 60);
900
+ this.attentionMs = thresholdToMs(options.attentionSeconds, 40 * 60);
843
901
  this.waitSliceMs = Number.isSafeInteger(options.waitSliceMs) && options.waitSliceMs > 0
844
902
  ? options.waitSliceMs
845
903
  : 1000;
846
904
  this.log = typeof options.log === 'function' ? options.log : null;
905
+ // Timers. `setTimeout`/`clearTimeout` are injectable so a test can drive the
906
+ // scheduled self-check deterministically instead of sleeping for ten minutes.
907
+ this.setTimer = typeof options.setTimeout === 'function' ? options.setTimeout : setTimeout;
908
+ this.clearTimer = typeof options.clearTimeout === 'function' ? options.clearTimeout : clearTimeout;
847
909
  this.activity = new TaskActivity({ now: this.now });
848
910
  /**
849
911
  * The repeated-failure detector. It is a SEPARATE clock from the two silence
@@ -871,21 +933,105 @@ export class TaskMonitor {
871
933
  this.ackedEventId = null;
872
934
  /** Episode identity: bumped whenever genuine activity ends the idle episode. */
873
935
  this.episode = 0;
936
+ /**
937
+ * The fixed origin used when the task's recorded start cannot be compared with this
938
+ * monitor's clock, or null while the recorded start is usable.
939
+ * @type {number | null}
940
+ */
941
+ this.originFallback = null;
874
942
  /** The episode the self-check already ran for, or null. */
875
943
  this.checkedEpisode = null;
944
+ /**
945
+ * The one ON-DEMAND self-check timer, or null.
946
+ *
947
+ * A run must be inspected even when NO observer is waiting (a commander that is not
948
+ * polling, or no client at all). So the monitor arms exactly ONE timer, at
949
+ * `runOrigin + selfCheckMs` — the instant the run really started plus the interval,
950
+ * whether or not the run is busy in between. It is cleared on disable, terminal
951
+ * state, cancellation and disposal. It is a SCHEDULER, not a clock: the instant it
952
+ * fires at comes from the same `runOrigin`/`selfCheckMs` the observation loop uses,
953
+ * and the latch that makes it run once per run is the same `checkedEpisode`.
954
+ * @type {{ id: unknown, at: number, episode: number } | null}
955
+ */
956
+ this.selfCheckTimer = null;
876
957
  /** The last self-check diagnostic, published on every summary. */
877
- this.selfCheck = { episode: null, checkedAt: null, verdict: null, detail: null };
958
+ this.selfCheck = {
959
+ episode: null,
960
+ checkedAt: null,
961
+ verdict: null,
962
+ detail: null,
963
+ sinceStartMs: null,
964
+ noDeliveryMs: null,
965
+ };
878
966
  /**
879
- * When the most recent attention report was DELIVERED, and for which idle
880
- * episode.
967
+ * The most recent REAL delivery of this task's progress to the commander: the interval it
968
+ * opened, and when.
881
969
  *
882
- * Exactly one pair, never a growing collection: the cooldown is a property of
883
- * the current silence, and an idle origin only moves forward, so an older entry
884
- * could never be reached again. `null` means "no attention has been delivered
885
- * for this episode yet".
886
- * @type {{ episode: number, origin: number, at: number } | null}
970
+ * This is the ONLY thing that advances the run progress check's clock (see
971
+ * {@link progressOrigin}). It is not "the last time an observation returned": a
972
+ * heartbeat, a `wait-limit`, a permission or question wait, a page refresh, the
973
+ * self-check and the 40-minute check itself are all REPORTED without being deliveries of
974
+ * progress, so they never move it.
975
+ * @type {{ delivery: number, origin: number, at: number } | null}
887
976
  */
888
977
  this.attentionDelivered = null;
978
+ /**
979
+ * Whether the run progress check has already been REPORTED for the current delivery
980
+ * interval.
981
+ *
982
+ * A latch, not a counter: the check fires at most once per interval, and a genuine
983
+ * delivery (or the run's own start) opens the next one and clears it. It is deliberately
984
+ * SEPARATE state from {@link attentionDelivered}: a report is not a delivery, and keeping
985
+ * them apart is what lets the monitor tell "this interval was already reported" from "a
986
+ * new interval opened".
987
+ * @type {{ origin: number, at: number } | null}
988
+ */
989
+ this.progressReported = null;
990
+ /**
991
+ * The origin of the interval the last delivery opened, or null.
992
+ *
993
+ * One latch shared by every way a delivery can arrive — the run's terminal outcome through
994
+ * {@link delivery}, and a real stage result through {@link noteStageResult} — so two
995
+ * confirmations for ONE interval advance the clock ONCE. Without it, a duplicate would be a
996
+ * second reset.
997
+ * @type {number | null}
998
+ */
999
+ this.deliveryCountedInterval = null;
1000
+ /**
1001
+ * When this run's scheduled self-check performed its inspection, or null.
1002
+ *
1003
+ * Kept apart from `selfCheck.checkedAt` because the two answer different questions:
1004
+ * `checkedAt` is "which inspection is the latest" (a diagnostic), while this is "when
1005
+ * the one timer fired" (a fact the check itself must be able to state). A diagnostic
1006
+ * published by an observation says nothing about whether the timer was allowed to run.
1007
+ * @type {number | null}
1008
+ */
1009
+ this.scheduledSelfCheckAt = null;
1010
+ /**
1011
+ * The instant the delivery interval was frozen at, or null while it is still measured.
1012
+ *
1013
+ * Set once when the run reaches a terminal state, to the run's recorded end. A finished
1014
+ * run can deliver nothing more, so "nothing returned for N" stops growing there instead
1015
+ * of describing a wait nobody could have shortened.
1016
+ * @type {number | null}
1017
+ */
1018
+ this.deliveredAtMs = null;
1019
+ /**
1020
+ * Every genuine delivery this monitor observed, as bounded evidence.
1021
+ *
1022
+ * A count plus the last interval/instant: never text, never a payload. This is what
1023
+ * lets the published state say "no delivery for 41 minutes" honestly instead of
1024
+ * inferring it from internal model activity.
1025
+ */
1026
+ this.deliveries = 0;
1027
+ /**
1028
+ * The identities of the stage results already counted, bounded.
1029
+ *
1030
+ * Only event ids, never content. It is what makes a stage result count AT MOST ONCE: a
1031
+ * retried or replayed confirmation with the same event id is a duplicate and moves nothing.
1032
+ * @type {Set<string>}
1033
+ */
1034
+ this.stageEvents = new Set();
889
1035
  /**
890
1036
  * Every observation currently waiting, so each one owns its own controller and
891
1037
  * one observer can never cancel another. Bounded by the number of callers; an
@@ -927,7 +1073,14 @@ export class TaskMonitor {
927
1073
  // makes "once per episode" true for the self-check and the attention latch:
928
1074
  // without it, a run that goes quiet, wakes, and goes quiet again would be
929
1075
  // treated as the SAME silence and could never alert a second time.
930
- if (active) this.episode += 1;
1076
+ if (active) {
1077
+ this.episode += 1;
1078
+ // The self-check clock reads the run's start, not this event, so nothing is
1079
+ // re-armed here: `scheduleSelfCheck` is a pure recompute and the engine calls it
1080
+ // once the run is really started. The episode identity is what keeps the
1081
+ // "already inspected" latch and the progress-report latch coherent across a run
1082
+ // that wakes and sleeps many times.
1083
+ }
931
1084
  return active;
932
1085
  } catch {
933
1086
  return false;
@@ -1026,45 +1179,229 @@ export class TaskMonitor {
1026
1179
  * Before the executor has produced anything, the episode begins when its run
1027
1180
  * began — a model that never streams a token is silent from the start, and
1028
1181
  * measuring from "never" would hide it.
1182
+ *
1183
+ * This is the EXECUTOR's silence measure. It describes the run ("quiet for 90 s", the
1184
+ * idle tool span) and it no longer arms anything: the ten-minute self-check runs from
1185
+ * {@link runOrigin} and the forty-minute check from {@link progressOrigin}, because
1186
+ * neither may be postponed by internal model activity.
1029
1187
  * @returns {number} epoch milliseconds.
1030
1188
  */
1031
1189
  idleOrigin() {
1032
1190
  if (this.activity.lastActivityAt !== null) return this.activity.lastActivityAt;
1033
- if (Number.isFinite(this.task?.startedAt)) return this.task.startedAt;
1034
- if (Number.isFinite(this.task?.createdAt)) return this.task.createdAt;
1035
- return this.now();
1191
+ const now = this.now();
1192
+ // A run whose recorded start was already inconsistent with this monitor's clock gets
1193
+ // ONE fixed origin — the instant that was first ruled unusable. Re-deriving it on
1194
+ // every read would slide the origin forward with the clock, and a sliding origin can
1195
+ // never become old enough for the threshold.
1196
+ if (this.originFallback !== null) return this.originFallback;
1197
+ // Before any real progress has been observed, the silence is measured from the run's
1198
+ // recorded start — but ONLY if that start is usable by THIS monitor's clock. The
1199
+ // engine stamps `startedAt`/`createdAt` from the wall clock, while this monitor reads
1200
+ // its injected `now`; a start in the future (a frozen or offset clock) or one so far
1201
+ // in the past that the threshold would look long spent must not be taken literally,
1202
+ // or a silence span would be invented. In production the two clocks agree and the
1203
+ // recorded start is used verbatim.
1204
+ for (const candidate of [this.task?.startedAt, this.task?.createdAt]) {
1205
+ if (!Number.isFinite(candidate) || candidate <= 0) continue;
1206
+ if (candidate > now || now - candidate > MAX_PLAUSIBLE_IDLE_MS) {
1207
+ this.originFallback = now;
1208
+ return this.originFallback;
1209
+ }
1210
+ return candidate;
1211
+ }
1212
+ return now;
1036
1213
  }
1037
1214
 
1038
1215
  /**
1039
- * Whether the current inactivity episode has reached the self-check threshold.
1216
+ * Whether this run's ONE self-check is due.
1217
+ *
1218
+ * Measured from the instant DSH demonstrably STARTED running the task
1219
+ * ({@link runOrigin}), NOT from the last output. The product asks for one local look
1220
+ * ten minutes into a real run, whatever the run is doing: a model that never stops
1221
+ * streaming and tools that keep answering still get that look. Queueing, creating a
1222
+ * Session and a mere request acknowledgement are not the start, so a task that has
1223
+ * not reached execution is never due.
1224
+ *
1225
+ * A disabled self-check (`selfCheckSeconds: 0`) is never due, which is the whole
1226
+ * point of the switch: the operator asked for no local inspection at all.
1040
1227
  * @param {number} [at] - reference time.
1041
1228
  * @returns {boolean} true when one read-only inspection is due.
1042
1229
  */
1043
1230
  selfCheckDue(at = this.now()) {
1044
- return at - this.idleOrigin() >= this.selfCheckMs;
1231
+ if (!enabled(this.selfCheckMs)) return false;
1232
+ const origin = this.runOrigin();
1233
+ if (origin === null) return false;
1234
+ return at - origin >= this.selfCheckMs;
1045
1235
  }
1046
1236
 
1047
1237
  /**
1048
- * Perform the 5-minute read-only inspection, at most once per idle episode.
1238
+ * Perform the read-only inspection, at most once per run.
1049
1239
  *
1050
1240
  * The inspection reads only what the engine itself already holds: whether the
1051
1241
  * task is alive, whether its executor settled, the phase, whether a permission
1052
- * request is pending, and which tool call is outstanding. It performs no model
1053
- * call, reads no diff or workspace file, changes no task state, and does not
1054
- * touch the deadline.
1242
+ * request is pending, and which tool call is outstanding — plus the two facts the
1243
+ * commander needs when it is reminded: how long nothing was delivered and what the
1244
+ * run is currently doing. It performs no model call, reads no diff or workspace
1245
+ * file, changes no task state, and does not touch the deadline. Disabled means
1246
+ * disabled: it returns null immediately.
1247
+ *
1248
+ * The same method serves both entry points — the observation loop and the scheduled
1249
+ * timer — so `checkedEpisode` is the ONE latch: whichever runs first makes the check,
1250
+ * and the other finds nothing to do for this run.
1055
1251
  * @param {number} [at] - reference time.
1056
1252
  * @returns {object | null} the diagnostic, or null when none was due.
1057
1253
  */
1058
1254
  runSelfCheck(at = this.now()) {
1059
1255
  if (this.disposed) return null;
1256
+ if (!enabled(this.selfCheckMs)) return null;
1060
1257
  if (!this.selfCheckDue(at)) return null;
1061
1258
  const episode = this.episode;
1062
1259
  if (this.checkedEpisode === episode) return null;
1260
+ if (terminalReason(this.task) !== null) return null;
1063
1261
  this.checkedEpisode = episode;
1064
1262
  this.selfCheck = this.inspect(at, episode);
1263
+ // This run's inspection is done, so its timer has nothing left to do.
1264
+ this.clearSelfCheckTimer();
1065
1265
  return this.selfCheck;
1066
1266
  }
1067
1267
 
1268
+ // -------------------------------------------------------------------------
1269
+ // The scheduled self-check: a read-only inspection with NO observer
1270
+ // -------------------------------------------------------------------------
1271
+ //
1272
+ // WHY a timer at all: the product requires that a run is inspected ONCE when it has
1273
+ // really been running for `selfCheckSeconds`, even when no Codex/MCP caller is
1274
+ // waiting — a commander that is not polling, or a closed client, must not leave a run
1275
+ // uninspected. It is a SCHEDULER, not a third clock:
1276
+ //
1277
+ // * the instant is computed from the SAME `runOrigin`/`selfCheckMs` the loop uses;
1278
+ // * it is measured from the real start of execution, so a busy run (model steps,
1279
+ // text deltas and tool receipts the whole way) is inspected all the same, and a
1280
+ // run that has not started yet is never inspected;
1281
+ // * `0` (disabled), a terminal state, cancellation and disposal leave NO timer;
1282
+ // * it is `unref`'d, so it can never keep the process alive;
1283
+ // * an EPOCH-DOMAIN monitor (the engine's) hands the real timer the exact epoch instant
1284
+ // the run's start and threshold produce, with the DELAY computed against this clock;
1285
+ // * it calls `runSelfCheck` — the same read-only inspection, no I/O, no model call,
1286
+ // no task action — and shares the `checkedEpisode` latch, so one run is
1287
+ // inspected ONCE whichever entry point got there first.
1288
+
1289
+ /**
1290
+ * (Re-)arm the one self-check timer for this run, or clear it.
1291
+ *
1292
+ * Safe to call at any time and as often as the caller likes: it is a pure recompute of
1293
+ * "should a timer exist, and when should it fire". Idempotent when the target instant
1294
+ * has not moved, so a burst of events costs at most one `setTimeout`.
1295
+ * @returns {void}
1296
+ */
1297
+ scheduleSelfCheck() {
1298
+ if (this.disposed) return this.clearSelfCheckTimer();
1299
+ // Off, already inspected for this run, or over: nothing may be scheduled.
1300
+ if (!enabled(this.selfCheckMs) || this.checkedEpisode === this.episode) return this.clearSelfCheckTimer();
1301
+ if (terminalReason(this.task) !== null) return this.clearSelfCheckTimer();
1302
+ const origin = this.runOrigin();
1303
+ // The run never really started (queueing, an unacknowledged request): no instant to
1304
+ // arm for. The next evidence of execution re-arms it, because the engine calls this
1305
+ // again whenever the run's real start becomes known.
1306
+ if (origin === null) return this.clearSelfCheckTimer();
1307
+ const dueAt = origin + this.selfCheckMs;
1308
+ const armed = this.selfCheckTimer;
1309
+ if (armed !== null && armed.at === dueAt && armed.episode === this.episode) return undefined;
1310
+ this.clearSelfCheckTimer();
1311
+ this.armSelfCheckTimer(dueAt, this.episode);
1312
+ return undefined;
1313
+ }
1314
+
1315
+ /**
1316
+ * Arm the one timer that owes this run's self-check at `dueAt`.
1317
+ *
1318
+ * The callback owns its slot: it records which slot it was armed for and CLEARS that
1319
+ * slot before doing anything else. That is what makes a timer which fires a moment too
1320
+ * early work instead of wedging — the next `scheduleSelfCheck()` then sees an empty slot
1321
+ * and arms a fresh timer for the same instant, instead of deduplicating against a slot
1322
+ * whose timer has already fired and can never run again.
1323
+ * @param {number} dueAt - the instant the check is owed.
1324
+ * @param {number} [episode] - the episode identity; defaults to the current one.
1325
+ * @returns {void}
1326
+ */
1327
+ armSelfCheckTimer(dueAt, episode = this.episode) {
1328
+ const now = this.now();
1329
+ // `setTimeout` cannot be trusted past its platform maximum (a delay beyond it fires
1330
+ // at once, in a tight loop). A threshold that is further away than a timer can express
1331
+ // therefore uses a SHORT poll: each one re-reads `now` and re-arms for the distance
1332
+ // that is really left, so it fires exactly when the threshold is reached. This is the
1333
+ // only case that repeats, and it still calls the same `runSelfCheck` with the same
1334
+ // latch — it is a scheduler, never a second clock.
1335
+ const remaining = dueAt - now;
1336
+ // A clock that is already past the threshold gets one tick, never a negative delay.
1337
+ const delay = remaining > MAX_TIMER_DELAY_MS
1338
+ ? SELF_CHECK_POLL_MS
1339
+ : Math.max(0, remaining);
1340
+ const slot = { id: null, at: dueAt, episode };
1341
+ // The epoch-domain instant this slot fires at, for a real platform timer: a timer armed
1342
+ // with a small delay can fire LATE, but the check belongs at the instant the threshold
1343
+ // was reached, so it is recorded there — bounded by this monitor's clock so an injected
1344
+ // (non-epoch) time base can never record a check at an invented future instant.
1345
+ const dueEpoch = Number.isFinite(dueAt) && Math.abs(dueAt - now) <= MAX_EPOCH_DOMAIN_MS ? dueAt : null;
1346
+ const handle = this.setTimer(() => {
1347
+ // Consume THIS slot first, whoever owns it now. A stale timer (its slot was replaced
1348
+ // or cleared) leaves the current slot alone.
1349
+ if (this.selfCheckTimer === slot) this.selfCheckTimer = null;
1350
+ else this.clearTimerOf(slot);
1351
+ // A disposed monitor, or a finished run, owes nothing.
1352
+ if (this.disposed) return;
1353
+ if (terminalReason(this.task) !== null) return;
1354
+ try {
1355
+ // A pure read of what the engine already holds: no I/O, no model, no task change.
1356
+ const checked = this.runSelfCheck(dueEpoch ?? this.now());
1357
+ if (checked !== null) {
1358
+ // Recorded on its own field: this is the one timer having fired, which is a
1359
+ // different fact from "which diagnostic is the latest".
1360
+ this.scheduledSelfCheckAt = checked.checkedAt;
1361
+ return;
1362
+ }
1363
+ } catch {
1364
+ // A diagnostic must never disturb the run that produced it.
1365
+ }
1366
+ // Not due yet by the clock's own reading (a timer that fired a moment early, or a
1367
+ // clock that moved): the run still owes a check, so re-arm for the SAME instant —
1368
+ // and only once this slot is already consumed.
1369
+ if (this.disposed) return;
1370
+ if (terminalReason(this.task) !== null) return;
1371
+ if (!enabled(this.selfCheckMs) || this.checkedEpisode === this.episode) return;
1372
+ this.scheduleSelfCheck();
1373
+ }, delay);
1374
+ // `unref` where the platform supports it: a pending self-check must not be a reason
1375
+ // for the process to stay alive.
1376
+ if (handle !== null && typeof handle === 'object' && typeof handle.unref === 'function') handle.unref();
1377
+ slot.id = handle;
1378
+ this.selfCheckTimer = slot;
1379
+ }
1380
+
1381
+ /**
1382
+ * Clear one specific timer handle, ignoring a failure.
1383
+ * @param {{ id: unknown }} slot - the slot whose timer should be cancelled.
1384
+ * @returns {void}
1385
+ */
1386
+ clearTimerOf(slot) {
1387
+ try {
1388
+ this.clearTimer(slot.id);
1389
+ } catch {
1390
+ // A timer that cannot be cleared is already gone; the slot is what matters.
1391
+ }
1392
+ }
1393
+
1394
+ /**
1395
+ * Clear the scheduled self-check, if any. Idempotent.
1396
+ * @returns {void}
1397
+ */
1398
+ clearSelfCheckTimer() {
1399
+ const armed = this.selfCheckTimer;
1400
+ if (armed === null) return;
1401
+ this.selfCheckTimer = null;
1402
+ this.clearTimerOf(armed);
1403
+ }
1404
+
1068
1405
  /**
1069
1406
  * The last self-check diagnostic, or null when none ever ran.
1070
1407
  * @returns {object | null} diagnostic.
@@ -1075,6 +1412,16 @@ export class TaskMonitor {
1075
1412
 
1076
1413
  /**
1077
1414
  * Build the read-only diagnostic for the current episode.
1415
+ *
1416
+ * It states the TWO facts a reminder must keep apart, and never merges them:
1417
+ *
1418
+ * 1. `noDeliveryForMs` / `noDeliveryMinutes` — how long NOTHING new was delivered back
1419
+ * to the commander. Internal model output, tool receipts and heartbeats do not move
1420
+ * this clock; only a real delivery to the commander does.
1421
+ * 2. `detail.activity` — what DSH is doing right now, from the same bounded activity
1422
+ * facts the task page uses (phase, open tool, counters). "I am working" and "I have
1423
+ * told the commander nothing for 41 minutes" are both true at once, and an operator
1424
+ * needs both sentences rather than one blended one.
1078
1425
  * @param {number} at - reference time.
1079
1426
  * @param {number} episode - episode identity.
1080
1427
  * @returns {object} bounded diagnostic.
@@ -1083,9 +1430,12 @@ export class TaskMonitor {
1083
1430
  const task = this.task ?? {};
1084
1431
  const pending = task.permission?.pending ?? null;
1085
1432
  const span = this.activity.toolSpan(at);
1086
- const idleMs = Math.max(0, at - this.idleOrigin());
1087
1433
  const nativeStarted = task.native?.started === true;
1088
1434
  const nativeSettled = task.native?.settled === true;
1435
+ // Both origins are bounded instants (see `runOrigin` / `progressOrigin`), so neither
1436
+ // can produce a nonsense duration from a host clock that disagrees with this one.
1437
+ const sinceStartMs = Math.max(0, at - this.runOrigin());
1438
+ const noDeliveryMs = Math.max(0, at - this.progressOrigin());
1089
1439
  let verdict;
1090
1440
  if (task.state === 'pending' || task.state === 'running') {
1091
1441
  if (pending !== null) verdict = 'waiting-for-permission';
@@ -1099,7 +1449,9 @@ export class TaskMonitor {
1099
1449
  return {
1100
1450
  episode,
1101
1451
  checkedAt: at,
1102
- idleMs,
1452
+ sinceStartMs,
1453
+ noDeliveryMs,
1454
+ noDeliveryMinutes: Math.floor(noDeliveryMs / 60_000),
1103
1455
  verdict,
1104
1456
  detail: {
1105
1457
  state: typeof task.state === 'string' ? task.state : null,
@@ -1113,57 +1465,409 @@ export class TaskMonitor {
1113
1465
  lastActivityAt: this.activity.lastActivityAt,
1114
1466
  activityEvents: this.activity.activityEvents(),
1115
1467
  events: this.activity.totalEvents(),
1468
+ // The independent "what is DSH doing" field. A closed vocabulary plus the open
1469
+ // tool name, so it cannot become a transcript.
1470
+ activity: this.runActivity(at),
1471
+ // The independent "how long has nothing been returned" field, restated here so
1472
+ // the diagnostic can be read on its own.
1473
+ noDeliveryForMs: noDeliveryMs,
1116
1474
  },
1117
1475
  };
1118
1476
  }
1119
1477
 
1120
1478
  /**
1121
- * Whether the current silence is old enough for an attention report, ignoring the
1122
- * cooldown of an earlier delivery.
1479
+ * What the run is currently doing, in a closed vocabulary.
1480
+ *
1481
+ * It describes the EXECUTOR, not the delivery: a run can be `model-working` while the
1482
+ * commander has heard nothing for an hour. Nothing here reads output, arguments or
1483
+ * files.
1123
1484
  * @param {number} [at] - reference time.
1124
- * @returns {boolean} true when the idle span has reached the threshold.
1485
+ * @returns {{ kind: string, currentTool: object | null }} bounded activity description.
1486
+ */
1487
+ runActivity(at = this.now()) {
1488
+ const task = this.task ?? {};
1489
+ const span = this.activity.toolSpan(at);
1490
+ let kind;
1491
+ if (task.state === 'pending') kind = 'queued';
1492
+ else if (task.state !== 'running') kind = 'settled';
1493
+ else if (task.permission?.pending !== null && task.permission?.pending !== undefined) kind = 'waiting-for-permission';
1494
+ else if (task.question?.pending !== null && task.question?.pending !== undefined) kind = 'waiting-for-answer';
1495
+ else if (span !== null) kind = 'tool-running';
1496
+ else if (this.activity.lastActivityAt !== null) kind = 'model-working';
1497
+ else kind = 'not-started';
1498
+ return {
1499
+ kind,
1500
+ currentTool: span === null ? null : { name: span.name, callId: span.callId, elapsedMs: span.elapsedMs },
1501
+ };
1502
+ }
1503
+
1504
+ /**
1505
+ * Whether the current delivery interval is old enough for an attention report, ignoring
1506
+ * whether this interval was already reported.
1507
+ * @param {number} [at] - reference time.
1508
+ * @returns {boolean} true when the no-delivery span has reached the threshold.
1125
1509
  */
1126
1510
  attentionDue(at = this.now()) {
1127
- return at - this.idleOrigin() >= this.attentionMs;
1511
+ return at - this.progressOrigin() >= this.attentionMs;
1128
1512
  }
1129
1513
 
1130
1514
  /**
1131
- * The instant the next attention report may be delivered, or `Infinity` while the
1132
- * thresholds have not been reached at all.
1515
+ * The instant the run progress check is due, or `Infinity` while it is impossible.
1133
1516
  *
1134
- * The rule is a cooldown, not a one-shot latch: the FIRST report is due at
1135
- * `idleOrigin + attentionSeconds`, and every later report for the same silence
1136
- * needs a FURTHER `attentionSeconds` since the previous delivery. Genuine
1137
- * activity resets both the origin and the delivery record, so a run that goes
1138
- * quiet again can alert again.
1517
+ * A disabled interval is never due. Otherwise it is `progressOrigin + attentionSeconds`;
1518
+ * once this interval has been reported, the value is `Infinity` (the recorded delivery
1519
+ * is kept for the view) and the loop never wakes for an instant that can no longer
1520
+ * produce an answer.
1139
1521
  * @returns {number} the next deliverable instant.
1140
1522
  */
1141
1523
  nextAttentionAt() {
1142
- const origin = this.idleOrigin();
1143
- const delivered = this.attentionDelivered;
1144
- let next = origin + this.attentionMs;
1145
- if (delivered !== null && delivered.episode === this.episode && delivered.origin === origin) {
1146
- next = Math.max(next, delivered.at + this.attentionMs);
1524
+ if (!enabled(this.attentionMs)) return Number.POSITIVE_INFINITY;
1525
+ const origin = this.progressOrigin();
1526
+ // Once THIS interval has been reported, no instant can produce a second answer for it. A
1527
+ // real delivery opens a NEW interval (a new origin), and that interval's instant is
1528
+ // reachable again.
1529
+ if (this.progressReported !== null && this.progressReported.origin === origin) {
1530
+ return Number.POSITIVE_INFINITY;
1147
1531
  }
1148
- return next;
1532
+ return origin + this.attentionMs;
1149
1533
  }
1150
1534
 
1151
1535
  /**
1152
- * Whether an attention report may be delivered at `at`, and atomically claims it
1536
+ * Whether the run progress check may be delivered at `at`, and atomically claims it
1153
1537
  * if so.
1154
1538
  *
1155
1539
  * The claim happens in the same synchronous step as the test, so two observers
1156
1540
  * reaching the threshold together cannot both return `attention`: the first
1157
- * claims, the second observes the fresh delivery record and keeps waiting.
1541
+ * claims, the second observes the fresh interval record and keeps waiting.
1542
+ *
1543
+ * ONE report per DELIVERY INTERVAL. The interval is the consecutive time with nothing
1544
+ * delivered back to the commander, measured from its origin — so a run that keeps
1545
+ * producing internal work while the commander hears nothing still reaches it, and one
1546
+ * interval can never be reported twice. The record this claim writes is the report itself,
1547
+ * never a delivery: it does not move {@link progressOrigin}, and the next interval begins
1548
+ * only when a genuine delivery arrives.
1158
1549
  * @param {number} [at] - delivery instant.
1159
1550
  * @returns {boolean} true for the observer that won the claim.
1160
1551
  */
1161
1552
  claimAttention(at = this.now()) {
1162
- if (at < this.nextAttentionAt()) return false;
1163
- this.attentionDelivered = { episode: this.episode, origin: this.idleOrigin(), at };
1553
+ if (!enabled(this.attentionMs)) return false;
1554
+ const origin = this.progressOrigin();
1555
+ // Already reported for THIS interval: nothing new to say.
1556
+ if (this.progressReported !== null && this.progressReported.origin === origin) return false;
1557
+ if (at - origin < this.attentionMs) return false;
1558
+ return this.claimAttentionAt(origin, at);
1559
+ }
1560
+
1561
+ // -------------------------------------------------------------------------
1562
+ // The two reminders: two SEPARATE clocks, each a REPORT worth acting on
1563
+ // -------------------------------------------------------------------------
1564
+ //
1565
+ // They are measured differently on purpose, and neither is gated on the run's total
1566
+ // duration:
1567
+ //
1568
+ // * `selfCheckSeconds` (default 10 min) — ONE read-only local inspection, armed from
1569
+ // the instant DSH really started running the task (`runOrigin`). A busy run is
1570
+ // inspected too: the product asks for that look, not for a long silence.
1571
+ // * `attentionSeconds` (default 40 min) — ONE notification to the commander asking it
1572
+ // to check the run's progress, armed from the last genuine DELIVERY to the
1573
+ // commander (`progressOrigin`).
1574
+ //
1575
+ // What moves the 40-minute clock: ONLY a new, effective result that TaskBridge actually
1576
+ // handed back to the commander. What does NOT move it — exhaustively, because each of
1577
+ // these was a way to hide a stuck delivery:
1578
+ //
1579
+ // * the run's own START — it opens the FIRST interval (the baseline), it is not a return;
1580
+ // * the LOCAL self-check diagnostic, on any answer, including a plain heartbeat: reading
1581
+ // facts the plugin already holds is not work returned to anyone, and letting it reset
1582
+ // the clock would let the run's own inspection hide the stall it exists to notice;
1583
+ // * DSH-internal model steps, streamed text, reasoning, tool calls and tool results
1584
+ // (they keep `idleOrigin`, the "how silent is the executor" measure, separate);
1585
+ // * heartbeats, empty polls, `wait-limit`, page refreshes and a plain state read;
1586
+ // * permission and ordinary-question waits;
1587
+ // * the repeated-failure reminder, and the 40-minute check itself.
1588
+ //
1589
+ // The protocol has to be honest about one limitation: there is no mid-run stage result in
1590
+ // it. {@link observe} delivers the run's result when the task ENDS; nothing in between is
1591
+ // handed to the commander. So this build advances the clock only on the terminal outcome,
1592
+ // plus one reserved, INTERNAL, event-deduplicated entry point for a real stage result that
1593
+ // a future producer could confirm ({@link noteStageResult}, unused by this build and
1594
+ // covered by its own test). Neither invents a delivery, and no tool, assistant text or
1595
+ // diagnostic is ever passed off as one.
1596
+
1597
+ /**
1598
+ * The instant DSH demonstrably STARTED running this task, or `null` when it has not.
1599
+ *
1600
+ * `runStartedAt` is the engine's own stamp at the one place it starts driving the run —
1601
+ * expressed in the clock this monitor reads — and it is preferred. `startedAt` is the
1602
+ * wall-clock fallback for a record built without that stamp (a fixture, or a record
1603
+ * restored before the engine drove it).
1604
+ *
1605
+ * Waiting in a queue, creating the DSH Session and having the request acknowledged are
1606
+ * all BEFORE that instant, so none of them can arm the ten-minute inspection.
1607
+ *
1608
+ * The value is only usable if THIS monitor's clock can compare with it: a start in the
1609
+ * future (a frozen or offset clock) or one so old that the threshold looks long spent is
1610
+ * not a real elapsed time, and `null` is the honest answer — nothing is scheduled or
1611
+ * reported until real evidence of execution arrives.
1612
+ * @returns {number | null} epoch milliseconds, or null.
1613
+ */
1614
+ runOrigin() {
1615
+ const now = this.now();
1616
+ for (const candidate of [this.task?.runStartedAt, this.task?.startedAt]) {
1617
+ if (!Number.isFinite(candidate) || candidate <= 0) continue;
1618
+ if (candidate > now || now - candidate > MAX_PLAUSIBLE_IDLE_MS) return null;
1619
+ return candidate;
1620
+ }
1621
+ return null;
1622
+ }
1623
+
1624
+ /**
1625
+ * The instant the current delivery interval began.
1626
+ *
1627
+ * That is the last genuine delivery to the commander, or the run's own start when
1628
+ * nothing has been delivered yet — a run that never delivered anything is "not returned
1629
+ * for" its whole life, which is exactly what the commander must be told. Before the run
1630
+ * has started, `now` is used so the interval is a zero-length fact rather than a
1631
+ * measurement of the queue.
1632
+ *
1633
+ * A finished run freezes it at the recorded end (`deliveredAtMs`), exactly like every
1634
+ * other elapsed value: "nothing returned for 40 minutes" must not keep growing after the
1635
+ * run stopped and nobody could have been told anything.
1636
+ * @returns {number} epoch milliseconds.
1637
+ */
1638
+ progressOrigin() {
1639
+ if (this.deliveredAtMs !== null) return this.deliveredAtMs;
1640
+ // A terminal run cannot deliver anything more, so its interval is frozen at the recorded
1641
+ // end. This is read from the RECORD rather than only from `dispose`, so the values are
1642
+ // frozen the moment the run ends — before any persist, view or wait reads them.
1643
+ if (terminalReason(this.task) !== null) {
1644
+ const endedAt = this.task?.endedAt;
1645
+ if (Number.isFinite(endedAt)) {
1646
+ this.freezeDelivery(endedAt);
1647
+ return this.deliveredAtMs;
1648
+ }
1649
+ }
1650
+ const delivered = this.attentionDelivered;
1651
+ if (delivered !== null) return delivered.delivery;
1652
+ // Before the run has started there is no interval to measure, and the RUN'S START is where
1653
+ // the FIRST interval begins — so a monitor that did not see the start (it may be created
1654
+ // by an observation while the task is still `pending`) adopts that same origin as soon as
1655
+ // it can read it.
1656
+ //
1657
+ // Every instant a caller passes to a delivery entry point is measured on THIS monitor's
1658
+ // clock, so the origin always belongs to the same time base. That is what lets the first
1659
+ // real delivery open a genuinely new interval instead of being refused as "already passed".
1660
+ return this.runOrigin() ?? this.now();
1661
+ }
1662
+
1663
+ /**
1664
+ * Whether the run progress check has already been reported for the current interval.
1665
+ * @returns {boolean} true when this interval's one report is spent.
1666
+ */
1667
+ progressReported() {
1668
+ return this.progressReported !== null && this.progressReported.origin === this.progressOrigin();
1669
+ }
1670
+
1671
+ /**
1672
+ * Claim one interval's progress check AT a specific instant, without recursing.
1673
+ *
1674
+ * The claim is bound to the interval's ORIGIN, so the same interval can never be reported
1675
+ * twice however often this is called, and a later interval (opened by a real delivery) is
1676
+ * unaffected. It writes the report latch only — never the delivery record: a report is not
1677
+ * a delivery, and a delivery is not a report.
1678
+ * @param {number} origin - the interval origin.
1679
+ * @param {number} at - the instant to judge at.
1680
+ * @returns {boolean} whether the check was claimed.
1681
+ */
1682
+ claimAttentionAt(origin, at = this.now()) {
1683
+ if (!enabled(this.attentionMs)) return false;
1684
+ if (this.progressReported !== null && this.progressReported.origin === origin) return false;
1685
+ if (at - origin < this.attentionMs) return false;
1686
+ this.progressReported = { origin, at };
1164
1687
  return true;
1165
1688
  }
1166
1689
 
1690
+ /**
1691
+ * Count one REAL delivery to the commander and open the next interval.
1692
+ *
1693
+ * A delivery is a result the commander did not have before. In THIS protocol that means the
1694
+ * run's terminal outcome (and, once a producer exists, a stage result through
1695
+ * {@link noteStageResult}). A local self-check diagnostic, internal model/tool activity, a
1696
+ * heartbeat, an empty poll, an approval or question wait, the progress check itself and the
1697
+ * run's own start are NOT deliveries: if any of them opened a new interval, polling or the
1698
+ * run's own inspection would postpone the reminder it exists to raise.
1699
+ *
1700
+ * Three rules keep the clock honest:
1701
+ *
1702
+ * * an instant that does not move past the current interval's origin (including the run's
1703
+ * start, which opens the FIRST interval) is refused as `opening-interval`/`stale`;
1704
+ * * a `stale` confirmation is refused explicitly and changes nothing;
1705
+ * * the result is IDEMPOTENT per interval: two confirmations between the same two
1706
+ * deliveries advance the clock ONCE.
1707
+ * @param {number} [at] - the delivery instant.
1708
+ * @param {object} [options] - `stale` for a confirmation known to be superseded.
1709
+ * @returns {{ counted: boolean, delivery: number, reason: string | null }} result.
1710
+ */
1711
+ noteDelivery(at = this.now(), options = {}) {
1712
+ const current = this.progressOrigin();
1713
+ if (options.stale === true) {
1714
+ return { counted: false, delivery: current, reason: 'stale' };
1715
+ }
1716
+ const instant = Number.isFinite(at) ? at : this.now();
1717
+ // A delivery must be dated AFTER the interval it opens. This check comes first, so every
1718
+ // refusal states the real reason (`opening-interval` / `stale`) instead of hiding behind the
1719
+ // per-interval duplicate below: an instant at or before the origin is not inside this
1720
+ // interval at all, it is the interval's own starting point.
1721
+ if (instant < current || (this.attentionDelivered === null && instant <= current)) {
1722
+ return {
1723
+ counted: false,
1724
+ delivery: current,
1725
+ reason: this.attentionDelivered === null ? 'opening-interval' : 'stale',
1726
+ };
1727
+ }
1728
+ // IDEMPOTENT per interval: a second confirmation for the SAME interval must not advance the
1729
+ // clock again. "Same interval" means the origin the last delivery opened is still the current
1730
+ // origin AND the confirmation is not dated later than that delivery — i.e. it describes the
1731
+ // interval that is already open. A confirmation dated after it belongs to the next interval
1732
+ // and must be able to open it.
1733
+ const opened = this.attentionDelivered;
1734
+ if (opened !== null && this.deliveryCountedInterval === current && instant <= opened.delivery) {
1735
+ return { counted: false, delivery: current, reason: null };
1736
+ }
1737
+ this.attentionDelivered = { delivery: instant, origin: instant, at: instant };
1738
+ this.deliveryCountedInterval = instant;
1739
+ this.deliveries += 1;
1740
+ // A new interval begins HERE, so its one report is unspent. The latch is keyed by the
1741
+ // interval origin, so it already reads as unspent — clearing it explicitly keeps the two
1742
+ // records impossible to contradict.
1743
+ this.progressReported = null;
1744
+ return { counted: true, delivery: instant, reason: null };
1745
+ }
1746
+
1747
+ /**
1748
+ * The INTERNAL entry point for a stage result that was really handed to the commander.
1749
+ *
1750
+ * This is the only way a mid-run result can advance the clock, and it is deliberately
1751
+ * minimal and closed:
1752
+ *
1753
+ * * it reads an opaque `eventId` and a `deliveredAt` instant, and NOTHING else — no content,
1754
+ * no prose, no diagnostics, so no transcript can travel through it;
1755
+ * * a stage result is counted AT MOST ONCE BY ITS EVENT: replaying the same `eventId` is a
1756
+ * duplicate and moves nothing, whatever instant the replay carries;
1757
+ * * it is accepted only for an event that already happened (`deliveredAt`); a missing or
1758
+ * unusable value is refused, because an unconfirmed result is not news anyone received;
1759
+ * * it is NOT an MCP argument, a tool schema, a settings field or a client route — no
1760
+ * public interface is widened by it.
1761
+ *
1762
+ * Nothing in this build produces such a stage result: the wait channel delivers the run's
1763
+ * result when the task ENDS. A caller that later has one (a real host-side delivery) may
1764
+ * confirm it here; tests drive this seam directly, which is what proves the rule.
1765
+ * @param {{ eventId?: unknown, deliveredAt?: unknown } | null} stage - the delivered stage result.
1766
+ * @returns {{ counted: boolean, delivery: number | null, reason: string | null }} result.
1767
+ */
1768
+ noteStageResult(stage) {
1769
+ if (stage === null || typeof stage !== 'object' || Array.isArray(stage)) {
1770
+ return { counted: false, delivery: null, reason: 'stage-required' };
1771
+ }
1772
+ const eventId = typeof stage.eventId === 'string' && stage.eventId !== '' ? stage.eventId : null;
1773
+ if (eventId === null) {
1774
+ return { counted: false, delivery: null, reason: 'event-id-required' };
1775
+ }
1776
+ const at = stage.deliveredAt;
1777
+ if (!Number.isFinite(at) || at <= 0) {
1778
+ return { counted: false, delivery: null, reason: 'delivery-instant-required' };
1779
+ }
1780
+ // Per-event deduplication: ONE stage result advances the clock once, however often it is
1781
+ // replayed or retried. The set is bounded, and only event identities are kept.
1782
+ if (this.stageEvents.has(eventId)) {
1783
+ return { counted: false, delivery: this.progressOrigin(), reason: 'duplicate' };
1784
+ }
1785
+ const result = this.noteDelivery(at);
1786
+ if (result.counted === true) {
1787
+ this.stageEvents.add(eventId);
1788
+ while (this.stageEvents.size > MAX_TRACKED_STAGE_EVENTS) {
1789
+ const oldest = this.stageEvents.values().next();
1790
+ if (oldest.done === true) break;
1791
+ this.stageEvents.delete(oldest.value);
1792
+ }
1793
+ }
1794
+ // The refusal reason is passed through, so a caller can tell "counted", "duplicate" and
1795
+ // "stale instant" apart instead of reading `counted: false` blindly.
1796
+ return { counted: result.counted, delivery: result.delivery, reason: result.reason };
1797
+ }
1798
+
1799
+ /**
1800
+ * Build the bounded diagnostic carried by the run progress check.
1801
+ *
1802
+ * Everything here is a fact the engine already holds: how long nothing was delivered to
1803
+ * the commander, what the run is doing, how long it has existed, the phase, the open tool
1804
+ * (if any) and the self-check verdict. There is no model text, no diff, no file content
1805
+ * and no review prose, so a check can never become a second, larger wait answer.
1806
+ * @param {number} at - reference time.
1807
+ * @returns {object} bounded diagnostic.
1808
+ */
1809
+ progressCheckpoint(at = this.now()) {
1810
+ const noDeliveryMs = Math.max(0, at - this.progressOrigin());
1811
+ return {
1812
+ kind: CHECKPOINTS.progress,
1813
+ thresholdMs: this.attentionMs,
1814
+ thresholdSeconds: Math.round(this.attentionMs / 1000),
1815
+ // Field one: how long NOTHING new reached the commander.
1816
+ noDeliveryMs,
1817
+ noDeliveryMinutes: Math.floor(noDeliveryMs / 60_000),
1818
+ lastDeliveryAt: this.attentionDelivered === null ? null : this.attentionDelivered.at,
1819
+ deliveries: this.deliveries,
1820
+ // Context only: a long run is not a reminder on its own.
1821
+ runElapsedMs: Math.max(0, at - (this.runOrigin() ?? at)),
1822
+ ...this.checkpointFacts(at),
1823
+ // Stated once, machine-readably, so a host never has to infer from prose that
1824
+ // this reminder did not touch the run.
1825
+ runContinues: true,
1826
+ };
1827
+ }
1828
+
1829
+ /**
1830
+ * The bounded facts a checkpoint reports, shared by every level of the view.
1831
+ *
1832
+ * At the instant a checkpoint fires no self-check has necessarily run yet (a busy run
1833
+ * reaches the delivery threshold long after its ten-minute inspection, and a disabled
1834
+ * self-check never runs at all), so the failure a reader would otherwise take for "we
1835
+ * inspected and found nothing" is avoided by publishing the verdict verbatim — `null`
1836
+ * means "not inspected", which is the honest answer.
1837
+ *
1838
+ * Two field groups are kept apart on purpose: `noDeliveryForMs` says how long nothing
1839
+ * reached the commander, and `activity` says what DSH is doing. A run that is actively
1840
+ * working has BOTH a long `noDeliveryForMs` and `activity.kind: "model-working"`, and an
1841
+ * operator must see both rather than one blended sentence.
1842
+ * @param {number} at - reference time.
1843
+ * @returns {object} bounded facts.
1844
+ */
1845
+ checkpointFacts(at = this.now()) {
1846
+ const task = this.task ?? {};
1847
+ const pending = task.permission?.pending ?? null;
1848
+ const span = this.activity.toolSpan(at);
1849
+ return {
1850
+ state: typeof task.state === 'string' ? task.state : null,
1851
+ phase: typeof task.phase === 'string' ? task.phase : null,
1852
+ // Field one, at the top level, so no reader has to know where to look. Measured
1853
+ // against the reference instant this view was asked for, and never at the wall clock,
1854
+ // so a settled run reports the frozen span its reader asked about.
1855
+ noDeliveryForMs: Math.max(0, at - this.progressOrigin()),
1856
+ // Field two: what the run is doing right now, in a closed vocabulary.
1857
+ activity: this.runActivity(at),
1858
+ // The executor-side measure, kept separate from the delivery clock: a long tool
1859
+ // call is described as an open call, not as idleness.
1860
+ lastActivityAt: this.activity.lastActivityAt,
1861
+ idleForMs: this.activity.idleForMs(at),
1862
+ currentTool: span === null ? null : { name: span.name, callId: span.callId, elapsedMs: span.elapsedMs },
1863
+ waitingOn: span === null ? 'idle' : 'tool',
1864
+ activityEvents: this.activity.activityEvents(),
1865
+ events: this.activity.totalEvents(),
1866
+ selfCheckVerdict: this.selfCheck.verdict,
1867
+ permissionPending: pending !== null,
1868
+ };
1869
+ }
1870
+
1167
1871
  /**
1168
1872
  * Publishable activity summary for a task view.
1169
1873
  *
@@ -1175,17 +1879,46 @@ export class TaskMonitor {
1175
1879
  */
1176
1880
  snapshot({ at = this.now(), toolActive = false } = {}) {
1177
1881
  const summary = this.activity.summary({ at, toolActive });
1882
+ const noDeliveryMs = Math.max(0, at - this.progressOrigin());
1178
1883
  return {
1179
1884
  ...summary,
1180
1885
  // Stated so a reader never has to derive the thresholds from a settings
1181
- // document that may have changed since this task froze its own.
1886
+ // document that may have changed since this task froze its own. `0` means the
1887
+ // reminder is switched off for this run. `attentionSeconds` is the run progress
1888
+ // check: the ONE notification interval this product has.
1182
1889
  selfCheckSeconds: Math.round(this.selfCheckMs / 1000),
1183
1890
  attentionSeconds: Math.round(this.attentionMs / 1000),
1891
+ // The self-check, described exactly as the timer arms it: measured from the real
1892
+ // start of execution, ONCE per run, and never due before the run started. When the
1893
+ // record carries a start this monitor's clock cannot compare with, the instant is
1894
+ // stated as `null` — "no usable start" is the honest answer, and it is checked
1895
+ // BEFORE adding, so `NaN` can never leak into a view.
1896
+ selfCheckDueAt: enabled(this.selfCheckMs) && this.runOrigin() !== null
1897
+ ? this.runOrigin() + this.selfCheckMs
1898
+ : null,
1899
+ // The run progress check, described in the same bounded terms the reminder itself
1900
+ // uses, so the task page and a wait answer agree without either reading a settings
1901
+ // document. There is no separate cadence and no total-runtime clock.
1902
+ progressCheck: {
1903
+ thresholdSeconds: Math.round(this.attentionMs / 1000),
1904
+ // Field one: consecutive time with NOTHING delivered to the commander.
1905
+ noDeliveryForMs: noDeliveryMs,
1906
+ noDeliveryMinutes: Math.floor(noDeliveryMs / 60_000),
1907
+ lastActivityAt: this.activity.lastActivityAt,
1908
+ lastDeliveryAt: this.attentionDelivered === null ? null : this.attentionDelivered.at,
1909
+ deliveries: this.deliveries,
1910
+ reportedThisEpisode: this.progressReported !== null && this.progressReported.origin === this.progressOrigin() && enabled(this.attentionMs),
1911
+ nextDueAt: Number.isFinite(this.nextAttentionAt()) ? this.nextAttentionAt() : null,
1912
+ ...this.checkpointFacts(at),
1913
+ },
1184
1914
  idleForMs: this.activity.idleForMs(at),
1185
1915
  selfCheck: {
1186
1916
  episode: this.selfCheck.episode,
1187
1917
  checkedAt: this.selfCheck.checkedAt,
1188
1918
  verdict: this.selfCheck.verdict,
1919
+ // Both independent fields, straight from the diagnostic.
1920
+ sinceStartMs: this.selfCheck.sinceStartMs ?? null,
1921
+ noDeliveryForMs: this.selfCheck.noDeliveryForMs ?? null,
1189
1922
  },
1190
1923
  // The repeated-failure reminder, as bounded evidence: one small object per
1191
1924
  // reported episode, never arguments, output or error prose.
@@ -1236,18 +1969,30 @@ export class TaskMonitor {
1236
1969
  * 2. `ready`/`failed`/`cancelled` — the task reached a terminal state. This wins
1237
1970
  * over a disposal wake, so an observation released by engine teardown still
1238
1971
  * reports the outcome the run actually reached;
1239
- * 3. `permission` — a per-call decision is outstanding. Waiting for approval is
1240
- * not a stall;
1241
- * 4. `attention` — the silence reached `attentionSeconds` (once, then on the
1242
- * cooldown) AND the claim was won. Genuine progress never produces this: it
1243
- * resets the silence instead, which is the whole point of the feature;
1972
+ * 3. `permission` / `question` — a human decision is outstanding. Waiting for an
1973
+ * answer is not a stall;
1974
+ * 3b. `attention` with `checkpoint: "failure"` — the repeated-tool-failure reminder.
1975
+ * Independent of any clock: a busy run can fail the same call over and over;
1976
+ * 4. `attention` with `checkpoint: "progress"` — the run has DELIVERED nothing new to
1977
+ * the commander for `attentionSeconds` (default 40 minutes) and the claim for this
1978
+ * delivery interval was won. DSH-internal model steps, text, tool activity,
1979
+ * heartbeats, the self-check and this very check never count as a delivery, so a
1980
+ * run that is visibly busy can still reach it — and one interval produces at most
1981
+ * one report;
1244
1982
  * 5. `heartbeat` — the bounded wait expired with nothing to report.
1245
1983
  *
1246
- * The self-check runs inside the loop, so a monitor with no observer costs
1247
- * nothing. Every caller gets its own controller and timer, so an observation
1248
- * never cancels another.
1984
+ * The self-check runs inside the loop AND on its own scheduled timer (see
1985
+ * {@link scheduleSelfCheck}): an observation finds it already done for this run when no
1986
+ * caller was waiting, and a run with no observer at all is still inspected. The diagnostic
1987
+ * it produces travels on the answer as a READ of local facts; it is not a delivery and does
1988
+ * not advance the 40-minute clock. Neither does a heartbeat, an empty poll, a `wait-limit`,
1989
+ * a permission/question wait, a failure reminder or the check itself — this channel
1990
+ * delivers the run's result when the task ENDS, and nothing before that is a result. A real
1991
+ * stage result could only arrive through {@link noteStageResult}.
1992
+ * Every caller gets its own controller and timer, so an observation never cancels
1993
+ * another.
1249
1994
  * @param {object} [options] - `waitMs`, `signal`.
1250
- * @returns {Promise<{ reason: string, activitySinceWait: boolean, waitedMs: number, selfCheck: object | null }>} outcome.
1995
+ * @returns {Promise<{ reason: string, checkpoint: string | null, activitySinceWait: boolean, waitedMs: number, selfCheck: object | null }>} outcome.
1251
1996
  */
1252
1997
  async observe(options = {}) {
1253
1998
  const signal = options.signal ?? null;
@@ -1279,20 +2024,28 @@ export class TaskMonitor {
1279
2024
  const at = this.now();
1280
2025
  const activitySinceWait = this.activity.sequence !== startingSequence;
1281
2026
  // A pure read of local facts, run BEFORE any reason is returned so every
1282
- // report carries the diagnostic that explains the silence.
2027
+ // report carries the diagnostic that explains the run's state.
1283
2028
  const checked = this.runSelfCheck(at);
1284
2029
  if (checked !== null) selfCheck = checked;
1285
2030
 
1286
2031
  // (2) The run's own outcome outranks a wake-up: a task that ended must be
1287
- // reported as ended even if the monitor was disposed in the same instant.
2032
+ // reported as ended even if the monitor was disposed in the same instant. The
2033
+ // outcome is a delivery only when THIS answer is the one that releases it, and the
2034
+ // engine decides that at the single place an answer is built (`observationOf`) — a
2035
+ // monitor-level pre-answer would claim a delivery nobody necessarily received.
1288
2036
  const terminal = terminalReason(this.task);
1289
- if (terminal !== null) return this.outcome(terminal, activitySinceWait, at - startedAt, selfCheck);
2037
+ if (terminal !== null) {
2038
+ return this.outcome(terminal, activitySinceWait, at - startedAt, selfCheck);
2039
+ }
1290
2040
 
1291
2041
  // (1) Only one's OWN abort (or disposal) interrupts.
1292
2042
  if (this.disposed || waiter.controller.aborted === true || (signal !== null && signal.aborted === true)) {
1293
2043
  return this.outcome(OBSERVE_REASONS.interrupted, activitySinceWait, at - startedAt, selfCheck);
1294
2044
  }
1295
2045
 
2046
+ // A permission or question wait is NOT a delivery of progress: the commander is
2047
+ // being asked something, and the 40-minute interval must keep running so a task
2048
+ // that is blocked on a human is still reported as "not returned for X minutes".
1296
2049
  if (this.task?.permission?.pending !== null && this.task?.permission?.pending !== undefined) {
1297
2050
  return this.outcome(OBSERVE_REASONS.permission, activitySinceWait, at - startedAt, selfCheck);
1298
2051
  }
@@ -1303,25 +2056,50 @@ export class TaskMonitor {
1303
2056
  // turn this into `attention`.
1304
2057
  return this.outcome(OBSERVE_REASONS.question, activitySinceWait, at - startedAt, selfCheck);
1305
2058
  }
1306
- // (3b) Repeated failures. Same reason as the silence report — it needs the
1307
- // commander — but it carries its own typed diagnostic and is NOT gated on
1308
- // silence: a busy run that keeps failing the same operation must still reach
1309
- // the host. Permission and a terminal state above outrank it.
2059
+ // (3b) Repeated failures. Same reason as the progress check — it needs the
2060
+ // commander — but it carries its own typed diagnostic and is NOT gated on the
2061
+ // delivery clock: a busy run that keeps failing the same operation must still
2062
+ // reach the host. Permission and a terminal state above outrank it. It is not a
2063
+ // delivery of progress either: a reminder is not a new result.
1310
2064
  const failure = this.claimFailureReport();
1311
2065
  if (failure !== null) {
1312
- return this.outcome(OBSERVE_REASONS.attention, activitySinceWait, at - startedAt, selfCheck, failure);
2066
+ return this.outcome(OBSERVE_REASONS.attention, activitySinceWait, at - startedAt, selfCheck, failure, CHECKPOINTS.failure);
1313
2067
  }
1314
- // (4) `claimAttention` is false while genuine progress has reset the clock,
1315
- // because the origin moved into the future relative to `nextAttentionAt()`.
1316
- if (this.claimAttention(at)) {
1317
- return this.outcome(OBSERVE_REASONS.attention, activitySinceWait, at - startedAt, selfCheck);
2068
+ // (4) The run progress check, measured on the DELIVERY clock (see
2069
+ // `progressOrigin`): it fires at most once per delivery interval and asks the
2070
+ // commander to check the run — it never cancels, restarts or resubmits anything,
2071
+ // and reporting it does NOT advance the clock.
2072
+ //
2073
+ // It is CLAIMED at the instant it became due (bounded by this reading), because a
2074
+ // single bounded wait routinely spans that instant: a caller must be told as soon as
2075
+ // the wait ends instead of keeping quiet. The diagnostic is still reported at THIS
2076
+ // reading, so the span it states is the time that has really passed.
2077
+ const dueAt = this.nextAttentionAt();
2078
+ if (Number.isFinite(dueAt) && dueAt <= at && this.claimAttention(dueAt)) {
2079
+ return this.outcome(
2080
+ OBSERVE_REASONS.attention,
2081
+ activitySinceWait,
2082
+ at - startedAt,
2083
+ selfCheck,
2084
+ null,
2085
+ CHECKPOINTS.progress,
2086
+ this.progressCheckpoint(at),
2087
+ );
1318
2088
  }
1319
2089
  const elapsed = at - startedAt;
1320
2090
  if (elapsed >= waitMs) {
2091
+ // A heartbeat is nothing new: it is explicitly NOT a delivery, so the
2092
+ // 40-minute clock is untouched by a commander that polls.
1321
2093
  return this.outcome(OBSERVE_REASONS.heartbeat, activitySinceWait, elapsed, selfCheck);
1322
2094
  }
1323
- const untilAttention = this.nextAttentionAt() - at;
1324
- const slice = Math.max(1, Math.min(this.waitSliceMs, waitMs - elapsed, untilAttention));
2095
+ // Wake for the next reminder the run could actually produce. A disabled reminder
2096
+ // contributes `Infinity`, so "off" cannot make the slice shorter.
2097
+ //
2098
+ // The slice is a TIME TO WAIT, so it is floored at 1 ms even when the next reminder
2099
+ // is already due: waking in the same millisecond would spin on a due instant the loop
2100
+ // is about to handle, which is how an interval could be claimed between two readings.
2101
+ const untilNext = Math.max(1, this.nextAttentionAt() - at);
2102
+ const slice = Math.max(1, Math.min(this.waitSliceMs, waitMs - elapsed, untilNext));
1325
2103
  try {
1326
2104
  await this.wait(slice, { signal: waiter.controller.signal });
1327
2105
  } catch {
@@ -1344,18 +2122,76 @@ export class TaskMonitor {
1344
2122
  * @param {object | null} selfCheck - the last self-check diagnostic.
1345
2123
  * @param {object | null} [failure] - the repeated-failure diagnostic, when that is
1346
2124
  * what ended the wait.
2125
+ * @param {string | null} [checkpoint] - which `attention` reminder this is
2126
+ * (`progress`/`stall`/`failure`), or null for a reason that is not one.
2127
+ * @param {object | null} [progress] - the bounded progress-checkpoint diagnostic.
1347
2128
  * @returns {object} outcome.
1348
2129
  */
1349
- outcome(reason, activitySinceWait, waitedMs, selfCheck, failure = null) {
2130
+ outcome(reason, activitySinceWait, waitedMs, selfCheck, failure = null, checkpoint = null, progress = null) {
1350
2131
  return {
1351
2132
  reason,
2133
+ // Only an `attention` reason has a checkpoint; stating one for any other reason
2134
+ // would invite a host to act on a reminder that was never made.
2135
+ checkpoint: reason === OBSERVE_REASONS.attention ? checkpoint : null,
1352
2136
  failure,
2137
+ progress,
1353
2138
  activitySinceWait: activitySinceWait === true,
1354
2139
  waitedMs: Math.max(0, Math.trunc(waitedMs)),
1355
2140
  selfCheck,
1356
2141
  };
1357
2142
  }
1358
2143
 
2144
+ /**
2145
+ * Publish the bounded delivery state, and count a delivery the ENGINE confirmed.
2146
+ *
2147
+ * Two things in one place so the engine never has to know how the interval is derived:
2148
+ *
2149
+ * * it reports how long the current interval is (`noDeliveryForMs`) and what the run is
2150
+ * doing (`activity`), which is exactly the pair of independent fields the reminder
2151
+ * must state;
2152
+ /**
2153
+ * Publish the bounded delivery state, and count the ONE delivery the engine can name.
2154
+ *
2155
+ * Two things in one place so the engine never has to know how the interval is derived:
2156
+ *
2157
+ * * it reports how long the current interval is (`noDeliveryForMs`) and what the run is
2158
+ * doing (`activity`) — exactly the pair of independent fields the reminder must state;
2159
+ * * when the engine passes `delivered: true`, the run reached its terminal outcome, which
2160
+ * IS the result the commander receives, so the clock advances once and `counted` says so.
2161
+ * Every other answer — a heartbeat, an empty poll, a self-check diagnostic, a permission
2162
+ * or question wait, a failure reminder, the progress check itself — counts nothing.
2163
+ * @param {object} [options] - `at`, `delivered`.
2164
+ * @returns {{ noDeliveryForMs: number, noDeliveryMinutes: number, lastDeliveryAt: number | null,
2165
+ * deliveries: number, activity: object, counted: boolean, countReason: string | null }} delivery state.
2166
+ */
2167
+ delivery({ at = this.now(), delivered = false } = {}) {
2168
+ const noted = delivered === true ? this.noteDelivery(at) : null;
2169
+ const noDeliveryMs = Math.max(0, at - this.progressOrigin());
2170
+ return {
2171
+ noDeliveryForMs: noDeliveryMs,
2172
+ noDeliveryMinutes: Math.floor(noDeliveryMs / 60_000),
2173
+ lastDeliveryAt: this.attentionDelivered === null ? null : this.attentionDelivered.at,
2174
+ deliveries: this.deliveries,
2175
+ activity: this.runActivity(at),
2176
+ counted: noted !== null && noted.counted === true,
2177
+ countReason: noted === null ? null : noted.reason,
2178
+ };
2179
+ }
2180
+
2181
+ /**
2182
+ * Freeze every elapsed value — including the delivery interval — at the run's end.
2183
+ *
2184
+ * Called once by {@link dispose}, so a stored record reports the spans the run really
2185
+ * had. The delivery interval is frozen only if it is not already frozen.
2186
+ * @param {number} endedAt - the recorded end instant.
2187
+ * @returns {void}
2188
+ */
2189
+ freezeDelivery(endedAt) {
2190
+ if (this.deliveredAtMs !== null) return;
2191
+ if (!Number.isFinite(endedAt)) return;
2192
+ this.deliveredAtMs = endedAt;
2193
+ }
2194
+
1359
2195
  /**
1360
2196
  * Drop every listener/timer this monitor owns. Idempotent.
1361
2197
  *
@@ -1365,9 +2201,16 @@ export class TaskMonitor {
1365
2201
  * @returns {void}
1366
2202
  */
1367
2203
  dispose(endedAt = undefined) {
1368
- if (typeof endedAt === 'number') this.activity.finalize(endedAt);
2204
+ if (typeof endedAt === 'number') {
2205
+ this.activity.finalize(endedAt);
2206
+ // A finished run can deliver nothing more, so its delivery interval stops being
2207
+ // measured at the recorded end instead of reporting a wait nobody could shorten.
2208
+ this.freezeDelivery(endedAt);
2209
+ }
1369
2210
  if (this.disposed) return;
1370
2211
  this.disposed = true;
2212
+ // The scheduled self-check goes with the run: a disposed monitor leaves no timer.
2213
+ this.clearSelfCheckTimer();
1371
2214
  // Open calls can never produce a result for a run that has ended; the reported
1372
2215
  // trail stays as bounded evidence. The undelivered reminder is dropped with it.
1373
2216
  this.failures.dispose();
@@ -1408,17 +2251,64 @@ function boundedWait(waitMs) {
1408
2251
  }
1409
2252
 
1410
2253
  /**
1411
- * Convert a validated seconds threshold to milliseconds, with the documented
1412
- * default when the value is absent.
2254
+ * Convert a validated seconds threshold to milliseconds.
2255
+ *
2256
+ * Three cases, deliberately distinct:
2257
+ * * a missing/invalid value takes the documented default — a monitor built without
2258
+ * a threshold must behave like the configured default, not like "off";
2259
+ * * `0` (or a negative value) is DISABLED and becomes `0` ms, which every caller
2260
+ * treats as "this reminder never fires";
2261
+ * * any other whole number of seconds becomes that many milliseconds.
1413
2262
  * @param {unknown} value - seconds.
1414
- * @param {number} fallbackSeconds - default.
1415
- * @returns {number} milliseconds.
2263
+ * @param {number} fallbackSeconds - documented default.
2264
+ * @returns {number} milliseconds, `0` meaning disabled.
1416
2265
  */
1417
- function secondsToMs(value, fallbackSeconds) {
1418
- const seconds = Number.isSafeInteger(value) && value > 0 ? value : fallbackSeconds;
2266
+ function thresholdToMs(value, fallbackSeconds) {
2267
+ const seconds = Number.isSafeInteger(value) ? value : fallbackSeconds;
2268
+ if (seconds <= 0) return 0;
1419
2269
  return seconds * 1000;
1420
2270
  }
1421
2271
 
2272
+ /** Whether a milliseconds threshold is enabled. */
2273
+ function enabled(ms) {
2274
+ return Number.isFinite(ms) && ms > 0;
2275
+ }
2276
+
2277
+ /**
2278
+ * The longest delay a `setTimeout` honours on both Node and the browser (~24.8 days).
2279
+ *
2280
+ * A longer delay is a platform-dependent overflow (Node clamps it to 1 ms), so it is never
2281
+ * passed to the timer: see the poll in {@link TaskMonitor#scheduleSelfCheck}.
2282
+ */
2283
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
2284
+
2285
+ /** Short poll used only when the threshold is further away than a timer can express. */
2286
+ const SELF_CHECK_POLL_MS = 60_000;
2287
+
2288
+ /**
2289
+ * How close an armed instant must be to the monitor's own clock to be treated as an epoch
2290
+ * instant a real platform timer can be given.
2291
+ *
2292
+ * A production monitor reads `Date.now()`, so its due instant is an epoch millisecond and is
2293
+ * handed to `setTimeout` verbatim: a timer that fires late still records the check at the
2294
+ * instant the threshold was reached. A monitor built over an injected (arbitrary) clock has
2295
+ * an instant that means nothing to the platform timer, so it is not handed over at all and
2296
+ * the check is recorded at that clock's own reading instead.
2297
+ */
2298
+ const MAX_EPOCH_DOMAIN_MS = 24 * 60 * 60 * 1000;
2299
+
2300
+ /**
2301
+ * The oldest recorded run start this monitor will measure silence from, relative to its
2302
+ * own clock.
2303
+ *
2304
+ * A task record carries its start from the HOST wall clock while the monitor reads its
2305
+ * injected clock. A difference beyond this is not a real elapsed time but two clocks that
2306
+ * disagree (a test's frozen clock, or a clock that moved); measuring from it would make a
2307
+ * fresh run look long silent. Past this bound the monitor measures from its own `now`,
2308
+ * which is the only instant it can honestly compare against.
2309
+ */
2310
+ const MAX_PLAUSIBLE_IDLE_MS = 24 * 60 * 60 * 1000;
2311
+
1422
2312
  /**
1423
2313
  * Default wait seam: a real, unref'd timeout that honours an abort signal.
1424
2314
  *