Open History to see the last commit
1import {
2 CommandId,
3 MessageId,
4 ScheduledTask,
5 ScheduledTaskError,
6 ScheduledTaskId,
7 ThreadId,
8 type ScheduledTaskDeleteInput,
9 type ScheduledTaskDeleteResult,
10 type ScheduledTaskListResult,
11 type ScheduledTaskMutationResult,
12 type ScheduledTaskRunNowInput,
13 type ScheduledTaskRunNowResult,
14 type ScheduledTaskSetEnabledInput,
15 type ScheduledTaskUpsertInput,
16} from "@t3tools/contracts";
17import * as Cause from "effect/Cause";
18import * as Context from "effect/Context";
19import * as Crypto from "effect/Crypto";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import * as PubSub from "effect/PubSub";
25import * as Ref from "effect/Ref";
26import * as Result from "effect/Result";
27import * as Schema from "effect/Schema";
28import * as Stream from "effect/Stream";
29import * as SqlClient from "effect/unstable/sql/SqlClient";
30
31import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
32import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
33import * as Scheduler from "../scheduling/Scheduler.ts";
34import { isMissedFixedTimeRun, isSameSchedule, nextScheduledRunAt } from "./Schedule.ts";
35
36const decodeTask = Schema.decodeUnknownEffect(ScheduledTask);
37const decodeTaskId = Schema.decodeUnknownOption(ScheduledTaskId);
38const decodeScheduleJson = Schema.decodeUnknownEffect(
39 Schema.fromJsonString(ScheduledTask.fields.schedule),
40);
41const decodeWorkspaceStrategyJson = Schema.decodeUnknownEffect(
42 Schema.fromJsonString(ScheduledTask.fields.workspaceStrategy),
43);
44const decodeModelSelectionJson = Schema.decodeUnknownEffect(
45 Schema.fromJsonString(ScheduledTask.fields.modelSelection),
46);
47
48interface ScheduledTaskRow {
49 readonly task_id: string;
50 readonly title: string;
51 readonly prompt: string;
52 readonly enabled: number;
53 readonly schedule_json: string;
54 readonly project_id: string;
55 readonly thread_id: string | null;
56 readonly workspace_strategy_json: string;
57 readonly model_selection_json: string;
58 readonly runtime_mode: string;
59 readonly interaction_mode: string;
60 readonly created_by: string;
61 readonly creation_source: string;
62 readonly created_at: string;
63 readonly updated_at: string;
64 readonly next_run_at: string | null;
65 readonly last_run_at: string | null;
66 readonly last_run_status: string;
67 readonly last_run_error: string | null;
68 readonly run_count: number;
69}
70
71export class ScheduledTaskService extends Context.Service<
72 ScheduledTaskService,
73 {
74 readonly list: () => Effect.Effect<ScheduledTaskListResult, ScheduledTaskError>;
75 /** Emits the full task list on subscribe and again after every change (CRUD, run transitions, reschedules). */
76 readonly subscribeList: () => Stream.Stream<ScheduledTaskListResult, ScheduledTaskError>;
77 readonly upsert: (
78 input: ScheduledTaskUpsertInput,
79 ) => Effect.Effect<ScheduledTaskMutationResult, ScheduledTaskError>;
80 /** Partial update flipping only the enabled flag; never touches other fields. */
81 readonly setEnabled: (
82 input: ScheduledTaskSetEnabledInput,
83 ) => Effect.Effect<ScheduledTaskMutationResult, ScheduledTaskError>;
84 readonly delete: (
85 input: ScheduledTaskDeleteInput,
86 ) => Effect.Effect<ScheduledTaskDeleteResult, ScheduledTaskError>;
87 readonly runNow: (
88 input: ScheduledTaskRunNowInput,
89 ) => Effect.Effect<ScheduledTaskRunNowResult, ScheduledTaskError>;
90 }
91>()("t3/scheduledTasks/ScheduledTaskService") {}
92
93function taskError(message: string, input?: { taskId?: ScheduledTaskId; cause?: unknown }) {
94 return new ScheduledTaskError({
95 message,
96 ...(input?.taskId === undefined ? {} : { taskId: input.taskId }),
97 ...(input?.cause === undefined ? {} : { cause: input.cause }),
98 });
99}
100
101function iso(value: DateTime.DateTime): string {
102 return DateTime.formatIso(DateTime.toUtc(value));
103}
104
105const localNow = DateTime.withCurrentZoneLocal(DateTime.nowInCurrentZone);
106
107function nextRunAt(
108 task: Pick<ScheduledTask, "enabled" | "schedule">,
109 from: DateTime.DateTime,
110): string | null {
111 if (!task.enabled) return null;
112 // A stored interval can decode yet overflow the representable DateTime
113 // range; an unrepresentable occurrence means the task has no next run.
114 try {
115 const next = nextScheduledRunAt(task.schedule, from);
116 return next !== null && Number.isFinite(DateTime.toEpochMillis(next)) ? iso(next) : null;
117 } catch {
118 return null;
119 }
120}
121
122function errorMessage(error: unknown): string {
123 if (Cause.isCause(error)) return Cause.pretty(error);
124 if (error instanceof Error) return error.message;
125 return String(error);
126}
127
128const decodeRow = (row: ScheduledTaskRow) =>
129 Effect.gen(function* () {
130 const schedule = yield* decodeScheduleJson(row.schedule_json);
131 const workspaceStrategy = yield* decodeWorkspaceStrategyJson(row.workspace_strategy_json);
132 const modelSelection = yield* decodeModelSelectionJson(row.model_selection_json);
133 return yield* decodeTask({
134 // The stored id decodes through the task schema so a corrupt value fails
135 // as a typed parse error, not a `ScheduledTaskId.make` defect.
136 id: row.task_id,
137 title: row.title,
138 prompt: row.prompt,
139 enabled: row.enabled === 1,
140 schedule,
141 projectId: row.project_id,
142 threadId: row.thread_id,
143 workspaceStrategy,
144 modelSelection,
145 runtimeMode: row.runtime_mode,
146 interactionMode: row.interaction_mode,
147 createdBy: row.created_by,
148 creationSource: row.creation_source,
149 createdAt: row.created_at,
150 updatedAt: row.updated_at,
151 nextRunAt: row.next_run_at,
152 lastRunAt: row.last_run_at,
153 lastRunStatus: row.last_run_status,
154 lastRunError: row.last_run_error,
155 runCount: row.run_count,
156 });
157 }).pipe(
158 Effect.mapError((cause) => {
159 // The typed diagnostic can only carry an id that itself decodes; a
160 // corrupt stored id is omitted rather than re-thrown as a defect.
161 const taskId = decodeTaskId(row.task_id);
162 return taskError("Could not decode schedule task row.", {
163 ...(Option.isSome(taskId) ? { taskId: taskId.value } : {}),
164 cause,
165 });
166 }),
167 );
168
169/** Select poll candidates before decoding their schedules or other JSON payloads. */
170export const listDueTasks = Effect.fn("ScheduledTaskService.listDueTasks")(function* (
171 now: DateTime.DateTime,
172) {
173 const sql = yield* SqlClient.SqlClient;
174 const rows = yield* sql<ScheduledTaskRow>`
175 SELECT * FROM scheduled_tasks
176 WHERE enabled = 1 AND next_run_at IS NOT NULL
177 AND next_run_at <= ${iso(now)} AND last_run_status <> 'running'
178 ORDER BY next_run_at ASC, task_id ASC
179 `;
180 const tasks: ScheduledTask[] = [];
181 for (const row of rows) {
182 const decoded = yield* Effect.result(decodeRow(row));
183 if (Result.isSuccess(decoded)) {
184 const task = decoded.success;
185 // next_run_at is a freeform string at the schema level; a stored value
186 // that cannot parse as a DateTime would defect the poll below, so the
187 // row is skipped here like any other corrupt row.
188 if (task.nextRunAt === null || Option.isSome(DateTime.make(task.nextRunAt))) {
189 tasks.push(task);
190 } else {
191 yield* Effect.logWarning("Skipping schedule task row with invalid next_run_at", {
192 taskId: row.task_id,
193 });
194 }
195 } else {
196 yield* Effect.logWarning("Skipping undecodable schedule task row", {
197 taskId: row.task_id,
198 cause: decoded.failure,
199 });
200 }
201 }
202 return tasks;
203});
204
205export const layer = Layer.effect(
206 ScheduledTaskService,
207 Effect.gen(function* () {
208 const sql = yield* SqlClient.SqlClient;
209 const crypto = yield* Crypto.Crypto;
210 const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;
211 const threadManagement = yield* ThreadManagementService.ThreadManagementService;
212 const scheduler = yield* Scheduler.Scheduler;
213 const activeRuns = yield* Ref.make<ReadonlySet<ScheduledTaskId>>(new Set());
214 // Sliding(1) coalesces the dirty-signal: every notification triggers a
215 // full list() re-emit anyway, so a slow subscriber only ever needs the
216 // latest signal — an unbounded backlog would just grow memory.
217 const changesPubSub = yield* PubSub.sliding<void>(1);
218 const notifyChanged = PubSub.publish(changesPubSub, undefined).pipe(Effect.asVoid);
219
220 const selectAllRows = () => sql<ScheduledTaskRow>`
221 SELECT
222 task_id,
223 title,
224 prompt,
225 enabled,
226 schedule_json,
227 project_id,
228 thread_id,
229 workspace_strategy_json,
230 model_selection_json,
231 runtime_mode,
232 interaction_mode,
233 created_by,
234 creation_source,
235 created_at,
236 updated_at,
237 next_run_at,
238 last_run_at,
239 last_run_status,
240 last_run_error,
241 run_count
242 FROM scheduled_tasks
243 ORDER BY updated_at DESC, task_id ASC
244 `;
245
246 // Strict decode for the API surface: a corrupt row is a visible error.
247 const listRows = Effect.fn("ScheduledTaskService.listRows")(function* () {
248 const rows = yield* selectAllRows();
249 return yield* Effect.forEach(rows, decodeRow, { concurrency: 1 });
250 });
251
252 const getRows = (id: ScheduledTaskId) => sql<ScheduledTaskRow>`
253 SELECT
254 task_id,
255 title,
256 prompt,
257 enabled,
258 schedule_json,
259 project_id,
260 thread_id,
261 workspace_strategy_json,
262 model_selection_json,
263 runtime_mode,
264 interaction_mode,
265 created_by,
266 creation_source,
267 created_at,
268 updated_at,
269 next_run_at,
270 last_run_at,
271 last_run_status,
272 last_run_error,
273 run_count
274 FROM scheduled_tasks
275 WHERE task_id = ${id}
276 `;
277
278 /** Load a task, returning `null` when it does not exist; real load/decode failures propagate. */
279 const findTask = Effect.fn("ScheduledTaskService.findTask")(function* (id: ScheduledTaskId) {
280 const rows = yield* getRows(id).pipe(
281 Effect.mapError((cause) =>
282 taskError("Could not load schedule task.", { taskId: id, cause }),
283 ),
284 );
285 const row = rows[0];
286 if (row === undefined) return null;
287 return yield* decodeRow(row);
288 });
289
290 const loadTask = Effect.fn("ScheduledTaskService.loadTask")(function* (id: ScheduledTaskId) {
291 const task = yield* findTask(id);
292 if (task === null) {
293 return yield* taskError("Schedule task not found.", { taskId: id });
294 }
295 return task;
296 });
297
298 // Run-state columns (last_run_*, run_count) are intentionally absent from
299 // the conflict clause: they are owned by the run transitions below, and a
300 // concurrent settings save must not overwrite an in-flight increment.
301 // Check existence in the write itself so an edit cannot undo a deletion
302 // that landed after upsert loaded the previous task.
303 const saveTask = (task: ScheduledTask, requireExisting: boolean) =>
304 sql<{ task_id: string }>`
305 INSERT INTO scheduled_tasks (
306 task_id,
307 title,
308 prompt,
309 enabled,
310 schedule_json,
311 project_id,
312 thread_id,
313 workspace_strategy_json,
314 model_selection_json,
315 runtime_mode,
316 interaction_mode,
317 created_by,
318 creation_source,
319 created_at,
320 updated_at,
321 next_run_at,
322 last_run_at,
323 last_run_status,
324 last_run_error,
325 run_count
326 )
327 SELECT
328 ${task.id},
329 ${task.title},
330 ${task.prompt},
331 ${task.enabled ? 1 : 0},
332 ${JSON.stringify(task.schedule)},
333 ${task.projectId},
334 ${task.threadId},
335 ${JSON.stringify(task.workspaceStrategy)},
336 ${JSON.stringify(task.modelSelection)},
337 ${task.runtimeMode},
338 ${task.interactionMode},
339 ${task.createdBy},
340 ${task.creationSource},
341 ${task.createdAt},
342 ${task.updatedAt},
343 ${task.nextRunAt},
344 ${task.lastRunAt},
345 ${task.lastRunStatus},
346 ${task.lastRunError},
347 ${task.runCount}
348 WHERE ${requireExisting ? 0 : 1} = 1
349 OR EXISTS (SELECT 1 FROM scheduled_tasks WHERE task_id = ${task.id})
350 ON CONFLICT (task_id)
351 DO UPDATE SET
352 title = excluded.title,
353 prompt = excluded.prompt,
354 enabled = excluded.enabled,
355 schedule_json = excluded.schedule_json,
356 project_id = excluded.project_id,
357 thread_id = excluded.thread_id,
358 workspace_strategy_json = excluded.workspace_strategy_json,
359 model_selection_json = excluded.model_selection_json,
360 runtime_mode = excluded.runtime_mode,
361 interaction_mode = excluded.interaction_mode,
362 creation_source = excluded.creation_source,
363 updated_at = excluded.updated_at,
364 next_run_at = excluded.next_run_at
365 RETURNING task_id
366 `.pipe(
367 Effect.mapError((cause) =>
368 taskError("Could not save schedule task.", { taskId: task.id, cause }),
369 ),
370 Effect.flatMap((rows) =>
371 rows.length > 0
372 ? Effect.void
373 : taskError("Schedule task not found.", { taskId: task.id }),
374 ),
375 );
376
377 const deleteRow = (id: ScheduledTaskId) =>
378 sql`DELETE FROM scheduled_tasks WHERE task_id = ${id}`.pipe(
379 Effect.mapError((cause) =>
380 taskError("Could not delete schedule task.", { taskId: id, cause }),
381 ),
382 );
383
384 // Run-state transitions use targeted UPDATEs (never the full-row upsert) so
385 // a completing run cannot resurrect a deleted task or clobber concurrent
386 // edits to the task definition.
387 const markRunning = (id: ScheduledTaskId, startedAtIso: string) =>
388 sql`
389 UPDATE scheduled_tasks
390 SET updated_at = ${startedAtIso},
391 last_run_at = ${startedAtIso},
392 last_run_status = 'running',
393 last_run_error = NULL
394 WHERE task_id = ${id}
395 `.pipe(
396 Effect.mapError((cause) =>
397 taskError("Could not mark schedule task as running.", { taskId: id, cause }),
398 ),
399 );
400
401 const markCompleted = (input: {
402 readonly id: ScheduledTaskId;
403 readonly completedAtIso: string;
404 readonly nextRunAtIso: string | null;
405 readonly status: "succeeded" | "failed";
406 readonly error: string | null;
407 readonly startedAtIso: string;
408 }) =>
409 sql`
410 UPDATE scheduled_tasks
411 SET updated_at = ${input.completedAtIso},
412 next_run_at = ${input.nextRunAtIso},
413 last_run_status = ${input.status},
414 last_run_error = ${input.error},
415 run_count = run_count + 1
416 WHERE task_id = ${input.id}
417 AND last_run_status = 'running'
418 AND last_run_at = ${input.startedAtIso}
419 `.pipe(
420 Effect.mapError((cause) =>
421 taskError("Could not record schedule task run.", { taskId: input.id, cause }),
422 ),
423 );
424
425 // Best-effort escape hatch: if anything fails between markRunning and
426 // markCompleted, write a full terminal record so runDueTasks neither skips
427 // the task forever (it filters out 'running' rows) nor re-fires it
428 // immediately: the dispatch may already have gone out, so next_run_at must
429 // advance and run_count must count the attempt.
430 const releaseStuckRun = (task: ScheduledTask, message: string) =>
431 Effect.gen(function* () {
432 const now = yield* localNow;
433 // Compute the next occurrence from the current row so a schedule
434 // edited while the run was in flight is honoured; fall back to the
435 // run's snapshot only if the re-read itself fails.
436 const reread = yield* Effect.result(findTask(task.id));
437 if (Result.isSuccess(reread) && reread.success === null) return; // deleted — nothing to release
438 const source = Result.isSuccess(reread) && reread.success !== null ? reread.success : task;
439 yield* sql`
440 UPDATE scheduled_tasks
441 SET last_run_status = 'failed',
442 last_run_error = ${message},
443 next_run_at = ${nextRunAt(source, now)},
444 updated_at = ${iso(now)},
445 run_count = run_count + 1
446 WHERE task_id = ${task.id} AND last_run_status = 'running'
447 `;
448 yield* notifyChanged;
449 }).pipe(
450 Effect.catch((cause) =>
451 Effect.logWarning("Could not release stuck schedule task run", {
452 taskId: task.id,
453 cause,
454 }),
455 ),
456 );
457
458 const runTask = Effect.fn("ScheduledTaskService.runTask")(function* (
459 task: ScheduledTask,
460 trigger: "scheduled" | "manual",
461 ) {
462 const reserved = yield* Ref.modify(activeRuns, (active) => {
463 if (active.has(task.id)) return [false, active] as const;
464 const next = new Set(active);
465 next.add(task.id);
466 return [true, next] as const;
467 });
468 if (!reserved) {
469 if (trigger === "manual") {
470 return yield* taskError("Schedule task is already running.", { taskId: task.id });
471 }
472 return task;
473 }
474
475 return yield* Effect.gen(function* () {
476 const startedAt = yield* localNow;
477 const startedAtIso = iso(startedAt);
478
479 // The in-memory snapshot may be stale: re-read before touching run
480 // state. The task may have been deleted, paused, or postponed since
481 // the poll loaded it — none of those may fire.
482 const active = yield* findTask(task.id);
483 if (active === null) {
484 // A manual run on a just-deleted task must fail loudly, not report
485 // a successful run that never dispatched.
486 if (trigger === "manual") {
487 return yield* taskError("Schedule task not found.", { taskId: task.id });
488 }
489 return task;
490 }
491 // A next_run_at corrupted between the poll read and this re-read must
492 // not defect the poll; an unparseable value is treated as not due.
493 const parsedNextRunAt =
494 active.nextRunAt === null ? Option.none() : DateTime.make(active.nextRunAt);
495 if (
496 trigger === "scheduled" &&
497 (!active.enabled ||
498 Option.isNone(parsedNextRunAt) ||
499 DateTime.toEpochMillis(parsedNextRunAt.value) > DateTime.toEpochMillis(startedAt))
500 ) {
501 return active;
502 }
503
504 yield* markRunning(active.id, startedAtIso);
505 yield* notifyChanged;
506
507 const fireKey = `${active.id}:${DateTime.toEpochMillis(startedAt)}:${trigger}`;
508 const commandId = CommandId.make(`scheduled-task:${fireKey}`);
509 const messageId = MessageId.make(`scheduled-task-message:${fireKey}`);
510 // Dispatch from the fresh row so prompt/model/binding edits made
511 // after the poll read are honoured.
512 const prompt = active.prompt;
513
514 // Effect.exit (not Effect.result) so defects and interruptions in the
515 // dispatch are also captured and recorded as a failed run instead of
516 // aborting before markCompleted.
517 const result =
518 active.threadId === null
519 ? yield* Effect.exit(
520 threadLaunch.launch({
521 commandId,
522 projectId: active.projectId,
523 title: active.title,
524 modelSelection: active.modelSelection,
525 runtimeMode: active.runtimeMode,
526 interactionMode: active.interactionMode,
527 workspaceStrategy: active.workspaceStrategy,
528 initialMessage: {
529 messageId,
530 scheduledTaskId: active.id,
531 text: prompt,
532 attachments: [],
533 },
534 createdBy: active.createdBy,
535 creationSource: active.creationSource,
536 }),
537 )
538 : yield* Effect.exit(
539 threadManagement.sendToThread({
540 projectId: active.projectId,
541 commandId,
542 threadId: ThreadId.make(active.threadId),
543 messageId,
544 scheduledTaskId: active.id,
545 text: prompt,
546 attachments: [],
547 modelSelection: active.modelSelection,
548 mode: "auto",
549 createdBy: active.createdBy,
550 creationSource: active.creationSource,
551 }),
552 );
553
554 const completedAt = yield* localNow;
555 const runSucceeded = result._tag === "Success";
556 const lastRunStatus = runSucceeded ? ("succeeded" as const) : ("failed" as const);
557 const lastRunError = runSucceeded ? null : errorMessage(result.cause);
558 // Re-read the task so the next run is computed from the schedule as it
559 // is *now* (the user may have edited or deleted it while we ran).
560 const current = yield* findTask(task.id);
561 const scheduleSource = current ?? task;
562 const completed: ScheduledTask = {
563 ...scheduleSource,
564 updatedAt: iso(completedAt),
565 lastRunAt: startedAtIso,
566 nextRunAt: nextRunAt(scheduleSource, completedAt),
567 lastRunStatus,
568 lastRunError,
569 runCount: scheduleSource.runCount + 1,
570 };
571 if (current !== null) {
572 // startedAtIso in the guard ensures this writes only to the row this
573 // run marked as running — a task deleted mid-run and recreated with
574 // the same id (idempotent commandId replay) must not be stamped.
575 yield* markCompleted({
576 id: task.id,
577 completedAtIso: completed.updatedAt,
578 nextRunAtIso: completed.nextRunAt,
579 status: lastRunStatus,
580 error: lastRunError,
581 startedAtIso,
582 });
583 yield* notifyChanged;
584 }
585 return completed;
586 }).pipe(
587 Effect.onError((cause) => releaseStuckRun(task, errorMessage(cause))),
588 Effect.ensuring(
589 Ref.update(activeRuns, (active) => {
590 const next = new Set(active);
591 next.delete(task.id);
592 return next;
593 }),
594 ),
595 );
596 });
597
598 // A due fixed-time run that is long past its slot (server was off or
599 // asleep) is skipped and re-aimed at its next occurrence, not fired late.
600 const rescheduleMissedRun = Effect.fn("ScheduledTaskService.rescheduleMissedRun")(function* (
601 task: ScheduledTask,
602 now: DateTime.DateTime,
603 ) {
604 const next = nextRunAt(task, now);
605 yield* Effect.logInfo("Skipping missed schedule task run", {
606 taskId: task.id,
607 missedRunAt: task.nextRunAt,
608 rescheduledTo: next,
609 });
610 yield* sql`
611 UPDATE scheduled_tasks
612 SET next_run_at = ${next},
613 updated_at = ${iso(now)}
614 WHERE task_id = ${task.id}
615 `.pipe(
616 Effect.mapError((cause) =>
617 taskError("Could not reschedule missed schedule task run.", { taskId: task.id, cause }),
618 ),
619 );
620 yield* notifyChanged;
621 });
622
623 const runDueTasks = Effect.fn("ScheduledTaskService.runDueTasks")(function* () {
624 const now = yield* localNow;
625 const tasks = yield* listDueTasks(now).pipe(
626 Effect.mapError((cause) => taskError("Could not list schedule tasks.", { cause })),
627 );
628 const due = tasks.flatMap((task) =>
629 task.nextRunAt === null ? [] : [{ task, dueAt: DateTime.makeUnsafe(task.nextRunAt) }],
630 );
631 yield* Effect.forEach(
632 due,
633 ({ task, dueAt }) =>
634 (isMissedFixedTimeRun(task.schedule, dueAt, now)
635 ? rescheduleMissedRun(task, now)
636 : runTask(task, "scheduled")
637 ).pipe(
638 Effect.catch((cause) =>
639 Effect.logWarning("Scheduled task run failed", { taskId: task.id, cause }),
640 ),
641 ),
642 { concurrency: 1, discard: true },
643 );
644 });
645
646 // Recover from a crash or hard shutdown mid-run: rows stuck in 'running'
647 // would otherwise be skipped by the due-task filter forever. The dispatch
648 // may already have gone out before the crash, so next_run_at must advance
649 // and run_count must count the attempt — otherwise the first poll after
650 // every restart re-fires the interrupted task (same rationale as
651 // releaseStuckRun). Schedules are JSON, so this is per-row Effect work
652 // rather than a single UPDATE.
653 yield* Effect.gen(function* () {
654 const rows = yield* selectAllRows();
655 const stuck = rows.filter((row) => row.last_run_status === "running");
656 if (stuck.length === 0) return;
657 const now = yield* localNow;
658 yield* Effect.forEach(
659 stuck,
660 (row) =>
661 Effect.gen(function* () {
662 const decoded = yield* Effect.result(decodeRow(row));
663 if (Result.isSuccess(decoded)) {
664 yield* sql`
665 UPDATE scheduled_tasks
666 SET last_run_status = 'failed',
667 last_run_error = 'Run was interrupted by a server restart.',
668 next_run_at = ${nextRunAt(decoded.success, now)},
669 updated_at = ${iso(now)},
670 run_count = run_count + 1
671 WHERE task_id IS ${row.task_id} AND last_run_status = 'running'
672 `;
673 return;
674 }
675 // The schedule cannot be decoded, so the next occurrence cannot
676 // be computed — still release the row so it is not stuck in
677 // 'running' (the lenient poller skips it, so it cannot re-fire).
678 yield* Effect.logWarning(
679 "Recovering undecodable schedule task row without rescheduling",
680 { taskId: row.task_id, cause: decoded.failure },
681 );
682 yield* sql`
683 UPDATE scheduled_tasks
684 SET last_run_status = 'failed',
685 last_run_error = 'Run was interrupted by a server restart.',
686 updated_at = ${iso(now)},
687 run_count = run_count + 1
688 WHERE task_id IS ${row.task_id} AND last_run_status = 'running'
689 `;
690 }),
691 { concurrency: 1, discard: true },
692 );
693 yield* notifyChanged;
694 }).pipe(
695 Effect.catch((cause) =>
696 Effect.logWarning("Could not reset interrupted schedule task runs", { cause }),
697 ),
698 );
699
700 yield* scheduler.register("scheduled-tasks", runDueTasks());
701
702 const list: ScheduledTaskService["Service"]["list"] = () =>
703 listRows().pipe(
704 Effect.map((tasks) => ({ tasks })),
705 Effect.mapError((cause) => taskError("Could not list schedule tasks.", { cause })),
706 );
707
708 const subscribeList: ScheduledTaskService["Service"]["subscribeList"] = () =>
709 Stream.unwrap(
710 Effect.gen(function* () {
711 // Subscribe before taking the snapshot so a change landing between
712 // the two is buffered by the subscription rather than dropped.
713 const subscription = yield* PubSub.subscribe(changesPubSub);
714 return Stream.concat(
715 Stream.fromEffect(list()),
716 Stream.fromSubscription(subscription).pipe(Stream.mapEffect(() => list())),
717 );
718 }),
719 );
720
721 const upsert: ScheduledTaskService["Service"]["upsert"] = (input) =>
722 Effect.gen(function* () {
723 const now = yield* localNow;
724 const uuid =
725 input.commandId === undefined
726 ? yield* crypto.randomUUIDv4.pipe(
727 Effect.mapError((cause) =>
728 taskError("Could not generate schedule task id.", { cause }),
729 ),
730 )
731 : null;
732 const id =
733 input.id ??
734 ScheduledTaskId.make(
735 input.commandId ? `scheduled-task:${input.commandId}` : `scheduled-task:${uuid}`,
736 );
737 // Look up by the *resolved* id so idempotent creates (commandId replays)
738 // keep their run history, and so real load failures propagate instead
739 // of silently resetting an existing row.
740 const existingTask = yield* findTask(id);
741 // Keep the existing next_run_at when the schedule itself is untouched:
742 // editing a title or prompt must not postpone (or resurrect) a due
743 // run — only schedule/enabled changes restart the clock.
744 const scheduleUnchanged =
745 existingTask !== null &&
746 existingTask.enabled === input.enabled &&
747 isSameSchedule(existingTask.schedule, input.schedule);
748 const task: ScheduledTask = {
749 id,
750 title: input.title,
751 prompt: input.prompt,
752 enabled: input.enabled,
753 schedule: input.schedule,
754 projectId: input.projectId,
755 threadId: input.threadId ?? null,
756 workspaceStrategy: input.workspaceStrategy,
757 modelSelection: input.modelSelection,
758 runtimeMode: input.runtimeMode,
759 interactionMode: input.interactionMode,
760 createdBy: existingTask?.createdBy ?? input.createdBy ?? "user",
761 creationSource: input.creationSource ?? "web",
762 createdAt: existingTask?.createdAt ?? iso(now),
763 updatedAt: iso(now),
764 nextRunAt: scheduleUnchanged
765 ? existingTask.nextRunAt
766 : nextRunAt({ enabled: input.enabled, schedule: input.schedule }, now),
767 lastRunAt: existingTask?.lastRunAt ?? null,
768 lastRunStatus: existingTask?.lastRunStatus ?? "never",
769 lastRunError: existingTask?.lastRunError ?? null,
770 runCount: existingTask?.runCount ?? 0,
771 };
772 yield* saveTask(task, input.requireExisting === true);
773 yield* notifyChanged;
774 return { task };
775 });
776
777 const setEnabled: ScheduledTaskService["Service"]["setEnabled"] = (input) =>
778 Effect.gen(function* () {
779 const existing = yield* loadTask(input.id);
780 if (existing.enabled === input.enabled) return { task: existing };
781 const now = yield* localNow;
782 const next = nextRunAt({ enabled: input.enabled, schedule: existing.schedule }, now);
783 // RETURNING so a task deleted between the load and this UPDATE is a
784 // visible not-found error, not a false success.
785 const updated = yield* sql<{ task_id: string }>`
786 UPDATE scheduled_tasks
787 SET enabled = ${input.enabled ? 1 : 0},
788 next_run_at = ${next},
789 updated_at = ${iso(now)}
790 WHERE task_id = ${input.id}
791 RETURNING task_id
792 `.pipe(
793 Effect.mapError((cause) =>
794 taskError("Could not update schedule task.", { taskId: input.id, cause }),
795 ),
796 );
797 if (updated.length === 0) {
798 return yield* taskError("Schedule task not found.", { taskId: input.id });
799 }
800 yield* notifyChanged;
801 return {
802 task: { ...existing, enabled: input.enabled, nextRunAt: next, updatedAt: iso(now) },
803 };
804 });
805
806 const deleteTask: ScheduledTaskService["Service"]["delete"] = (input) =>
807 deleteRow(input.id).pipe(Effect.andThen(notifyChanged), Effect.as({ id: input.id }));
808
809 const runNow: ScheduledTaskService["Service"]["runNow"] = (input: ScheduledTaskRunNowInput) =>
810 Effect.gen(function* () {
811 const task = yield* loadTask(input.id);
812 const next = yield* runTask(task, "manual").pipe(
813 Effect.mapError((cause) =>
814 taskError("Could not run schedule task.", { taskId: input.id, cause }),
815 ),
816 );
817 return { task: next };
818 });
819
820 return ScheduledTaskService.of({
821 list,
822 subscribeList,
823 upsert,
824 setEnabled,
825 delete: deleteTask,
826 runNow,
827 });
828 }),
829);