@tidegap/core 0.19.0 → 0.21.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 (171) hide show
  1. package/README.md +1 -1
  2. package/dist/agent-snippet.d.ts +30 -0
  3. package/dist/agent-snippet.js +120 -0
  4. package/dist/channels/commands.d.ts +137 -0
  5. package/dist/channels/commands.js +377 -0
  6. package/dist/channels/delivery-codes.d.ts +9 -0
  7. package/dist/channels/delivery-codes.js +53 -0
  8. package/dist/channels/digest.d.ts +102 -0
  9. package/dist/channels/digest.js +146 -0
  10. package/dist/channels/format.d.ts +138 -0
  11. package/dist/channels/format.js +425 -0
  12. package/dist/channels/index.d.ts +15 -0
  13. package/dist/channels/index.js +15 -0
  14. package/dist/channels/kinds/command.d.ts +13 -0
  15. package/dist/channels/kinds/command.js +65 -0
  16. package/dist/channels/kinds/discord.d.ts +16 -0
  17. package/dist/channels/kinds/discord.js +67 -0
  18. package/dist/channels/kinds/email.d.ts +20 -0
  19. package/dist/channels/kinds/email.js +162 -0
  20. package/dist/channels/kinds/index.d.ts +8 -0
  21. package/dist/channels/kinds/index.js +17 -0
  22. package/dist/channels/kinds/ntfy.d.ts +25 -0
  23. package/dist/channels/kinds/ntfy.js +163 -0
  24. package/dist/channels/kinds/pushover.d.ts +11 -0
  25. package/dist/channels/kinds/pushover.js +77 -0
  26. package/dist/channels/kinds/shared.d.ts +25 -0
  27. package/dist/channels/kinds/shared.js +39 -0
  28. package/dist/channels/kinds/shortcuts.d.ts +9 -0
  29. package/dist/channels/kinds/shortcuts.js +45 -0
  30. package/dist/channels/kinds/slack.d.ts +8 -0
  31. package/dist/channels/kinds/slack.js +57 -0
  32. package/dist/channels/kinds/telegram.d.ts +4 -0
  33. package/dist/channels/kinds/telegram.js +26 -0
  34. package/dist/channels/kinds/webhook.d.ts +30 -0
  35. package/dist/channels/kinds/webhook.js +177 -0
  36. package/dist/channels/payload.d.ts +36 -0
  37. package/dist/channels/payload.js +61 -0
  38. package/dist/channels/plan.d.ts +24 -0
  39. package/dist/channels/plan.js +66 -0
  40. package/dist/channels/registry.d.ts +191 -0
  41. package/dist/channels/registry.js +125 -0
  42. package/dist/channels/telegram.d.ts +110 -0
  43. package/dist/channels/telegram.js +168 -0
  44. package/dist/channels/types.d.ts +107 -0
  45. package/dist/channels/types.js +26 -0
  46. package/dist/claude-tools.d.ts +29 -0
  47. package/dist/claude-tools.js +49 -0
  48. package/dist/data/tables.generated.d.ts +6 -0
  49. package/dist/data/tables.generated.js +37 -0
  50. package/dist/energy.d.ts +84 -0
  51. package/dist/energy.js +138 -0
  52. package/dist/grid.d.ts +17 -2
  53. package/dist/grid.js +43 -4
  54. package/dist/handoff.d.ts +171 -0
  55. package/dist/handoff.js +482 -0
  56. package/dist/history.d.ts +17 -0
  57. package/dist/history.js +14 -1
  58. package/dist/index.d.ts +49 -15
  59. package/dist/index.js +36 -8
  60. package/dist/job-cadence.d.ts +76 -0
  61. package/dist/job-cadence.js +240 -0
  62. package/dist/jobs.d.ts +183 -0
  63. package/dist/jobs.js +917 -0
  64. package/dist/notify.d.ts +11 -0
  65. package/dist/notify.js +19 -4
  66. package/dist/postpone.d.ts +113 -0
  67. package/dist/postpone.js +185 -0
  68. package/dist/providers/anthropic.js +14 -8
  69. package/dist/providers/base.d.ts +145 -2
  70. package/dist/providers/base.js +41 -1
  71. package/dist/providers/budget.d.ts +25 -0
  72. package/dist/providers/budget.js +57 -0
  73. package/dist/providers/defaults.js +4 -0
  74. package/dist/providers/defer.d.ts +16 -0
  75. package/dist/providers/defer.js +31 -0
  76. package/dist/providers/gemini.d.ts +4 -0
  77. package/dist/providers/gemini.js +34 -24
  78. package/dist/providers/http.d.ts +40 -0
  79. package/dist/providers/http.js +82 -0
  80. package/dist/providers/index.d.ts +2 -2
  81. package/dist/providers/index.js +1 -1
  82. package/dist/providers/ollama.d.ts +4 -0
  83. package/dist/providers/ollama.js +32 -25
  84. package/dist/providers/openai.js +11 -9
  85. package/dist/providers/timeout.d.ts +36 -0
  86. package/dist/providers/timeout.js +71 -0
  87. package/dist/quota.d.ts +7 -2
  88. package/dist/quota.js +12 -27
  89. package/dist/readiness.d.ts +205 -0
  90. package/dist/readiness.js +326 -0
  91. package/dist/redact.d.ts +42 -0
  92. package/dist/redact.js +110 -0
  93. package/dist/region-host.d.ts +30 -0
  94. package/dist/region-host.js +69 -0
  95. package/dist/region.d.ts +102 -20
  96. package/dist/region.js +175 -23
  97. package/dist/run-limits.d.ts +268 -0
  98. package/dist/run-limits.js +572 -0
  99. package/dist/run-session.d.ts +36 -0
  100. package/dist/run-session.js +72 -0
  101. package/dist/schedule-job.d.ts +118 -0
  102. package/dist/schedule-job.js +243 -0
  103. package/dist/scheduler.d.ts +391 -18
  104. package/dist/scheduler.js +1341 -177
  105. package/dist/sign.d.ts +8 -1
  106. package/dist/sign.js +49 -3
  107. package/dist/storage/sqlite.d.ts +183 -5
  108. package/dist/storage/sqlite.js +720 -19
  109. package/dist/task-events.d.ts +117 -0
  110. package/dist/task-events.js +345 -0
  111. package/dist/tool-surface.d.ts +31 -2
  112. package/dist/tool-surface.js +390 -65
  113. package/dist/types.d.ts +267 -3
  114. package/dist/types.js +6 -1
  115. package/dist/zone-time.d.ts +22 -0
  116. package/dist/zone-time.js +76 -0
  117. package/package.json +13 -5
  118. package/dist/aggregator.d.ts.map +0 -1
  119. package/dist/aggregator.js.map +0 -1
  120. package/dist/budget.d.ts.map +0 -1
  121. package/dist/budget.js.map +0 -1
  122. package/dist/data/tables.generated.d.ts.map +0 -1
  123. package/dist/data/tables.generated.js.map +0 -1
  124. package/dist/energy.d.ts.map +0 -1
  125. package/dist/energy.js.map +0 -1
  126. package/dist/grid.d.ts.map +0 -1
  127. package/dist/grid.js.map +0 -1
  128. package/dist/history.d.ts.map +0 -1
  129. package/dist/history.js.map +0 -1
  130. package/dist/index.d.ts.map +0 -1
  131. package/dist/index.js.map +0 -1
  132. package/dist/notify.d.ts.map +0 -1
  133. package/dist/notify.js.map +0 -1
  134. package/dist/paths.d.ts.map +0 -1
  135. package/dist/paths.js.map +0 -1
  136. package/dist/providers/anthropic.d.ts.map +0 -1
  137. package/dist/providers/anthropic.js.map +0 -1
  138. package/dist/providers/base.d.ts.map +0 -1
  139. package/dist/providers/base.js.map +0 -1
  140. package/dist/providers/defaults.d.ts.map +0 -1
  141. package/dist/providers/defaults.js.map +0 -1
  142. package/dist/providers/gemini.d.ts.map +0 -1
  143. package/dist/providers/gemini.js.map +0 -1
  144. package/dist/providers/index.d.ts.map +0 -1
  145. package/dist/providers/index.js.map +0 -1
  146. package/dist/providers/ollama.d.ts.map +0 -1
  147. package/dist/providers/ollama.js.map +0 -1
  148. package/dist/providers/openai.d.ts.map +0 -1
  149. package/dist/providers/openai.js.map +0 -1
  150. package/dist/quota.d.ts.map +0 -1
  151. package/dist/quota.js.map +0 -1
  152. package/dist/recommend.d.ts.map +0 -1
  153. package/dist/recommend.js.map +0 -1
  154. package/dist/redact.d.ts.map +0 -1
  155. package/dist/redact.js.map +0 -1
  156. package/dist/region.d.ts.map +0 -1
  157. package/dist/region.js.map +0 -1
  158. package/dist/routing.d.ts.map +0 -1
  159. package/dist/routing.js.map +0 -1
  160. package/dist/scheduler.d.ts.map +0 -1
  161. package/dist/scheduler.js.map +0 -1
  162. package/dist/select-window.d.ts.map +0 -1
  163. package/dist/select-window.js.map +0 -1
  164. package/dist/sign.d.ts.map +0 -1
  165. package/dist/sign.js.map +0 -1
  166. package/dist/storage/sqlite.d.ts.map +0 -1
  167. package/dist/storage/sqlite.js.map +0 -1
  168. package/dist/tool-surface.d.ts.map +0 -1
  169. package/dist/tool-surface.js.map +0 -1
  170. package/dist/types.d.ts.map +0 -1
  171. package/dist/types.js.map +0 -1
package/dist/scheduler.js CHANGED
@@ -18,17 +18,25 @@
18
18
  */
19
19
  import { randomUUID } from "node:crypto";
20
20
  import { carbonBudgetUsage, receiptCarbonG, windowBounds, } from "./budget.js";
21
- import { gramsForIntensity, resolveModelEnergy } from "./energy.js";
21
+ import { billModelUsage, gramsForIntensity, resolveModelEnergy, singleModelCounts } from "./energy.js";
22
+ import { claudeCodeToolsError } from "./claude-tools.js";
23
+ import { handoffCwdError, outputPathError, profileTools, resultPathError, sameTools, wakeError } from "./handoff.js";
22
24
  import { mockGridFeed } from "./grid.js";
25
+ import { deferRetryAt } from "./providers/defer.js";
26
+ import { postponeOptions, resolveLimitReset, resolvePostpone, taskProvider, writeLimitResetHint, } from "./postpone.js";
23
27
  import { candidateId, parseCandidates, previewRouting, scoreCandidates, } from "./routing.js";
24
28
  import { capHistory, deriveTitle, displayTitle, isRepeating, taskActions, taskHistory } from "./history.js";
29
+ import { BATCH_SUBMIT_INTERRUPTED_ERROR, JOB_CAPS_KEYS, JOB_INTERRUPTED_ERROR } from "./jobs.js";
30
+ import { attemptNumber, CAPS_VERSION, capValueError, classifyFailure, failureFactsOf, finalFailureError, isRetryableFailure, loadRunLimitSettings, planRetry, resolveTaskRunLimits, retryPolicyOf, runLimitsDetails, taskRunLimitsView, } from "./run-limits.js";
25
31
  import { resolveQuotaDeadline } from "./quota.js";
32
+ import { tickDispatch } from "./readiness.js";
26
33
  import { redactBodyJson, redactPrompt } from "./redact.js";
27
34
  import { selectWindow } from "./select-window.js";
28
35
  import { loadOrCreateSigningKey, signReceipt, } from "./sign.js";
29
36
  import { TaskStore } from "./storage/sqlite.js";
30
- const PENDING_STATUSES = ["queued", "scheduled"];
31
- const UNFINISHED_STATUSES = ["queued", "scheduled", "submitted", "running"];
37
+ import { PROGRESS_BUSY_MS, createProgressRecorder, eventDetails, impliedEventKind, } from "./task-events.js";
38
+ export const PENDING_STATUSES = ["queued", "scheduled"];
39
+ export const UNFINISHED_STATUSES = ["queued", "scheduled", "submitted", "running"];
32
40
  const TERMINAL = new Set(["completed", "failed", "cancelled"]);
33
41
  const DEFAULT_REGION = "US-CAL-CISO";
34
42
  const MAX_HORIZON_HOURS = 72;
@@ -40,6 +48,7 @@ const SUPPORTED_PROVIDERS = new Set([
40
48
  "openai",
41
49
  "gemini",
42
50
  "ollama",
51
+ "claude-code",
43
52
  ]);
44
53
  /** Thrown when no candidate window meets the user-supplied carbon budget. */
45
54
  export class CarbonBudgetExceededError extends Error {
@@ -62,14 +71,22 @@ export class InvalidDeadlineError extends Error {
62
71
  this.name = "InvalidDeadlineError";
63
72
  }
64
73
  }
74
+ /** How often a held run's row is read for a cancel, or any other move off `running`, by another writer. */
75
+ const RUN_STATUS_CHECK_MS = 10_000;
76
+ /** The tick result of a run stopped because its task was cancelled. */
77
+ const STOPPED_RUN_ERROR = "task was cancelled while running; its run was stopped";
65
78
  export class Scheduler {
66
79
  feed;
67
- defaultRegion;
80
+ defaultRegionOption;
68
81
  rng;
69
82
  tasks = new Map();
70
83
  pendingTimers = new Map();
71
84
  resolvers = new Map();
72
85
  bodies = new Map();
86
+ /** Rows a tick moved to `running` whose dispatch has not settled (KTD12), and what each is doing. */
87
+ held = new Map();
88
+ /** Failed attempts per task without a ledger, where no `attempt_failed` event is stored to count. */
89
+ attemptsWithoutLedger = new Map();
73
90
  store;
74
91
  // Mutable: a single load failure disables signing for the rest of
75
92
  // this scheduler instance (see `getSigningKey`).
@@ -78,9 +95,18 @@ export class Scheduler {
78
95
  carbonBudget;
79
96
  onCarbonAlert;
80
97
  quotaConfig;
98
+ limitReset;
99
+ actor;
100
+ sleepCounter;
101
+ lockedTick;
102
+ runLimitSettings;
103
+ defaultRegion() {
104
+ const option = this.defaultRegionOption;
105
+ return typeof option === "function" ? option() : option;
106
+ }
81
107
  constructor(opts = {}) {
82
108
  this.feed = opts.feed ?? mockGridFeed();
83
- this.defaultRegion = opts.defaultRegion ?? DEFAULT_REGION;
109
+ this.defaultRegionOption = opts.defaultRegion ?? DEFAULT_REGION;
84
110
  this.rng = opts.rng ?? Math.random;
85
111
  if (opts.store) {
86
112
  this.store = opts.store;
@@ -92,6 +118,32 @@ export class Scheduler {
92
118
  this.carbonBudget = opts.carbonBudget;
93
119
  this.onCarbonAlert = opts.onCarbonAlert;
94
120
  this.quotaConfig = opts.quotaConfig;
121
+ this.limitReset = opts.limitReset;
122
+ this.actor = opts.actor ?? "system";
123
+ this.lockedTick = opts.lockedTick;
124
+ this.sleepCounter = opts.sleepCounter;
125
+ this.runLimitSettings = opts.runLimits ?? (() => loadRunLimitSettings());
126
+ }
127
+ /**
128
+ * The time limits a run of `spec` gets if it starts now: the stored
129
+ * values, then the settings, then the defaults. A settings read that
130
+ * throws gives the stored values and the defaults.
131
+ */
132
+ runLimitsFor(spec) {
133
+ return resolveTaskRunLimits(spec, this.settingsNow());
134
+ }
135
+ /** A task's time limits as views show them: the ones its newest run recorded, else the ones a run now gets. */
136
+ taskRunLimits(record, events = this.listTaskEvents(record.taskId)) {
137
+ return taskRunLimitsView(record.bodyJson, events, this.settingsNow());
138
+ }
139
+ /** The run-limit settings now; a reader that throws gives none (the stored values and the defaults apply). */
140
+ settingsNow() {
141
+ try {
142
+ return this.runLimitSettings();
143
+ }
144
+ catch {
145
+ return { values: {}, ignored: [] };
146
+ }
95
147
  }
96
148
  /**
97
149
  * Compute the current aggregate carbon-budget status (ROADMAP item 4)
@@ -274,6 +326,10 @@ export class Scheduler {
274
326
  cached.readAt = undefined;
275
327
  return changed;
276
328
  }
329
+ /** A task's events from the ledger, oldest first; [] without a store. */
330
+ listTaskEvents(taskId, opts = {}) {
331
+ return this.store?.listTaskEvents(taskId, opts) ?? [];
332
+ }
277
333
  /** Record that a ticker ran at `at` (ledger meta `last_tick_at`). No-op without a store. */
278
334
  recordTickRun(at = new Date()) {
279
335
  this.store?.setMeta(LAST_TICK_META_KEY, at.toISOString());
@@ -282,6 +338,55 @@ export class Scheduler {
282
338
  lastTickAt() {
283
339
  return this.store?.getMeta(LAST_TICK_META_KEY);
284
340
  }
341
+ /** The ledger this scheduler writes through to, if any. Jobs live there too. */
342
+ ledger() {
343
+ return this.store;
344
+ }
345
+ /**
346
+ * Insert one job occurrence and plan it (floating recurring jobs, KTD4).
347
+ * The row is built here, not through `enqueueProviderCall` (which refuses
348
+ * `provider: "command"`): `scheduled`, `notBefore = earliest`,
349
+ * `scheduledFor = earliest + 1 min` (never equal to `notBefore`, which
350
+ * would read as an exact pin), the slot deadline with no widening,
351
+ * `repeat = none` and no series, so `rollSeries` never touches it. The
352
+ * insert is `insertIfAbsent` on the derived id; returns false, writing
353
+ * nothing, when the row exists. Planning picks the cleanest forecast hour
354
+ * inside `[earliest, deadline]`, or leaves the row unplanned for
355
+ * `replanSweep` when the forecast does not reach it (or fails).
356
+ */
357
+ async materializeOccurrence(occ, details) {
358
+ if (!this.store)
359
+ throw new Error("materializeOccurrence: jobs need a ledger (dbPath)");
360
+ const earliestMs = Date.parse(occ.earliest);
361
+ const deadlineMs = Date.parse(occ.deadline);
362
+ const record = {
363
+ taskId: occ.taskId,
364
+ status: "scheduled",
365
+ enqueuedAt: new Date().toISOString(),
366
+ region: this.defaultRegion(),
367
+ bodyJson: occ.bodyJson,
368
+ deadline: new Date(deadlineMs).toISOString(),
369
+ notBefore: new Date(earliestMs).toISOString(),
370
+ scheduledFor: new Date(Math.min(earliestMs + MINUTE_MS, deadlineMs)).toISOString(),
371
+ title: occ.title,
372
+ originHost: occ.originHost,
373
+ originCwd: occ.originCwd,
374
+ repeat: "none",
375
+ jobId: occ.jobId,
376
+ };
377
+ const created = this.eventFor(undefined, record, { kind: "created", actor: "system", details });
378
+ if (!this.store.insertIfAbsent(record, created))
379
+ return false;
380
+ this.cacheRow(record);
381
+ try {
382
+ await this.scheduleProviderCall(record.taskId, new Date(deadlineMs));
383
+ }
384
+ catch (err) {
385
+ // eslint-disable-next-line no-console
386
+ console.warn(`[tidegap/scheduler] could not plan job occurrence ${record.taskId}: ${describeErr(err)}; replanSweep plans it later`);
387
+ }
388
+ return true;
389
+ }
285
390
  /**
286
391
  * Defer a task. Returns a promise that resolves with the task's eventual
287
392
  * result when Tidegap dispatches it.
@@ -320,7 +425,7 @@ export class Scheduler {
320
425
  throw new Error(`repeat ${JSON.stringify(opts.repeat)} needs a provider-call task; closure tasks cannot repeat`);
321
426
  }
322
427
  const taskId = opts.taskId ?? `t-${randomUUID()}`;
323
- const region = opts.region ?? this.defaultRegion;
428
+ const region = opts.region ?? this.defaultRegion();
324
429
  const record = {
325
430
  taskId,
326
431
  status: "queued",
@@ -332,7 +437,7 @@ export class Scheduler {
332
437
  };
333
438
  this.tasks.set(taskId, record);
334
439
  this.bodies.set(taskId, task);
335
- this.store?.upsert(record);
440
+ this.store?.upsert(record, this.eventFor(undefined, record, { kind: "created", actor: opts.actor }));
336
441
  // Fire-and-forget, but never unhandled: a rejecting grid feed (or any
337
442
  // scheduling error) must fail the task — rejecting the defer() promise
338
443
  // — instead of crashing the process with an unhandledRejection.
@@ -365,7 +470,74 @@ export class Scheduler {
365
470
  if (typeof spec.prompt !== "string" || spec.prompt.length === 0) {
366
471
  throw new Error("enqueueProviderCall: spec.prompt must be a non-empty string");
367
472
  }
368
- const deadline = normalizeDeadline(opts.deadline);
473
+ if (spec.caps !== undefined) {
474
+ spec = { ...spec, caps: checkedCaps(spec.caps, MODEL_CALL_CAPS_KEYS, "enqueueProviderCall") };
475
+ }
476
+ const checked = checkedHandoff(spec, opts, "enqueueProviderCall");
477
+ if (checked.tools !== undefined) {
478
+ const toolsError = claudeCodeToolsError(checked.tools);
479
+ if (toolsError)
480
+ throw new Error(`enqueueProviderCall: ${toolsError}`);
481
+ }
482
+ // The title is never rewritten at terminal transitions, so it is stored
483
+ // redacted from the start (same patterns as the receipt prompt).
484
+ const title = deriveTitle(opts.title ?? spec.prompt, spec.redactInReceipt) ??
485
+ (opts.title !== undefined ? deriveTitle(spec.prompt, spec.redactInReceipt) : undefined);
486
+ return this.insertProviderCall(checked, opts, title);
487
+ }
488
+ /**
489
+ * Queue a one-off shell command (`tidegap queue add --runner command`):
490
+ * the row of a command job run (`provider: "command"`, `model: "none"`,
491
+ * an empty prompt) with `command.origin: "cli"` and no job id, planned
492
+ * like any provider call. Only the CLI tick's command adapter runs it.
493
+ * Checks: a command of 1 to 32,000 characters, an existing absolute
494
+ * folder, valid caps, and the result path rules. Only the caps the caller
495
+ * set are stored; the time limits not set come from the settings when the
496
+ * run starts. `enqueueProviderCall` keeps refusing `command`, and
497
+ * `retryTask` refuses these rows: running a shell command again is the
498
+ * user's call.
499
+ */
500
+ async enqueueCommandTask(task, opts = {}) {
501
+ if (typeof task.run !== "string" || task.run.trim() === "") {
502
+ throw new Error("enqueueCommandTask: the command must be a non-empty string");
503
+ }
504
+ if (task.run.length > COMMAND_MAX_CHARS) {
505
+ throw new Error(`enqueueCommandTask: the command is longer than ${COMMAND_MAX_CHARS} characters`);
506
+ }
507
+ const cwdError = handoffCwdError(task.cwd, "command");
508
+ if (cwdError)
509
+ throw new Error(`enqueueCommandTask: ${cwdError}`);
510
+ const caps = checkedCaps(task.caps, JOB_CAPS_KEYS, "enqueueCommandTask");
511
+ if (task.resultPath !== undefined) {
512
+ const pathError = resultPathError(task.resultPath, { cwd: task.cwd, originCwd: opts.originCwd });
513
+ if (pathError)
514
+ throw new Error(`enqueueCommandTask: ${pathError}`);
515
+ }
516
+ const wakeRefused = wakeError(task.wake, task.origin, opts.originSessionId);
517
+ if (wakeRefused)
518
+ throw new Error(`enqueueCommandTask: ${wakeRefused}`);
519
+ const handoff = {
520
+ ...(task.resultPath !== undefined ? { resultPath: task.resultPath } : {}),
521
+ ...(task.wake === true ? { wake: true } : {}),
522
+ };
523
+ const spec = {
524
+ type: "provider_call",
525
+ provider: "command",
526
+ model: "none",
527
+ prompt: "",
528
+ command: { run: task.run, cwd: task.cwd, secrets: [], origin: "cli" },
529
+ caps,
530
+ ...(Object.keys(handoff).length > 0 ? { handoff } : {}),
531
+ ...(task.origin ? { origin: task.origin } : {}),
532
+ };
533
+ return this.insertProviderCall(spec, opts, deriveTitle(opts.title ?? task.run));
534
+ }
535
+ /** Insert a checked provider-call row with its `created` event, then plan its window. */
536
+ async insertProviderCall(spec, opts, title) {
537
+ const requested = normalizeDeadline(opts.deadline);
538
+ const notBefore = earliestStart(opts.notBefore);
539
+ const start = notBefore ? startFields(notBefore.getTime(), requested.getTime()) : undefined;
540
+ const deadline = start ? new Date(start.deadline) : requested;
369
541
  if (opts.taskId !== undefined) {
370
542
  if (typeof opts.taskId !== "string" || opts.taskId.length === 0) {
371
543
  throw new Error(`Invalid taskId: must be a non-empty string`);
@@ -382,11 +554,7 @@ export class Scheduler {
382
554
  throw new Error(`repeat "quota_reset" needs deadlineKind "quota_reset" and a quotaProvider label`);
383
555
  }
384
556
  const taskId = opts.taskId ?? `t-${randomUUID()}`;
385
- const region = opts.region ?? this.defaultRegion;
386
- // The title is never rewritten at terminal transitions, so it is stored
387
- // redacted from the start (same patterns as the receipt prompt).
388
- const title = deriveTitle(opts.title ?? spec.prompt, spec.redactInReceipt) ??
389
- (opts.title !== undefined ? deriveTitle(spec.prompt, spec.redactInReceipt) : undefined);
557
+ const region = opts.region ?? this.defaultRegion();
390
558
  const record = {
391
559
  taskId,
392
560
  status: "queued",
@@ -397,8 +565,26 @@ export class Scheduler {
397
565
  deadline: deadline.toISOString(),
398
566
  ...identityFields(taskId, opts, title),
399
567
  };
568
+ if (start) {
569
+ record.notBefore = start.notBefore;
570
+ record.scheduledFor = start.scheduledFor;
571
+ }
400
572
  this.tasks.set(taskId, record);
401
- this.store?.upsert(record);
573
+ // Insert once: another process that enqueued the same id since the
574
+ // check above keeps its row.
575
+ const created = this.eventFor(undefined, record, {
576
+ kind: "created",
577
+ actor: opts.actor,
578
+ details: opts.parentTaskId ? { parent_task_id: opts.parentTaskId } : {},
579
+ });
580
+ if (this.store && !this.store.insertIfAbsent(record, created)) {
581
+ this.tasks.delete(taskId);
582
+ throw new Error(`Task id "${taskId}" is already in the queue`);
583
+ }
584
+ // A task from a session counts for that session's notices even when the
585
+ // first notice query runs only after it finished.
586
+ if (record.originSessionId)
587
+ this.store?.startSessionNotices(new Date(record.enqueuedAt));
402
588
  // Schedule a carbon window but DO NOT register an in-process timer that
403
589
  // calls `dispatch` — provider-call tasks are driven exclusively by
404
590
  // `Scheduler.tick`. We still write `scheduled` + `scheduledFor` so the
@@ -421,11 +607,33 @@ export class Scheduler {
421
607
  * (`enqueue` / `defer`) are NOT touched by this method — only this
422
608
  * process can run those.
423
609
  */
424
- async tick(adapters) {
610
+ async tick(adapters, opts = {}) {
425
611
  const results = [];
426
612
  let dispatched = 0;
427
613
  let failed = 0;
614
+ let deferred = 0;
615
+ let retrying = 0;
428
616
  let inspected = 0;
617
+ // Provider and model → retryAt after its first defer this tick: later due
618
+ // tasks on that provider and model defer to the same time without a
619
+ // dispatch (KTD7.4). Keyed by model too: a spent per-model window (for
620
+ // example a weekly "Fable" limit) must not hold back the other models.
621
+ const deferrals = new Map();
622
+ const count = (entry) => {
623
+ if (entry.status === "completed")
624
+ dispatched++;
625
+ else if (entry.status === "deferred")
626
+ deferred++;
627
+ else if (entry.status === "retrying")
628
+ retrying++;
629
+ else
630
+ failed++;
631
+ };
632
+ // ---- (0) Rows a dead tick left running, under the tick lock only ----
633
+ for (const entry of this.freeDeadTickRuns()) {
634
+ results.push(await this.planRetryWindow(entry));
635
+ count(entry);
636
+ }
429
637
  // ---- (1) Batch-submit sweep, BEFORE the due sweep ----
430
638
  // A batch-eligible task's deferral mechanism IS the Batch API: the
431
639
  // provider runs it within its own 24h SLA and picks the execution
@@ -439,6 +647,8 @@ export class Scheduler {
439
647
  // time to start the batch).
440
648
  const submittedThisTick = new Set();
441
649
  for (const record of this.collectBatchSubmitCandidates(adapters)) {
650
+ if (opts.signal?.aborted)
651
+ break;
442
652
  // Reuse the scheduled→running claim so a racing tick can't submit
443
653
  // the same row twice (double-billed batch). In-memory-only mode
444
654
  // has no cross-process race, so claim only when a store exists.
@@ -465,12 +675,9 @@ export class Scheduler {
465
675
  continue;
466
676
  }
467
677
  inspected++;
468
- const entry = await this.dispatchProviderCall(record, adapters);
678
+ const entry = await this.holding(record, "provider_call", () => this.dispatchProviderCall(record, adapters, deferrals));
469
679
  results.push(entry);
470
- if (entry.status === "completed")
471
- dispatched++;
472
- else
473
- failed++;
680
+ count(entry);
474
681
  continue;
475
682
  }
476
683
  }
@@ -481,16 +688,14 @@ export class Scheduler {
481
688
  record.status = "running";
482
689
  }
483
690
  inspected++;
484
- const entry = await this.submitBatch(record, adapters);
691
+ const entry = await this.holding(record, "batch_submit", () => this.submitBatch(record, adapters));
485
692
  results.push(entry);
486
693
  if (entry.status === "submitted") {
487
694
  batchSubmitted++;
488
695
  submittedThisTick.add(record.taskId);
489
696
  }
490
- else if (entry.status === "completed")
491
- dispatched++;
492
697
  else
493
- failed++;
698
+ count(entry);
494
699
  }
495
700
  // ---- (2) Due sweep (sync provider calls) ----
496
701
  const now = Date.now();
@@ -511,10 +716,20 @@ export class Scheduler {
511
716
  continue;
512
717
  if (!this.isDue(record, now))
513
718
  continue;
719
+ // A command job's shell step runs only where a `command` adapter
720
+ // exists (the CLI tick). Elsewhere the row stays `scheduled`: no
721
+ // claim, no failure. With `holdUnserved`, so does any row this host
722
+ // has no adapter for.
723
+ if (unservedCommand(record, adapters))
724
+ continue;
725
+ if (opts.holdUnserved && unserved(record, adapters))
726
+ continue;
514
727
  candidates.push(record);
515
728
  seen.add(record.taskId);
516
729
  }
517
730
  for (const record of candidates) {
731
+ if (opts.signal?.aborted)
732
+ break;
518
733
  // Row-level claim: only one tick gets to dispatch this task. If
519
734
  // the store is configured, the claim is also visible to other
520
735
  // processes pointing at the same SQLite file (e.g. an
@@ -543,16 +758,16 @@ export class Scheduler {
543
758
  }
544
759
  }
545
760
  inspected++;
546
- const entry = await this.dispatchProviderCall(record, adapters);
761
+ const entry = await this.holding(record, "provider_call", () => this.dispatchProviderCall(record, adapters, deferrals));
547
762
  results.push(entry);
548
- if (entry.status === "completed")
549
- dispatched++;
550
- else
551
- failed++;
763
+ count(entry);
552
764
  }
553
765
  // ---- (3) Batch-poll sweep, AFTER the due sweep ----
766
+ this.freeStrandedPolls(Date.now());
554
767
  let batchPolled = 0;
555
768
  for (const record of this.collectSubmittedCandidates(submittedThisTick)) {
769
+ if (opts.signal?.aborted)
770
+ break;
556
771
  // Claim submitted→running so two racing ticks can't double-complete.
557
772
  if (this.store) {
558
773
  let claimed = false;
@@ -573,14 +788,12 @@ export class Scheduler {
573
788
  record.status = "running";
574
789
  }
575
790
  inspected++;
576
- const entry = await this.pollBatch(record, adapters);
791
+ const entry = await this.holding(record, "batch_poll", () => this.pollBatch(record, adapters));
577
792
  results.push(entry);
578
- if (entry.status === "completed")
579
- dispatched++;
580
- else if (entry.status === "submitted")
793
+ if (entry.status === "submitted")
581
794
  batchPolled++;
582
795
  else
583
- failed++;
796
+ count(entry);
584
797
  }
585
798
  // ---- (4) Aggregate carbon-budget alert (ROADMAP item 4) ----
586
799
  // After every receipt this tick wrote (sync due-sweep + batch poll),
@@ -600,6 +813,8 @@ export class Scheduler {
600
813
  results,
601
814
  batchSubmitted,
602
815
  batchPolled,
816
+ deferred,
817
+ retrying,
603
818
  };
604
819
  }
605
820
  /**
@@ -680,6 +895,47 @@ export class Scheduler {
680
895
  releaseClaim(record) {
681
896
  this.writeIf(record, { ...record, status: "scheduled" }, ["running"]);
682
897
  }
898
+ /**
899
+ * The head of the Batch-poll sweep (batch 27 KTD9): a plain row that a
900
+ * killed tick left `running` with its batch id goes back to `submitted`
901
+ * once its deadline plus `STRANDED_POLL_GRACE_MS` has passed, and the sweep
902
+ * then polls it. The batch id proves a live batch. A row goes to a Batch
903
+ * API only with a deadline over a day ahead, and the providers end every
904
+ * batch within 24 h, so a row past its deadline has a finished batch: the
905
+ * step rarely meets a live poll in another process, and compare-and-set
906
+ * still lands one completion if it does. Job rows are the job sweep's;
907
+ * rows this scheduler's tick holds are live. No event, as in
908
+ * `failHeldRuns`.
909
+ */
910
+ freeStrandedPolls(now) {
911
+ if (!this.store)
912
+ return;
913
+ let rows;
914
+ try {
915
+ rows = this.store.list({ status: "running" });
916
+ }
917
+ catch (err) {
918
+ // eslint-disable-next-line no-console
919
+ console.warn(`[tidegap/scheduler] tick: could not read running rows: ${describeErr(err)}; no stranded Batch poll freed this round`);
920
+ return;
921
+ }
922
+ for (const row of rows) {
923
+ if (!row.batchId || row.jobId || this.held.has(row.taskId))
924
+ continue;
925
+ const deadline = Date.parse(row.deadline ?? "");
926
+ if (!Number.isFinite(deadline) || now - deadline <= STRANDED_POLL_GRACE_MS)
927
+ continue;
928
+ const record = this.tasks.get(row.taskId) ?? row;
929
+ try {
930
+ this.writeIf(record, { ...row, status: "submitted", completedAt: undefined, error: undefined }, ["running"]);
931
+ this.tasks.set(row.taskId, record);
932
+ }
933
+ catch (err) {
934
+ // eslint-disable-next-line no-console
935
+ console.warn(`[tidegap/scheduler] tick: could not free stranded Batch poll ${row.taskId}: ${describeErr(err)}; skipping this round`);
936
+ }
937
+ }
938
+ }
683
939
  /**
684
940
  * Collect every "submitted" provider-call task awaiting batch results.
685
941
  * `exclude` skips tasks submitted earlier in the same tick — submit and
@@ -758,14 +1014,53 @@ export class Scheduler {
758
1014
  Object.assign(cached, row);
759
1015
  return cached;
760
1016
  }
1017
+ /**
1018
+ * The progress callback of one run: the lines an adapter reports become
1019
+ * `progress` events (actor `tick`) within the core caps. None without a
1020
+ * ledger. Each write waits at most `PROGRESS_BUSY_MS` for a busy ledger.
1021
+ * A failed write costs its line, never the run; the first failure of a
1022
+ * task logs one warning that says later failed lines are dropped too.
1023
+ */
1024
+ progressFor(taskId) {
1025
+ const store = this.store;
1026
+ if (!store)
1027
+ return undefined;
1028
+ let warned = false;
1029
+ return createProgressRecorder((details) => {
1030
+ try {
1031
+ store.recordEvent(taskId, { kind: "progress", actor: "tick", details }, { busyMs: PROGRESS_BUSY_MS });
1032
+ }
1033
+ catch (err) {
1034
+ if (warned)
1035
+ return;
1036
+ warned = true;
1037
+ // eslint-disable-next-line no-console
1038
+ console.warn(`[tidegap/scheduler] task ${taskId}: could not record a progress event (this and later failed lines are dropped): ${describeErr(err)}`);
1039
+ }
1040
+ }, { existing: () => store.countTaskEvents(taskId, "progress") });
1041
+ }
1042
+ /** `{ tick }` for a `dispatched` event under the tick lock; else nothing. */
1043
+ tickDetails() {
1044
+ return this.lockedTick ? { tick: this.lockedTick.tick } : {};
1045
+ }
1046
+ /** `{ sleep }` for a `dispatched` event when the host reads a sleep counter; else nothing. Never throws. */
1047
+ sleepDetails() {
1048
+ try {
1049
+ const r = this.sleepCounter?.();
1050
+ return r && Number.isFinite(r.boot_at) && Number.isFinite(r.slept_ms) ? { sleep: { boot_at: r.boot_at, slept_ms: r.slept_ms } } : {};
1051
+ }
1052
+ catch {
1053
+ return {};
1054
+ }
1055
+ }
761
1056
  /**
762
1057
  * Compare-and-set write: store `next` only while the row's status is in
763
1058
  * `expected`; on success copy it onto the cached record. On a miss the
764
1059
  * cache is reloaded from the ledger and false is returned. Without a
765
1060
  * store the write always succeeds.
766
1061
  */
767
- writeIf(record, next, expected) {
768
- if (this.store && !this.store.transitionIf(next, expected)) {
1062
+ writeIf(record, next, expected, event) {
1063
+ if (this.store && !this.store.transitionIf(next, expected, undefined, this.eventFor(record, next, event))) {
769
1064
  const current = this.store.get(record.taskId);
770
1065
  if (current)
771
1066
  Object.assign(record, current);
@@ -774,6 +1069,17 @@ export class Scheduler {
774
1069
  Object.assign(record, next);
775
1070
  return true;
776
1071
  }
1072
+ /**
1073
+ * The `task_events` row for a write from `prev` to `next`: the given kind,
1074
+ * or a terminal kind the status change implies; undefined = no event.
1075
+ * `spec.details` are extra keys on top of {@link eventDetails}.
1076
+ */
1077
+ eventFor(prev, next, spec) {
1078
+ const kind = spec?.kind ?? (prev ? impliedEventKind(prev.status, next.status) : undefined);
1079
+ if (!kind)
1080
+ return undefined;
1081
+ return { kind, actor: spec?.actor ?? this.actor, details: eventDetails(kind, prev, next, spec?.details) };
1082
+ }
777
1083
  /**
778
1084
  * Series rollover (ui v2, KTD6). Called when an occurrence with a repeat
779
1085
  * rule finishes (completed, failed, or cancelled as a skip), BEFORE its
@@ -832,7 +1138,12 @@ export class Scheduler {
832
1138
  quotaProvider: deadlineKind === "quota_reset" ? quotaProvider : undefined,
833
1139
  };
834
1140
  if (this.store) {
835
- if (this.store.insertIfAbsent(successor)) {
1141
+ const created = this.eventFor(undefined, successor, {
1142
+ kind: "created",
1143
+ actor: "system",
1144
+ details: { series_id: record.seriesId, previous_task_id: record.taskId },
1145
+ });
1146
+ if (this.store.insertIfAbsent(successor, created)) {
836
1147
  this.cacheRow(successor);
837
1148
  // A stop written between the read above and the insert: end the
838
1149
  // successor too. `cancelTask(..., {series})` also cancels pending
@@ -855,7 +1166,7 @@ export class Scheduler {
855
1166
  * `record` itself, with `repeat = none` (stop series). Compare-and-set per
856
1167
  * row; a row another process claimed meanwhile is left to the dispatcher.
857
1168
  */
858
- endSeriesOccurrences(record) {
1169
+ endSeriesOccurrences(record, actor) {
859
1170
  if (!this.store || !record.seriesId)
860
1171
  return;
861
1172
  for (const row of this.store.list({ seriesId: record.seriesId })) {
@@ -871,7 +1182,7 @@ export class Scheduler {
871
1182
  completedAt: new Date().toISOString(),
872
1183
  bodyJson: redactBodyJson(row.bodyJson),
873
1184
  repeat: "none",
874
- }, ["queued", "scheduled"]);
1185
+ }, ["queued", "scheduled"], { kind: "cancelled", actor, details: { series: true } });
875
1186
  }
876
1187
  }
877
1188
  /** The newest quota label stored on any occurrence of the record's series. */
@@ -898,7 +1209,10 @@ export class Scheduler {
898
1209
  * claimed the row first, the cancel lands on the `running` row; the
899
1210
  * dispatcher re-checks the status before finalizing and drops the late
900
1211
  * result. `opts.series` also ends the series (`repeat = none`) in the
901
- * same write ("stop series").
1212
+ * same write ("stop series"); on a finished occurrence it ends the
1213
+ * series at its live occurrence. `opts.expectedStatus` cancels only a row in
1214
+ * one of those states and returns any other row unchanged: the job code
1215
+ * passes the pending states, so a row a tick claimed runs to its end.
902
1216
  */
903
1217
  cancelTask(taskId, opts = {}) {
904
1218
  for (let attempt = 0; attempt < 2; attempt++) {
@@ -906,7 +1220,17 @@ export class Scheduler {
906
1220
  if (!record) {
907
1221
  throw new TaskActionError(`cancelTask: task ${JSON.stringify(taskId)} not found`);
908
1222
  }
909
- if (TERMINAL.has(record.status))
1223
+ if (TERMINAL.has(record.status)) {
1224
+ // "Stop series" from a finished occurrence ends the series at its
1225
+ // live occurrence, so a later run does not roll it on.
1226
+ if (opts.series && record.seriesId) {
1227
+ const live = this.store?.list({ seriesId: record.seriesId }).find((r) => !TERMINAL.has(r.status));
1228
+ if (live)
1229
+ this.cancelTask(live.taskId, { series: true, actor: opts.actor });
1230
+ }
1231
+ return record;
1232
+ }
1233
+ if (opts.expectedStatus && !opts.expectedStatus.includes(record.status))
910
1234
  return record;
911
1235
  this.clearPendingTimer(taskId);
912
1236
  if (record.status === "submitted") {
@@ -931,10 +1255,15 @@ export class Scheduler {
931
1255
  this.rollSeries(record);
932
1256
  // A miss means another process moved the row (claimed or finished it)
933
1257
  // between our read and this write: re-read and try once more.
934
- if (!this.writeIf(record, next, [record.status]))
1258
+ const event = {
1259
+ kind: "cancelled",
1260
+ actor: opts.actor,
1261
+ details: { ...opts.details, ...(opts.series ? { series: true } : {}) },
1262
+ };
1263
+ if (!this.writeIf(record, next, [record.status], event))
935
1264
  continue;
936
1265
  if (opts.series)
937
- this.endSeriesOccurrences(record);
1266
+ this.endSeriesOccurrences(record, opts.actor);
938
1267
  const resolver = this.resolvers.get(taskId);
939
1268
  resolver?.reject(new Error(`task ${taskId} cancelled`));
940
1269
  this.bodies.delete(taskId);
@@ -951,7 +1280,7 @@ export class Scheduler {
951
1280
  * survives onto the completed row. Throws when the task's state does not
952
1281
  * allow it (see `taskActions`).
953
1282
  */
954
- runNow(taskId) {
1283
+ runNow(taskId, opts = {}) {
955
1284
  const record = this.refreshTask(taskId);
956
1285
  if (!record)
957
1286
  throw new TaskActionError(`runNow: task ${JSON.stringify(taskId)} not found`);
@@ -966,7 +1295,7 @@ export class Scheduler {
966
1295
  intensitySource: "expedited",
967
1296
  notBefore: undefined,
968
1297
  };
969
- if (!this.writeIf(record, next, PENDING_STATUSES)) {
1298
+ if (!this.writeIf(record, next, PENDING_STATUSES, { kind: "expedited", actor: opts.actor })) {
970
1299
  throw new TaskActionError(refusal("runNow", record, "only queued or scheduled provider-call tasks can run now"));
971
1300
  }
972
1301
  return record;
@@ -981,7 +1310,11 @@ export class Scheduler {
981
1310
  * compare-and-set on the pending statuses; throws when the task is not
982
1311
  * movable.
983
1312
  */
984
- async rescheduleTask(taskId, target) {
1313
+ async rescheduleTask(taskId, target, opts = {}) {
1314
+ return this.moveTask(taskId, target, { kind: "rescheduled", actor: opts.actor });
1315
+ }
1316
+ /** `rescheduleTask` with the event to record (`rescheduled` or `postponed`). */
1317
+ async moveTask(taskId, target, event) {
985
1318
  const why = "only queued or scheduled provider-call tasks can be rescheduled";
986
1319
  const shape = rescheduleShape(target);
987
1320
  const record = this.refreshTask(taskId);
@@ -1008,13 +1341,22 @@ export class Scheduler {
1008
1341
  deadline: new Date(deadlineMs).toISOString(),
1009
1342
  estimatedCarbonGCo2: undefined,
1010
1343
  };
1011
- if (!this.writeIf(record, next, PENDING_STATUSES)) {
1344
+ if (!this.writeIf(record, next, PENDING_STATUSES, event)) {
1012
1345
  throw new TaskActionError(refusal("reschedule", record, why));
1013
1346
  }
1014
1347
  return record;
1015
1348
  }
1016
1349
  let deadline;
1017
- if (shape.kind === "deadline") {
1350
+ if (shape.kind === "notBefore") {
1351
+ const start = parseInstant(shape.notBefore, "notBefore");
1352
+ const startMs = Math.max(start.getTime(), Date.now());
1353
+ const given = shape.deadline !== undefined ? normalizeDeadline(shape.deadline).getTime() : 0;
1354
+ const current = record.deadline ? Date.parse(record.deadline) : 0;
1355
+ const fields = startFields(startMs, given || current);
1356
+ deadline = new Date(fields.deadline);
1357
+ Object.assign(record, absolute, fields, { estimatedCarbonGCo2: undefined });
1358
+ }
1359
+ else if (shape.kind === "deadline") {
1018
1360
  deadline = normalizeDeadline(shape.deadline);
1019
1361
  Object.assign(record, absolute, { notBefore: undefined, deadline: deadline.toISOString() });
1020
1362
  }
@@ -1042,7 +1384,7 @@ export class Scheduler {
1042
1384
  scheduledFor: new Date(dayStart.getTime() + Math.max(offset, MINUTE_MS)).toISOString(),
1043
1385
  });
1044
1386
  }
1045
- if (!(await this.scheduleProviderCall(taskId, deadline))) {
1387
+ if (!(await this.scheduleProviderCall(taskId, deadline, event))) {
1046
1388
  throw new TaskActionError(refusal("reschedule", record, why));
1047
1389
  }
1048
1390
  // Planning can fail the task (no hour under its carbon budget): report
@@ -1052,6 +1394,53 @@ export class Scheduler {
1052
1394
  }
1053
1395
  return record;
1054
1396
  }
1397
+ /**
1398
+ * "Later" (coherence KTD4): move a queued or scheduled provider-call task
1399
+ * so it never runs earlier than its planned start. Resolves the target
1400
+ * with {@link resolvePostpone} and writes it through `rescheduleTask`, so
1401
+ * the write is the same compare-and-set on the pending statuses. An
1402
+ * `after_limit_reset` target uses its own `resetAt` (stored as the hint),
1403
+ * else the plugged-in `limitReset` source, else a still-future hint.
1404
+ * Throws `TaskActionError` with the refusal reason.
1405
+ */
1406
+ async postponeTask(taskId, target, opts = {}) {
1407
+ const record = this.refreshTask(taskId);
1408
+ if (!record)
1409
+ throw new TaskActionError(`later: task ${JSON.stringify(taskId)} not found`);
1410
+ const now = new Date();
1411
+ const afterReset = "preset" in target && target.preset === "after_limit_reset";
1412
+ const givenReset = afterReset ? target.resetAt : undefined;
1413
+ const reset = afterReset && givenReset === undefined ? await resolveLimitReset(record, now, this.limitReset, this.store) : null;
1414
+ // Resolve against the row as it is after the wait: another process may
1415
+ // have moved it meanwhile, and "later" is measured from its current plan.
1416
+ const current = this.refreshTask(taskId);
1417
+ if (!current)
1418
+ throw new TaskActionError(`later: task ${JSON.stringify(taskId)} not found`);
1419
+ const resolved = resolvePostpone(current, target, now, reset);
1420
+ if (!resolved.ok)
1421
+ throw new TaskActionError(`later: task ${taskId}: ${resolved.reason}`);
1422
+ const moved = await this.moveTask(taskId, resolved.reschedule, {
1423
+ kind: "postponed",
1424
+ actor: opts.actor,
1425
+ details: "preset" in target ? { preset: target.preset } : {},
1426
+ });
1427
+ if (givenReset !== undefined)
1428
+ writeLimitResetHint(this.store, new Date(givenReset), taskProvider(record));
1429
+ return moved;
1430
+ }
1431
+ /**
1432
+ * The Later presets of a task with their resolved times (KTD6), using
1433
+ * the plugged-in reset source and the stored hint.
1434
+ */
1435
+ async postponeOptionsFor(task, now = new Date()) {
1436
+ const record = typeof task === "string" ? this.refreshTask(task) : task;
1437
+ if (!record)
1438
+ throw new TaskActionError(`later: task ${JSON.stringify(task)} not found`);
1439
+ const reset = taskActions(record).later
1440
+ ? await resolveLimitReset(record, now, this.limitReset, this.store)
1441
+ : null;
1442
+ return postponeOptions(record, now, reset);
1443
+ }
1055
1444
  /**
1056
1445
  * Reply to a completed provider-call task (ui v2, brainstorm R16/R17):
1057
1446
  * enqueue a child with the parent's conversation as history, the reply as
@@ -1070,6 +1459,7 @@ export class Scheduler {
1070
1459
  throw new TaskActionError("reply: text must be a non-empty string");
1071
1460
  }
1072
1461
  const spec = JSON.parse(parent.bodyJson);
1462
+ const handoff = replyHandoff(spec);
1073
1463
  const child = {
1074
1464
  type: "provider_call",
1075
1465
  provider: spec.provider,
@@ -1081,8 +1471,16 @@ export class Scheduler {
1081
1471
  ...(spec.maxTokens !== undefined ? { maxTokens: spec.maxTokens } : {}),
1082
1472
  ...(spec.temperature !== undefined ? { temperature: spec.temperature } : {}),
1083
1473
  ...(spec.redactInReceipt !== undefined ? { redactInReceipt: spec.redactInReceipt } : {}),
1474
+ ...(spec.tools !== undefined ? { tools: spec.tools } : {}),
1475
+ // The reply works in the parent's folder with its profile (checked
1476
+ // again at enqueue); it writes no result file of its own.
1477
+ ...(handoff ? { handoff } : {}),
1478
+ // With keepOrigin, the reply runs in the parent's origin session too
1479
+ // (with the parent's turns as history), so it keeps the facts the run needs.
1480
+ ...(opts.keepOrigin === true && spec.origin !== undefined ? { origin: spec.origin } : {}),
1084
1481
  };
1085
- return this.enqueueProviderCall(child, {
1482
+ const created = await this.enqueueProviderCall(child, {
1483
+ actor: opts.actor,
1086
1484
  deadline: opts.deadline ?? new Date(Date.now() + HOUR_MS),
1087
1485
  region: parent.region,
1088
1486
  parentTaskId: parent.taskId,
@@ -1091,6 +1489,20 @@ export class Scheduler {
1091
1489
  originCwd: opts.originCwd ?? parent.originCwd,
1092
1490
  originSessionId: opts.originSessionId ?? parent.originSessionId,
1093
1491
  });
1492
+ // The child is already committed (with its own `created` event): a
1493
+ // failed audit write on the parent must not fail the reply.
1494
+ try {
1495
+ this.store?.recordEvent(parent.taskId, {
1496
+ kind: "replied",
1497
+ actor: opts.actor ?? this.actor,
1498
+ details: { child_task_id: created.taskId },
1499
+ });
1500
+ }
1501
+ catch (err) {
1502
+ // eslint-disable-next-line no-console
1503
+ console.warn(`[tidegap/scheduler] task ${parent.taskId}: could not record the replied event: ${String(err)}`);
1504
+ }
1505
+ return created;
1094
1506
  }
1095
1507
  /**
1096
1508
  * Dispatch a queued/scheduled provider-call task immediately,
@@ -1098,7 +1510,7 @@ export class Scheduler {
1098
1510
  * `intensitySource: "expedited"`. Closure-based tasks (from
1099
1511
  * `defer`) are not expediteable; we throw a clear error.
1100
1512
  */
1101
- async expediteTask(taskId, adapters) {
1513
+ async expediteTask(taskId, adapters, opts = {}) {
1102
1514
  const record = this.refreshTask(taskId);
1103
1515
  if (!record) {
1104
1516
  throw new Error(`expediteTask: task ${JSON.stringify(taskId)} not found`);
@@ -1117,6 +1529,9 @@ export class Scheduler {
1117
1529
  if (!record.bodyJson) {
1118
1530
  throw new Error(`expediteTask: task ${taskId} is a closure-based task; only provider-call tasks can be expedited`);
1119
1531
  }
1532
+ if (unservedCommand(record, adapters)) {
1533
+ throw new Error(`expediteTask: task ${taskId} runs a shell command, which only the tidegap tick runs; use run now instead`);
1534
+ }
1120
1535
  this.clearPendingTimer(taskId);
1121
1536
  const next = {
1122
1537
  ...record,
@@ -1128,7 +1543,7 @@ export class Scheduler {
1128
1543
  // Same row-level claim `tick` uses: if a concurrent process (e.g. the
1129
1544
  // cron tick) grabbed the row between our read and here, do NOT
1130
1545
  // dispatch a second (double-billed) provider call.
1131
- if (!this.writeIf(record, next, PENDING_STATUSES) ||
1546
+ if (!this.writeIf(record, next, PENDING_STATUSES, { kind: "expedited", actor: opts.actor }) ||
1132
1547
  (this.store && !this.store.claimScheduled(taskId))) {
1133
1548
  throw new Error(`task ${taskId} was just claimed by another process (racing tick?)`);
1134
1549
  }
@@ -1164,7 +1579,8 @@ export class Scheduler {
1164
1579
  if (record.bodyJson) {
1165
1580
  // A new deadline replaces any pinned earliest start.
1166
1581
  record.notBefore = undefined;
1167
- if (!(await this.scheduleProviderCall(taskId, parsedDeadline))) {
1582
+ const event = { kind: "rescheduled", actor: opts.actor, details: { reason: "deadline" } };
1583
+ if (!(await this.scheduleProviderCall(taskId, parsedDeadline, event))) {
1168
1584
  throw new Error(`updateDeadline: task ${taskId} is ${record.status}; can only update queued/scheduled tasks`);
1169
1585
  }
1170
1586
  }
@@ -1199,44 +1615,64 @@ export class Scheduler {
1199
1615
  return false;
1200
1616
  record.deadline = newDeadline.toISOString();
1201
1617
  this.clearPendingTimer(taskId);
1202
- return this.scheduleProviderCall(taskId, newDeadline);
1618
+ return this.scheduleProviderCall(taskId, newDeadline, {
1619
+ kind: "rescheduled",
1620
+ actor: "system",
1621
+ details: { reason: "quota_sweep" },
1622
+ });
1203
1623
  }
1204
1624
  /**
1205
- * Re-dispatch a failed task. Useful when the original failure was a
1206
- * transient provider error (rate-limit, 5xx) and the underlying
1207
- * spec is still valid. Only `failed` tasks are eligible; throws
1208
- * otherwise.
1625
+ * Retry a failed task by hand, starting a new attempt count. With a ready
1626
+ * adapter for the task's provider in `adapters`, the call runs now and
1627
+ * its result comes back. Otherwise, and always for a `command` or
1628
+ * `claude-code` task, which only the tidegap tick runs, the task is due
1629
+ * now ({@link retryLater}) and the next tick runs it. A manual retry
1630
+ * ignores the deadline: the user asked for it. Throws for a task that is
1631
+ * not failed, stopped during its Batch submit, closure-based or a run of
1632
+ * a job.
1209
1633
  */
1210
- async retryTask(taskId, adapters) {
1634
+ async retryTask(taskId, adapters, opts = {}) {
1211
1635
  const record = this.refreshTask(taskId);
1212
1636
  if (!record) {
1213
- throw new Error(`retryTask: task ${JSON.stringify(taskId)} not found`);
1214
- }
1215
- if (record.status !== "failed") {
1216
- throw new Error(`retryTask: task ${taskId} has status ${record.status}; retry is only valid on failed tasks`);
1637
+ throw new TaskActionError(`retryTask: task ${JSON.stringify(taskId)} not found`);
1217
1638
  }
1218
- if (!record.bodyJson) {
1219
- throw new Error(`retryTask: task ${taskId} is closure-based; only provider-call tasks can be retried`);
1639
+ retryRefusal("retryTask", record);
1640
+ const provider = taskProvider(record);
1641
+ const adapter = provider ? adapters[provider] : undefined;
1642
+ if (provider === "command" || provider === "claude-code" || !adapter?.ready) {
1643
+ const queued = this.retryLater(taskId, opts);
1644
+ return { taskId, status: "scheduled", scheduledFor: queued.scheduledFor };
1220
1645
  }
1221
- const next = {
1222
- ...record,
1223
- status: "scheduled",
1224
- scheduledFor: new Date().toISOString(),
1225
- completedAt: undefined,
1226
- error: undefined,
1227
- // A retry re-dispatches synchronously via the due path below — clear
1228
- // any stale batchId from a prior batch attempt so the completed row
1229
- // no longer points at a dead/failed batch.
1230
- batchId: undefined,
1231
- };
1232
1646
  // Row-level claim: don't double-dispatch if a concurrent tick in
1233
1647
  // another process grabbed the freshly re-scheduled row first.
1234
- if (!this.writeIf(record, next, ["failed"]) ||
1235
- (this.store && !this.store.claimScheduled(taskId))) {
1236
- throw new Error(`task ${taskId} was just claimed by another process (racing tick?)`);
1648
+ if (!this.writeIf(record, retryWrite(record), ["failed"], retryEvent(opts)) || (this.store && !this.store.claimScheduled(taskId))) {
1649
+ throw new TaskActionError(`retryTask: task ${taskId} was just claimed by another process (racing tick?)`);
1237
1650
  }
1651
+ this.attemptsWithoutLedger.delete(taskId);
1238
1652
  return await this.dispatchProviderCall(record, adapters);
1239
1653
  }
1654
+ /**
1655
+ * Retry a failed task on the next tick: `failed → scheduled`, due now, its
1656
+ * earliest start, error and completion time cleared, with a `rescheduled`
1657
+ * event (`reason: retry`), which starts a new attempt count. A write
1658
+ * only, for a process that does not dispatch (the CLI, the page's server)
1659
+ * or holds no adapter for the task. A manual retry ignores the deadline.
1660
+ * Throws {@link TaskActionError} for a task that is not failed, stopped
1661
+ * during its Batch submit, closure-based or a run of a job, and when
1662
+ * another process moved the row first.
1663
+ */
1664
+ retryLater(taskId, opts = {}) {
1665
+ const record = this.refreshTask(taskId);
1666
+ if (!record)
1667
+ throw new TaskActionError(`retryLater: task ${JSON.stringify(taskId)} not found`);
1668
+ retryRefusal("retryLater", record);
1669
+ this.clearPendingTimer(taskId);
1670
+ if (!this.writeIf(record, retryWrite(record), ["failed"], retryEvent(opts))) {
1671
+ throw new TaskActionError(`retryLater: task ${taskId} was just claimed by another process (racing tick?)`);
1672
+ }
1673
+ this.attemptsWithoutLedger.delete(taskId);
1674
+ return record;
1675
+ }
1240
1676
  /**
1241
1677
  * Pure read-only planning helper: compute the scheduled window and
1242
1678
  * carbon receipt that the same call to `enqueueProviderCall` would
@@ -1244,14 +1680,26 @@ export class Scheduler {
1244
1680
  * with `dry_run: true`.
1245
1681
  */
1246
1682
  async previewProviderCall(spec, opts = {}) {
1247
- const deadline = normalizeDeadline(opts.deadline);
1248
- const region = opts.region ?? this.defaultRegion;
1683
+ // The same refusals as the commit path, so a preview never shows a task
1684
+ // the real enqueue would refuse.
1685
+ checkedHandoff(spec, opts, "previewProviderCall");
1686
+ const requested = normalizeDeadline(opts.deadline);
1687
+ // An earliest start (after_limit_reset): same rule as the commit path.
1688
+ const notBefore = earliestStart(opts.notBefore);
1689
+ const deadline = notBefore
1690
+ ? new Date(startFields(notBefore.getTime(), requested.getTime()).deadline)
1691
+ : requested;
1692
+ const earliestMs = notBefore ? notBefore.getTime() + MINUTE_MS : 0;
1693
+ const region = opts.region ?? this.defaultRegion();
1249
1694
  const horizonH = Math.max(1, Math.min(MAX_HORIZON_HOURS, Math.ceil((deadline.getTime() - Date.now()) / (60 * 60 * 1000))));
1250
1695
  const forecast = await this.feed.fetchForecast(region, horizonH);
1696
+ const entries = notBefore
1697
+ ? forecast.entries.filter((e) => Date.parse(e.datetime) + HOUR_MS > notBefore.getTime())
1698
+ : forecast.entries;
1251
1699
  const budgetG = opts.carbonBudgetG;
1252
1700
  const survivors = budgetG !== undefined
1253
- ? forecast.entries.filter((e) => intensityToGrams(e.carbonIntensityGCo2PerKwh, spec.model) <= budgetG)
1254
- : forecast.entries;
1701
+ ? entries.filter((e) => intensityToGrams(e.carbonIntensityGCo2PerKwh, spec.model) <= budgetG)
1702
+ : entries;
1255
1703
  // Shared selection (§2.1): preview and the eventual commit both run
1256
1704
  // `selectWindow` over the same budget survivors, so they agree on the
1257
1705
  // candidate band even though each makes its own random pick within it.
@@ -1272,7 +1720,7 @@ export class Scheduler {
1272
1720
  // No usable window inside the deadline. Mirror what the commit path
1273
1721
  // (`scheduleProviderCall`) does — schedule for "now" — instead of
1274
1722
  // throwing, so dry_run and the real call cannot diverge.
1275
- const head = forecast.entries[0];
1723
+ const head = entries[0] ?? forecast.entries[0];
1276
1724
  if (!head) {
1277
1725
  throw new Error("previewProviderCall: forecast returned no entries");
1278
1726
  }
@@ -1286,12 +1734,13 @@ export class Scheduler {
1286
1734
  rng: this.rng,
1287
1735
  });
1288
1736
  return {
1289
- scheduledFor: new Date().toISOString(),
1737
+ scheduledFor: new Date(Math.max(Date.now(), earliestMs)).toISOString(),
1290
1738
  estimatedCarbonGCo2: Math.round(intensityToGrams(head.carbonIntensityGCo2PerKwh, spec.model) * 10) / 10,
1291
1739
  intensityGCo2PerKwh: head.carbonIntensityGCo2PerKwh,
1292
1740
  band: head.band,
1293
1741
  batchEligible,
1294
1742
  region,
1743
+ deadline: deadline.toISOString(),
1295
1744
  ...(routingPreviewNow ? { routingPreview: routingPreviewNow } : {}),
1296
1745
  };
1297
1746
  }
@@ -1306,14 +1755,17 @@ export class Scheduler {
1306
1755
  return {
1307
1756
  // A candidate whose hour started in the past is the *current* hour —
1308
1757
  // the commit path dispatches now, so the preview says "now" too.
1309
- scheduledFor: new Date(candidate.datetime).getTime() <= Date.now()
1310
- ? new Date().toISOString()
1311
- : candidate.datetime,
1758
+ scheduledFor: earliestMs > new Date(candidate.datetime).getTime()
1759
+ ? new Date(earliestMs).toISOString()
1760
+ : new Date(candidate.datetime).getTime() <= Date.now()
1761
+ ? new Date().toISOString()
1762
+ : candidate.datetime,
1312
1763
  estimatedCarbonGCo2: Math.round(intensityToGrams(candidate.carbonIntensityGCo2PerKwh, spec.model) * 10) / 10,
1313
1764
  intensityGCo2PerKwh: candidate.carbonIntensityGCo2PerKwh,
1314
1765
  band: candidate.band,
1315
1766
  batchEligible,
1316
1767
  region,
1768
+ deadline: deadline.toISOString(),
1317
1769
  cleanBandSize: selection.band.length,
1318
1770
  ...(routingPreview ? { routingPreview } : {}),
1319
1771
  };
@@ -1322,6 +1774,278 @@ export class Scheduler {
1322
1774
  listTasks() {
1323
1775
  return Array.from(this.tasks.values());
1324
1776
  }
1777
+ /** Runs the dispatch of a row the tick moved to `running`, holding the row until it settles. */
1778
+ async holding(record, phase, dispatch) {
1779
+ this.held.set(record.taskId, { record, phase });
1780
+ try {
1781
+ return await dispatch();
1782
+ }
1783
+ finally {
1784
+ this.held.delete(record.taskId);
1785
+ }
1786
+ }
1787
+ /**
1788
+ * Watch a held row while its run is in flight: read its status every
1789
+ * {@link RUN_STATUS_CHECK_MS} and abort the returned signal once another
1790
+ * writer moved it off `running` (a cancel, or a `failed` written
1791
+ * elsewhere), so a retry can never overlap the run; `end` stops the watch
1792
+ * when the run settles.
1793
+ */
1794
+ cancelWatch(taskId) {
1795
+ const controller = new AbortController();
1796
+ const timer = setInterval(() => {
1797
+ let status;
1798
+ try {
1799
+ status = (this.store?.get(taskId) ?? this.tasks.get(taskId))?.status;
1800
+ }
1801
+ catch {
1802
+ return; // a busy ledger: the next check reads it again
1803
+ }
1804
+ if (status === undefined || status === "running")
1805
+ return;
1806
+ clearInterval(timer);
1807
+ controller.abort();
1808
+ }, RUN_STATUS_CHECK_MS);
1809
+ timer.unref?.();
1810
+ return { signal: controller.signal, end: () => clearInterval(timer) };
1811
+ }
1812
+ /**
1813
+ * A run the watch stopped because its row left `running`. A cancel keeps
1814
+ * the row, and its event gains `stopped_run: true`; any other move (a row
1815
+ * failed elsewhere) keeps what that writer wrote. Nothing else is written,
1816
+ * as for a late result; the writer that moved the row settled its series.
1817
+ */
1818
+ stoppedRun(record) {
1819
+ let status = "cancelled";
1820
+ try {
1821
+ status = this.store?.get(record.taskId)?.status ?? record.status;
1822
+ }
1823
+ catch {
1824
+ // A busy ledger: report it as the cancel the watch most likely saw.
1825
+ }
1826
+ record.status = status;
1827
+ if (status !== "cancelled") {
1828
+ // eslint-disable-next-line no-console
1829
+ console.warn(`[tidegap/scheduler] task ${record.taskId} was ${status} while running; its run was stopped`);
1830
+ return { taskId: record.taskId, status: "failed", error: `task was ${status} while running; its run was stopped` };
1831
+ }
1832
+ try {
1833
+ this.store?.annotateEvent(record.taskId, "cancelled", { stopped_run: true });
1834
+ }
1835
+ catch (err) {
1836
+ // eslint-disable-next-line no-console
1837
+ console.warn(`[tidegap/scheduler] task ${record.taskId}: could not note the stopped run: ${describeErr(err)}`);
1838
+ }
1839
+ // eslint-disable-next-line no-console
1840
+ console.warn(`[tidegap/scheduler] task ${record.taskId} was cancelled while running; its run was stopped`);
1841
+ return { taskId: record.taskId, status: "failed", error: STOPPED_RUN_ERROR };
1842
+ }
1843
+ /**
1844
+ * The retry funnel: every provider-call run that fails ends here. A
1845
+ * one-off row whose failure class may retry, with retries left and a next
1846
+ * start that fits before its deadline, goes back to `scheduled`
1847
+ * (compare-and-set on `expected`, `running` by default) with an
1848
+ * `attempt_failed` event: `notBefore` is the next start, the fallback time
1849
+ * one minute later, the deadline unchanged, the estimate, the run-now mark
1850
+ * and any batch id cleared. Anything else fails for good: `failed`, with
1851
+ * `attempts` and `failure_class` on the event and `(after N attempts)` on
1852
+ * the error when more than one ran. A job row always fails for good (the
1853
+ * job sweep makes its retry row). The series rolls on a final failure
1854
+ * only. Synchronous; an async caller then plans the next attempt's window
1855
+ * ({@link planRetryWindow}).
1856
+ */
1857
+ failRun(record, failure, expected = ["running"]) {
1858
+ const now = Date.now();
1859
+ const failureClass = classifyFailure(failure.facts);
1860
+ const attempt = this.store ? attemptNumber(this.listTaskEvents(record.taskId)) : (this.attemptsWithoutLedger.get(record.taskId) ?? 0) + 1;
1861
+ let spec;
1862
+ try {
1863
+ spec = JSON.parse(record.bodyJson ?? "null");
1864
+ }
1865
+ catch {
1866
+ spec = undefined;
1867
+ }
1868
+ const deadlineMs = record.deadline ? Date.parse(record.deadline) : Number.NaN;
1869
+ const notBeforeMs = record.notBefore ? Date.parse(record.notBefore) : Number.NaN;
1870
+ let plan;
1871
+ if (!record.jobId && typeof spec?.provider === "string" && isRetryableFailure(failureClass)) {
1872
+ plan = planRetry({
1873
+ attempt,
1874
+ ...retryPolicyOf(this.runLimitsFor(spec)),
1875
+ failedAt: now,
1876
+ ...(Number.isFinite(deadlineMs) ? { deadline: deadlineMs } : {}),
1877
+ ...(Number.isFinite(notBeforeMs) ? { notBefore: notBeforeMs } : {}),
1878
+ });
1879
+ }
1880
+ const firstLine = failure.error.split("\n")[0].slice(0, 300);
1881
+ if (plan && "retryAt" in plan) {
1882
+ const retryAt = new Date(plan.retryAt).toISOString();
1883
+ const fallback = Number.isFinite(deadlineMs) ? Math.min(plan.retryAt + MINUTE_MS, deadlineMs) : plan.retryAt + MINUTE_MS;
1884
+ const next = {
1885
+ ...record,
1886
+ status: "scheduled",
1887
+ notBefore: retryAt,
1888
+ scheduledFor: new Date(fallback).toISOString(),
1889
+ estimatedCarbonGCo2: undefined,
1890
+ intensitySource: undefined,
1891
+ batchId: undefined,
1892
+ completedAt: undefined,
1893
+ error: undefined,
1894
+ };
1895
+ const event = {
1896
+ kind: "attempt_failed",
1897
+ details: { ...failure.details, attempt, failure_class: failureClass, error: firstLine, retry_at: retryAt },
1898
+ };
1899
+ if (!this.writeIf(record, next, expected, event)) {
1900
+ return { taskId: record.taskId, status: "failed", error: `task was ${record.status} while running; retry dropped` };
1901
+ }
1902
+ if (!this.store)
1903
+ this.attemptsWithoutLedger.set(record.taskId, attempt);
1904
+ return { taskId: record.taskId, status: "retrying", retryAt, error: failure.error };
1905
+ }
1906
+ // The Batch submit marker stays exact: retry refusals compare the error with it.
1907
+ const error = failureClass === "batch_submit_interrupted" ? failure.error : finalFailureError(failure.error, attempt, plan && "final" in plan ? plan.final : undefined);
1908
+ if (!failure.keepSeries)
1909
+ this.rollSeries(record);
1910
+ this.attemptsWithoutLedger.delete(record.taskId);
1911
+ this.writeIf(record, { ...record, status: "failed", completedAt: new Date(now).toISOString(), error }, expected, {
1912
+ kind: "failed",
1913
+ details: { ...failure.details, attempts: attempt, failure_class: failureClass },
1914
+ });
1915
+ return { taskId: record.taskId, status: "failed", error };
1916
+ }
1917
+ /** {@link failRun} for a thrown error: its facts, and its run details (`steps`, `stopped_by`, `truncated`) for the event. */
1918
+ failRunWith(record, err) {
1919
+ const details = runDetails(err?.details);
1920
+ return this.failRun(record, { error: err instanceof Error ? err.message : String(err), facts: failureFactsOf(err), details });
1921
+ }
1922
+ /**
1923
+ * After {@link failRun} queued another attempt: plan it at the cleanest
1924
+ * hour between its earliest start and its deadline. Best effort: without
1925
+ * a deadline, or when the forecast fails, the row keeps its fallback time
1926
+ * and `replanSweep` plans it before a later tick.
1927
+ */
1928
+ async planRetryWindow(entry) {
1929
+ if (entry.status !== "retrying")
1930
+ return entry;
1931
+ const record = this.tasks.get(entry.taskId);
1932
+ if (!record?.deadline)
1933
+ return entry;
1934
+ try {
1935
+ await this.scheduleProviderCall(entry.taskId, new Date(record.deadline));
1936
+ }
1937
+ catch (err) {
1938
+ // eslint-disable-next-line no-console
1939
+ console.warn(`[tidegap/scheduler] could not plan the next attempt of ${entry.taskId}: ${describeErr(err)}; replanSweep plans it later`);
1940
+ }
1941
+ return entry;
1942
+ }
1943
+ /**
1944
+ * The tick-lock rule for a `running` row, shared by the head of a locked
1945
+ * tick and the job sweep: true when the run was dispatched under another
1946
+ * locked tick whose process is gone, false when that tick is this one or
1947
+ * its process still runs. Undefined when this scheduler holds no lock, the
1948
+ * row's newest event (progress lines aside) is not a dispatch with tick
1949
+ * details (no locked tick ran it, or the row moved on since), or the host
1950
+ * cannot tell whether that tick's process runs: the run may be live.
1951
+ */
1952
+ deadTickRun(row) {
1953
+ const locked = this.lockedTick;
1954
+ if (!locked)
1955
+ return undefined;
1956
+ const tick = tickDispatch(this.listTaskEvents(row.taskId))?.tick;
1957
+ if (!tick)
1958
+ return undefined;
1959
+ if (tick.id === locked.tick.id)
1960
+ return false;
1961
+ try {
1962
+ const running = locked.isRunning(tick);
1963
+ return running === undefined ? undefined : !running;
1964
+ }
1965
+ catch {
1966
+ return undefined;
1967
+ }
1968
+ }
1969
+ /**
1970
+ * The head of a locked tick, before any sweep claims a row: a one-off
1971
+ * `running` row whose run a dead tick dispatched ({@link deadTickRun})
1972
+ * fails as interrupted through the retry funnel (another attempt when the
1973
+ * policy allows it), and a Batch row with its batch id goes back to
1974
+ * `submitted` for the poll sweep. Compare-and-set from `running`. Job rows
1975
+ * are the job sweep's; rows this scheduler holds are live. Returns the
1976
+ * entries of the rows it failed or queued again.
1977
+ */
1978
+ freeDeadTickRuns() {
1979
+ if (!this.lockedTick || !this.store)
1980
+ return [];
1981
+ let rows;
1982
+ try {
1983
+ rows = this.store.list({ status: "running" });
1984
+ }
1985
+ catch (err) {
1986
+ // eslint-disable-next-line no-console
1987
+ console.warn(`[tidegap/scheduler] tick: could not read running rows: ${describeErr(err)}; no dead tick's row freed this round`);
1988
+ return [];
1989
+ }
1990
+ const out = [];
1991
+ for (const row of rows) {
1992
+ if (row.jobId || this.held.has(row.taskId))
1993
+ continue;
1994
+ try {
1995
+ if (this.deadTickRun(row) !== true)
1996
+ continue;
1997
+ const record = this.cacheRow(row);
1998
+ if (row.batchId) {
1999
+ this.writeIf(record, { ...row, status: "submitted", completedAt: undefined, error: undefined }, ["running"]);
2000
+ continue;
2001
+ }
2002
+ const entry = this.failRun(record, { error: JOB_INTERRUPTED_ERROR, facts: { interrupted: "run" }, details: { reason: "interrupted" } });
2003
+ if (entry.status === "retrying" || record.status === "failed")
2004
+ out.push(entry);
2005
+ }
2006
+ catch (err) {
2007
+ // eslint-disable-next-line no-console
2008
+ console.warn(`[tidegap/scheduler] tick: could not free ${row.taskId} of a dead tick: ${describeErr(err)}; skipping this round`);
2009
+ }
2010
+ }
2011
+ return out;
2012
+ }
2013
+ /**
2014
+ * A forced stop of the tick (KTD12, batch 25 KTD4): settle every row this
2015
+ * scheduler moved to `running` in a tick whose dispatch has not settled,
2016
+ * by what the row was doing:
2017
+ * - a provider call fails as interrupted (`JOB_INTERRUPTED_ERROR`)
2018
+ * through the retry funnel: a one-off row with retries left is
2019
+ * queued again, its window planned before a later tick;
2020
+ * - a Batch poll goes back to `submitted` with its `batchId`: the batch
2021
+ * is live at the provider, and the next tick polls it again;
2022
+ * - a Batch submit fails with `BATCH_SUBMIT_INTERRUPTED_ERROR`: the
2023
+ * provider may have accepted the batch, so no retry path runs it again.
2024
+ * Compare-and-set from `running`, so a row another writer finished first
2025
+ * keeps its status; rows another process holds, or a crashed tick
2026
+ * stranded, are not touched (the job sweep frees job runs, and the next
2027
+ * tick a Batch poll past its deadline: `freeStrandedPolls`). Synchronous, for
2028
+ * a process about to exit. Returns the ids it failed or queued again; a
2029
+ * second call changes nothing.
2030
+ */
2031
+ failHeldRuns() {
2032
+ const failed = [];
2033
+ for (const { record, phase } of this.held.values()) {
2034
+ if (phase === "batch_poll") {
2035
+ this.writeIf(record, { ...record, status: "submitted", completedAt: undefined, error: undefined }, ["running"]);
2036
+ continue;
2037
+ }
2038
+ const submit = phase === "batch_submit";
2039
+ const details = { reason: "interrupted", ...(submit ? { phase } : {}), ...(record.jobId ? { job_id: record.jobId } : {}) };
2040
+ const error = submit ? BATCH_SUBMIT_INTERRUPTED_ERROR : JOB_INTERRUPTED_ERROR;
2041
+ // The next attempt keeps its fallback time; replanSweep plans it before a later tick.
2042
+ const entry = this.failRun(record, { error, facts: { interrupted: submit ? "batch_submit" : "run" }, details });
2043
+ if (entry.status === "retrying" || record.status === "failed")
2044
+ failed.push(record.taskId);
2045
+ }
2046
+ this.held.clear();
2047
+ return failed;
2048
+ }
1325
2049
  /** Cancel and clean up timers. Mostly for tests. */
1326
2050
  shutdown() {
1327
2051
  for (const timer of this.pendingTimers.values()) {
@@ -1368,7 +2092,9 @@ export class Scheduler {
1368
2092
  return;
1369
2093
  }
1370
2094
  if (!this.writeIf(record, { ...record, status: "scheduled", scheduledFor: candidate.datetime }, PENDING_STATUSES)) {
1371
- return; // cancelled from another process meanwhile
2095
+ // Cancelled from another process during the forecast fetch.
2096
+ this.rejectMissedClosure(taskId, record);
2097
+ return;
1372
2098
  }
1373
2099
  const wait = Math.max(0, new Date(candidate.datetime).getTime() - Date.now());
1374
2100
  // Node's setTimeout overflows the signed-32-bit ms range (~24.85 days).
@@ -1397,6 +2123,17 @@ export class Scheduler {
1397
2123
  this.failTask(taskId, err instanceof Error ? err : new Error(String(err)));
1398
2124
  });
1399
2125
  }
2126
+ /**
2127
+ * A closure task's write missed: another process cancelled, claimed or
2128
+ * finished its row. Reject the awaiter with the status the ledger now
2129
+ * holds and drop the body, so `defer()` never waits forever. A no-op for
2130
+ * a provider call, which has no awaiter.
2131
+ */
2132
+ rejectMissedClosure(taskId, record) {
2133
+ this.resolvers.get(taskId)?.reject(new Error(`task ${taskId} ${record.status}`));
2134
+ this.bodies.delete(taskId);
2135
+ this.resolvers.delete(taskId);
2136
+ }
1400
2137
  failTask(taskId, err, onlyIfPending = false) {
1401
2138
  const record = this.tasks.get(taskId);
1402
2139
  if (!record)
@@ -1417,6 +2154,7 @@ export class Scheduler {
1417
2154
  // Compare-and-set: never overwrite a row another process finished or
1418
2155
  // cancelled meanwhile.
1419
2156
  if (!this.writeIf(record, next, onlyIfPending ? PENDING_STATUSES : UNFINISHED_STATUSES)) {
2157
+ this.rejectMissedClosure(taskId, record);
1420
2158
  return false;
1421
2159
  }
1422
2160
  const resolver = this.resolvers.get(taskId);
@@ -1431,11 +2169,9 @@ export class Scheduler {
1431
2169
  const resolver = this.resolvers.get(taskId);
1432
2170
  if (!record || !body)
1433
2171
  return;
1434
- if (!this.writeIf(record, { ...record, status: "running" }, PENDING_STATUSES)) {
2172
+ if (!this.writeIf(record, { ...record, status: "running" }, PENDING_STATUSES, { kind: "dispatched" })) {
1435
2173
  // Cancelled (possibly from another process) before the window came.
1436
- resolver?.reject(new Error(`task ${taskId} ${record.status}`));
1437
- this.bodies.delete(taskId);
1438
- this.resolvers.delete(taskId);
2174
+ this.rejectMissedClosure(taskId, record);
1439
2175
  return;
1440
2176
  }
1441
2177
  const start = Date.now();
@@ -1562,7 +2298,7 @@ export class Scheduler {
1562
2298
  * [notBefore, deadline] with no estimate ("unplanned"); `replanSweep`
1563
2299
  * re-scores it once the forecast covers it.
1564
2300
  */
1565
- async scheduleProviderCall(taskId, deadline) {
2301
+ async scheduleProviderCall(taskId, deadline, event) {
1566
2302
  const record = this.tasks.get(taskId);
1567
2303
  if (!record)
1568
2304
  return false;
@@ -1606,10 +2342,12 @@ export class Scheduler {
1606
2342
  record.status = "scheduled";
1607
2343
  record.scheduledFor = clampIso(record.scheduledFor, notBeforeMs, deadline.getTime());
1608
2344
  record.estimatedCarbonGCo2 = undefined;
1609
- return this.persist(record, before);
2345
+ return this.persist(record, before, event);
1610
2346
  }
1611
2347
  }
1612
- const earliest = pinned ? notBeforeMs : Date.now();
2348
+ // One minute past a pinned start: a picked hour that contains it would
2349
+ // otherwise give `scheduledFor === notBefore`, which reads as an exact pin.
2350
+ const earliest = pinned ? notBeforeMs + MINUTE_MS : Date.now();
1613
2351
  const budgetG = record.carbonBudgetG;
1614
2352
  const survivors = budgetG !== undefined
1615
2353
  ? entries.filter((e) => intensityToGrams(e.carbonIntensityGCo2PerKwh, specModel) <= budgetG)
@@ -1638,7 +2376,7 @@ export class Scheduler {
1638
2376
  record.estimatedCarbonGCo2 =
1639
2377
  Math.round(intensityToGrams(nowIntensity, routedModelNow) * 10) / 10;
1640
2378
  }
1641
- return this.persist(record, before);
2379
+ return this.persist(record, before, event);
1642
2380
  }
1643
2381
  record.status = "scheduled";
1644
2382
  // A candidate whose hour started in the past is the *current* hour —
@@ -1653,7 +2391,7 @@ export class Scheduler {
1653
2391
  const routedModel = this.applyRoutingIfNeeded(record, spec, candidate.carbonIntensityGCo2PerKwh);
1654
2392
  record.estimatedCarbonGCo2 =
1655
2393
  Math.round(intensityToGrams(candidate.carbonIntensityGCo2PerKwh, routedModel) * 10) / 10;
1656
- return this.persist(record, before);
2394
+ return this.persist(record, before, event);
1657
2395
  }
1658
2396
  /**
1659
2397
  * Write a scheduling result with a compare-and-set on the pending
@@ -1662,10 +2400,11 @@ export class Scheduler {
1662
2400
  * written, the cached record is reloaded from the ledger, and false is
1663
2401
  * returned.
1664
2402
  */
1665
- persist(record, before) {
2403
+ persist(record, before, event) {
1666
2404
  if (!this.store)
1667
2405
  return true;
1668
- if (this.store.transitionIf(record, PENDING_STATUSES, before))
2406
+ const ev = event ? this.eventFor(before, record, event) : undefined;
2407
+ if (this.store.transitionIf(record, PENDING_STATUSES, before, ev))
1669
2408
  return true;
1670
2409
  const current = this.store.get(record.taskId);
1671
2410
  if (current)
@@ -1708,20 +2447,17 @@ export class Scheduler {
1708
2447
  record.routingDecision = decision;
1709
2448
  return chosen?.model ?? spec.model;
1710
2449
  }
1711
- async dispatchProviderCall(record, adapters) {
2450
+ async dispatchProviderCall(record, adapters, deferrals) {
1712
2451
  let spec;
1713
2452
  try {
1714
2453
  spec = JSON.parse(record.bodyJson ?? "null");
1715
2454
  }
1716
2455
  catch (err) {
1717
2456
  const msg = err instanceof Error ? err.message : String(err);
1718
- this.failTask(record.taskId, new Error(`tick: corrupt body_json: ${msg}`));
1719
- return { taskId: record.taskId, status: "failed", error: msg };
2457
+ return this.failRun(record, { error: `tick: corrupt body_json: ${msg}`, facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
1720
2458
  }
1721
2459
  if (!spec || spec.type !== "provider_call") {
1722
- const msg = `tick: body is not a provider_call spec`;
1723
- this.failTask(record.taskId, new Error(msg));
1724
- return { taskId: record.taskId, status: "failed", error: msg };
2460
+ return this.failRun(record, { error: "tick: body is not a provider_call spec", facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
1725
2461
  }
1726
2462
  // Cross-provider routing fallback (ROADMAP item 1): when a routing
1727
2463
  // decision is attached, dispatch the highest-scoring candidate whose
@@ -1739,9 +2475,7 @@ export class Scheduler {
1739
2475
  if (!picked) {
1740
2476
  const msg = `tick: no configured/ready adapter for any routing candidate ` +
1741
2477
  `(${routing.considered.map((c) => candidateId(c)).join(", ")})`;
1742
- this.rollSeries(record);
1743
- this.failTask(record.taskId, new Error(msg));
1744
- return { taskId: record.taskId, status: "failed", error: msg };
2478
+ return this.failRun(record, { error: msg, facts: { permanent: true } }, UNFINISHED_STATUSES);
1745
2479
  }
1746
2480
  const pickedId = candidateId(picked);
1747
2481
  if (pickedId !== routing.chosen) {
@@ -1761,14 +2495,28 @@ export class Scheduler {
1761
2495
  // No rollover: a missing adapter is a skip (OpenClaw restores the row
1762
2496
  // to `scheduled`), and a successor would run beside the occurrence.
1763
2497
  // A retry that completes rolls the series then.
1764
- this.failTask(record.taskId, new Error(msg));
1765
- return { taskId: record.taskId, status: "failed", error: msg };
2498
+ return this.failRun(record, { error: msg, facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
1766
2499
  }
2500
+ const deferKey = deferKeyOf(spec);
2501
+ const earlier = deferrals?.get(deferKey);
2502
+ if (earlier) {
2503
+ return this.deferTask(record, earlier, `${spec.provider}: deferred with an earlier task this tick until ${earlier.toISOString()}`);
2504
+ }
2505
+ const limits = this.runLimitsFor(spec);
1767
2506
  let stillOurs = true;
1768
2507
  try {
1769
2508
  // The row was claimed (`running`) or, without a store, is ours. A
1770
2509
  // cancel that landed after the claim wins: do not make the call.
1771
- stillOurs = this.writeIf(record, { ...record, status: "running" }, ["running", "scheduled"]);
2510
+ stillOurs = this.writeIf(record, { ...record, status: "running" }, ["running", "scheduled"], {
2511
+ kind: "dispatched",
2512
+ details: {
2513
+ provider: spec.provider,
2514
+ model: spec.model,
2515
+ limits: runLimitsDetails(limits),
2516
+ ...this.sleepDetails(),
2517
+ ...this.tickDetails(),
2518
+ },
2519
+ });
1772
2520
  }
1773
2521
  catch (err) {
1774
2522
  // eslint-disable-next-line no-console
@@ -1789,6 +2537,10 @@ export class Scheduler {
1789
2537
  // dispatch must NEVER be re-labelled "failed" (a retry would bill the
1790
2538
  // provider a second time).
1791
2539
  let result;
2540
+ // Lines the run reports while it runs (the command adapter's output);
2541
+ // nothing is written once the call settled.
2542
+ const progress = this.progressFor(record.taskId);
2543
+ const watch = this.cancelWatch(record.taskId);
1792
2544
  try {
1793
2545
  // Batch routing (deadline > 24h) is handled by the dedicated
1794
2546
  // submit/poll sweeps in tick(); by the time a task reaches this
@@ -1798,13 +2550,26 @@ export class Scheduler {
1798
2550
  maxTokens: spec.maxTokens,
1799
2551
  system: spec.systemPrompt,
1800
2552
  messages: spec.messages,
1801
- }));
2553
+ ...(spec.tools !== undefined ? { tools: spec.tools } : {}),
2554
+ ...dispatchOrigin(record, spec),
2555
+ ...jobDispatchOptions(record, spec, limits),
2556
+ ...(progress ? { onProgress: (line) => progress.onLine(line), onProgressEnd: () => progress.close() } : {}),
2557
+ signal: watch.signal,
2558
+ }), watch.signal).finally(() => progress?.close());
1802
2559
  }
1803
2560
  catch (err) {
2561
+ if (watch.signal.aborted)
2562
+ return this.stoppedRun(record);
1804
2563
  const msg = err instanceof Error ? err.message : String(err);
1805
- this.rollSeries(record);
1806
- this.writeIf(record, { ...record, status: "failed", completedAt: new Date().toISOString(), error: msg }, ["running"]);
1807
- return { taskId: record.taskId, status: "failed", error: msg };
2564
+ const retryAt = deferRetryAt(err);
2565
+ if (retryAt) {
2566
+ deferrals?.set(deferKey, retryAt);
2567
+ return this.deferTask(record, retryAt, msg);
2568
+ }
2569
+ return this.planRetryWindow(this.failRunWith(record, err));
2570
+ }
2571
+ finally {
2572
+ watch.end();
1808
2573
  }
1809
2574
  const durationMs = Date.now() - start;
1810
2575
  // The task may have been cancelled while the provider call was in
@@ -1850,19 +2615,26 @@ export class Scheduler {
1850
2615
  // we re-estimate energy with the real token counts the provider
1851
2616
  // reported (when available) — that turns the receipt from "typical
1852
2617
  // task at this model" into "this specific call at this model".
1853
- const usage = result.usage;
1854
- const inputTokens = typeof usage?.inputTokens === "number" ? usage.inputTokens : undefined;
1855
- const outputTokens = typeof usage?.outputTokens === "number" ? usage.outputTokens : undefined;
1856
- const actualModel = result.model ?? spec.model;
1857
- const totalTokens = typeof usage?.totalTokens === "number" ? usage.totalTokens : undefined;
2618
+ // A count that is absent, not a number, negative or not finite is
2619
+ // unreported: billed at the typical count and left out (KTD2).
2620
+ const counts = singleModelCounts(result.usage);
2621
+ const modelUsage = result.modelUsage;
1858
2622
  let receipt;
1859
2623
  try {
2624
+ // A run that used two or more models is billed model by model (KTD7);
2625
+ // the totals, the dominant model and the weakest tiers come from the
2626
+ // bill. Otherwise `usage` is billed under one model, as before.
2627
+ const bill = Array.isArray(modelUsage) ? billModelUsage(intensityG, modelUsage) : undefined;
2628
+ const actualModel = bill?.model ?? result.model ?? spec.model;
2629
+ const totalTokens = bill ? bill.totalTokens : counts.totalTokens;
2630
+ const tokenCounts = bill ? bill.tokenCounts : counts.tokenCounts;
1860
2631
  const actualCarbonGCo2 = intensityG !== undefined
1861
- ? Math.round(gramsForIntensity(intensityG, {
1862
- model: actualModel,
1863
- inputTokens,
1864
- outputTokens,
1865
- }) * 10) / 10
2632
+ ? Math.round((bill?.carbonGCo2 ??
2633
+ gramsForIntensity(intensityG, {
2634
+ model: actualModel,
2635
+ inputTokens: counts.inputTokens,
2636
+ outputTokens: counts.outputTokens,
2637
+ })) * 10) / 10
1866
2638
  : (record.estimatedCarbonGCo2 ?? 0);
1867
2639
  const estimatedCarbonGCo2 = record.estimatedCarbonGCo2 ?? actualCarbonGCo2;
1868
2640
  const deltaPct = estimatedCarbonGCo2 > 0
@@ -1879,7 +2651,7 @@ export class Scheduler {
1879
2651
  // what was requested — the OpenClaw runtime bridge may run a
1880
2652
  // different model than spec.model. The batch path has no model.
1881
2653
  provider: result.provider ?? spec.provider,
1882
- model: result.model ?? spec.model,
2654
+ model: actualModel,
1883
2655
  durationMs,
1884
2656
  prompt: redactPrompt(spec.prompt, spec.redactInReceipt),
1885
2657
  totalTokens,
@@ -1891,12 +2663,20 @@ export class Scheduler {
1891
2663
  intensityGCo2PerKwh: intensityG,
1892
2664
  gridSource,
1893
2665
  signalType,
1894
- energySource: resolveModelEnergy(actualModel).coeffs.source,
1895
- energyResolution: resolveModelEnergy(actualModel).tier,
2666
+ energySource: bill?.energySource ?? resolveModelEnergy(actualModel).coeffs.source,
2667
+ energyResolution: bill?.energyResolution ?? resolveModelEnergy(actualModel).tier,
1896
2668
  // Cross-provider routing provenance (ROADMAP item 1): the scored
1897
2669
  // candidate list, weights, chosen id (+ any dispatch fallbackFrom).
1898
2670
  // Inside the signed payload; omitted when routing was not used.
1899
2671
  routing: record.routingDecision,
2672
+ tools: result.tools,
2673
+ session: result.session,
2674
+ // Per-model breakdown (KTD5): inside the signed payload; absent for
2675
+ // a single-model run, whose receipt is unchanged.
2676
+ models: bill?.models,
2677
+ // Signed; written only when a count was not reported in full, so a
2678
+ // fully reported receipt keeps its canonical bytes (KTD1).
2679
+ ...(tokenCounts !== undefined ? { tokenCounts } : {}),
1900
2680
  });
1901
2681
  }
1902
2682
  catch (err) {
@@ -1919,8 +2699,9 @@ export class Scheduler {
1919
2699
  bodyJson: redactBodyJson(record.bodyJson),
1920
2700
  };
1921
2701
  this.rollSeries(record);
2702
+ const completedDetails = runDetails(result.details);
1922
2703
  try {
1923
- if (!this.writeIf(record, completed, ["running"])) {
2704
+ if (!this.writeIf(record, completed, ["running"], completedDetails ? { kind: "completed", details: completedDetails } : undefined)) {
1924
2705
  // eslint-disable-next-line no-console
1925
2706
  console.warn(`[tidegap/scheduler] task ${record.taskId} was ${record.status} while running; dropping its late result`);
1926
2707
  return {
@@ -1935,10 +2716,48 @@ export class Scheduler {
1935
2716
  console.warn(`[tidegap/scheduler] failed to persist completed task ${record.taskId}: ${describeErr(err)}`);
1936
2717
  }
1937
2718
  if (spec.outputPath && receipt) {
1938
- await writeOutputFile(spec.outputPath, record.taskId, result, receipt);
2719
+ await writeOutputFile(spec.outputPath, record.taskId, result, receipt, {
2720
+ cwd: spec.handoff?.cwd,
2721
+ originCwd: record.originCwd,
2722
+ });
1939
2723
  }
1940
2724
  return { taskId: record.taskId, status: "completed" };
1941
2725
  }
2726
+ /**
2727
+ * Put a running task back in the queue until `retryAt` (KTD7): `scheduled`,
2728
+ * `notBefore = retryAt`, one minute later as the fallback time, the
2729
+ * deadline raised to at least `retryAt + 2 h`, the estimate cleared so
2730
+ * `replanSweep` moves it to the cleanest hour once the forecast covers it.
2731
+ * Compare-and-set on `running`: a cancel during the run wins. Past the
2732
+ * 8-day cap from `enqueuedAt` the task fails with `message` instead.
2733
+ */
2734
+ deferTask(record, retryAt, message) {
2735
+ const retryMs = retryAt.getTime();
2736
+ const capMs = Date.parse(record.enqueuedAt) + DEFER_CAP_MS;
2737
+ if (retryMs + NOT_BEFORE_SPAN_MS > capMs) {
2738
+ // A later attempt would meet the same cap: permanent.
2739
+ return this.failRun(record, { error: `${message}; limit did not reset before the 8-day cap`, facts: { permanent: true } });
2740
+ }
2741
+ const next = {
2742
+ ...record,
2743
+ status: "scheduled",
2744
+ ...startFields(retryMs, record.deadline ? Date.parse(record.deadline) : 0),
2745
+ estimatedCarbonGCo2: undefined,
2746
+ intensitySource: undefined,
2747
+ };
2748
+ const event = {
2749
+ kind: "deferred",
2750
+ details: { retry_at: retryAt.toISOString(), reason: message.split("\n")[0].slice(0, 300) },
2751
+ };
2752
+ if (!this.writeIf(record, next, ["running"], event)) {
2753
+ return {
2754
+ taskId: record.taskId,
2755
+ status: "failed",
2756
+ error: `task was ${record.status} while running; deferral dropped`,
2757
+ };
2758
+ }
2759
+ return { taskId: record.taskId, status: "deferred", retryAt: retryAt.toISOString(), error: message };
2760
+ }
1942
2761
  /**
1943
2762
  * Submit a batch-eligible task to the provider's Batch API. The row was
1944
2763
  * already claimed (scheduled → running) by the caller. On success the
@@ -1955,8 +2774,7 @@ export class Scheduler {
1955
2774
  }
1956
2775
  catch (err) {
1957
2776
  const msg = err instanceof Error ? err.message : String(err);
1958
- this.failTask(record.taskId, new Error(`tick: corrupt body_json: ${msg}`));
1959
- return { taskId: record.taskId, status: "failed", error: msg };
2777
+ return this.failRun(record, { error: `tick: corrupt body_json: ${msg}`, facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
1960
2778
  }
1961
2779
  const adapter = adapters[spec.provider];
1962
2780
  const dispatchBatch = adapter?.dispatchBatch;
@@ -1964,8 +2782,7 @@ export class Scheduler {
1964
2782
  // Should not happen — collectBatchSubmitCandidates already filtered
1965
2783
  // — but stay defensive: fall back to a clear failure.
1966
2784
  const msg = `tick: batch submit selected but adapter/dispatchBatch missing for ${spec.provider}`;
1967
- this.failTask(record.taskId, new Error(msg));
1968
- return { taskId: record.taskId, status: "failed", error: msg };
2785
+ return this.failRun(record, { error: msg, facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
1969
2786
  }
1970
2787
  try {
1971
2788
  const handle = await retryWithBackoff(() => dispatchBatch.call(adapter, spec.model, [spec.prompt], {
@@ -1975,7 +2792,14 @@ export class Scheduler {
1975
2792
  messages: spec.messages,
1976
2793
  }));
1977
2794
  try {
1978
- this.writeIf(record, { ...record, status: "submitted", batchId: handle.batchId }, ["running"]);
2795
+ if (!this.writeIf(record, { ...record, status: "submitted", batchId: handle.batchId }, ["running"], { kind: "dispatched", details: { batch_id: handle.batchId, ...this.tickDetails() } })) {
2796
+ // Another writer moved the row (a cancel) during the submit: it
2797
+ // keeps its status, and the live batch is reported, not stored.
2798
+ const error = `task was ${record.status} while its batch was submitted; batch ${handle.batchId} is not stored, and the provider may still run and bill it`;
2799
+ // eslint-disable-next-line no-console
2800
+ console.warn(`[tidegap/scheduler] ${record.taskId}: ${error}`);
2801
+ return { taskId: record.taskId, status: "failed", error };
2802
+ }
1979
2803
  }
1980
2804
  catch (err) {
1981
2805
  // eslint-disable-next-line no-console
@@ -1998,11 +2822,15 @@ export class Scheduler {
1998
2822
  record.status = "scheduled";
1999
2823
  record.batchId = undefined;
2000
2824
  record.error = undefined;
2825
+ // The submit failed, so no batch exists: a forced stop from here on
2826
+ // interrupts a provider call.
2827
+ const held = this.held.get(record.taskId);
2828
+ if (held)
2829
+ held.phase = "provider_call";
2001
2830
  return this.dispatchProviderCall(record, adapters);
2002
2831
  }
2003
- this.rollSeries(record);
2004
- this.writeIf(record, { ...record, status: "failed", completedAt: new Date().toISOString(), error: msg }, ["running"]);
2005
- return { taskId: record.taskId, status: "failed", error: msg };
2832
+ // The submit failed, so no batch exists: a later attempt may submit again.
2833
+ return this.planRetryWindow(this.failRunWith(record, err));
2006
2834
  }
2007
2835
  }
2008
2836
  /**
@@ -2022,8 +2850,7 @@ export class Scheduler {
2022
2850
  }
2023
2851
  catch (err) {
2024
2852
  const msg = err instanceof Error ? err.message : String(err);
2025
- this.failTask(record.taskId, new Error(`tick: corrupt body_json: ${msg}`));
2026
- return { taskId: record.taskId, status: "failed", error: msg };
2853
+ return this.failRun(record, { error: `tick: corrupt body_json: ${msg}`, facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
2027
2854
  }
2028
2855
  const adapter = adapters[spec.provider];
2029
2856
  if (!adapter || typeof adapter.retrieveBatch !== "function") {
@@ -2037,9 +2864,7 @@ export class Scheduler {
2037
2864
  }
2038
2865
  const batchId = record.batchId;
2039
2866
  if (!batchId) {
2040
- const msg = "tick: submitted task has no batchId";
2041
- this.failTask(record.taskId, new Error(msg));
2042
- return { taskId: record.taskId, status: "failed", error: msg };
2867
+ return this.failRun(record, { error: "tick: submitted task has no batchId", facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
2043
2868
  }
2044
2869
  const ranAt = new Date();
2045
2870
  let poll;
@@ -2059,18 +2884,13 @@ export class Scheduler {
2059
2884
  return { taskId: record.taskId, status: "submitted" };
2060
2885
  }
2061
2886
  if (poll.status === "failed" || poll.status === "expired") {
2062
- const msg = poll.error ?? `batch ${poll.status}`;
2063
- this.rollSeries(record);
2064
- this.writeIf(record, { ...record, status: "failed", completedAt: new Date().toISOString(), error: msg }, ["running"]);
2065
- return { taskId: record.taskId, status: "failed", error: msg };
2887
+ // The batch is over at the provider: a later attempt submits the task again.
2888
+ return this.planRetryWindow(this.failRun(record, { error: poll.error ?? `batch ${poll.status}`, facts: {} }));
2066
2889
  }
2067
2890
  // completed — take the first (single-prompt) result.
2068
2891
  const first = poll.results?.[0];
2069
2892
  if (!first) {
2070
- const msg = "batch completed with no results";
2071
- this.rollSeries(record);
2072
- this.writeIf(record, { ...record, status: "failed", completedAt: new Date().toISOString(), error: msg }, ["running"]);
2073
- return { taskId: record.taskId, status: "failed", error: msg };
2893
+ return this.planRetryWindow(this.failRun(record, { error: "batch completed with no results", facts: {} }));
2074
2894
  }
2075
2895
  // Shape a DispatchResult-like object so the receipt path is identical
2076
2896
  // to the sync dispatch.
@@ -2095,18 +2915,16 @@ export class Scheduler {
2095
2915
  // eslint-disable-next-line no-console
2096
2916
  console.warn(`[tidegap/scheduler] intensity fetch for the receipt failed (${describeErr(err)}); receipt falls back to the schedule-time estimate`);
2097
2917
  }
2098
- const usage = result.usage;
2099
- const inputTokens = typeof usage?.inputTokens === "number" ? usage.inputTokens : undefined;
2100
- const outputTokens = typeof usage?.outputTokens === "number" ? usage.outputTokens : undefined;
2918
+ // The count rule of the sync path (KTD2).
2919
+ const counts = singleModelCounts(result.usage);
2101
2920
  const actualModel = result.model;
2102
- const totalTokens = typeof usage?.totalTokens === "number" ? usage.totalTokens : undefined;
2103
2921
  let receipt;
2104
2922
  try {
2105
2923
  const actualCarbonGCo2 = intensityG !== undefined
2106
2924
  ? Math.round(gramsForIntensity(intensityG, {
2107
2925
  model: actualModel,
2108
- inputTokens,
2109
- outputTokens,
2926
+ inputTokens: counts.inputTokens,
2927
+ outputTokens: counts.outputTokens,
2110
2928
  }) * 10) / 10
2111
2929
  : (record.estimatedCarbonGCo2 ?? 0);
2112
2930
  const estimatedCarbonGCo2 = record.estimatedCarbonGCo2 ?? actualCarbonGCo2;
@@ -2123,7 +2941,7 @@ export class Scheduler {
2123
2941
  provider: result.provider ?? spec.provider,
2124
2942
  model: actualModel,
2125
2943
  prompt: redactPrompt(spec.prompt, spec.redactInReceipt),
2126
- totalTokens,
2944
+ totalTokens: counts.totalTokens,
2127
2945
  intensityGCo2PerKwh: intensityG,
2128
2946
  gridSource,
2129
2947
  signalType,
@@ -2132,6 +2950,7 @@ export class Scheduler {
2132
2950
  // Cross-provider routing provenance (ROADMAP item 1) — see the sync
2133
2951
  // dispatch path. Present only when the task carried >= 2 candidates.
2134
2952
  routing: record.routingDecision,
2953
+ ...(counts.tokenCounts !== undefined ? { tokenCounts: counts.tokenCounts } : {}),
2135
2954
  });
2136
2955
  }
2137
2956
  catch (err) {
@@ -2162,7 +2981,10 @@ export class Scheduler {
2162
2981
  console.warn(`[tidegap/scheduler] failed to persist completed task ${record.taskId}: ${describeErr(err)}`);
2163
2982
  }
2164
2983
  if (spec.outputPath && receipt) {
2165
- await writeOutputFile(spec.outputPath, record.taskId, result, receipt);
2984
+ await writeOutputFile(spec.outputPath, record.taskId, result, receipt, {
2985
+ cwd: spec.handoff?.cwd,
2986
+ originCwd: record.originCwd,
2987
+ });
2166
2988
  }
2167
2989
  return { taskId: record.taskId, status: "completed" };
2168
2990
  }
@@ -2192,6 +3014,136 @@ export class Scheduler {
2192
3014
  };
2193
3015
  }
2194
3016
  }
3017
+ /** The caps keys a one-off model call takes: its LLM time limit and its retry policy. */
3018
+ const MODEL_CALL_CAPS_KEYS = new Set(["llmTimeoutMs", "retries", "retryDelayMs"]);
3019
+ /**
3020
+ * The caps a one-off row stores: only the keys the caller set, each checked
3021
+ * (a time limit from 1 s to 7 days or `"none"`, retries from 0 to 10, a
3022
+ * retry delay from 1 s to 7 days, any other cap a positive number), with
3023
+ * `capsVersion: 2`. Throws on an unknown key or a bad value.
3024
+ */
3025
+ function checkedCaps(caps, keys, what) {
3026
+ if (caps === undefined)
3027
+ return { capsVersion: CAPS_VERSION };
3028
+ if (!caps || typeof caps !== "object" || Array.isArray(caps))
3029
+ throw new Error(`${what}: caps must be an object`);
3030
+ const out = {};
3031
+ for (const [key, value] of Object.entries(caps)) {
3032
+ if (key === "capsVersion" || value === undefined)
3033
+ continue;
3034
+ if (!keys.has(key))
3035
+ throw new Error(`${what}: unknown cap "${key}"`);
3036
+ const error = capValueError(key, value);
3037
+ if (error)
3038
+ throw new Error(`${what}: ${error}`);
3039
+ out[key] = value;
3040
+ }
3041
+ return { ...out, capsVersion: CAPS_VERSION };
3042
+ }
3043
+ /**
3044
+ * Dispatch options of a run: its resolved time limits, the caps' budget,
3045
+ * and for a row with `job_id` its working directory and job id. A
3046
+ * `claude-code` row without a job gets its handoff folder. A `command` body
3047
+ * also hands over its shell and summarize steps.
3048
+ */
3049
+ function jobDispatchOptions(record, spec, limits) {
3050
+ const out = {};
3051
+ if (limits.llm_timeout)
3052
+ out.timeoutMs = limits.llm_timeout.value;
3053
+ if (limits.command_timeout)
3054
+ out.commandTimeoutMs = limits.command_timeout.value;
3055
+ if (spec.caps?.maxBudgetUsd !== undefined)
3056
+ out.maxBudgetUsd = spec.caps.maxBudgetUsd;
3057
+ if (record.jobId) {
3058
+ out.jobId = record.jobId;
3059
+ if (record.originCwd)
3060
+ out.cwd = record.originCwd;
3061
+ }
3062
+ else if (spec.provider === "claude-code" && typeof spec.handoff?.cwd === "string") {
3063
+ // A handed-off folder: the adapter forks the origin session when it is
3064
+ // the session's project folder, else runs fresh there.
3065
+ out.cwd = spec.handoff.cwd;
3066
+ }
3067
+ if (spec.provider === "command") {
3068
+ if (spec.command)
3069
+ out.command = spec.command;
3070
+ if (spec.summarize)
3071
+ out.summarize = spec.summarize;
3072
+ if (spec.caps)
3073
+ out.caps = spec.caps;
3074
+ }
3075
+ return out;
3076
+ }
3077
+ /**
3078
+ * The usage limit a dispatch can hit: its provider and model. A command
3079
+ * job's limit is its summarize step's, so a limit hit there defers the
3080
+ * other calls to that provider this tick, not every command job.
3081
+ */
3082
+ function deferKeyOf(spec) {
3083
+ if (spec.provider === "command" && spec.summarize) {
3084
+ return `${spec.summarize.provider}\u0000${spec.summarize.model ?? spec.model}`;
3085
+ }
3086
+ return `${spec.provider}\u0000${spec.model}`;
3087
+ }
3088
+ /** The known {@link RunDetails} keys of an adapter result or error, or undefined when none is set. */
3089
+ function runDetails(raw) {
3090
+ if (!raw || typeof raw !== "object")
3091
+ return undefined;
3092
+ const d = raw;
3093
+ const out = {};
3094
+ if (Array.isArray(d.steps))
3095
+ out.steps = d.steps.filter((x) => typeof x === "string");
3096
+ if (typeof d.stopped_by === "string")
3097
+ out.stopped_by = d.stopped_by;
3098
+ if (d.truncated === true)
3099
+ out.truncated = true;
3100
+ return Object.keys(out).length > 0 ? out : undefined;
3101
+ }
3102
+ /** True for a command-job row when `adapters` has no `command` adapter to run it. */
3103
+ function unservedCommand(record, adapters) {
3104
+ if (adapters.command || !record.bodyJson)
3105
+ return false;
3106
+ try {
3107
+ return JSON.parse(record.bodyJson).provider === "command";
3108
+ }
3109
+ catch {
3110
+ return false;
3111
+ }
3112
+ }
3113
+ /** True when no adapter serves the row: none for its provider and none for a routing candidate. */
3114
+ function unserved(record, adapters) {
3115
+ let provider;
3116
+ try {
3117
+ provider = JSON.parse(record.bodyJson ?? "null")?.provider;
3118
+ }
3119
+ catch {
3120
+ return false; // a corrupt body fails with its own error
3121
+ }
3122
+ if (typeof provider === "string" && adapters[provider])
3123
+ return false;
3124
+ return !record.routingDecision?.considered.some((c) => adapters[c.provider] !== undefined);
3125
+ }
3126
+ /**
3127
+ * The `origin` dispatch option (KTD13): only for a `claude-code` task whose
3128
+ * record names a session and a directory and whose spec names the agent.
3129
+ * The adapter registered as `anthropic` may be the Claude Code adapter, so
3130
+ * the check is on the task's provider, not on the adapter.
3131
+ */
3132
+ function dispatchOrigin(record, spec) {
3133
+ // A job occurrence never resumes or forks a session (KD8).
3134
+ if (spec.provider !== "claude-code" || !spec.origin || record.jobId)
3135
+ return {};
3136
+ if (!record.originSessionId || !record.originCwd)
3137
+ return {};
3138
+ return {
3139
+ origin: {
3140
+ sessionId: record.originSessionId,
3141
+ cwd: record.originCwd,
3142
+ agent: spec.origin.agent,
3143
+ ...(spec.origin.transcriptPath ? { transcriptPath: spec.origin.transcriptPath } : {}),
3144
+ },
3145
+ };
3146
+ }
2195
3147
  function intensityToGrams(gCo2PerKwh, model) {
2196
3148
  return gramsForIntensity(gCo2PerKwh, { model });
2197
3149
  }
@@ -2258,9 +3210,123 @@ function identityFields(taskId, opts, title) {
2258
3210
  originSessionId: opts.originSessionId,
2259
3211
  };
2260
3212
  }
3213
+ /** Longest one-off shell command `enqueueCommandTask` accepts. */
3214
+ export const COMMAND_MAX_CHARS = 32_000;
3215
+ /**
3216
+ * The spec with its handoff fields checked and its profile turned into
3217
+ * tools; throws on a refusal. `cwd` and a profile apply to `claude-code`
3218
+ * only (a cwd alone means profile `read`); a stored tool list must equal the
3219
+ * profile's. A result path follows the create-only rules and an
3220
+ * `outputPath` the location rules, both against the task's folder, the
3221
+ * session's project folder (`originCwd`) and the temp folders. A result
3222
+ * path needs a one-off task: each run of a series would write the same new
3223
+ * file. A wake needs a checked session origin.
3224
+ */
3225
+ function checkedHandoff(spec, opts, where) {
3226
+ const { originCwd, repeat } = opts;
3227
+ let out = spec;
3228
+ const h = spec.handoff;
3229
+ if (h !== undefined) {
3230
+ if (!h || typeof h !== "object" || Array.isArray(h))
3231
+ throw new Error(`${where}: handoff must be an object`);
3232
+ const handoff = h;
3233
+ const { cwd, profile, resultPath } = handoff;
3234
+ const wakeRefused = wakeError(handoff.wake, spec.origin, opts.originSessionId);
3235
+ if (wakeRefused)
3236
+ throw new Error(`${where}: ${wakeRefused}`);
3237
+ if (cwd !== undefined || profile !== undefined) {
3238
+ if (spec.provider !== "claude-code") {
3239
+ throw new Error(`${where}: cwd and a tool profile apply to the claude-code runner only, not ${spec.provider}`);
3240
+ }
3241
+ if (Array.isArray(spec.candidates) && spec.candidates.length > 1) {
3242
+ throw new Error(`${where}: cwd and a tool profile cannot be combined with routing candidates`);
3243
+ }
3244
+ }
3245
+ if (cwd !== undefined) {
3246
+ const cwdError = handoffCwdError(cwd, "claude-code");
3247
+ if (cwdError)
3248
+ throw new Error(`${where}: ${cwdError}`);
3249
+ }
3250
+ const choice = profileTools(profile, cwd);
3251
+ if (choice.error)
3252
+ throw new Error(`${where}: ${choice.error}`);
3253
+ let tools = spec.tools;
3254
+ if (choice.tools) {
3255
+ if (tools !== undefined && !(Array.isArray(tools) && sameTools(tools, choice.tools))) {
3256
+ throw new Error(`${where}: tools ${JSON.stringify(tools)} differ from profile ${choice.profile} (${choice.tools.join(", ") || "no tools"}); pass one of them`);
3257
+ }
3258
+ tools = choice.tools;
3259
+ }
3260
+ if (resultPath !== undefined) {
3261
+ if (repeat !== undefined && repeat !== "none") {
3262
+ throw new Error(`${where}: a result path needs a one-off task: each run of a series would write the same new file; omit repeat or the result path`);
3263
+ }
3264
+ const pathError = resultPathError(resultPath, { cwd, originCwd });
3265
+ if (pathError)
3266
+ throw new Error(`${where}: ${pathError}`);
3267
+ }
3268
+ out = {
3269
+ ...spec,
3270
+ ...(tools !== undefined ? { tools } : {}),
3271
+ handoff: { ...handoff, ...(choice.profile ? { profile: choice.profile } : {}) },
3272
+ };
3273
+ }
3274
+ if (spec.outputPath !== undefined) {
3275
+ const pathError = outputPathError(spec.outputPath, { cwd: out.handoff?.cwd, originCwd });
3276
+ if (pathError)
3277
+ throw new Error(`${where}: ${pathError}`);
3278
+ }
3279
+ return out;
3280
+ }
3281
+ /** The handoff a reply keeps from its parent: the folder and the profile, never the result path. */
3282
+ function replyHandoff(spec) {
3283
+ const h = spec.handoff;
3284
+ if (!h || typeof h !== "object")
3285
+ return undefined;
3286
+ const out = {
3287
+ ...(h.cwd !== undefined ? { cwd: h.cwd } : {}),
3288
+ ...(h.profile !== undefined ? { profile: h.profile } : {}),
3289
+ };
3290
+ return Object.keys(out).length > 0 ? out : undefined;
3291
+ }
2261
3292
  const MINUTE_MS = 60_000;
2262
3293
  const HOUR_MS = 3_600_000;
2263
3294
  const DAY_MS = 24 * HOUR_MS;
3295
+ /**
3296
+ * A plain Batch row that a killed tick left `running` goes back to
3297
+ * `submitted` once its deadline plus this grace has passed (batch 27 KTD9),
3298
+ * the job sweep's limit for a job's Batch row. Wall-clock time: a provider
3299
+ * ends a batch whether or not this machine slept.
3300
+ * `test/fixtures/stranded-batch-polls.json` holds it for both cores.
3301
+ */
3302
+ export const STRANDED_POLL_GRACE_MS = 5 * MINUTE_MS;
3303
+ /** Minimum span between an earliest start and the deadline. */
3304
+ const NOT_BEFORE_SPAN_MS = 2 * HOUR_MS;
3305
+ /** A deferred task never moves past `enqueuedAt` plus this. */
3306
+ const DEFER_CAP_MS = 8 * DAY_MS;
3307
+ /**
3308
+ * The timing columns of a task with an earliest start at `startMs`: the
3309
+ * deadline raised to at least `startMs + 2 h`, and the fallback time one
3310
+ * minute past the start, because `scheduledFor === notBefore` reads as an
3311
+ * exact-time pin, which `replanSweep` and the batch sweep skip.
3312
+ */
3313
+ function startFields(startMs, deadlineMs) {
3314
+ return {
3315
+ notBefore: new Date(startMs).toISOString(),
3316
+ scheduledFor: new Date(startMs + MINUTE_MS).toISOString(),
3317
+ deadline: new Date(Math.max(deadlineMs, startMs + NOT_BEFORE_SPAN_MS)).toISOString(),
3318
+ };
3319
+ }
3320
+ /** A future earliest start, or undefined (absent or past). */
3321
+ function earliestStart(v) {
3322
+ if (v === undefined || v === null)
3323
+ return undefined;
3324
+ const d = v instanceof Date ? v : new Date(v);
3325
+ if (Number.isNaN(d.getTime())) {
3326
+ throw new Error(`notBefore is not an ISO-8601 instant: ${JSON.stringify(v)}`);
3327
+ }
3328
+ return d.getTime() > Date.now() ? d : undefined;
3329
+ }
2264
3330
  /**
2265
3331
  * The next deadline of a period series: `prevMs` plus whole periods until
2266
3332
  * it is at least one hour ahead of `now`.
@@ -2280,7 +3346,6 @@ function occurrenceNumber(record) {
2280
3346
  const n = Number.parseInt(record.taskId.slice(prefix.length), 10);
2281
3347
  return Number.isFinite(n) && n > 0 ? n : 1;
2282
3348
  }
2283
- /** One-line refusal in the shared style: `<action>: task <id> is <status>; <allowed>`. */
2284
3349
  /**
2285
3350
  * A task action refused by the task's state or by its input (ui v2): the
2286
3351
  * message is a one-line rule safe to show a user. Any other error from an
@@ -2289,17 +3354,73 @@ function occurrenceNumber(record) {
2289
3354
  export class TaskActionError extends Error {
2290
3355
  name = "TaskActionError";
2291
3356
  }
3357
+ /** One-line refusal in the shared style: `<action>: task <id> is <status>; <allowed>`. */
2292
3358
  function refusal(action, record, allowed) {
2293
3359
  const what = record.bodyJson ? record.status : `${record.status} (closure-based)`;
2294
3360
  return `${action}: task ${record.taskId} is ${what}; ${allowed}`;
2295
3361
  }
3362
+ /**
3363
+ * Throws the refusal of a manual retry, or returns for a task that can be
3364
+ * retried: a failed provider-call one-off that did not stop during its
3365
+ * Batch submit.
3366
+ */
3367
+ function retryRefusal(action, record) {
3368
+ const taskId = record.taskId;
3369
+ if (record.status !== "failed") {
3370
+ throw new TaskActionError(`${action}: task ${taskId} has status ${record.status}; retry is only valid on failed tasks`);
3371
+ }
3372
+ if (record.error === BATCH_SUBMIT_INTERRUPTED_ERROR) {
3373
+ // Before the job-run refusal: the job does not retry this run either.
3374
+ throw new TaskActionError(`${action}: task ${taskId} stopped during its Batch submit, and the provider may have accepted the batch; ` +
3375
+ "a retry could run and bill it twice, so check the provider's batch list and enqueue the task again only if no batch exists");
3376
+ }
3377
+ if (!record.bodyJson) {
3378
+ throw new TaskActionError(`${action}: task ${taskId} is closure-based; only provider-call tasks can be retried`);
3379
+ }
3380
+ if (record.jobId) {
3381
+ // The job sweep already recorded this failure and queued a retry or
3382
+ // the next run; a second run of the same slot would go unrecorded.
3383
+ throw new TaskActionError(`${action}: task ${taskId} is a run of job ${record.jobId}, which retries failed runs itself; use run now on the job`);
3384
+ }
3385
+ }
3386
+ /**
3387
+ * A failed row retried by hand: due now with no earliest start, error and
3388
+ * completion time cleared, and no stale batch id (the retry dispatches
3389
+ * synchronously). The run-now mark keeps it off the Batch API.
3390
+ */
3391
+ function retryWrite(record) {
3392
+ return {
3393
+ ...record,
3394
+ status: "scheduled",
3395
+ scheduledFor: new Date().toISOString(),
3396
+ notBefore: undefined,
3397
+ completedAt: undefined,
3398
+ error: undefined,
3399
+ batchId: undefined,
3400
+ intensitySource: "expedited",
3401
+ };
3402
+ }
3403
+ /** The event of a manual retry; its reason starts a new attempt count. */
3404
+ function retryEvent(opts) {
3405
+ return { kind: "rescheduled", actor: opts.actor, details: { reason: "retry" } };
3406
+ }
2296
3407
  /** Classify a reschedule target; exactly one shape must be given. */
2297
3408
  function rescheduleShape(target) {
2298
3409
  const t = (target ?? {});
2299
3410
  const has = (k) => t[k] !== undefined && t[k] !== null;
3411
+ if (has("notBefore")) {
3412
+ if (has("at") || has("dayStart") || has("dayEnd")) {
3413
+ throw new TaskActionError("reschedule: {notBefore} takes only an optional deadline");
3414
+ }
3415
+ return {
3416
+ kind: "notBefore",
3417
+ notBefore: t.notBefore,
3418
+ deadline: has("deadline") ? t.deadline : undefined,
3419
+ };
3420
+ }
2300
3421
  const shapes = [has("deadline"), has("at"), has("dayStart") || has("dayEnd")].filter(Boolean);
2301
3422
  if (shapes.length !== 1) {
2302
- throw new TaskActionError("reschedule: pass exactly one of {deadline}, {at} or {dayStart, dayEnd}");
3423
+ throw new TaskActionError("reschedule: pass exactly one of {deadline}, {at}, {dayStart, dayEnd} or {notBefore}");
2303
3424
  }
2304
3425
  if (has("deadline"))
2305
3426
  return { kind: "deadline", deadline: t.deadline };
@@ -2370,13 +3491,19 @@ export function pickBestWindow(entries, deadline) {
2370
3491
  * errors raised *before* the request could reach the provider
2371
3492
  * (ECONNREFUSED / ENOTFOUND / EAI_AGAIN). Ambiguous mid-flight errors
2372
3493
  * (ETIMEDOUT, ECONNRESET) are NOT retried — the provider may already
2373
- * have accepted and billed the call. Other 4xx bubble up immediately.
3494
+ * have accepted and billed the call. Other 4xx bubble up immediately;
3495
+ * a 408 or 425 then gets the task retry (`isPermanentStatus` in run-limits).
3496
+ *
3497
+ * This is the in-call resend for Tidegap: provider adapters construct
3498
+ * their SDK clients with `maxRetries: 0` so vendor-side retries cannot
3499
+ * multiply with this one. The task's retry policy (a later attempt) is a
3500
+ * separate layer, in the scheduler's retry funnel.
2374
3501
  *
2375
- * This is the single retry policy for Tidegap: provider adapters
2376
- * construct their SDK clients with `maxRetries: 0` so vendor-side
2377
- * retries cannot multiply with this one.
3502
+ * `signal` (the task's cancel watch) ends the waits: once it aborts, no
3503
+ * further call is made, even when the adapter ignored the signal, and the
3504
+ * last error is thrown.
2378
3505
  */
2379
- async function retryWithBackoff(fn) {
3506
+ export async function retryWithBackoff(fn, signal) {
2380
3507
  const waits = [1_000, 4_000, 16_000];
2381
3508
  let lastErr;
2382
3509
  for (let attempt = 0; attempt <= waits.length; attempt++) {
@@ -2385,19 +3512,36 @@ async function retryWithBackoff(fn) {
2385
3512
  }
2386
3513
  catch (err) {
2387
3514
  lastErr = err;
2388
- if (!isRetryable(err) || attempt === waits.length) {
3515
+ if (!isRetryable(err) || attempt === waits.length || signal?.aborted) {
2389
3516
  throw err;
2390
3517
  }
2391
3518
  // eslint-disable-next-line no-console
2392
3519
  console.warn(`[tidegap/scheduler] dispatch attempt ${attempt + 1} failed (${describeErr(err)}); retrying in ${waits[attempt] / 1000}s`);
2393
- await new Promise((r) => setTimeout(r, waits[attempt]));
3520
+ await waitUnlessAborted(waits[attempt], signal);
3521
+ if (signal?.aborted)
3522
+ throw err;
2394
3523
  }
2395
3524
  }
2396
3525
  throw lastErr;
2397
3526
  }
3527
+ /** Wait `ms`, or less when `signal` aborts first. */
3528
+ function waitUnlessAborted(ms, signal) {
3529
+ return new Promise((resolve) => {
3530
+ const done = () => {
3531
+ clearTimeout(timer);
3532
+ signal?.removeEventListener("abort", done);
3533
+ resolve();
3534
+ };
3535
+ const timer = setTimeout(done, ms);
3536
+ signal?.addEventListener("abort", done, { once: true });
3537
+ });
3538
+ }
2398
3539
  function isRetryable(err) {
2399
3540
  if (!err || typeof err !== "object")
2400
3541
  return false;
3542
+ // A job's shell step, or a call retrying cannot help (NonRetryableError).
3543
+ if (err.nonRetryable === true)
3544
+ return false;
2401
3545
  const e = err;
2402
3546
  const status = e.status ?? e.statusCode;
2403
3547
  if (typeof status === "number") {
@@ -2439,16 +3583,36 @@ function describeErr(err) {
2439
3583
  return String(err);
2440
3584
  }
2441
3585
  /**
2442
- * Write { taskId, result, receipt } as JSON to the spec's
2443
- * `outputPath`. Failures are logged but do not fail the task — the
2444
- * SQLite ledger is the source of truth, the file is a convenience.
3586
+ * Write { taskId, result, receipt } as JSON to the spec's `outputPath`,
3587
+ * after the location rules pass again (the folder must exist; a file there
3588
+ * must be a regular file this user owns, which is replaced; a link at the
3589
+ * path is never followed). Failures are logged but do not fail the task —
3590
+ * the SQLite ledger is the source of truth, the file is a convenience.
2445
3591
  */
2446
- async function writeOutputFile(path, taskId, result, receipt) {
3592
+ async function writeOutputFile(path, taskId, result, receipt, roots) {
2447
3593
  try {
2448
- const { mkdir, writeFile } = await import("node:fs/promises");
2449
- const { dirname } = await import("node:path");
2450
- await mkdir(dirname(path), { recursive: true });
2451
- await writeFile(path, JSON.stringify({ taskId, result, receipt }, null, 2));
3594
+ const refused = outputPathError(path, roots);
3595
+ if (refused)
3596
+ throw new Error(refused);
3597
+ const { open } = await import("node:fs/promises");
3598
+ const { constants } = await import("node:fs");
3599
+ // Never through a link, never into a pipe (O_NONBLOCK fails at once with
3600
+ // no reader), and no truncation before the opened file is checked.
3601
+ const flags = constants.O_WRONLY | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
3602
+ const file = await open(path, flags, 0o666);
3603
+ try {
3604
+ const st = await file.stat();
3605
+ const uid = process.getuid?.();
3606
+ // A second name (a hard link) could sit outside the allowed folders.
3607
+ if (!st.isFile() || st.nlink !== 1 || (uid !== undefined && st.uid !== uid)) {
3608
+ throw new Error("the file there is not a regular file you own with one name");
3609
+ }
3610
+ await file.truncate(0);
3611
+ await file.writeFile(JSON.stringify({ taskId, result, receipt }, null, 2));
3612
+ }
3613
+ finally {
3614
+ await file.close();
3615
+ }
2452
3616
  }
2453
3617
  catch (err) {
2454
3618
  // eslint-disable-next-line no-console