Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"@cloudflare/workers-oauth-provider": "^0.10.3",
"@modelcontextprotocol/hono": "^2.0.0",
"@modelcontextprotocol/server": "^2.0.0",
"cron-parser": "^5.10.1",
"hono": "^4.11.4",
"mustache": "^4.2.0",
"zod": "^4.6.2"
Expand Down
5 changes: 4 additions & 1 deletion packages/app/src/flow-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ export const listEventsSchema = z.object({
const stringRecordSchema = z.record(z.string(), z.string());
export const triggerSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("manual"), config: z.object({}).strict().default({}) }).strict(),
z.object({ kind: z.literal("schedule"), config: z.record(z.string(), z.unknown()) }).strict(),
z.object({ kind: z.literal("schedule"), config: z.object({
cron: z.string().trim().min(1), timezone: z.string().trim().min(1),
context: z.string().max(50_000).optional(), parameters: stringRecordSchema.default({}),
}).strict() }).strict(),
z.object({ kind: z.literal("webhook"), config: z.record(z.string(), z.unknown()) }).strict(),
]);
export const jobInputSchema = z.object({
Expand Down
6 changes: 6 additions & 0 deletions packages/app/src/job-domain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,10 @@ export const JOB_SCHEMA = `
);
CREATE INDEX IF NOT EXISTS job_runs_queue ON job_runs(state, created_at);
CREATE INDEX IF NOT EXISTS job_runs_active ON job_runs(job_id, state);
CREATE TABLE IF NOT EXISTS schedule_state (
trigger_id TEXT PRIMARY KEY REFERENCES triggers(id) ON DELETE CASCADE,
job_id TEXT NOT NULL UNIQUE REFERENCES jobs(id) ON DELETE CASCADE,
next_run_at INTEGER, last_triggered_at TEXT
);
CREATE INDEX IF NOT EXISTS schedules_due ON schedule_state(next_run_at);
`;
28 changes: 28 additions & 0 deletions packages/app/src/schedule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { CronExpressionParser } from "cron-parser";

export interface ScheduleConfig {
cron: string;
timezone: string;
context?: string;
parameters?: Record<string, string>;
}

export function validateScheduleConfig(value: unknown): ScheduleConfig {
const config = value as ScheduleConfig;
if (!config || typeof config.cron !== "string" || typeof config.timezone !== "string") throw new Error("Schedule cron and timezone are required");
try { new Intl.DateTimeFormat("en-US", { timeZone: config.timezone }).format(); }
catch { throw new Error("Schedule timezone must be a valid IANA timezone"); }
try { CronExpressionParser.parse(config.cron, { tz: config.timezone }); }
catch { throw new Error("Schedule cron expression is invalid"); }
return config;
}

/** cron-parser resolves skipped and repeated wall-clock times deterministically in the supplied IANA zone. */
export function nextOccurrence(config: ScheduleConfig, after: Date): Date {
return CronExpressionParser.parse(config.cron, { currentDate: after, tz: config.timezone }).next().toDate();
}

export function catchUpOccurrence(config: ScheduleConfig, nextDue: Date, wakeAt: Date): { occurredAt: Date; nextRunAt: Date } | null {
if (nextDue.getTime() > wakeAt.getTime()) return null;
return { occurredAt: nextDue, nextRunAt: nextOccurrence(config, wakeAt) };
}
56 changes: 53 additions & 3 deletions packages/app/src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { DEFAULT_CONTEXT_TEMPLATE, LinearSourceAdapter, linearTicketPrompt, rend
import { renderSourcePrompt } from "./source-lifecycle";
import { JOB_SCHEMA, renderJobPrompt } from "./job-domain";
import { normalizeExecutionState, type RunHandle } from "./execution";
import { catchUpOccurrence, nextOccurrence, validateScheduleConfig, type ScheduleConfig } from "./schedule";

export { DEFAULT_CONTEXT_TEMPLATE, linearTicketPrompt, renderContextTemplate } from "./linear-source";

Expand Down Expand Up @@ -152,6 +153,7 @@ export class Tenant extends DurableObject<Env> {

async alarm(): Promise<void> {
await this.processGitHubVerifications();
await this.processDueSchedules();
// Release completed slots before looking at the queue, so capacity is used
// immediately rather than waiting for the next polling alarm.
const running = this.rows("SELECT * FROM runs WHERE state IN ('running','blocked','recovering') ORDER BY updated_at LIMIT 40");
Expand All @@ -171,7 +173,9 @@ export class Tenant extends DurableObject<Env> {
const pending = this.one("SELECT count(*) AS count FROM runs WHERE state IN ('queued','starting','running','blocked','recovering')") as Row;
const verification = this.one("SELECT min(next_attempt_at) AS next_attempt_at FROM pending_verifications") as Row;
const nextVerification = Number(verification?.next_attempt_at || 0);
if (Number(pending.count) > 0 || nextVerification) await this.ctx.storage.setAlarm(nextVerification ? Math.min(Date.now() + 15_000, nextVerification) : Date.now() + 15_000);
const schedule = this.one("SELECT min(next_run_at) AS next_run_at FROM schedule_state") as Row;
const candidates = [Number(pending.count) > 0 ? Date.now() + 15_000 : 0, nextVerification, Number(schedule?.next_run_at || 0)].filter(Boolean);
if (candidates.length) await this.ctx.storage.setAlarm(Math.min(...candidates));
}

private async saveLinear(input: unknown): Promise<Response> {
Expand Down Expand Up @@ -296,7 +300,8 @@ export class Tenant extends DurableObject<Env> {
promptTemplate: await decrypt(String(row.encrypted_prompt_template), this.env.CREDENTIAL_ENCRYPTION_KEY),
parameterDefaults, concurrencyLimit: Number(row.concurrency_limit),
executionTargetId: String(executionTarget.connectionId ?? ""),
trigger: { kind: String(trigger?.kind ?? "manual"), config: triggerConfig },
trigger: { kind: String(trigger?.kind ?? "manual"), config: triggerConfig,
...(trigger?.kind === "schedule" ? (() => { const state = this.one("SELECT next_run_at,last_triggered_at FROM schedule_state WHERE job_id=?", row.id) as Row | undefined; return { nextRunAt: state?.next_run_at == null ? null : new Date(Number(state.next_run_at)).toISOString(), lastTriggeredAt: state?.last_triggered_at ?? null }; })() : {}) },
enabled: Boolean(row.enabled), createdAt: row.created_at, updatedAt: row.updated_at,
};
}
Expand All @@ -313,13 +318,26 @@ export class Tenant extends DurableObject<Env> {
if (!input.trigger || !["manual", "schedule", "webhook"].includes(input.trigger.kind)) throw new Error("Job trigger is invalid");
if (Object.prototype.hasOwnProperty.call(input.parameterDefaults ?? {}, "context")) throw new Error("context is reserved and cannot be a job parameter");
Mustache.parse(input.promptTemplate);
if (input.trigger.kind === "schedule") validateScheduleConfig(input.trigger.config);
}

private async resetSchedule(jobId: string): Promise<void> {
const job = this.one("SELECT j.enabled,t.id AS trigger_id,t.kind,t.config FROM jobs j JOIN triggers t ON t.job_id=j.id WHERE j.id=?", jobId) as Row | undefined;
if (!job || job.kind !== "schedule") { this.ctx.storage.sql.exec("DELETE FROM schedule_state WHERE job_id=?", jobId); return; }
const config = validateScheduleConfig(JSON.parse(String(job.config)));
const next = Boolean(job.enabled) ? nextOccurrence(config, new Date()).getTime() : null;
this.ctx.storage.sql.exec("INSERT INTO schedule_state(trigger_id,job_id,next_run_at) VALUES(?,?,?) ON CONFLICT(job_id) DO UPDATE SET trigger_id=excluded.trigger_id,next_run_at=excluded.next_run_at", job.trigger_id, jobId, next);
if (next === null) return;
const alarm = await this.ctx.storage.getAlarm();
if (alarm === null || next < alarm) await this.ctx.storage.setAlarm(next);
}

private async createJob(input: any): Promise<Response> {
this.validateJobInput(input);
const target = await this.jobTarget(input.executionTargetId), jobId = id(), triggerId = id(), timestamp = now();
this.ctx.storage.sql.exec("INSERT INTO jobs VALUES (?,?,?,?,?,?,?,?,?)", jobId, input.name, await encrypt(input.promptTemplate, this.env.CREDENTIAL_ENCRYPTION_KEY), JSON.stringify(input.parameterDefaults ?? {}), JSON.stringify(target), input.concurrencyLimit, 1, timestamp, timestamp);
this.ctx.storage.sql.exec("INSERT INTO triggers VALUES (?,?,?,?,?,?)", triggerId, jobId, input.trigger.kind, JSON.stringify(input.trigger.config ?? {}), timestamp, timestamp);
await this.resetSchedule(jobId);
return json(await this.publicJob(this.one("SELECT * FROM jobs WHERE id = ?", jobId) as Row));
}

Expand All @@ -334,12 +352,14 @@ export class Tenant extends DurableObject<Env> {
const target = await this.jobTarget(input.executionTargetId), timestamp = now();
this.ctx.storage.sql.exec("UPDATE jobs SET name=?,encrypted_prompt_template=?,parameter_defaults=?,execution_target=?,concurrency_limit=?,updated_at=? WHERE id=?", input.name, await encrypt(input.promptTemplate, this.env.CREDENTIAL_ENCRYPTION_KEY), JSON.stringify(input.parameterDefaults ?? {}), JSON.stringify(target), input.concurrencyLimit, timestamp, jobId);
this.ctx.storage.sql.exec("UPDATE triggers SET kind=?,config=?,updated_at=? WHERE job_id=?", input.trigger.kind, JSON.stringify(input.trigger.config ?? {}), timestamp, jobId);
await this.resetSchedule(jobId);
return json(await this.publicJob(this.one("SELECT * FROM jobs WHERE id = ?", jobId) as Row));
}

private setJobEnabled(jobId: string, enabled: boolean): Response {
private async setJobEnabled(jobId: string, enabled: boolean): Promise<Response> {
if (!this.one("SELECT id FROM jobs WHERE id = ?", jobId)) return new Response("Not found", { status: 404 });
this.ctx.storage.sql.exec("UPDATE jobs SET enabled=?,updated_at=? WHERE id=?", enabled ? 1 : 0, now(), jobId);
await this.resetSchedule(jobId);
return json({ id: jobId, enabled });
}

Expand Down Expand Up @@ -376,6 +396,36 @@ export class Tenant extends DurableObject<Env> {
return json({ invocationId, runId, state: "queued", duplicate: false });
}

private async processDueSchedules(): Promise<void> {
const wake = Date.now();
const due = this.rows("SELECT s.job_id,s.next_run_at,t.config FROM schedule_state s JOIN jobs j ON j.id=s.job_id JOIN triggers t ON t.id=s.trigger_id WHERE j.enabled=1 AND t.kind='schedule' AND s.next_run_at<=? ORDER BY s.next_run_at LIMIT 100", wake);
for (const row of due) {
const config = validateScheduleConfig(JSON.parse(String(row.config))) as ScheduleConfig;
const catchUp = catchUpOccurrence(config, new Date(Number(row.next_run_at)), new Date(wake));
if (!catchUp) continue;
const occurredAt = catchUp.occurredAt.toISOString();
await this.enqueueScheduledJob(String(row.job_id), occurredAt, config);
this.ctx.storage.sql.exec("UPDATE schedule_state SET next_run_at=?,last_triggered_at=? WHERE job_id=? AND next_run_at=?", catchUp.nextRunAt.getTime(), occurredAt, row.job_id, row.next_run_at);
}
}

private async enqueueScheduledJob(jobId: string, occurredAt: string, config: ScheduleConfig): Promise<void> {
const row = this.one("SELECT * FROM jobs WHERE id=? AND enabled=1", jobId) as Row | undefined;
if (!row) return;
const claimKey = `schedule:${occurredAt}`;
if (this.one("SELECT id FROM invocations WHERE job_id=? AND claim_key=?", jobId, claimKey)) return;
const job = await this.publicJob(row), parameters = config.parameters ?? {};
const prompt = renderJobPrompt({ promptTemplate: String(job.promptTemplate), parameterDefaults: job.parameterDefaults as Record<string, string> }, { context: config.context, parameters });
const invocationId = id(), runId = id(), timestamp = now(), occurrence = JSON.stringify({ occurredAt });
this.ctx.storage.sql.exec("INSERT OR IGNORE INTO invocations (id,job_id,source,claim_key,context,parameters,occurrence,created_at) VALUES (?,?,?,?,?,?,?,?)", invocationId, jobId, "schedule", claimKey, config.context ?? null, JSON.stringify(parameters), occurrence, timestamp);
const winner = this.one("SELECT id FROM invocations WHERE job_id=? AND claim_key=?", jobId, claimKey) as Row;
if (winner.id !== invocationId) return;
const encryptedPrompt = await encrypt(prompt, this.env.CREDENTIAL_ENCRYPTION_KEY);
this.ctx.storage.sql.exec("INSERT INTO job_runs (id,job_id,invocation_id,state,encrypted_prompt,created_at,updated_at) VALUES (?,?,?,?,?,?,?)", runId, jobId, invocationId, "queued", encryptedPrompt, timestamp, timestamp);
let target: Record<string, unknown> = {}; try { target = JSON.parse(String(row.execution_target)); } catch {}
this.ctx.storage.sql.exec("INSERT INTO runs (id,pipe_id,issue_id,issue_title,issue_url,claim_key,agent_name,workspace_name,agent_kind,state,prompt,prompt_delivery_state,provider,execution_backend_kind,execution_capabilities,destination_url,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", runId, jobId, invocationId, String(row.name), null, claimKey, `factorize-${runId}`, String(target.workspace ?? ""), String(target.agentKind ?? ""), "queued", encryptedPrompt, "pending", "schedule", "exe-herdr", JSON.stringify(["output", "prompt-delivery", "recovery", "stop"]), "https://exe.dev/", timestamp, timestamp);
}

private deletePipe(pipeId: string): Response {
if (!pipeId || !this.one("SELECT id FROM pipes WHERE id = ?", pipeId)) return new Response("Not found", { status: 404 });
this.ctx.storage.sql.exec("DELETE FROM active_claims WHERE pipe_id = ?", pipeId);
Expand Down
2 changes: 1 addition & 1 deletion packages/app/test/flow-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ describe("shared API schemas", () => {
});

it("validates job configuration and reserved invocation context", () => {
const job = jobInputSchema.parse({ name: "Deploy", promptTemplate: "Deploy {{environment}}: {{context}}", parameterDefaults: { environment: "staging" }, concurrencyLimit: 2, executionTargetId: "exe-1", trigger: { kind: "schedule", config: { cron: "0 * * * *" } } });
const job = jobInputSchema.parse({ name: "Deploy", promptTemplate: "Deploy {{environment}}: {{context}}", parameterDefaults: { environment: "staging" }, concurrencyLimit: 2, executionTargetId: "exe-1", trigger: { kind: "schedule", config: { cron: "0 * * * *", timezone: "UTC" } } });
expect(job.trigger.kind).toBe("schedule");
expect(() => jobInputSchema.parse({ ...job, apiToken: "secret" })).toThrow();
expect(() => jobInputSchema.parse({ ...job, parameterDefaults: { context: "wrong" } })).toThrow();
Expand Down
1 change: 1 addition & 0 deletions packages/app/test/job-domain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ describe("job invocation domain", () => {
it("defines exactly one trigger per job and durable claims in the clean schema", () => {
expect(JOB_SCHEMA).toContain("job_id TEXT NOT NULL UNIQUE");
expect(JOB_SCHEMA).toContain("UNIQUE(job_id, claim_key)");
expect(JOB_SCHEMA).toContain("CREATE TABLE IF NOT EXISTS schedule_state");
expect(JOB_SCHEMA).not.toContain("pipes");
});
});
28 changes: 28 additions & 0 deletions packages/app/test/schedule.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import { catchUpOccurrence, nextOccurrence, validateScheduleConfig } from "../src/schedule";

describe("durable schedules", () => {
it("calculates occurrences in the configured IANA timezone", () => {
const config = validateScheduleConfig({ cron: "0 9 * * *", timezone: "America/New_York" });
expect(nextOccurrence(config, new Date("2026-01-15T00:00:00Z")).toISOString()).toBe("2026-01-15T14:00:00.000Z");
expect(nextOccurrence(config, new Date("2026-07-15T00:00:00Z")).toISOString()).toBe("2026-07-15T13:00:00.000Z");
});

it("handles spring-forward and fall-back deterministically", () => {
const config = validateScheduleConfig({ cron: "30 2 * * *", timezone: "America/New_York" });
expect(nextOccurrence(config, new Date("2026-03-08T00:00:00Z")).toISOString()).toBe("2026-03-08T07:30:00.000Z");
expect(nextOccurrence(config, new Date("2026-11-01T00:00:00Z")).toISOString()).toBe("2026-11-01T07:30:00.000Z");
});

it("rejects invalid cron and timezone values", () => {
expect(() => validateScheduleConfig({ cron: "nope", timezone: "UTC" })).toThrow(/cron/);
expect(() => validateScheduleConfig({ cron: "0 * * * *", timezone: "Mars/Olympus" })).toThrow(/IANA/);
});

it("coalesces any number of missed intervals into one catch-up", () => {
const config = validateScheduleConfig({ cron: "*/5 * * * *", timezone: "UTC" });
const result = catchUpOccurrence(config, new Date("2026-09-16T10:00:00Z"), new Date("2026-09-16T11:02:00Z"));
expect(result?.occurredAt.toISOString()).toBe("2026-09-16T10:00:00.000Z");
expect(result?.nextRunAt.toISOString()).toBe("2026-09-16T11:05:00.000Z");
});
});