import { afterEach, beforeEach, expect, test } from 'bun:test'; import { mkdtemp, readFile, writeFile, rm, mkdir, appendFile, utimes } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { createTask, upsertTask, listTasks, cronDataRoot, recentRuns, appendRun, markRunsRead, getTask, } from '../src/store.js'; import { createCronFromDraft, draftCronFromText, updateCronFromPatch } from '../src/service.js'; import { nextScheduleRunMs, latestScheduleRunMs } from '../src/scheduleEngine.js'; import { Scheduler, boundedWakeDelay } from '../src/scheduler.js'; import { enqueueRun, requestStop } from '../src/requests.js'; import { tryAcquireSchedulerLock, releaseSchedulerLock } from '../src/lock.js'; let root: string; let oldHome: string | undefined; let oldOverride: string | undefined; const schedulers: Scheduler[] = []; beforeEach(async () => { oldHome = process.env.MINIMAL_AGENT_HOME; oldOverride = process.env.MINIMAL_AGENT_CRON_RUNNER_HOME; root = await mkdtemp(join(tmpdir(), 'cron-reliability-')); process.env.MINIMAL_AGENT_HOME = root; delete process.env.MINIMAL_AGENT_CRON_RUNNER_HOME; }); afterEach(async () => { for (const s of schedulers.splice(0)) await s.stop(); await rm(root, { recursive: true, force: true }); if (oldHome === undefined) delete process.env.MINIMAL_AGENT_HOME; else process.env.MINIMAL_AGENT_HOME = oldHome; if (oldOverride === undefined) delete process.env.MINIMAL_AGENT_CRON_RUNNER_HOME; else process.env.MINIMAL_AGENT_CRON_RUNNER_HOME = oldOverride; }); const provider = { name: 'test', baseURL: 'https://example.invalid', apiKey: 'test', model: 'test', contextWindow: 128000, }; const task = () => createTask({ name: 'test', intervalMs: 60000, timezone: 'UTC', cwd: root, sessionMode: 'fresh', action: { type: 'prompt', prompt: 'test' }, }); async function until(check: () => Promise) { const end = Date.now() + 4000; while (!(await check())) { if (Date.now() > end) throw new Error('condition timeout'); await Bun.sleep(10); } } test('portable root and corrupt tasks never silently become an empty collection', async () => { expect(cronDataRoot()).toBe(join(root, '.minimal-agent', 'plugins', 'cron-runner')); await upsertTask(task()); const file = join(cronDataRoot(), 'tasks.json'); await writeFile(file, '{broken'); await expect(listTasks()).rejects.toThrow('原件未修改'); await expect(upsertTask(task())).rejects.toThrow('原件未修改'); expect(await readFile(file, 'utf8')).toBe('{broken'); }); test('IANA timezone and daylight-saving change the actual UTC slot', () => { const base = Date.parse('2026-09-10T00:00:00Z'); const schedule = { type: 'cron' as const, cron: '0 9 * * *', timezone: 'Asia/Shanghai', human: '', }; expect(nextScheduleRunMs(schedule, base)).toBe(Date.parse('2026-09-10T01:00:00Z')); expect(nextScheduleRunMs({ ...schedule, timezone: 'UTC' }, base)).toBe( Date.parse('2026-09-10T09:00:00Z'), ); expect( nextScheduleRunMs( { ...schedule, timezone: 'America/New_York' }, Date.parse('2026-03-08T00:00:00Z'), ), ).toBe(Date.parse('2026-03-08T13:00:00Z')); expect(latestScheduleRunMs(schedule, Date.parse('2026-09-10T01:00:00Z'))).toBe( Date.parse('2026-09-10T01:00:00Z'), ); expect(boundedWakeDelay(base + 365 * 86400000, base)).toBeLessThanOrEqual(1000); }); test('natural text handles afternoons, glued intervals, tomorrow and raw cron', () => { const ctx = { cwd: root, sessionMode: 'fresh' as const }; expect(draftCronFromText('每天下午3点整理报告', ctx).task?.schedule).toMatchObject({ type: 'cron', cron: '0 15 * * *', }); expect(draftCronFromText('每隔2小时整理报告', ctx).task?.schedule).toMatchObject({ type: 'interval', intervalMs: 7200000, }); expect(draftCronFromText('明天上午9点提醒我', ctx).task?.schedule.type).toBe('once'); expect(draftCronFromText('0 9 * * 1-5 hello', ctx).task?.schedule).toMatchObject({ type: 'cron', cron: '0 9 * * 1-5', }); }); test('CAS conflict and invalid patches leave the task unchanged', async () => { const original = await upsertTask(task()); await updateCronFromPatch({ id: original.id, expectedRevision: 0, name: 'new' }); await expect( updateCronFromPatch({ id: original.id, expectedRevision: 0, name: 'stale' }), ).rejects.toThrow('已被其他操作更新'); await expect( updateCronFromPatch({ id: original.id, schedule: { type: 'interval', intervalMs: -1 } }), ).rejects.toThrow(); expect((await getTask(original.id))?.name).toBe('new'); }); test('cross-process task writers preserve every addition', async () => { const module = new URL('../src/store.ts', import.meta.url).href; const processes = Array.from({ length: 4 }, (_, i) => Bun.spawn( [ process.execPath, '-e', `import {createTask,upsertTask} from ${JSON.stringify(module)}; for(let j=0;j<5;j++) await upsertTask(createTask({name:'worker-${i}-'+j,cron:'0 9 * * *',timezone:'UTC',cwd:${JSON.stringify(root)},sessionMode:'fresh',action:{type:'prompt',prompt:'x'}}));`, ], { env: { ...process.env }, stdout: 'pipe', stderr: 'pipe' }, ), ); for (const p of processes) { expect(await p.exited).toBe(0); expect(await new Response(p.stderr).text()).toBe(''); } expect(await listTasks()).toHaveLength(20); }, 10000); test('truncated log lines do not hide valid runs; read markers cannot regress terminal state', async () => { const t = await upsertTask(task()); const run = await enqueueRun(t, 'a'); await appendRun({ ...run, status: 'running' }); await markRunsRead(t.id); await appendFile(join(cronDataRoot(), 'runs', `${t.id}.jsonl`), '{truncated'); await appendRun({ ...run, status: 'success', result: 'complete result' }); expect((await recentRuns(t.id))[0]).toMatchObject({ status: 'success', result: 'complete result', }); expect((await recentRuns(t.id))[0]?.readAt).toBeUndefined(); await markRunsRead(t.id); expect((await recentRuns(t.id))[0]?.readAt).toBeTruthy(); }); test('standby takes over and durable queued requests run only once', async () => { const t = await upsertTask(task()); let calls = 0; const ctx = { provider, runAgentTurn: async () => { calls++; return { ok: true, result: 'done', numTurns: 1, events: [{ type: 'turn_done', completionStatus: 'completed' }] }; }, }; const first = new Scheduler(ctx); const second = new Scheduler(ctx); schedulers.push(first, second); first.start(); await until(() => first.isActiveScheduler()); second.start(); expect(await second.isActiveScheduler()).toBe(false); await first.stop(); await until(() => second.isActiveScheduler()); const a = await enqueueRun(t, 'same'); const b = await enqueueRun(t, 'same'); expect(a.id).toBe(b.id); second.wake(); await until(async () => (await recentRuns(t.id))[0]?.status === 'success'); expect(calls).toBe(1); }); test('stopping a running task propagates cancellation without disabling its schedule', async () => { const t = await upsertTask(task()); let started = false; const s = new Scheduler({ provider, runAgentTurn: async (opts) => { started = true; await new Promise((resolve) => { if (opts.signal?.aborted) resolve(); else opts.signal?.addEventListener('abort', () => resolve(), { once: true }); }); return { ok: false, result: '', numTurns: 1, events: [] }; }, }); schedulers.push(s); s.start(); await until(() => s.isActiveScheduler()); await enqueueRun(t, 'stop-me'); s.wake(); await until(async () => started); await requestStop(t.id); s.wake(); await until(async () => (await recentRuns(t.id))[0]?.status === 'cancelled'); expect((await getTask(t.id))?.status).toBe('active'); }); test('crash recovery marks started attempts unknown and resumes only queued attempts', async () => { const t = await upsertTask(task()); const old = await enqueueRun(t, 'old'); await appendRun({ ...old, status: 'running', owner: 'dead-process' }); let calls = 0; const s = new Scheduler({ provider, runAgentTurn: async () => { calls++; return { ok: true, result: 'ok', numTurns: 1, events: [{ type: 'turn_done', completionStatus: 'completed' }] }; }, }); schedulers.push(s); s.start(); await until(async () => (await recentRuns(t.id))[0]?.status === 'interrupted'); expect(calls).toBe(0); await enqueueRun(t, 'new'); s.wake(); await until(async () => (await recentRuns(t.id))[0]?.status === 'success'); expect(calls).toBe(1); }); test('fresh sessions differ per run; a future once schedule preserves its date', async () => { const t = await createCronFromDraft({ name: 'once', kind: 'once', status: 'active', schedule: { type: 'once', at: new Date(Date.now() + 86400000).toISOString() }, runtime: { cwd: root, sessionMode: 'fresh' }, action: { type: 'prompt', prompt: 'x' }, }); const a = await enqueueRun(t, 'a'); await appendRun({ ...a, status: 'success' }); const b = await enqueueRun(t, 'b'); expect(a.sessionId).not.toBe(b.sessionId); expect((await getTask(t.id))?.schedule).toMatchObject({ type: 'once', at: (t.schedule as { at: string }).at, }); }); test('corrupt legacy lock and stale lease are recoverable', async () => { const file = join(root, 'scheduler.lock'); await writeFile(file, '{'); await mkdir(`${file}.lease`); const past = new Date(Date.now() - 60000); await utimes(`${file}.lease`, past, past); expect(await tryAcquireSchedulerLock(file, 'owner')).toBe(true); await releaseSchedulerLock(file, 'owner'); }); test('creation request identity is durable and clearing limits works', async () => { const draft = { name: 'idempotent', kind: 'recurring' as const, status: 'active' as const, maxRuns: 2, schedule: { type: 'interval' as const, intervalMs: 60000 }, runtime: { cwd: root, sessionMode: 'fresh' as const, maxTurns: 10 }, action: { type: 'prompt' as const, prompt: 'x' }, }; const [first, second] = await Promise.all([ createCronFromDraft(draft, 'same-request'), createCronFromDraft(draft, 'same-request'), ]); expect(first.id).toBe(second.id); expect(await listTasks()).toHaveLength(1); const cleared = await updateCronFromPatch({ id: first.id, clearMaxRuns: true, clearMaxTurns: true, }); expect(cleared.maxRuns).toBeUndefined(); expect(cleared.runtime.maxTurns).toBeUndefined(); }); test('metadata edits preserve cursors and resuming skips intentionally paused time', async () => { const t = createTask({ name: 'resume', intervalMs: 60000, timezone: 'UTC', cwd: root, sessionMode: 'fresh', action: { type: 'prompt', prompt: 'x' }, }); t.schedule.lastScheduledFor = new Date(Date.now() - 3600000).toISOString(); await upsertTask(t); const edited = await updateCronFromPatch({ id: t.id, name: 'renamed', schedule: { type: 'interval', intervalMs: 60000 }, }); expect(edited.schedule.lastScheduledFor).toBe(t.schedule.lastScheduledFor); await updateCronFromPatch({ id: t.id, status: 'paused' }); const before = Date.now(); const resumed = await updateCronFromPatch({ id: t.id, status: 'active' }); expect(Date.parse(resumed.schedule.lastScheduledFor!)).toBeGreaterThanOrEqual(before); }); test('active one-time schedules reject elapsed dates at creation and reactivation', async () => { const draft = { name: 'past', status: 'active' as const, kind: 'once' as const, schedule: { type: 'once' as const, at: new Date(Date.now() - 60000).toISOString() }, runtime: { cwd: root, sessionMode: 'fresh' as const }, action: { type: 'prompt' as const, prompt: 'x' }, }; await expect(createCronFromDraft(draft)).rejects.toThrow('未来'); const saved = await createCronFromDraft({ ...draft, status: 'paused' }); await expect(updateCronFromPatch({ id: saved.id, status: 'active' })).rejects.toThrow('未来'); expect((await getTask(saved.id))?.status).toBe('paused'); }); test('real scheduled execution reaches Agent, workflow-runner and writes its artifact', async () => { const script = fileURLToPath(new URL('./scheduled-workflow.fixture.ts', import.meta.url)); const process = Bun.spawn([Bun.which('bun')!, script], { cwd: root, env: { ...globalThis.process.env }, stdout: 'pipe', stderr: 'pipe', }); const [code, output, error] = await Promise.all([ process.exited, new Response(process.stdout).text(), new Response(process.stderr).text(), ]); if (code !== 0) throw new Error(`${output}\n${error}`); expect(output).toContain('"passed":true'); }, 20000);