// Scheduled jobs on disk (lab 09): /jobs.json, replaced atomically on every change. // // A job has a schedule (cron, or a one-off "at" time), a prompt, and bookkeeping: when it runs // next, when it last ran, and how that went. Jobs come from two places: your config // (createdBy "owner") and the assistant's schedule_task tool (createdBy "assistant"). import { readFile } from 'node:fs/promises'; import path from 'node:path'; import { Mutex, writeFileAtomic } from '../runtime/atomic.ts'; import type { JobConfig } from '../config/config.ts'; import { nextRun, parseCron } from './cron.ts'; export interface Job { id: string; cron?: string; at?: string; prompt: string; enabled: boolean; createdBy: 'owner' | 'assistant'; createdAt: string; /** ISO time of the next run; absent when the job will not run again. */ nextRun?: string; lastRun?: string; lastStatus?: string; } export class JobStore { readonly file: string; /** Read-modify-write updates run one at a time (a job finishing while the assistant schedules). */ private readonly lock = new Mutex(); constructor(dataDir: string) { this.file = path.join(dataDir, 'jobs.json'); } async list(): Promise { try { const parsed = JSON.parse(await readFile(this.file, 'utf8')) as { jobs?: Job[] }; return parsed.jobs ?? []; } catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []; throw err; } } async save(jobs: readonly Job[]): Promise { await this.lock.run(() => this.write(jobs)); } private async write(jobs: readonly Job[]): Promise { await writeFileAtomic(this.file, JSON.stringify({ jobs }, null, 2) + '\n'); } async get(id: string): Promise { return (await this.list()).find((job) => job.id === id); } /** Adds or replaces a job by id. */ async put(job: Job): Promise { await this.lock.run(async () => { const jobs = (await this.list()).filter((j) => j.id !== job.id); await this.write([...jobs, job]); }); } async remove(id: string): Promise { return this.lock.run(async () => { const jobs = await this.list(); const kept = jobs.filter((j) => j.id !== id); if (kept.length === jobs.length) return false; await this.write(kept); return true; }); } /** * Makes the owner's jobs from config match the store: adds new ones, updates changed ones, * removes owner jobs no longer in config. Assistant-created jobs are left alone. */ async syncOwnerJobs( configured: readonly JobConfig[], now: Date, timezone: string, ): Promise { await this.lock.run(() => this.sync(configured, now, timezone)); } private async sync(configured: readonly JobConfig[], now: Date, timezone: string): Promise { const jobs = await this.list(); const assistantJobs = jobs.filter((j) => j.createdBy === 'assistant'); const ownerJobs = configured.map((c): Job => { const existing = jobs.find((j) => j.id === c.id && j.createdBy === 'owner'); const same = existing && existing.cron === c.cron && existing.at === c.at; return { id: c.id, ...(c.cron ? { cron: c.cron } : {}), ...(c.at ? { at: c.at } : {}), prompt: c.prompt, enabled: c.enabled, createdBy: 'owner', createdAt: existing?.createdAt ?? now.toISOString(), ...(same && existing?.lastRun ? { lastRun: existing.lastRun } : {}), ...(same && existing?.lastStatus ? { lastStatus: existing.lastStatus } : {}), ...(same && existing?.nextRun ? { nextRun: existing.nextRun } : firstRun(c, now, timezone)), }; }); await this.write([...ownerJobs, ...assistantJobs]); } } /** The first run time of a new job, as a partial Job. */ export function firstRun( job: Pick, now: Date, timezone: string, ): Pick { if (job.at) { const at = new Date(job.at); if (Number.isNaN(at.getTime())) throw new Error(`not a valid time: ${job.at}`); return { nextRun: at.toISOString() }; } const next = nextRun(parseCron(job.cron ?? ''), now, timezone); return next ? { nextRun: next.toISOString() } : {}; }