@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
@@ -40,6 +40,12 @@
40
40
  * (nullable = none, ui v2); written at insert and
41
41
  * afterwards only by transitionIf ("stop series")
42
42
  * - not_before ISO-8601 earliest dispatch time (nullable, ui v2)
43
+ * - job_id the job this row is an occurrence of (nullable,
44
+ * written once at insert)
45
+ *
46
+ * The `jobs` table (TS-only; the Python core never reads it) holds floating
47
+ * recurring jobs. Every job write after the insert is a compare-and-set on
48
+ * `revision` (`updateJobIf`).
43
49
  *
44
50
  * Writes from separate processes (the UI server, the CLI, a ticker) use
45
51
  * compare-and-set: `transitionIf` updates a row only while its status is in
@@ -49,9 +55,14 @@
49
55
  * JSON-serializable are stored as `{ "_repr": "<toString>" }` so audit
50
56
  * trails survive odd values without crashing the store.
51
57
  */
52
- import { chmodSync, existsSync } from "node:fs";
58
+ import { chmodSync, existsSync, mkdirSync } from "node:fs";
53
59
  import { createRequire } from "node:module";
54
60
  import { dirname } from "node:path";
61
+ import { DEFAULT_JOB_CAPS, } from "../types.js";
62
+ import { isChannelKind } from "../channels/kinds/index.js";
63
+ import { snakeToCamelKey } from "../sign.js";
64
+ import { EVENT_KINDS } from "../channels/types.js";
65
+ import { isTaskEventKind, normalizeActor } from "../task-events.js";
55
66
  const requireFn = createRequire(import.meta.url);
56
67
  const SCHEMA = `
57
68
  CREATE TABLE IF NOT EXISTS tasks (
@@ -109,6 +120,71 @@ CREATE TABLE IF NOT EXISTS meta (
109
120
  key TEXT PRIMARY KEY,
110
121
  value TEXT NOT NULL
111
122
  );
123
+
124
+ -- Notification channels (coherence KTD10): a paired Telegram chat, etc.
125
+ -- TS-only; the Python core never reads it. Secrets (the bot token) are
126
+ -- never stored here.
127
+ CREATE TABLE IF NOT EXISTS channels (
128
+ id TEXT PRIMARY KEY,
129
+ kind TEXT NOT NULL,
130
+ enabled INTEGER NOT NULL DEFAULT 1,
131
+ events_json TEXT NOT NULL,
132
+ config_json TEXT NOT NULL,
133
+ created_at TEXT NOT NULL
134
+ );
135
+
136
+ -- Task events (audit trail): one row per change of a task, written in the
137
+ -- same transaction as the task write. Shared with the Python core (same
138
+ -- DDL). The trigger keeps events exactly as long as their task row.
139
+ CREATE TABLE IF NOT EXISTS task_events (
140
+ id INTEGER PRIMARY KEY,
141
+ task_id TEXT NOT NULL,
142
+ at TEXT NOT NULL,
143
+ kind TEXT NOT NULL,
144
+ actor TEXT NOT NULL,
145
+ details TEXT NOT NULL
146
+ );
147
+ CREATE INDEX IF NOT EXISTS task_events_task_idx ON task_events(task_id, at);
148
+ CREATE TRIGGER IF NOT EXISTS task_events_retention AFTER DELETE ON tasks
149
+ BEGIN
150
+ DELETE FROM task_events WHERE task_id = OLD.task_id;
151
+ END;
152
+
153
+ -- Floating recurring jobs. TS-only; the Python core never reads it. Each
154
+ -- job keeps one live occurrence in tasks (tasks.job_id). The run template
155
+ -- and caps are JSON, read whole; cadence, window and status are columns.
156
+ CREATE TABLE IF NOT EXISTS jobs (
157
+ job_id TEXT PRIMARY KEY,
158
+ title TEXT NOT NULL,
159
+ status TEXT NOT NULL,
160
+ cadence TEXT NOT NULL,
161
+ cadence_hours INTEGER,
162
+ cadence_days TEXT,
163
+ window_start TEXT,
164
+ window_end TEXT,
165
+ time_zone TEXT NOT NULL,
166
+ runner TEXT NOT NULL,
167
+ template_json TEXT NOT NULL,
168
+ caps_json TEXT NOT NULL,
169
+ notify TEXT NOT NULL DEFAULT 'every_run',
170
+ origin_host TEXT,
171
+ origin_cwd TEXT,
172
+ created_by TEXT,
173
+ created_at TEXT NOT NULL,
174
+ updated_at TEXT NOT NULL,
175
+ revision INTEGER NOT NULL DEFAULT 1,
176
+ next_seq INTEGER NOT NULL DEFAULT 1,
177
+ pending_task_id TEXT,
178
+ last_task_id TEXT,
179
+ last_run_started_at TEXT,
180
+ last_outcome TEXT,
181
+ consecutive_failures INTEGER NOT NULL DEFAULT 0,
182
+ retry_used INTEGER NOT NULL DEFAULT 0,
183
+ pause_reason TEXT,
184
+ paused_at TEXT,
185
+ pause_notified_at TEXT
186
+ );
187
+ CREATE INDEX IF NOT EXISTS jobs_status_idx ON jobs(status);
112
188
  `;
113
189
  /**
114
190
  * Idempotent column migrations. SQLite allows `ADD COLUMN` on a
@@ -176,6 +252,10 @@ function ensureColumns(db) {
176
252
  addColumn("origin_session_id", "TEXT");
177
253
  addColumn("not_before", "TEXT");
178
254
  db.exec(`CREATE INDEX IF NOT EXISTS tasks_series_idx ON tasks(series_id)`);
255
+ // Floating recurring jobs: the job a row is an occurrence of. No backfill:
256
+ // NULL means "not a job occurrence".
257
+ addColumn("job_id", "TEXT");
258
+ db.exec(`CREATE INDEX IF NOT EXISTS tasks_job_idx ON tasks(job_id)`);
179
259
  }
180
260
  const REPEAT_RULES = new Set(["none", "daily", "weekly", "quota_reset"]);
181
261
  /** Every column of the tasks table, in INSERT order. */
@@ -184,7 +264,7 @@ const INSERT_COLUMNS = [
184
264
  "region", "carbon_budget_g", "result_json", "error", "receipt_json", "intensity_source",
185
265
  "body_json", "estimated_carbon_g", "deadline", "batch_id", "routing_decision",
186
266
  "title", "origin_host", "origin_cwd", "parent_task_id", "deadline_kind", "quota_provider",
187
- "series_id", "repeat", "origin_session_id", "not_before",
267
+ "series_id", "repeat", "origin_session_id", "not_before", "job_id",
188
268
  ];
189
269
  const INSERT_SQL = `INSERT INTO tasks (${INSERT_COLUMNS.join(", ")})
190
270
  VALUES (${INSERT_COLUMNS.map((c) => `@${c}`).join(", ")})`;
@@ -207,7 +287,7 @@ function recordParams(record) {
207
287
  carbon_budget_g: record.carbonBudgetG ?? null,
208
288
  result_json: safeStringify(record.result),
209
289
  error: record.error ?? null,
210
- receipt_json: safeStringify(record.receipt),
290
+ receipt_json: receiptJson(record.receipt),
211
291
  intensity_source: record.intensitySource ?? null,
212
292
  body_json: record.bodyJson ?? null,
213
293
  estimated_carbon_g: record.estimatedCarbonGCo2 ?? null,
@@ -224,8 +304,52 @@ function recordParams(record) {
224
304
  repeat: record.repeat ?? null,
225
305
  origin_session_id: record.originSessionId ?? null,
226
306
  not_before: record.notBefore ?? null,
307
+ job_id: record.jobId ?? null,
227
308
  };
228
309
  }
310
+ /**
311
+ * The stored `receipt_json` text of each receipt {@link readerReceipt}
312
+ * returned (KTD1). A write of the same receipt, unchanged, puts that text
313
+ * back, so a Node write never rewrites a receipt the Python core stored.
314
+ */
315
+ const storedReceiptText = new WeakMap();
316
+ /**
317
+ * A stored receipt as Node readers expect it. The Python core stores
318
+ * `CarbonReceipt.to_dict()`: snake_case keys and `null` for an absent
319
+ * field. Top-level `null` values are dropped, and each top-level key is
320
+ * renamed by `snakeToCamelKey`, the rule `verifyReceipt` normalizes with.
321
+ * A key keeps its stored name when another non-null key renames to the
322
+ * same name (two renderings of one field), or when its new name would
323
+ * rename again: so the copy carries two renderings exactly when the
324
+ * stored receipt does, and verification of either reports the same.
325
+ * Nested values are kept: Python stores `routing` and `models` in camelCase.
326
+ */
327
+ function readerReceipt(text) {
328
+ const parsed = safeParse(text);
329
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
330
+ return parsed;
331
+ const entries = Object.entries(parsed).filter(([, value]) => value !== null);
332
+ const renderings = new Map();
333
+ for (const [key] of entries) {
334
+ const name = snakeToCamelKey(key);
335
+ renderings.set(name, (renderings.get(name) ?? 0) + 1);
336
+ }
337
+ const out = {};
338
+ for (const [key, value] of entries) {
339
+ const name = snakeToCamelKey(key);
340
+ out[renderings.get(name) === 1 && snakeToCamelKey(name) === name ? name : key] = value;
341
+ }
342
+ storedReceiptText.set(out, text);
343
+ return out;
344
+ }
345
+ /** `receipt_json` for a write: the stored text when `receipt` is a read copy nobody changed, else its JSON. */
346
+ function receiptJson(receipt) {
347
+ const json = safeStringify(receipt);
348
+ const stored = receipt ? storedReceiptText.get(receipt) : undefined;
349
+ if (stored === undefined)
350
+ return json;
351
+ return safeStringify(readerReceipt(stored)) === json ? stored : json;
352
+ }
229
353
  function safeStringify(value) {
230
354
  if (value === undefined)
231
355
  return null;
@@ -246,13 +370,44 @@ function safeParse(s) {
246
370
  return undefined;
247
371
  }
248
372
  }
373
+ /**
374
+ * Ledger meta key: a session notice covers only tasks that finished at or
375
+ * after this ISO time. Set once, by the first notice query, so an upgrade
376
+ * does not replay the history of every session.
377
+ */
378
+ export const SESSION_NOTICES_SINCE_META_KEY = "session_notices_since";
379
+ /** A finished task stays a session notice for this long. */
380
+ export const SESSION_NOTICE_MAX_AGE_MS = 7 * 86_400_000;
381
+ /** What a notice needs from a task body: a checked Claude Code origin and the result file path. */
382
+ function noticeBody(bodyJson) {
383
+ if (typeof bodyJson !== "string")
384
+ return { checked: false };
385
+ try {
386
+ const body = JSON.parse(bodyJson);
387
+ const resultPath = body?.handoff?.resultPath;
388
+ return {
389
+ checked: body?.origin?.agent === "claude-code",
390
+ ...(typeof resultPath === "string" && resultPath !== "" ? { resultPath } : {}),
391
+ };
392
+ }
393
+ catch {
394
+ return { checked: false };
395
+ }
396
+ }
249
397
  export class TaskStore {
250
398
  db;
399
+ txDepth = 0;
251
400
  constructor(opts) {
252
401
  if (opts.db) {
253
402
  this.db = opts.db;
254
403
  }
255
404
  else {
405
+ // A fresh home has no ~/.tidegap until `tidegap install`; every
406
+ // command opens the ledger here, so create its directory (0700, like
407
+ // the chmod below) instead of failing with "unable to open database
408
+ // file". recursive: an existing directory is left as it is.
409
+ if (opts.dbPath !== ":memory:")
410
+ mkdirSync(dirname(opts.dbPath), { recursive: true, mode: 0o700 });
256
411
  this.db = openSqliteSync(opts.dbPath);
257
412
  }
258
413
  // v0.11: enable WAL on disk-backed stores. WAL lifts SQLite's
@@ -271,7 +426,9 @@ export class TaskStore {
271
426
  if (opts.dbPath !== ":memory:") {
272
427
  try {
273
428
  this.db.exec("PRAGMA journal_mode = WAL");
274
- this.db.exec("PRAGMA busy_timeout = 5000");
429
+ const busy = opts.busyTimeoutMs;
430
+ const busyMs = typeof busy === "number" && Number.isFinite(busy) && busy >= 0 ? Math.floor(busy) : 5000;
431
+ this.db.exec(`PRAGMA busy_timeout = ${busyMs}`);
275
432
  // synchronous=NORMAL is the standard WAL companion — durable
276
433
  // across app crashes, faster than FULL, only loses the very
277
434
  // last transaction on a hard power loss. Tidegap dispatch is
@@ -308,7 +465,7 @@ export class TaskStore {
308
465
  }
309
466
  }
310
467
  }
311
- upsert(record) {
468
+ upsert(record, event) {
312
469
  const stmt = this.db.prepare(`
313
470
  ${INSERT_SQL}
314
471
  ON CONFLICT(task_id) DO UPDATE SET
@@ -334,13 +491,17 @@ export class TaskStore {
334
491
  END
335
492
  `);
336
493
  // Identity columns (title, origin_*, parent_task_id, series_id,
337
- // origin_session_id) and repeat are written on insert only and are
494
+ // origin_session_id, job_id) and repeat are written on insert only and are
338
495
  // deliberately absent from DO UPDATE: a stale in-memory copy must not
339
496
  // undo a "stop series" another process wrote (transitionIf owns repeat).
340
497
  // read_at is never written here: the tick and the UI are separate
341
498
  // processes, and an in-memory record without readAt must not clear a
342
499
  // mark another process set. Use markRead / markUnread.
343
- stmt.run(recordParams(record));
500
+ this.tx(() => {
501
+ stmt.run(recordParams(record));
502
+ if (event)
503
+ this.insertEvent(record.taskId, event);
504
+ });
344
505
  }
345
506
  /**
346
507
  * Insert a row only if no row with this id exists (ui v2). Returns true iff
@@ -348,11 +509,16 @@ export class TaskStore {
348
509
  * successor id, so two dispatchers finishing the same occurrence create
349
510
  * exactly one successor.
350
511
  */
351
- insertIfAbsent(record) {
352
- const res = this.db
353
- .prepare(`${INSERT_SQL} ON CONFLICT(task_id) DO NOTHING`)
354
- .run(recordParams(record));
355
- return Number(res.changes) === 1;
512
+ insertIfAbsent(record, event) {
513
+ return this.tx(() => {
514
+ const res = this.db
515
+ .prepare(`${INSERT_SQL} ON CONFLICT(task_id) DO NOTHING`)
516
+ .run(recordParams(record));
517
+ const inserted = Number(res.changes) === 1;
518
+ if (inserted && event)
519
+ this.insertEvent(record.taskId, event);
520
+ return inserted;
521
+ });
356
522
  }
357
523
  /**
358
524
  * Compare-and-set write (ui v2): store the mutable columns of `record`, but
@@ -366,8 +532,11 @@ export class TaskStore {
366
532
  * that earlier read: a write computed from a stale read (a forecast fetch
367
533
  * that awaited while the UI ran a task now or pinned it) then misses
368
534
  * instead of overwriting the newer timing.
535
+ *
536
+ * `event`, when given, is written to `task_events` in the same
537
+ * transaction, and only when the update hit.
369
538
  */
370
- transitionIf(record, expectedStatuses, unchangedSince) {
539
+ transitionIf(record, expectedStatuses, unchangedSince, event) {
371
540
  if (expectedStatuses.length === 0)
372
541
  return false;
373
542
  const placeholders = expectedStatuses.map((_, i) => `@expected_${i}`).join(", ");
@@ -390,7 +559,7 @@ export class TaskStore {
390
559
  params[`was_${col}`] = prev[col];
391
560
  guard = TIMING_GUARD_COLUMNS.map((col) => ` AND ${col} IS @was_${col}`).join("");
392
561
  }
393
- const res = this.db
562
+ const update = this.db
394
563
  .prepare(`UPDATE tasks SET
395
564
  status = @status,
396
565
  scheduled_for = @scheduled_for,
@@ -414,10 +583,293 @@ export class TaskStore {
414
583
  THEN NULL
415
584
  ELSE COALESCE(@quota_provider, quota_provider)
416
585
  END
417
- WHERE task_id = @task_id AND status IN (${placeholders})${guard}`)
418
- .run(params);
586
+ WHERE task_id = @task_id AND status IN (${placeholders})${guard}`);
587
+ return this.tx(() => {
588
+ const hit = Number(update.run(params).changes) === 1;
589
+ if (hit && event)
590
+ this.insertEvent(record.taskId, event);
591
+ return hit;
592
+ });
593
+ }
594
+ /**
595
+ * Append one event to a task's log in its own transaction. `busyMs` bounds
596
+ * the wait for another writer's lock for this write only (a progress line
597
+ * of a running command must not hold the tick for seconds): past it the
598
+ * write throws SQLITE_BUSY. The connection's own busy timeout is restored
599
+ * in `finally`, so no other write gets the short wait. It only shortens
600
+ * the wait: a connection whose own timeout is already shorter (or cannot
601
+ * be read) keeps it.
602
+ */
603
+ recordEvent(taskId, event, opts = {}) {
604
+ const bound = opts.busyMs === undefined || this.txDepth > 0 ? undefined : Math.max(0, Math.floor(opts.busyMs));
605
+ const own = bound === undefined ? NaN : Number(this.db.prepare("PRAGMA busy_timeout").get()?.["timeout"]);
606
+ if (bound === undefined || !Number.isFinite(own) || own <= bound) {
607
+ this.tx(() => this.insertEvent(taskId, event));
608
+ return;
609
+ }
610
+ this.db.exec(`PRAGMA busy_timeout = ${bound}`);
611
+ try {
612
+ this.tx(() => this.insertEvent(taskId, event));
613
+ }
614
+ finally {
615
+ this.db.exec(`PRAGMA busy_timeout = ${own}`);
616
+ }
617
+ }
618
+ /** How many events of `kind` a task has: one `COUNT(*)`, no rows read. */
619
+ countTaskEvents(taskId, kind) {
620
+ const row = this.db.prepare("SELECT COUNT(*) AS n FROM task_events WHERE task_id = ? AND kind = ?").get(taskId, kind);
621
+ return Number(row?.["n"] ?? 0);
622
+ }
623
+ /**
624
+ * Merge `details` into the newest `kind` event of a task: a fact learned
625
+ * after another writer recorded the event (the tick that stopped a
626
+ * cancelled run adds `stopped_run`). Returns false when the task has no
627
+ * such event.
628
+ */
629
+ annotateEvent(taskId, kind, details) {
630
+ const res = this.db
631
+ .prepare(`UPDATE task_events SET details = json_patch(details, ?)
632
+ WHERE id = (SELECT id FROM task_events WHERE task_id = ? AND kind = ? ORDER BY id DESC LIMIT 1)`)
633
+ .run(safeStringify(details) ?? "{}", taskId, kind);
419
634
  return Number(res.changes) === 1;
420
635
  }
636
+ /**
637
+ * A task's events, oldest first. `limit` keeps the newest `limit` rows.
638
+ * Rows with an unknown kind (a newer writer) are skipped.
639
+ */
640
+ listTaskEvents(taskId, opts = {}) {
641
+ const limit = opts.limit !== undefined && opts.limit > 0 ? Math.floor(opts.limit) : -1;
642
+ const rows = this.db
643
+ .prepare(`SELECT * FROM (
644
+ SELECT id, task_id, at, kind, actor, details FROM task_events
645
+ WHERE task_id = ? ORDER BY at DESC, id DESC LIMIT ?
646
+ ) ORDER BY at ASC, id ASC`)
647
+ .all(taskId, limit);
648
+ const out = [];
649
+ for (const row of rows) {
650
+ if (!isTaskEventKind(row.kind))
651
+ continue;
652
+ out.push(rowToEvent(row, row.kind));
653
+ }
654
+ return out;
655
+ }
656
+ /**
657
+ * Events of every task with `at` in (`since`, `until`], oldest first,
658
+ * optionally of the given kinds only. Rows with an unknown kind are skipped.
659
+ */
660
+ listEventsSince(since, until, kinds) {
661
+ const byKind = kinds ? ` AND kind IN (${kinds.map(() => "?").join(", ") || "NULL"})` : "";
662
+ const rows = this.db
663
+ .prepare(`SELECT id, task_id, at, kind, actor, details FROM task_events WHERE at > ? AND at <= ?${byKind} ORDER BY at ASC, id ASC`)
664
+ .all(since, until, ...(kinds ?? []));
665
+ const out = [];
666
+ for (const row of rows) {
667
+ if (!isTaskEventKind(row.kind))
668
+ continue;
669
+ out.push(rowToEvent(row, row.kind));
670
+ }
671
+ return out;
672
+ }
673
+ /**
674
+ * A task's events with an `id` greater than `afterId`, oldest first: the
675
+ * cursor of `queue events --after`, since `id` grows with each insert.
676
+ * Rows with an unknown kind are skipped.
677
+ */
678
+ listTaskEventsAfter(taskId, afterId) {
679
+ const after = Number.isFinite(afterId) ? Math.floor(afterId) : 0;
680
+ const rows = this.db
681
+ .prepare(`SELECT id, task_id, at, kind, actor, details FROM task_events WHERE task_id = ? AND id > ? ORDER BY id ASC`)
682
+ .all(taskId, after);
683
+ const out = [];
684
+ for (const row of rows) {
685
+ if (!isTaskEventKind(row.kind))
686
+ continue;
687
+ out.push(rowToEvent(row, row.kind));
688
+ }
689
+ return out;
690
+ }
691
+ /**
692
+ * Finished tasks a Claude Code session has not been told about, oldest
693
+ * first: `completed`, `failed` or `cancelled`, queued from `sessionId`
694
+ * (every session when absent) with a checked origin in the body, no
695
+ * `notified` event for this finish (its `completed_at`; a retried task
696
+ * that finishes again is a new notice), and finished at or after
697
+ * {@link SESSION_NOTICES_SINCE_META_KEY} and within
698
+ * {@link SESSION_NOTICE_MAX_AGE_MS}. A completed task that asked for a
699
+ * result file waits until its `result_file` event exists. A person's read
700
+ * marker does not matter here.
701
+ */
702
+ listSessionNotices(opts = {}) {
703
+ const now = opts.now ?? new Date();
704
+ const since = this.noticesSince(now);
705
+ const oldest = new Date(now.getTime() - SESSION_NOTICE_MAX_AGE_MS).toISOString();
706
+ const bySession = opts.sessionId !== undefined ? ` AND t.origin_session_id = ?` : ` AND t.origin_session_id IS NOT NULL`;
707
+ const rows = this.db
708
+ .prepare(`SELECT t.*,
709
+ (SELECT e.details FROM task_events e
710
+ WHERE e.task_id = t.task_id AND e.kind = 'result_file'
711
+ ORDER BY e.id DESC LIMIT 1) AS notice_result_file
712
+ FROM tasks t
713
+ WHERE t.status IN ('completed', 'failed', 'cancelled')${bySession}
714
+ AND t.completed_at >= ? AND t.completed_at >= ?
715
+ AND NOT EXISTS (SELECT 1 FROM task_events n
716
+ WHERE n.task_id = t.task_id AND n.kind = 'notified'
717
+ AND json_extract(n.details, '$.completed_at') IS t.completed_at)
718
+ ORDER BY t.completed_at ASC, t.rowid ASC`)
719
+ .all(...(opts.sessionId !== undefined ? [opts.sessionId] : []), since, oldest);
720
+ const out = [];
721
+ for (const row of rows) {
722
+ const body = noticeBody(row.body_json);
723
+ if (!body.checked)
724
+ continue;
725
+ const fileEvent = safeParse(row.notice_result_file);
726
+ const resultFile = fileEvent && typeof fileEvent === "object" && !Array.isArray(fileEvent) ? fileEvent : undefined;
727
+ if (body.resultPath && row.status === "completed" && !resultFile)
728
+ continue;
729
+ out.push({
730
+ record: rowToRecord(row),
731
+ ...(body.resultPath ? { resultPath: body.resultPath } : {}),
732
+ ...(resultFile ? { resultFile } : {}),
733
+ });
734
+ }
735
+ return out;
736
+ }
737
+ /**
738
+ * Record that a session was told about a task's current finish: a
739
+ * `notified` event whose details carry the task's `completed_at`, written
740
+ * only when no `notified` event has that `completed_at` yet. Returns true
741
+ * iff this call wrote it, so the prompt hook, `queue wait` and a wake never
742
+ * claim the same finish twice, and a retried task that finishes again is
743
+ * claimed again. A task that does not exist is never claimed.
744
+ */
745
+ claimNotice(taskId, details, actor = "system") {
746
+ return this.tx(() => {
747
+ const res = this.db
748
+ .prepare(`INSERT INTO task_events (task_id, at, kind, actor, details)
749
+ SELECT t.task_id, ?, 'notified', ?, json_set(?, '$.completed_at', t.completed_at)
750
+ FROM tasks t
751
+ WHERE t.task_id = ?
752
+ AND NOT EXISTS (SELECT 1 FROM task_events n
753
+ WHERE n.task_id = t.task_id AND n.kind = 'notified'
754
+ AND json_extract(n.details, '$.completed_at') IS t.completed_at)`)
755
+ .run(new Date().toISOString(), normalizeActor(actor), JSON.stringify(details), taskId);
756
+ return Number(res.changes) === 1;
757
+ });
758
+ }
759
+ /**
760
+ * Completed tasks that asked for a result file (`handoff.resultPath` in
761
+ * the body) and have no `result_file` event yet, oldest first, whichever
762
+ * core finished them. A body that is not valid JSON is skipped.
763
+ */
764
+ listResultFilesDue() {
765
+ return this.db
766
+ .prepare(`SELECT t.* FROM tasks t
767
+ WHERE t.status = 'completed'
768
+ AND (CASE WHEN json_valid(t.body_json) THEN json_type(t.body_json, '$.handoff.resultPath') END) = 'text'
769
+ AND NOT EXISTS (SELECT 1 FROM task_events e WHERE e.task_id = t.task_id AND e.kind = 'result_file')
770
+ ORDER BY t.completed_at ASC, t.rowid ASC`)
771
+ .all()
772
+ .map(rowToRecord);
773
+ }
774
+ /**
775
+ * Record the outcome of a task's result file: a `result_file` event
776
+ * (actor `tick`), written only when the task has none yet. Returns true
777
+ * iff this call wrote it.
778
+ */
779
+ recordResultFile(taskId, details) {
780
+ return this.tx(() => {
781
+ const res = this.db
782
+ .prepare(`INSERT INTO task_events (task_id, at, kind, actor, details)
783
+ SELECT t.task_id, ?, 'result_file', 'tick', ? FROM tasks t
784
+ WHERE t.task_id = ?
785
+ AND NOT EXISTS (SELECT 1 FROM task_events e WHERE e.task_id = t.task_id AND e.kind = 'result_file')`)
786
+ .run(new Date().toISOString(), safeStringify(details) ?? "{}", taskId);
787
+ return Number(res.changes) === 1;
788
+ });
789
+ }
790
+ /**
791
+ * Set {@link SESSION_NOTICES_SINCE_META_KEY} to `at` unless it is set. The
792
+ * scheduler calls it when it queues a task from a session, so that task's
793
+ * notice is not lost when the first notice query runs only after it
794
+ * finished. Best-effort: a read-only ledger is left alone.
795
+ */
796
+ startSessionNotices(at = new Date()) {
797
+ if (this.getMeta(SESSION_NOTICES_SINCE_META_KEY) !== undefined)
798
+ return;
799
+ try {
800
+ this.db.prepare(`INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING`).run(SESSION_NOTICES_SINCE_META_KEY, at.toISOString());
801
+ }
802
+ catch {
803
+ // read-only ledger
804
+ }
805
+ }
806
+ /**
807
+ * {@link SESSION_NOTICES_SINCE_META_KEY}, set to `now` on first use; `now`
808
+ * when the ledger cannot be written. Read first, so a set key costs no
809
+ * write lock (the prompt hook runs this on every delivery).
810
+ */
811
+ noticesSince(now) {
812
+ const set = this.getMeta(SESSION_NOTICES_SINCE_META_KEY);
813
+ if (set !== undefined)
814
+ return set;
815
+ try {
816
+ this.db.prepare(`INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING`).run(SESSION_NOTICES_SINCE_META_KEY, now.toISOString());
817
+ }
818
+ catch {
819
+ // A read-only ledger: an unset key then means nothing is a notice yet.
820
+ }
821
+ return this.getMeta(SESSION_NOTICES_SINCE_META_KEY) ?? now.toISOString();
822
+ }
823
+ /** Completed and failed tasks with `completed_at` in (`since`, `until`], oldest first (both cores write `completed_at`). */
824
+ listFinishedSince(since, until) {
825
+ return this.db
826
+ .prepare(`SELECT * FROM tasks WHERE status IN ('completed', 'failed') AND completed_at > ? AND completed_at <= ? ORDER BY completed_at ASC`)
827
+ .all(since, until)
828
+ .map(rowToRecord);
829
+ }
830
+ insertEvent(taskId, event) {
831
+ this.db
832
+ .prepare(`INSERT INTO task_events (task_id, at, kind, actor, details) VALUES (?, ?, ?, ?, ?)`)
833
+ .run(taskId, new Date().toISOString(), event.kind, normalizeActor(event.actor), safeStringify(event.details ?? {}) ?? "{}");
834
+ }
835
+ /**
836
+ * Run `fn` in one write transaction (`BEGIN IMMEDIATE`), rolled back when
837
+ * it throws. Re-entrant: a nested call joins the open transaction.
838
+ */
839
+ tx(fn) {
840
+ if (this.txDepth > 0)
841
+ return fn();
842
+ this.db.exec("BEGIN IMMEDIATE");
843
+ this.txDepth++;
844
+ try {
845
+ const out = fn();
846
+ this.db.exec("COMMIT");
847
+ return out;
848
+ }
849
+ catch (err) {
850
+ try {
851
+ this.db.exec("ROLLBACK");
852
+ }
853
+ catch {
854
+ // already rolled back by SQLite
855
+ }
856
+ throw err;
857
+ }
858
+ finally {
859
+ this.txDepth--;
860
+ }
861
+ }
862
+ /**
863
+ * The receipt of `taskId` exactly as stored, in either key rendering, or
864
+ * undefined. Signature checks read it: a Python receipt signed by v0.11 or
865
+ * older verifies only against its original snake_case keys, which
866
+ * {@link get} renames.
867
+ */
868
+ storedReceipt(taskId) {
869
+ const row = this.db.prepare(`SELECT receipt_json FROM tasks WHERE task_id = ?`).get(taskId);
870
+ const parsed = safeParse(row?.receipt_json);
871
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
872
+ }
421
873
  get(taskId) {
422
874
  const row = this.db
423
875
  .prepare(`SELECT * FROM tasks WHERE task_id = ?`)
@@ -427,10 +879,14 @@ export class TaskStore {
427
879
  list(filter) {
428
880
  const where = [];
429
881
  const params = [];
430
- if (filter?.status) {
882
+ if (typeof filter?.status === "string") {
431
883
  where.push(`status = ?`);
432
884
  params.push(filter.status);
433
885
  }
886
+ else if (filter?.status) {
887
+ where.push(`status IN (${filter.status.map(() => "?").join(", ") || "NULL"})`);
888
+ params.push(...filter.status);
889
+ }
434
890
  if (filter?.unread) {
435
891
  where.push(`status IN ('completed', 'failed') AND read_at IS NULL`);
436
892
  }
@@ -445,9 +901,23 @@ export class TaskStore {
445
901
  where.push(`series_id = ?`);
446
902
  params.push(filter.seriesId);
447
903
  }
904
+ if (filter?.jobId) {
905
+ where.push(`job_id = ?`);
906
+ params.push(filter.jobId);
907
+ }
908
+ if (filter?.originSessionId) {
909
+ where.push(`origin_session_id = ?`);
910
+ params.push(filter.originSessionId);
911
+ }
448
912
  const clause = where.length > 0 ? ` WHERE ${where.join(" AND ")}` : "";
913
+ const order = filter?.newestFirst ? "enqueued_at DESC, rowid DESC" : "enqueued_at ASC";
914
+ let limit = "";
915
+ if (filter?.limit !== undefined) {
916
+ limit = " LIMIT ?";
917
+ params.push(Math.max(0, Math.floor(filter.limit)));
918
+ }
449
919
  return this.db
450
- .prepare(`SELECT * FROM tasks${clause} ORDER BY enqueued_at ASC`)
920
+ .prepare(`SELECT * FROM tasks${clause} ORDER BY ${order}${limit}`)
451
921
  .all(...params)
452
922
  .map(rowToRecord);
453
923
  }
@@ -494,6 +964,61 @@ export class TaskStore {
494
964
  ON CONFLICT(key) DO UPDATE SET value = excluded.value`)
495
965
  .run(key, value);
496
966
  }
967
+ /** Remove one meta value; a missing key is a no-op. */
968
+ deleteMeta(key) {
969
+ this.db.prepare(`DELETE FROM meta WHERE key = ?`).run(key);
970
+ }
971
+ /**
972
+ * Compare-and-set one meta value across processes: write `next` (delete
973
+ * the key when `next` is undefined) only while the stored value is still
974
+ * `expected` (undefined: the key is absent). Returns whether it wrote. Two
975
+ * processes that read the same value cannot both win.
976
+ */
977
+ setMetaIf(key, expected, next) {
978
+ return this.tx(() => {
979
+ if (this.getMeta(key) !== expected)
980
+ return false;
981
+ if (next === undefined)
982
+ this.deleteMeta(key);
983
+ else
984
+ this.setMeta(key, next);
985
+ return true;
986
+ });
987
+ }
988
+ /** Every channel row, oldest first; a row with an unknown kind or bad JSON is skipped. */
989
+ listChannels() {
990
+ const rows = this.db.prepare(`SELECT * FROM channels ORDER BY created_at, id`).all();
991
+ const out = [];
992
+ for (const row of rows) {
993
+ const kind = row.kind;
994
+ const events = safeParse(row.events_json);
995
+ const config = safeParse(row.config_json);
996
+ if (!isChannelKind(kind) || !Array.isArray(events) || !config || typeof config !== "object")
997
+ continue;
998
+ out.push({
999
+ id: row.id,
1000
+ kind,
1001
+ enabled: Number(row.enabled) === 1,
1002
+ events: events.filter((e) => EVENT_KINDS.includes(e)),
1003
+ config: config,
1004
+ createdAt: row.created_at,
1005
+ });
1006
+ }
1007
+ return out;
1008
+ }
1009
+ /** Insert or replace a channel row (pairing the same chat again replaces it). */
1010
+ insertChannel(channel) {
1011
+ this.db
1012
+ .prepare(`INSERT INTO channels (id, kind, enabled, events_json, config_json, created_at)
1013
+ VALUES (?, ?, ?, ?, ?, ?)
1014
+ ON CONFLICT(id) DO UPDATE SET kind = excluded.kind, enabled = excluded.enabled,
1015
+ events_json = excluded.events_json, config_json = excluded.config_json`)
1016
+ .run(channel.id, channel.kind, channel.enabled ? 1 : 0, JSON.stringify(channel.events), JSON.stringify(channel.config), channel.createdAt);
1017
+ }
1018
+ /** Remove a channel; false when no row had that id. */
1019
+ removeChannel(id) {
1020
+ return Number(this.db.prepare(`DELETE FROM channels WHERE id = ?`).run(id).changes) > 0;
1021
+ }
497
1022
  /**
498
1023
  * Conditional write for the quota sweep: store the columns a reschedule
499
1024
  * (or a budget failure) changes, but only while the row is still pending
@@ -583,12 +1108,187 @@ export class TaskStore {
583
1108
  .get(windowKind, windowStart, thresholdG);
584
1109
  return row !== undefined;
585
1110
  }
1111
+ /** Insert a new job row. Throws when the id exists. */
1112
+ insertJob(job) {
1113
+ this.db.prepare(`INSERT INTO jobs (${JOB_COLUMNS.join(", ")}) VALUES (${JOB_COLUMNS.map((c) => `@${c}`).join(", ")})`).run(jobParams(job));
1114
+ }
1115
+ getJob(jobId) {
1116
+ const row = this.db.prepare(`SELECT * FROM jobs WHERE job_id = ?`).get(jobId);
1117
+ return row ? rowToJob(row) : undefined;
1118
+ }
1119
+ /** Jobs, oldest first; `status` limits the list to one or several statuses. */
1120
+ listJobs(filter = {}) {
1121
+ const statuses = filter.status === undefined ? [] : typeof filter.status === "string" ? [filter.status] : [...filter.status];
1122
+ const clause = statuses.length > 0 ? ` WHERE status IN (${statuses.map(() => "?").join(", ")})` : "";
1123
+ return this.db
1124
+ .prepare(`SELECT * FROM jobs${clause} ORDER BY created_at ASC, job_id ASC`)
1125
+ .all(...statuses)
1126
+ .map(rowToJob);
1127
+ }
1128
+ /**
1129
+ * Compare-and-set job write: store the mutable columns of `next` only while
1130
+ * the row's revision is `expectedRevision`, and add one to the revision.
1131
+ * Returns false, writing nothing, when another writer got there first.
1132
+ * `job_id`, `created_at`, `created_by` and the origin columns never change.
1133
+ */
1134
+ updateJobIf(next, expectedRevision) {
1135
+ const all = jobParams(next);
1136
+ const params = { expected_revision: expectedRevision };
1137
+ for (const col of JOB_MUTABLE_COLUMNS)
1138
+ params[col] = all[col];
1139
+ params.job_id = all.job_id;
1140
+ const res = this.db
1141
+ .prepare(`UPDATE jobs SET ${JOB_MUTABLE_COLUMNS.map((c) => `${c} = @${c}`).join(", ")}, revision = revision + 1
1142
+ WHERE job_id = @job_id AND revision = @expected_revision`)
1143
+ .run(params);
1144
+ return Number(res.changes) === 1;
1145
+ }
586
1146
  close() {
587
1147
  this.db.close();
588
1148
  }
589
1149
  }
1150
+ /** Columns of the jobs table, in INSERT order. */
1151
+ const JOB_COLUMNS = [
1152
+ "job_id", "title", "status", "cadence", "cadence_hours", "cadence_days", "window_start", "window_end",
1153
+ "time_zone", "runner", "template_json", "caps_json", "notify", "origin_host", "origin_cwd", "created_by",
1154
+ "created_at", "updated_at", "revision", "next_seq", "pending_task_id", "last_task_id", "last_run_started_at",
1155
+ "last_outcome", "consecutive_failures", "retry_used", "pause_reason", "paused_at", "pause_notified_at",
1156
+ ];
1157
+ /** Columns `updateJobIf` writes: everything except the identity and the revision. */
1158
+ const JOB_MUTABLE_COLUMNS = JOB_COLUMNS.filter((c) => !["job_id", "created_at", "created_by", "origin_host", "origin_cwd", "revision"].includes(c));
1159
+ const JOB_STATUSES = new Set(["active", "paused", "removed"]);
1160
+ const JOB_NOTIFY = new Set(["every_run", "failures", "summary"]);
1161
+ const JOB_OUTCOMES = new Set(["ok", "failed", "skipped"]);
1162
+ function jobParams(job) {
1163
+ const c = job.cadence;
1164
+ return {
1165
+ job_id: job.jobId,
1166
+ title: job.title,
1167
+ status: job.status,
1168
+ cadence: c.kind,
1169
+ cadence_hours: c.kind === "hours" ? c.every : null,
1170
+ cadence_days: c.kind === "weekly" ? c.days.join(",") : null,
1171
+ window_start: job.window?.start ?? null,
1172
+ window_end: job.window?.end ?? null,
1173
+ time_zone: job.timeZone,
1174
+ runner: job.template.runner,
1175
+ template_json: JSON.stringify(job.template),
1176
+ caps_json: JSON.stringify(job.caps),
1177
+ notify: job.notify,
1178
+ origin_host: job.originHost ?? null,
1179
+ origin_cwd: job.originCwd ?? null,
1180
+ created_by: job.createdBy ?? null,
1181
+ created_at: job.createdAt,
1182
+ updated_at: job.updatedAt,
1183
+ revision: job.revision,
1184
+ next_seq: job.nextSeq,
1185
+ pending_task_id: job.pendingTaskId ?? null,
1186
+ last_task_id: job.lastTaskId ?? null,
1187
+ last_run_started_at: job.lastRunStartedAt ?? null,
1188
+ last_outcome: job.lastOutcome ?? null,
1189
+ consecutive_failures: job.consecutiveFailures,
1190
+ retry_used: job.retryUsed,
1191
+ pause_reason: job.pauseReason ?? null,
1192
+ paused_at: job.pausedAt ?? null,
1193
+ pause_notified_at: job.pauseNotifiedAt ?? null,
1194
+ };
1195
+ }
1196
+ /** The template stored for a job, or undefined when it is not a template object. */
1197
+ function parseTemplate(raw, runner) {
1198
+ const t = safeParse(raw);
1199
+ if (!t || typeof t !== "object" || Array.isArray(t))
1200
+ return undefined;
1201
+ const tpl = t;
1202
+ if (tpl.runner !== runner)
1203
+ return undefined;
1204
+ if (tpl.runner === "prompt" && typeof tpl.prompt === "string" && typeof tpl.provider === "string")
1205
+ return tpl;
1206
+ if (tpl.runner === "command" && typeof tpl.command === "string" && Array.isArray(tpl.secrets))
1207
+ return tpl;
1208
+ return undefined;
1209
+ }
1210
+ function rowToCadence(row) {
1211
+ switch (row.cadence) {
1212
+ case "daily":
1213
+ return { kind: "daily" };
1214
+ case "weekdays":
1215
+ return { kind: "weekdays" };
1216
+ case "weekly": {
1217
+ const days = String(row.cadence_days ?? "").split(",").filter((d) => d !== "");
1218
+ return { kind: "weekly", days };
1219
+ }
1220
+ case "hours":
1221
+ return { kind: "hours", every: Number(row.cadence_hours) };
1222
+ default:
1223
+ return undefined;
1224
+ }
1225
+ }
1226
+ /** The `retry_used` column as a count: a row from before held 0 or 1 (true), which reads as that many retries. */
1227
+ function retryCount(raw) {
1228
+ const n = Number(raw ?? 0);
1229
+ return Number.isInteger(n) && n > 0 ? n : 0;
1230
+ }
1231
+ /**
1232
+ * A job row as a record. A row whose template (or cadence) does not parse
1233
+ * reads as `paused` with reason `corrupt template` instead of throwing, so
1234
+ * one bad row never stops the sweep or a list.
1235
+ */
1236
+ function rowToJob(row) {
1237
+ const str = (v) => (v === null || v === undefined ? undefined : String(v));
1238
+ const template = parseTemplate(row.template_json, row.runner);
1239
+ const cadence = rowToCadence(row);
1240
+ const caps = safeParse(row.caps_json);
1241
+ const status = JOB_STATUSES.has(row.status) ? row.status : "paused";
1242
+ const job = {
1243
+ jobId: String(row.job_id),
1244
+ title: String(row.title),
1245
+ status,
1246
+ cadence: cadence ?? { kind: "daily" },
1247
+ window: row.window_start != null && row.window_end != null
1248
+ ? { start: String(row.window_start), end: String(row.window_end) }
1249
+ : undefined,
1250
+ timeZone: String(row.time_zone),
1251
+ template: template ?? (row.runner === "command"
1252
+ ? { runner: "command", command: "", secrets: [] }
1253
+ : { runner: "prompt", prompt: "", provider: "claude-code", tools: "none" }),
1254
+ caps: { ...DEFAULT_JOB_CAPS, ...(caps && typeof caps === "object" && !Array.isArray(caps) ? caps : {}) },
1255
+ notify: JOB_NOTIFY.has(row.notify) ? row.notify : "every_run",
1256
+ originHost: str(row.origin_host),
1257
+ originCwd: str(row.origin_cwd),
1258
+ createdBy: str(row.created_by),
1259
+ createdAt: String(row.created_at),
1260
+ updatedAt: String(row.updated_at),
1261
+ revision: Number(row.revision),
1262
+ nextSeq: Number(row.next_seq),
1263
+ pendingTaskId: str(row.pending_task_id),
1264
+ lastTaskId: str(row.last_task_id),
1265
+ lastRunStartedAt: str(row.last_run_started_at),
1266
+ lastOutcome: JOB_OUTCOMES.has(row.last_outcome) ? row.last_outcome : undefined,
1267
+ consecutiveFailures: Number(row.consecutive_failures ?? 0),
1268
+ retryUsed: retryCount(row.retry_used),
1269
+ pauseReason: str(row.pause_reason),
1270
+ pausedAt: str(row.paused_at),
1271
+ pauseNotifiedAt: str(row.pause_notified_at),
1272
+ };
1273
+ if ((!template || !cadence) && job.status !== "removed") {
1274
+ job.status = "paused";
1275
+ job.pauseReason = "corrupt template";
1276
+ }
1277
+ return job;
1278
+ }
1279
+ function rowToEvent(row, kind) {
1280
+ const details = safeParse(row.details);
1281
+ return {
1282
+ id: Number(row.id),
1283
+ taskId: String(row.task_id),
1284
+ at: String(row.at),
1285
+ kind,
1286
+ actor: normalizeActor(row.actor),
1287
+ details: details && typeof details === "object" && !Array.isArray(details) ? details : {},
1288
+ };
1289
+ }
590
1290
  function rowToRecord(row) {
591
- const receipt = safeParse(row.receipt_json);
1291
+ const receipt = readerReceipt(row.receipt_json);
592
1292
  const result = safeParse(row.result_json);
593
1293
  return {
594
1294
  taskId: row.task_id,
@@ -623,6 +1323,7 @@ function rowToRecord(row) {
623
1323
  : undefined,
624
1324
  originSessionId: row.origin_session_id ?? undefined,
625
1325
  notBefore: row.not_before ?? undefined,
1326
+ jobId: row.job_id ?? undefined,
626
1327
  };
627
1328
  }
628
1329
  /** Load Node's built-in SQLite (node:sqlite, Node >= 22.5), if available. */