From dcfb461f213c7902e0c0b9b587c6889ce6e44095 Mon Sep 17 00:00:00 2001 From: Brendan Date: Wed, 16 Sep 2026 19:50:14 +0000 Subject: [PATCH] GEN-2008 support multiple job triggers --- docs/execution-boundaries.md | 12 +- packages/app/src/flow-schemas.ts | 10 +- packages/app/src/flow-service.ts | 8 +- packages/app/src/job-domain.ts | 30 ++-- packages/app/src/protected-api.ts | 4 +- packages/app/src/tenant.ts | 191 +++++++++++++++++++------ packages/app/src/ui.ts | 14 +- packages/app/test/flow-service.test.ts | 6 +- packages/app/test/job-domain.test.ts | 9 +- 9 files changed, 203 insertions(+), 81 deletions(-) diff --git a/docs/execution-boundaries.md b/docs/execution-boundaries.md index bcc75594..03040314 100644 --- a/docs/execution-boundaries.md +++ b/docs/execution-boundaries.md @@ -36,16 +36,20 @@ state and request/response receipt. ## Job invocation boundary A `Job` owns a Mustache prompt template, string parameter defaults, an execution -target, a positive concurrency limit, enabled state, and exactly one `Trigger`. -Triggers have one of three domain kinds: `manual`, `schedule`, or `webhook`. +target, a positive concurrency limit, enabled state, and a collection of +`Trigger` records. Stored triggers are `schedule`, `webhook`, or `jobLifecycle`; +manual invocation is an operation available to every enabled Job. Trigger adapters do only source-specific authentication and normalization. They then call the same `InvocationService.invoke(jobId, request)` operation. Its canonical request carries the source, optional reserved `context`, string parameter overrides, a durable claim key, and optional occurrence metadata. The invocation boundary validates and renders the prompt, applies defaults, -encrypts the rendered prompt, and atomically persists an `Invocation` plus its -queued `JobRun`. The `(job_id, claim_key)` constraint makes retries idempotent. +encrypts the rendered prompt, and persists the durable occurrence claim. An +automatic signal creates a queued `JobRun` only when the Job has no pending or +active automatic run; otherwise it marks one bounded trailing wake. The +`(job_id, claim_key)` constraint keeps every source retry idempotent and +lifecycle delivery also claims `(trigger_id, source_run_id, terminal_state)`. Queue consumers call `startIfCapacity`; concurrency is counted by job, never by trigger source. Provider adapters must not render prompts, insert runs, claim diff --git a/packages/app/src/flow-schemas.ts b/packages/app/src/flow-schemas.ts index 3f75f271..4432da21 100644 --- a/packages/app/src/flow-schemas.ts +++ b/packages/app/src/flow-schemas.ts @@ -42,12 +42,14 @@ export const webhookTriggerConfigSchema = z.discriminatedUnion("provider", [ webhookCommonSchema.extend({ provider: z.literal("custom"), secret: z.string().min(16).optional() }).strict(), ]); 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.object({ + z.object({ id: z.string().min(1).optional(), kind: z.literal("schedule"), enabled: z.boolean().default(true), 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: webhookTriggerConfigSchema }).strict(), + z.object({ id: z.string().min(1).optional(), kind: z.literal("webhook"), enabled: z.boolean().default(true), config: webhookTriggerConfigSchema }).strict(), + z.object({ id: z.string().min(1).optional(), kind: z.literal("jobLifecycle"), enabled: z.boolean().default(true), config: z.object({ + sourceJobIds: z.array(z.string().min(1)).min(1), states: z.array(z.enum(["succeeded", "failed", "stopped"])).min(1), + }).strict() }).strict(), ]); export const jobInputSchema = z.object({ name: z.string().trim().min(1).max(120), @@ -55,7 +57,7 @@ export const jobInputSchema = z.object({ parameterDefaults: stringRecordSchema.default({}), concurrencyLimit: z.number().int().min(1).max(50).default(1), executionTargetId: z.string().min(1), - trigger: triggerSchema, + triggers: z.array(triggerSchema).max(50).default([]), }).strict().superRefine((value, ctx) => { if (Object.prototype.hasOwnProperty.call(value.parameterDefaults, "context")) ctx.addIssue({ code: "custom", path: ["parameterDefaults", "context"], message: "context is reserved" }); }); diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index f7df7a84..774399c3 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -50,9 +50,11 @@ export class FlowService { } private publicJob(value: any) { - const provider = value?.trigger?.kind === "webhook" ? value.trigger.config?.provider : undefined; - if (provider === "cloudflareTail") value.trigger.config.destination = `${this.env.APP_ORIGIN}/webhooks/cloudflare/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(value.id)}`; - if (provider === "custom") value.trigger.config.destination = `${this.env.APP_ORIGIN}/webhooks/custom/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(value.id)}`; + for (const trigger of value?.triggers ?? []) { + const provider = trigger.kind === "webhook" ? trigger.config?.provider : undefined; + if (provider === "cloudflareTail") trigger.config.destination = `${this.env.APP_ORIGIN}/webhooks/cloudflare/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(value.id)}`; + if (provider === "custom") trigger.config.destination = `${this.env.APP_ORIGIN}/webhooks/custom/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(value.id)}`; + } return value; } diff --git a/packages/app/src/job-domain.ts b/packages/app/src/job-domain.ts index a567ca25..1f471b8f 100644 --- a/packages/app/src/job-domain.ts +++ b/packages/app/src/job-domain.ts @@ -1,8 +1,8 @@ import Mustache from "mustache"; -export type TriggerKind = "manual" | "schedule" | "webhook"; -export type InvocationSource = TriggerKind; -export type JobRunState = "queued" | "running" | "succeeded" | "failed" | "cancelled"; +export type TriggerKind = "schedule" | "webhook" | "jobLifecycle"; +export type InvocationSource = "manual" | TriggerKind; +export type JobRunState = "queued" | "running" | "succeeded" | "failed" | "stopped"; export interface ExecutionTarget { connectionId: string; @@ -15,6 +15,7 @@ export interface Trigger { id: string; jobId: string; kind: TriggerKind; + enabled: boolean; config: Record; createdAt: string; updatedAt: string; @@ -28,7 +29,7 @@ export interface Job { executionTarget: ExecutionTarget; concurrencyLimit: number; enabled: boolean; - trigger: Trigger; + triggers: Trigger[]; createdAt: string; updatedAt: string; } @@ -112,7 +113,7 @@ export class InvocationService { async invoke(jobId: string, input: InvocationRequest): Promise { if (!input.claimKey?.trim()) throw new InvocationError("invalid_invocation", "An invocation claim key is required."); - if (!(["manual", "schedule", "webhook"] as const).includes(input.source)) throw new InvocationError("invalid_invocation", "Invocation source is invalid."); + if (!(["manual", "schedule", "webhook", "jobLifecycle"] as const).includes(input.source)) throw new InvocationError("invalid_invocation", "Invocation source is invalid."); const job = await this.repository.getJob(jobId); if (!job) throw new InvocationError("job_not_found", "Job not found."); if (!job.enabled) throw new InvocationError("job_disabled", "Job is disabled."); @@ -149,20 +150,20 @@ export const JOB_SCHEMA = ` created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS triggers ( - id TEXT PRIMARY KEY, job_id TEXT NOT NULL UNIQUE REFERENCES jobs(id) ON DELETE CASCADE, - kind TEXT NOT NULL CHECK (kind IN ('manual','schedule','webhook')), config TEXT NOT NULL, + id TEXT PRIMARY KEY, job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE, + kind TEXT NOT NULL CHECK (kind IN ('schedule','webhook','jobLifecycle')), enabled INTEGER NOT NULL DEFAULT 1, config TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS invocations ( id TEXT PRIMARY KEY, job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE, - source TEXT NOT NULL CHECK (source IN ('manual','schedule','webhook')), claim_key TEXT NOT NULL, + source TEXT NOT NULL CHECK (source IN ('manual','schedule','webhook','jobLifecycle')), claim_key TEXT NOT NULL, context TEXT, parameters TEXT NOT NULL, occurrence TEXT, created_at TEXT NOT NULL, UNIQUE(job_id, claim_key) ); CREATE TABLE IF NOT EXISTS job_runs ( id TEXT PRIMARY KEY, job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE, invocation_id TEXT NOT NULL UNIQUE REFERENCES invocations(id) ON DELETE CASCADE, - state TEXT NOT NULL CHECK (state IN ('queued','running','succeeded','failed','cancelled')), + state TEXT NOT NULL CHECK (state IN ('queued','running','succeeded','failed','stopped')), encrypted_prompt TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, started_at TEXT ); CREATE INDEX IF NOT EXISTS job_runs_queue ON job_runs(state, created_at); @@ -175,8 +176,17 @@ export const JOB_SCHEMA = ` CREATE INDEX IF NOT EXISTS job_events_by_job ON job_events(job_id, received_at DESC); 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, + job_id TEXT NOT NULL 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); + CREATE TABLE IF NOT EXISTS automatic_wakes ( + job_id TEXT PRIMARY KEY REFERENCES jobs(id) ON DELETE CASCADE, + trailing INTEGER NOT NULL DEFAULT 0, summary TEXT NOT NULL DEFAULT '{}', updated_at TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS lifecycle_deliveries ( + trigger_id TEXT NOT NULL REFERENCES triggers(id) ON DELETE CASCADE, + source_run_id TEXT NOT NULL, terminal_state TEXT NOT NULL, created_at TEXT NOT NULL, + PRIMARY KEY(trigger_id,source_run_id,terminal_state) + ); `; diff --git a/packages/app/src/protected-api.ts b/packages/app/src/protected-api.ts index d233b82e..35f6d1f3 100644 --- a/packages/app/src/protected-api.ts +++ b/packages/app/src/protected-api.ts @@ -85,7 +85,7 @@ export class ProtectedApiHandler extends WorkerEntrypoint { tool("list_projects", "List Linear projects", z.object({}), () => service.listProjects()); tool("list_flow_options", "List match-rule options", z.object({}), () => service.listFlowOptions()); tool("list_exe_connections", "List safe metadata for saved exe.dev connections. Select a connectionId before creating or updating a flow; API tokens are never returned.", z.object({}), () => service.listExeConnections()); - tool("list_runs", "List and filter job runs by job ID, state, and an optional case-insensitive literal substring of the exact triggered context. Context matches include only a bounded excerpt.", listRunsSchema, (input: any) => service.listRuns(queryOf(input))); + tool("list_runs", "List authoritative job runs by job ID, state, and an optional case-insensitive literal substring of triggered context. Automatic webhook, schedule, and lifecycle signals coalesce, so query runs and the provider API for authoritative work. Context matches include only a bounded excerpt.", listRunsSchema, (input: any) => service.listRuns(queryOf(input))); tool("get_run", "Get a run with its full triggered context, invocation metadata, execution metadata, output, and activity", runIdSchema, ({ runId }: any) => service.getRun(runId)); tool("list_flow_events", "List webhook activity for a flow", listEventsSchema, (input: any) => service.listFlowEvents(queryOf(input))); tool("stop_run", "Stop an active run", runIdSchema, ({ runId }: any) => service.stopRun(runId)); @@ -96,7 +96,7 @@ export class ProtectedApiHandler extends WorkerEntrypoint { tool("delete_job", "Delete a job and its queued invocation history", jobIdSchema, ({ jobId }: any) => service.deleteJob(jobId)); tool("enable_job", "Enable a job", jobIdSchema, ({ jobId }: any) => service.setJobEnabled(jobId, true)); tool("disable_job", "Disable a job", jobIdSchema, ({ jobId }: any) => service.setJobEnabled(jobId, false)); - tool("invoke_job", "Manually invoke any enabled job, overriding string parameters and optional reserved context", manualInvocationSchema.extend({ jobId: z.string().min(1) }), ({ jobId, ...input }: any) => service.invokeJob(jobId, input)); + tool("invoke_job", "Explicitly invoke any enabled job, overriding string parameters and optional reserved context. Manual invocations are never coalesced with automatic wakes.", manualInvocationSchema.extend({ jobId: z.string().min(1) }), ({ jobId, ...input }: any) => service.invokeJob(jobId, input)); tool("list_job_webhook_activity", "List matching, rejected, duplicate, and accepted webhook activity for a job", z.object({ jobId: z.string().min(1), limit: z.number().int().min(1).max(100).default(50) }), ({ jobId, limit }: any) => service.listJobEvents(jobId, limit)); tool("list_execution_targets", "List non-secret execution target metadata and capabilities", z.object({}), () => service.listExecutionTargets()); const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined }); diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index 680a2899..d5ef68e1 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -90,6 +90,37 @@ export class Tenant extends DurableObject { this.ensureColumn("runs", "destination_url", "TEXT"); for (const [column, definition] of Object.entries({ herdr_server_namespace: "TEXT NOT NULL DEFAULT 'default'", worktree_path: "TEXT", ownership_lease: "TEXT", ownership_generation: "INTEGER NOT NULL DEFAULT 0", agent_session_generation: "INTEGER NOT NULL DEFAULT 0", output_captured: "INTEGER NOT NULL DEFAULT 0", claim_released: "INTEGER NOT NULL DEFAULT 0", pane_collected: "INTEGER NOT NULL DEFAULT 0", worktree_disposition: "TEXT" })) this.ensureColumn("runs", column, definition); for (const [column, definition] of Object.entries({ herdr_workspace_id: "TEXT", herdr_pane_id: "TEXT", herdr_terminal_id: "TEXT", agent_session_source: "TEXT", agent_session_kind: "TEXT", agent_session_value: "TEXT", herdr_cwd: "TEXT", last_agent_status: "TEXT", recovery_attempt: "INTEGER NOT NULL DEFAULT 0", recovery_reason: "TEXT", recovery_started_at: "TEXT", recovery_last_action: "TEXT", recovery_next_at: "INTEGER", recovery_comment_started: "INTEGER NOT NULL DEFAULT 0", recovery_comment_finished: "INTEGER NOT NULL DEFAULT 0", prompt_accepted: "INTEGER NOT NULL DEFAULT 0", recovery_prompt_attempted: "INTEGER NOT NULL DEFAULT 0", recovery_prompt_accepted: "INTEGER NOT NULL DEFAULT 0" })) this.ensureColumn("runs", column, definition); + this.migrateSingularJobTriggers(); + } + + /** Rebuild v1 Job tables because SQLite cannot drop UNIQUE/CHECK constraints in place. */ + private migrateSingularJobTriggers(): void { + const table = this.one("SELECT sql FROM sqlite_master WHERE type='table' AND name='triggers'") as Row | undefined; + if (!String(table?.sql ?? "").includes("job_id TEXT NOT NULL UNIQUE")) return; + this.ctx.storage.sql.exec(` + DROP TABLE IF EXISTS lifecycle_deliveries; + DROP TABLE IF EXISTS automatic_wakes; + ALTER TABLE schedule_state RENAME TO schedule_state_v1; + ALTER TABLE job_runs RENAME TO job_runs_v1; + ALTER TABLE invocations RENAME TO invocations_v1; + ALTER TABLE triggers RENAME TO triggers_v1; + ${JOB_SCHEMA} + INSERT INTO triggers(id,job_id,kind,enabled,config,created_at,updated_at) + SELECT id,job_id,kind,1,config,created_at,updated_at FROM triggers_v1 WHERE kind IN ('schedule','webhook'); + INSERT INTO invocations(id,job_id,source,claim_key,context,parameters,occurrence,created_at) + SELECT id,job_id,source,claim_key,context,parameters,occurrence,created_at FROM invocations_v1; + INSERT INTO job_runs(id,job_id,invocation_id,state,encrypted_prompt,created_at,updated_at,started_at) + SELECT id,job_id,invocation_id,CASE state WHEN 'cancelled' THEN 'stopped' ELSE state END,encrypted_prompt,created_at,updated_at,started_at FROM job_runs_v1; + INSERT INTO schedule_state(trigger_id,job_id,next_run_at,last_triggered_at) + SELECT s.trigger_id,s.job_id,s.next_run_at,s.last_triggered_at FROM schedule_state_v1 s JOIN triggers t ON t.id=s.trigger_id; + DROP TABLE schedule_state_v1; + DROP TABLE job_runs_v1; + DROP TABLE invocations_v1; + DROP TABLE triggers_v1; + 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 INDEX IF NOT EXISTS schedules_due ON schedule_state(next_run_at); + `); } async fetch(request: Request): Promise { @@ -305,7 +336,7 @@ export class Tenant extends DurableObject { })), ...ampConnections.map(connection => ({ id: `amp:${connection.connectionId}`, kind: "amp", name: `Amp · ${connection.project}`, workspace: connection.project, cwd: "Cloud orb", agentKind: "Amp", capabilities: ["stop"] }))]); } - private triggerFor(jobId: unknown): Row | undefined { return this.one("SELECT * FROM triggers WHERE job_id = ?", jobId) as Row | undefined; } + private triggersFor(jobId: unknown): Row[] { return this.rows("SELECT * FROM triggers WHERE job_id = ? ORDER BY created_at,id", jobId); } private executionConfig(value: unknown): Row | undefined { const pipe = this.one("SELECT * FROM pipes WHERE id = ?", value) as Row | undefined; @@ -318,23 +349,26 @@ export class Tenant extends DurableObject { } private async publicJob(row: Row): Promise> { - const trigger = this.triggerFor(row.id); - let parameterDefaults: Record = {}, executionTarget: Record = {}, triggerConfig: Record = {}; + const triggers = this.triggersFor(row.id); + let parameterDefaults: Record = {}, executionTarget: Record = {}; try { parameterDefaults = JSON.parse(String(row.parameter_defaults)); } catch { /* malformed internal state is presented safely */ } try { executionTarget = JSON.parse(String(row.execution_target)); } catch { /* malformed internal state is presented safely */ } - try { triggerConfig = JSON.parse(String(trigger?.config ?? "{}")); } catch { /* malformed internal state is presented safely */ } - if (trigger?.kind === "webhook") { - const rawConfig = triggerConfig as WebhookTriggerConfig; - triggerConfig = publicWebhookConfig(rawConfig); - } const activity = this.one("SELECT count(*) AS count,max(received_at) AS last_received_at FROM job_events WHERE job_id=?", row.id) as Row | undefined; + const publicTriggers = triggers.map(trigger => { + let config: Record = {}; + try { config = JSON.parse(String(trigger.config)); } catch { /* present malformed state safely */ } + if (trigger.kind === "webhook") config = publicWebhookConfig(config as WebhookTriggerConfig); + const runtime = trigger.kind === "schedule" ? this.one("SELECT next_run_at,last_triggered_at FROM schedule_state WHERE trigger_id=?", trigger.id) as Row | undefined : undefined; + return { id: trigger.id, kind: trigger.kind, enabled: Boolean(trigger.enabled), config, createdAt: trigger.created_at, updatedAt: trigger.updated_at, + activity: { count: Number(activity?.count ?? 0), lastReceivedAt: activity?.last_received_at ?? null }, + ...(runtime ? { nextRunAt: runtime.next_run_at == null ? null : new Date(Number(runtime.next_run_at)).toISOString(), lastTriggeredAt: runtime.last_triggered_at ?? null } : {}) }; + }); return { id: row.id, name: row.name, promptTemplate: await decrypt(String(row.encrypted_prompt_template), this.env.CREDENTIAL_ENCRYPTION_KEY), parameterDefaults, concurrencyLimit: Number(row.concurrency_limit), executionTargetId: `${executionTarget.backendKind === "amp" ? "amp:" : ""}${String(executionTarget.connectionId ?? "")}`, - trigger: { kind: String(trigger?.kind ?? "manual"), config: triggerConfig, activity: { count: Number(activity?.count ?? 0), lastReceivedAt: activity?.last_received_at ?? null }, - ...(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 }; })() : {}) }, + triggers: publicTriggers, enabled: Boolean(row.enabled), createdAt: row.created_at, updatedAt: row.updated_at, }; } @@ -353,29 +387,32 @@ export class Tenant extends DurableObject { private validateJobInput(input: any): void { if (!input?.name || !input.promptTemplate) throw new Error("Job name and prompt template are required"); - if (!input.trigger || !["manual", "schedule", "webhook"].includes(input.trigger.kind)) throw new Error("Job trigger is invalid"); + if (!Array.isArray(input.triggers) || input.triggers.some((trigger: any) => !["schedule", "webhook", "jobLifecycle"].includes(trigger?.kind))) throw new Error("Job triggers are 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); + for (const trigger of input.triggers) if (trigger.kind === "schedule") validateScheduleConfig(trigger.config); } - private async resetSchedule(jobId: string): Promise { - 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 resetSchedules(jobId: string): Promise { + const job = this.one("SELECT enabled FROM jobs WHERE id=?", jobId) as Row | undefined; + const schedules = this.rows("SELECT id,enabled,config FROM triggers WHERE job_id=? AND kind='schedule'", jobId); + this.ctx.storage.sql.exec("DELETE FROM schedule_state WHERE job_id=? AND trigger_id NOT IN (SELECT id FROM triggers WHERE job_id=? AND kind='schedule')", jobId, jobId); + for (const trigger of schedules) { + const config = validateScheduleConfig(JSON.parse(String(trigger.config))); + const next = Boolean(job?.enabled) && Boolean(trigger.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(trigger_id) DO UPDATE SET next_run_at=excluded.next_run_at", trigger.id, jobId, next); + const alarm = await this.ctx.storage.getAlarm(); + if (next !== null && (alarm === null || next < alarm)) await this.ctx.storage.setAlarm(next); + } } private async createJob(input: any): Promise { this.validateJobInput(input); - const target = await this.jobTarget(input.executionTargetId), jobId = id(), triggerId = id(), timestamp = now(); + const target = await this.jobTarget(input.executionTargetId), jobId = id(), timestamp = now(); + this.validateLifecycleGraph(jobId, input.triggers); 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); + for (const trigger of input.triggers) this.ctx.storage.sql.exec("INSERT INTO triggers (id,job_id,kind,enabled,config,created_at,updated_at) VALUES (?,?,?,?,?,?,?)", trigger.id ?? id(), jobId, trigger.kind, trigger.enabled === false ? 0 : 1, JSON.stringify(trigger.config ?? {}), timestamp, timestamp); + await this.resetSchedules(jobId); return json(await this.publicJob(this.one("SELECT * FROM jobs WHERE id = ?", jobId) as Row)); } @@ -387,20 +424,45 @@ export class Tenant extends DurableObject { private async updateJob(jobId: string, input: any): Promise { if (!this.one("SELECT id FROM jobs WHERE id = ?", jobId)) return new Response("Not found", { status: 404 }); this.validateJobInput(input); + this.validateLifecycleGraph(jobId, input.triggers); 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); + const existing = new Map(this.triggersFor(jobId).map(trigger => [String(trigger.id), trigger])); + const retained = new Set(); + for (const trigger of input.triggers) { + const triggerId = typeof trigger.id === "string" && existing.has(trigger.id) ? trigger.id : id(); retained.add(triggerId); + if (existing.has(triggerId)) this.ctx.storage.sql.exec("UPDATE triggers SET kind=?,enabled=?,config=?,updated_at=? WHERE id=? AND job_id=?", trigger.kind, trigger.enabled === false ? 0 : 1, JSON.stringify(trigger.config ?? {}), timestamp, triggerId, jobId); + else this.ctx.storage.sql.exec("INSERT INTO triggers (id,job_id,kind,enabled,config,created_at,updated_at) VALUES (?,?,?,?,?,?,?)", triggerId, jobId, trigger.kind, trigger.enabled === false ? 0 : 1, JSON.stringify(trigger.config ?? {}), timestamp, timestamp); + } + for (const triggerId of existing.keys()) if (!retained.has(triggerId)) this.ctx.storage.sql.exec("DELETE FROM triggers WHERE id=? AND job_id=?", triggerId, jobId); + await this.resetSchedules(jobId); return json(await this.publicJob(this.one("SELECT * FROM jobs WHERE id = ?", jobId) as Row)); } private async setJobEnabled(jobId: string, enabled: boolean): Promise { 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); + await this.resetSchedules(jobId); return json({ id: jobId, enabled }); } + private validateLifecycleGraph(jobId: string, proposed: any[]): void { + const graph = new Map(); + for (const job of this.rows("SELECT id FROM jobs")) graph.set(String(job.id), []); + graph.set(jobId, []); + for (const trigger of this.rows("SELECT job_id,config FROM triggers WHERE kind='jobLifecycle'")) { + if (String(trigger.job_id) === jobId) continue; + try { graph.set(String(trigger.job_id), [...(graph.get(String(trigger.job_id)) ?? []), ...JSON.parse(String(trigger.config)).sourceJobIds]); } catch { /* invalid old state cannot add an edge */ } + } + const sources = proposed.filter(trigger => trigger.kind === "jobLifecycle").flatMap(trigger => trigger.config.sourceJobIds as string[]); + if (sources.includes(jobId)) throw new Error("A job cannot subscribe to itself"); + for (const source of sources) if (!graph.has(source)) throw new Error(`Lifecycle source job not found: ${source}`); + graph.set(jobId, sources); + const visiting = new Set(), visited = new Set(); + const visit = (node: string): boolean => { if (visiting.has(node)) return true; if (visited.has(node)) return false; visiting.add(node); for (const next of graph.get(node) ?? []) if (visit(next)) return true; visiting.delete(node); visited.add(node); return false; }; + for (const node of graph.keys()) if (visit(node)) throw new Error("Job lifecycle subscriptions cannot contain cycles"); + } + private deleteJob(jobId: string): Response { if (!this.one("SELECT id FROM jobs WHERE id = ?", jobId)) return new Response("Not found", { status: 404 }); this.ctx.storage.sql.exec("DELETE FROM active_claims WHERE pipe_id = ?", jobId); @@ -418,8 +480,8 @@ export class Tenant extends DurableObject { return json(result); } - /** Single persistence boundary used by manual, schedule, and webhook adapters. */ - private async invokeCanonicalJob(jobId: string, source: "manual" | "schedule" | "webhook", claimKey: string, context?: string, parameters: Record = {}, occurrence?: Record): Promise | null> { + /** Single persistence boundary used by manual and every automatic trigger adapter. */ + private async invokeCanonicalJob(jobId: string, source: "manual" | "schedule" | "webhook" | "jobLifecycle", claimKey: string, context?: string, parameters: Record = {}, occurrence?: Record): Promise | null> { const row = this.one("SELECT * FROM jobs WHERE id = ?", jobId) as Row | undefined; if (!row || !Boolean(row.enabled)) return null; const existing = this.one("SELECT i.id AS invocation_id,r.id AS run_id,r.state FROM invocations i JOIN job_runs r ON r.invocation_id=i.id WHERE i.job_id=? AND i.claim_key=?", jobId, claimKey) as Row | undefined; @@ -444,21 +506,56 @@ export class Tenant extends DurableObject { return { invocationId, runId, state: "queued", duplicate: false }; } + private async signalAutomaticJob(jobId: string, source: "schedule" | "webhook" | "jobLifecycle", claimKey: string, context?: string, parameters: Record = {}, occurrence?: Record): Promise | null> { + const existing = this.one("SELECT i.id AS invocation_id,r.id AS run_id,r.state FROM invocations i LEFT JOIN job_runs r ON r.invocation_id=i.id WHERE i.job_id=? AND i.claim_key=?", jobId, claimKey) as Row | undefined; + if (existing) return { invocationId: existing.invocation_id, runId: existing.run_id ?? null, state: existing.state ?? "coalesced", duplicate: true }; + const active = this.one("SELECT id,state FROM job_runs WHERE job_id=? AND state IN ('queued','running') ORDER BY created_at LIMIT 1", jobId) as Row | undefined; + if (!active) return this.invokeCanonicalJob(jobId, source, claimKey, context, parameters, occurrence); + const timestamp = now(), invocationId = id(); + this.ctx.storage.sql.exec("INSERT OR IGNORE INTO invocations (id,job_id,source,claim_key,context,parameters,occurrence,created_at) VALUES (?,?,?,?,?,?,?,?)", invocationId, jobId, source, claimKey, context ?? null, JSON.stringify(parameters), occurrence ? JSON.stringify(occurrence) : null, timestamp); + let summary: any = { counts: {}, latest: {} }; + const prior = this.one("SELECT summary FROM automatic_wakes WHERE job_id=?", jobId) as Row | undefined; + try { if (prior) summary = JSON.parse(String(prior.summary)); } catch { /* reset malformed summary */ } + summary.counts[source] = Math.min(1_000_000, Number(summary.counts[source] ?? 0) + 1); + summary.latest[source] = { claimKey: claimKey.slice(-200), occurredAt: (occurrence as any)?.occurredAt ?? timestamp, externalId: String((occurrence as any)?.externalId ?? "").slice(-200) }; + this.ctx.storage.sql.exec("INSERT INTO automatic_wakes(job_id,trailing,summary,updated_at) VALUES(?,1,?,?) ON CONFLICT(job_id) DO UPDATE SET trailing=1,summary=excluded.summary,updated_at=excluded.updated_at", jobId, JSON.stringify(summary), timestamp); + return { invocationId, runId: active.id, state: active.state, duplicate: false, coalesced: true }; + } + + private async afterJobTerminal(jobId: string, sourceRunId: string, terminalState: "succeeded" | "failed" | "stopped", transitionedAt = now()): Promise { + const wake = this.one("SELECT summary FROM automatic_wakes WHERE job_id=? AND trailing=1", jobId) as Row | undefined; + if (wake) { + this.ctx.storage.sql.exec("UPDATE automatic_wakes SET trailing=0,summary='{}',updated_at=? WHERE job_id=? AND trailing=1", transitionedAt, jobId); + await this.invokeCanonicalJob(jobId, "jobLifecycle", `trailing:${sourceRunId}:${transitionedAt}`, `Automatic wake summary: ${String(wake.summary).slice(0,4000)}`, {}, { occurredAt: transitionedAt, metadata: { coalesced: true } }); + } + const subscribers = this.rows("SELECT t.id,t.job_id,t.config FROM triggers t JOIN jobs j ON j.id=t.job_id WHERE t.kind='jobLifecycle' AND t.enabled=1 AND j.enabled=1"); + for (const trigger of subscribers) { + let config: any; try { config = JSON.parse(String(trigger.config)); } catch { continue; } + if (!config.sourceJobIds?.includes(jobId) || !config.states?.includes(terminalState)) continue; + this.ctx.storage.sql.exec("INSERT OR IGNORE INTO lifecycle_deliveries(trigger_id,source_run_id,terminal_state,created_at) VALUES(?,?,?,?)", trigger.id, sourceRunId, terminalState, transitionedAt); + const claimed = this.one("SELECT changes() AS count") as Row; + if (!Number(claimed.count)) continue; + const destination = `job:${String(trigger.job_id)}`; + const context = JSON.stringify({ sourceJobId: jobId, sourceRunId, finalState: terminalState, transitionedAt, observationDestination: destination }); + await this.signalAutomaticJob(String(trigger.job_id), "jobLifecycle", `lifecycle:${trigger.id}:${sourceRunId}:${terminalState}`, context, {}, { occurredAt: transitionedAt, externalId: sourceRunId, metadata: { triggerId: trigger.id, sourceJobId: jobId, finalState: terminalState, observationDestination: destination } }); + } + } + private async processDueSchedules(): Promise { 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); + const due = this.rows("SELECT s.job_id,s.trigger_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.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); + await this.enqueueScheduledJob(String(row.job_id), String(row.trigger_id), occurredAt, config); + this.ctx.storage.sql.exec("UPDATE schedule_state SET next_run_at=?,last_triggered_at=? WHERE trigger_id=? AND next_run_at=?", catchUp.nextRunAt.getTime(), occurredAt, row.trigger_id, row.next_run_at); } } - private async enqueueScheduledJob(jobId: string, occurredAt: string, config: ScheduleConfig): Promise { - await this.invokeCanonicalJob(jobId, "schedule", `schedule:${occurredAt}`, config.context, config.parameters ?? {}, { occurredAt }); + private async enqueueScheduledJob(jobId: string, triggerId: string, occurredAt: string, config: ScheduleConfig): Promise { + await this.signalAutomaticJob(jobId, "schedule", `schedule:${triggerId}:${occurredAt}`, config.context, config.parameters ?? {}, { occurredAt, metadata: { triggerId } }); } private deletePipe(pipeId: string): Response { @@ -652,8 +749,9 @@ export class Tenant extends DurableObject { } } this.ctx.storage.sql.exec("UPDATE runs SET state = 'stopped', result = ?, updated_at = ? WHERE id = ?", await encrypt("Stopped by user", this.env.CREDENTIAL_ENCRYPTION_KEY), now(), runId); - this.ctx.storage.sql.exec("UPDATE job_runs SET state='cancelled',updated_at=? WHERE id=?", now(), runId); + this.ctx.storage.sql.exec("UPDATE job_runs SET state='stopped',updated_at=? WHERE id=?", now(), runId); this.ctx.storage.sql.exec("DELETE FROM active_claims WHERE run_id = ?", runId); + await this.afterJobTerminal(String(run.pipe_id), runId, "stopped"); return json({ id: runId, state: "stopped", stopped: true }); } @@ -675,9 +773,9 @@ export class Tenant extends DurableObject { return json({ statuses: statusData.workflowStates.nodes, users: userData.users.nodes, labels: labelData.issueLabels.nodes }); } - private webhookJobs(provider: WebhookProvider): Array<{ job: Row; config: WebhookTriggerConfig }> { - return this.rows("SELECT j.*,t.config AS trigger_config FROM jobs j JOIN triggers t ON t.job_id=j.id WHERE j.enabled=1 AND t.kind='webhook'") - .flatMap(job => { try { const config = JSON.parse(String(job.trigger_config)) as WebhookTriggerConfig; return config.provider === provider ? [{ job, config }] : []; } catch { return []; } }); + private webhookJobs(provider: WebhookProvider): Array<{ job: Row; triggerId: string; config: WebhookTriggerConfig }> { + return this.rows("SELECT j.*,t.id AS trigger_id,t.config AS trigger_config FROM jobs j JOIN triggers t ON t.job_id=j.id WHERE j.enabled=1 AND t.enabled=1 AND t.kind='webhook'") + .flatMap(job => { try { const config = JSON.parse(String(job.trigger_config)) as WebhookTriggerConfig; return config.provider === provider ? [{ job, triggerId: String(job.trigger_id), config }] : []; } catch { return []; } }); } private recordJobEvent(jobId: string, provider: string, deliveryId: string, outcome: string, detail: string): void { @@ -685,10 +783,10 @@ export class Tenant extends DurableObject { } private async invokeWebhookJobs(provider: WebhookProvider, deliveryId: string, payload: Record, eventName?: string): Promise { - for (const { job, config } of this.webhookJobs(provider)) { + for (const { job, triggerId, config } of this.webhookJobs(provider)) { const invocation = adaptWebhook(config, provider, deliveryId, payload, eventName); if (!invocation) { this.recordJobEvent(String(job.id), provider, deliveryId, "ignored", "Webhook did not match this job trigger."); continue; } - const result = await this.invokeCanonicalJob(String(job.id), "webhook", invocation.claimKey, invocation.context, invocation.parameters, invocation.occurrence); + const result = await this.signalAutomaticJob(String(job.id), "webhook", `webhook:${triggerId}:${invocation.claimKey}`, invocation.context, invocation.parameters, { ...invocation.occurrence, metadata: { ...invocation.occurrence?.metadata, triggerId } }); this.recordJobEvent(String(job.id), provider, deliveryId, result?.duplicate ? "duplicate" : result ? "accepted" : "ignored", result?.duplicate ? "Webhook occurrence was already claimed." : result ? "Webhook occurrence queued through canonical job invocation." : "Job was unavailable."); } } @@ -879,7 +977,7 @@ export class Tenant extends DurableObject { const delays = [0, 5_000, 15_000, 30_000, 60_000]; for (const verification of pending) { const pipe = this.one("SELECT * FROM pipes WHERE id=?", verification.flow_id) as Row | undefined; - const job = pipe ? undefined : this.one("SELECT j.*,t.config AS trigger_config FROM jobs j JOIN triggers t ON t.job_id=j.id WHERE j.id=? AND j.enabled=1 AND t.kind='webhook'", verification.flow_id) as Row | undefined; + const job = pipe ? undefined : this.one("SELECT j.*,t.id AS trigger_id,t.config AS trigger_config FROM jobs j JOIN triggers t ON t.job_id=j.id WHERE j.id=? AND j.enabled=1 AND t.enabled=1 AND t.kind='webhook' ORDER BY t.created_at LIMIT 1", verification.flow_id) as Row | undefined; const target = pipe ?? job; if (!target) { this.ctx.storage.sql.exec("DELETE FROM pending_verifications WHERE id=?", verification.id); continue; } const installation = this.one("SELECT state FROM github_installations WHERE installation_id=?", verification.installation_id) as Row | undefined; @@ -901,7 +999,7 @@ export class Tenant extends DurableObject { const payload = { ...saved, pull_request: { ...saved.pull_request, ...pull } }; const invocation = adaptWebhook(config, "github", String(verification.delivery_id), payload, "pull_request"); this.ctx.storage.sql.exec("DELETE FROM pending_verifications WHERE id=?", verification.id); - if (invocation) await this.invokeCanonicalJob(String(job.id), "webhook", invocation.claimKey, invocation.context, invocation.parameters, invocation.occurrence); + if (invocation) await this.signalAutomaticJob(String(job.id), "webhook", `webhook:${String(job.trigger_id)}:${invocation.claimKey}`, invocation.context, invocation.parameters, invocation.occurrence); this.recordJobEvent(String(job.id), "github", String(verification.delivery_id), invocation ? "accepted" : "ignored", invocation ? "Verified webhook queued through canonical job invocation." : "Job trigger changed while verification was pending."); continue; } @@ -987,8 +1085,9 @@ export class Tenant extends DurableObject { if (observation.state === "failed") return this.finishRun(run, "failed", observation.detail ?? "Amp run failed."); if (observation.state === "stopped") { this.ctx.storage.sql.exec("UPDATE runs SET state='stopped',updated_at=? WHERE id=?", now(), run.id); - this.ctx.storage.sql.exec("UPDATE job_runs SET state='cancelled',updated_at=? WHERE id=?", now(), run.id); + this.ctx.storage.sql.exec("UPDATE job_runs SET state='stopped',updated_at=? WHERE id=?", now(), run.id); this.ctx.storage.sql.exec("DELETE FROM active_claims WHERE run_id=?", run.id); + await this.afterJobTerminal(String(run.pipe_id), String(run.id), "stopped"); return; } this.ctx.storage.sql.exec("UPDATE runs SET state=?,updated_at=? WHERE id=?", observation.state, now(), run.id); @@ -1125,11 +1224,13 @@ export class Tenant extends DurableObject { private async finishRecovery(run: Row, state: "running" | "failed", action: string, live?: HerdrIdentity): Promise { this.activity(run.id, state === "running" ? "recovery_succeeded" : "recovery_failed", action); if (live) this.persistIdentity(run.id, live, state); this.ctx.storage.sql.exec("UPDATE runs SET state=?,recovery_attempt=0,recovery_reason=NULL,recovery_started_at=NULL,recovery_last_action=?,recovery_next_at=NULL,recovery_comment_finished=1,updated_at=? WHERE id=?", state, action, now(), run.id); if (!Number(run.recovery_comment_finished) && String(run.provider || "linear") === "linear") await this.safeLinearComment(String(run.issue_id), `Factorize automatic recovery ${state === "running" ? "succeeded" : "permanently failed"} for run \`${run.id}\`: ${action}`); if (state === "failed") { const encrypted = await encrypt(action, this.env.CREDENTIAL_ENCRYPTION_KEY); this.ctx.storage.sql.exec("UPDATE runs SET result=? WHERE id=?", encrypted, run.id); this.ctx.storage.sql.exec("DELETE FROM active_claims WHERE pipe_id=? AND issue_id=?", run.pipe_id, run.claim_key || run.issue_id); this.ctx.storage.sql.exec("UPDATE runs SET claim_released=1 WHERE id=?", run.id); } } private async finishRun(run: Row, state: Extract, result: string, outputCaptured = false): Promise { + const transitionedAt = now(); const encryptedResult = await encrypt(result, this.env.CREDENTIAL_ENCRYPTION_KEY); - this.ctx.storage.sql.exec("UPDATE runs SET state = ?, result = ?, output_captured=?, updated_at = ? WHERE id = ?", state, encryptedResult, outputCaptured ? 1 : Number(run.output_captured || 0), now(), run.id); - this.ctx.storage.sql.exec("UPDATE job_runs SET state=?,updated_at=? WHERE id=?", state === "done" ? "succeeded" : "failed", now(), run.id); + this.ctx.storage.sql.exec("UPDATE runs SET state = ?, result = ?, output_captured=?, updated_at = ? WHERE id = ?", state, encryptedResult, outputCaptured ? 1 : Number(run.output_captured || 0), transitionedAt, run.id); + this.ctx.storage.sql.exec("UPDATE job_runs SET state=?,updated_at=? WHERE id=?", state === "done" ? "succeeded" : "failed", transitionedAt, run.id); this.ctx.storage.sql.exec("DELETE FROM active_claims WHERE pipe_id = ? AND issue_id = ?", run.pipe_id, run.claim_key || run.issue_id); this.ctx.storage.sql.exec("UPDATE runs SET claim_released=1 WHERE id=?", run.id); + await this.afterJobTerminal(String(run.pipe_id), String(run.id), state === "done" ? "succeeded" : "failed", transitionedAt); await this.collectRunPane({ ...run, state, output_captured: outputCaptured ? 1 : Number(run.output_captured || 0), claim_released: 1 }); const heading = state === "done" ? "Factorize completed the agent run." : "Factorize could not complete the agent run."; if (String(run.provider || "linear") === "linear") await this.safeLinearComment(String(run.issue_id), `${heading}\n\nRun ID: \`${run.id}\`. Review the Herdr session on the configured VM for details.`); diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 6237a8f9..4cfd20b4 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -199,32 +199,32 @@ const request=async(url,options)=>{const r=await fetch(url,options),body=await r const pairs=v=>Object.entries(v||{}).map(([k,x])=>k+'='+x).join('\\n'); const record=v=>Object.fromEntries(String(v||'').split(/\\n/).map(x=>x.trim()).filter(Boolean).map(x=>{const i=x.indexOf('=');if(i<1)throw new Error('Parameters must use name=value, one per line.');return[x.slice(0,i).trim(),x.slice(i+1)]})); const stateBadge=v=>''+esc(v)+''; -const triggerBadge=t=>{const labels={manual:'Manual only',schedule:'Scheduled',webhook:'Webhook'};return ''+labels[t]+''}; +const triggerBadge=t=>{const labels={manual:'Manual only',schedule:'Scheduled',webhook:'Webhook',jobLifecycle:'Job lifecycle'};return ''+(labels[t]||t)+''}; `; export const jobsPage = (viewer: { email: string }) => shell("Jobs — Factorize", viewer, `
${dashboardHead("Jobs", "Create reusable agent work and choose exactly how it starts.", 'Create job')}

Loading jobs…

`, `${uiHelpers} -async function load(){const jobs=await request('/api/jobs');const root=$('#jobs');if(!jobs.length){root.innerHTML='

No jobs yet

Create a manual, scheduled, or webhook job.

';return}root.innerHTML='
    '+jobs.map(j=>'
  • '+esc(j.name)+''+triggerBadge(j.trigger.kind)+(j.enabled?'':'Disabled')+'

    '+esc(j.concurrencyLimit)+' concurrent · updated '+new Date(j.updatedAt).toLocaleString()+(j.trigger.nextRunAt?' · next '+new Date(j.trigger.nextRunAt).toLocaleString():'')+'

    View →
  • ').join('')+'
'}load().catch(e=>$('#jobs').innerHTML='

'+esc(e.message)+'

');`); +async function load(){const jobs=await request('/api/jobs');const root=$('#jobs');if(!jobs.length){root.innerHTML='

No jobs yet

Create a manual-only or automatically triggered job.

';return}root.innerHTML='
    '+jobs.map(j=>{const triggers=j.triggers||[],next=triggers.find(t=>t.nextRunAt)?.nextRunAt;return '
  • '+esc(j.name)+''+(triggers.length?triggers.map(t=>triggerBadge(t.kind)).join(''):triggerBadge('manual'))+(j.enabled?'':'Disabled')+'

    '+esc(j.concurrencyLimit)+' concurrent · updated '+new Date(j.updatedAt).toLocaleString()+(next?' · next '+new Date(next).toLocaleString():'')+'

    View →
  • '}).join('')+'
'}load().catch(e=>$('#jobs').innerHTML='

'+esc(e.message)+'

');`); export const jobPage = (viewer: { email: string }, jobId?: string) => shell(`${jobId ? "Edit" : "Create"} job — Factorize`, viewer, `
← Jobs
${dashboardHead(jobId ? "Edit job" : "Create a job", "Prompts use Mustache variables. Parameter values are always strings.")}
-

Trigger

Choose exactly one way this job starts.

${[["manual","Manual only","Run from the dashboard or MCP."],["schedule","Schedule","Run automatically on a clock."],["webhook","Webhook","Run from a provider event."]].map(([v,l,d]) => ``).join("")}
+

Automatic triggers

Manual invocation is always available. Configure a primary trigger and any additional triggers below.

${[["manual","Manual only","No primary automatic trigger."],["schedule","Schedule","Run automatically on a clock."],["webhook","Webhook","Run from a provider event."]].map(([v,l,d]) => ``).join("")}
-
+
`, `${uiHelpers} const jobId=${JSON.stringify(jobId ?? null)},form=$('#job'),schedule=$('#schedule'),webhook=$('#webhook'); function syncTrigger(){const kind=new FormData(form).get('triggerKind');schedule.classList.toggle('hidden',kind!=='schedule');webhook.classList.toggle('hidden',kind!=='webhook')} let previewTimer;function syncCron(){const f=form.frequency.value,advanced=f==='advanced';$('#cron-wrap').classList.toggle('hidden',!advanced);const cron=advanced?form.cron.value:f;$('#cron-output').textContent=cron;const zone=form.timezone.value;$('#next-run').textContent='Calculating next occurrence…';clearTimeout(previewTimer);previewTimer=setTimeout(async()=>{try{const x=await request('/api/schedules/preview',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({cron,timezone:zone})});$('#next-run').textContent='Next occurrence: '+new Date(x.nextRunAt).toLocaleString()+' ('+zone+')'}catch(e){$('#next-run').textContent=e.message}},150)} function syncProvider(){const p=form.provider.value;$('#linear-hook').classList.toggle('hidden',p!=='linear');$('#github-hook').classList.toggle('hidden',p!=='github');$('#managed-hook').classList.toggle('hidden',p==='linear'||p==='github')} form.onchange=e=>{if(e.target.name==='triggerKind')syncTrigger();if(['frequency','timezone','cron'].includes(e.target.name))syncCron();if(e.target.name==='provider')syncProvider()};$('#copy-cron').onclick=()=>navigator.clipboard.writeText($('#cron-output').textContent); -async function init(){const targets=await request('/api/execution-targets');form.executionTargetId.innerHTML=''+targets.map(t=>'').join('');if(!jobId)return;const j=await request('/api/jobs/'+encodeURIComponent(jobId));form.name.value=j.name;form.promptTemplate.value=j.promptTemplate;form.parameters.value=pairs(j.parameterDefaults);form.concurrencyLimit.value=j.concurrencyLimit;form.executionTargetId.value=j.executionTargetId;form.querySelector('[value="'+j.trigger.kind+'"]').checked=true;const c=j.trigger.config||{};if(j.trigger.kind==='schedule'){form.timezone.value=c.timezone;form.cron.value=c.cron;const common=[...form.frequency.options].find(o=>o.value===c.cron);form.frequency.value=common?c.cron:'advanced';form.scheduledContext.value=c.context||'';form.scheduledParameters.value=pairs(c.parameters)}if(j.trigger.kind==='webhook'){form.provider.value=c.provider;form.projectId.value=c.projectId||'';form.statusId.value=c.matchRules?.[0]?.targetId||'';form.installationId.value=c.installationId||'';form.repositoryId.value=c.repositoryId||'';form.event.value=c.event||'pull_request';form.action.value=c.action||'dequeued';form.webhookContext.value=c.context||'';form.webhookParameters.value=pairs(c.parameters)}syncTrigger();syncCron();syncProvider()} -form.onsubmit=async e=>{e.preventDefault();const save=$('#save'),err=$('#error');err.classList.add('hidden');save.disabled=true;try{const d=new FormData(form),kind=d.get('triggerKind');let trigger={kind,config:{}};if(kind==='schedule')trigger.config={cron:$('#cron-output').textContent.trim(),timezone:String(d.get('timezone')),context:String(d.get('scheduledContext')||'')||undefined,parameters:record(d.get('scheduledParameters'))};if(kind==='webhook'){const provider=d.get('provider'),base={provider,context:String(d.get('webhookContext')||'')||undefined,parameters:record(d.get('webhookParameters'))};if(provider==='linear')trigger.config={...base,projectId:String(d.get('projectId')),matchRules:[{type:'status',targetId:String(d.get('statusId'))}]};else if(provider==='github')trigger.config={...base,installationId:Number(d.get('installationId')),repositoryId:Number(d.get('repositoryId')),event:String(d.get('event')),action:String(d.get('action'))};else trigger.config=base}const body={name:String(d.get('name')),promptTemplate:String(d.get('promptTemplate')),parameterDefaults:record(d.get('parameters')),concurrencyLimit:Number(d.get('concurrencyLimit')),executionTargetId:String(d.get('executionTargetId')),trigger};const result=await request('/api/jobs'+(jobId?'/'+encodeURIComponent(jobId):''),{method:jobId?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});location.href='/jobs/'+encodeURIComponent(result.id)}catch(e){err.textContent=e.message;err.classList.remove('hidden');save.disabled=false}};init().then(()=>{syncTrigger();syncCron();syncProvider()}).catch(e=>{const err=$('#error');err.textContent=e.message;err.classList.remove('hidden')});`); +async function init(){const targets=await request('/api/execution-targets');form.executionTargetId.innerHTML=''+targets.map(t=>'').join('');if(!jobId)return;const j=await request('/api/jobs/'+encodeURIComponent(jobId));form.name.value=j.name;form.promptTemplate.value=j.promptTemplate;form.parameters.value=pairs(j.parameterDefaults);form.concurrencyLimit.value=j.concurrencyLimit;form.executionTargetId.value=j.executionTargetId;const primary=(j.triggers||[]).find(t=>t.kind==='schedule'||t.kind==='webhook'),kind=primary?.kind||'manual';form.querySelector('[value="'+kind+'"]').checked=true;form.additionalTriggers.value=JSON.stringify((j.triggers||[]).filter(t=>t!==primary),null,2);const c=primary?.config||{};if(kind==='schedule'){form.timezone.value=c.timezone;form.cron.value=c.cron;const common=[...form.frequency.options].find(o=>o.value===c.cron);form.frequency.value=common?c.cron:'advanced';form.scheduledContext.value=c.context||'';form.scheduledParameters.value=pairs(c.parameters)}if(kind==='webhook'){form.provider.value=c.provider;form.projectId.value=c.projectId||'';form.statusId.value=c.matchRules?.[0]?.targetId||'';form.installationId.value=c.installationId||'';form.repositoryId.value=c.repositoryId||'';form.event.value=c.event||'pull_request';form.action.value=c.action||'dequeued';form.webhookContext.value=c.context||'';form.webhookParameters.value=pairs(c.parameters)}form.dataset.primaryId=primary?.id||'';syncTrigger();syncCron();syncProvider()} +form.onsubmit=async e=>{e.preventDefault();const save=$('#save'),err=$('#error');err.classList.add('hidden');save.disabled=true;try{const d=new FormData(form),kind=d.get('triggerKind'),triggers=[];let trigger={id:form.dataset.primaryId||undefined,kind,enabled:true,config:{}};if(kind==='schedule')trigger.config={cron:$('#cron-output').textContent.trim(),timezone:String(d.get('timezone')),context:String(d.get('scheduledContext')||'')||undefined,parameters:record(d.get('scheduledParameters'))};if(kind==='webhook'){const provider=d.get('provider'),base={provider,context:String(d.get('webhookContext')||'')||undefined,parameters:record(d.get('webhookParameters'))};if(provider==='linear')trigger.config={...base,projectId:String(d.get('projectId')),matchRules:[{type:'status',targetId:String(d.get('statusId'))}]};else if(provider==='github')trigger.config={...base,installationId:Number(d.get('installationId')),repositoryId:Number(d.get('repositoryId')),event:String(d.get('event')),action:String(d.get('action'))};else trigger.config=base}if(kind!=='manual')triggers.push(trigger);const additional=JSON.parse(String(d.get('additionalTriggers')||'[]'));if(!Array.isArray(additional))throw new Error('Additional triggers must be a JSON array.');triggers.push(...additional);const body={name:String(d.get('name')),promptTemplate:String(d.get('promptTemplate')),parameterDefaults:record(d.get('parameters')),concurrencyLimit:Number(d.get('concurrencyLimit')),executionTargetId:String(d.get('executionTargetId')),triggers};const result=await request('/api/jobs'+(jobId?'/'+encodeURIComponent(jobId):''),{method:jobId?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});location.href='/jobs/'+encodeURIComponent(result.id)}catch(e){err.textContent=e.message;err.classList.remove('hidden');save.disabled=false}};init().then(()=>{syncTrigger();syncCron();syncProvider()}).catch(e=>{const err=$('#error');err.textContent=e.message;err.classList.remove('hidden')});`); export const jobDetailPage = (viewer: { email: string }, jobId: string) => shell("Job — Factorize", viewer, `
← Jobs

Loading job…

`, `${uiHelpers} const id=$('#job-detail').dataset.id,root=$('#job-detail'); async function runNow(job){const context=prompt('Optional run context (Cancel for none):','');if(context===null)return;const raw=prompt('Optional parameter overrides, one name=value per line:','');if(raw===null)return;const x=await request('/api/jobs/'+encodeURIComponent(id)+'/invocations',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({context:context||undefined,parameters:record(raw)})});location.href='/job-runs/'+encodeURIComponent(x.runId)} -async function load(){const [j,runs]=await Promise.all([request('/api/jobs/'+encodeURIComponent(id)),request('/api/job-runs?jobId='+encodeURIComponent(id))]);const cfg=j.trigger.config||{},triggerDetail=j.trigger.kind==='schedule'?esc(cfg.cron)+' · '+esc(cfg.timezone)+(j.trigger.nextRunAt?' · next '+new Date(j.trigger.nextRunAt).toLocaleString():''):j.trigger.kind==='webhook'?esc(cfg.provider)+' provider':'Dashboard or MCP';root.innerHTML='

'+esc(j.name)+'

'+triggerBadge(j.trigger.kind)+(j.enabled?'':'Disabled')+'

'+triggerDetail+' · '+j.concurrencyLimit+' concurrent

Edit

Prompt template

'+esc(j.promptTemplate)+'

Defaults: '+esc(pairs(j.parameterDefaults)||'None')+'

Runs

'+(runs.items.length?'':'

No runs yet.

')+'
';$('#run').onclick=()=>runNow(j).catch(alert);$('#toggle').onclick=async()=>{await request('/api/jobs/'+encodeURIComponent(id)+'/'+(j.enabled?'disable':'enable'),{method:'POST'});load()};$('#delete').onclick=async()=>{if(confirm('Delete this job and its queued history?')){await request('/api/jobs/'+encodeURIComponent(id),{method:'DELETE'});location.href='/jobs'}}}load().catch(e=>root.innerHTML='

'+esc(e.message)+'

');`); +async function load(){const [j,runs]=await Promise.all([request('/api/jobs/'+encodeURIComponent(id)),request('/api/job-runs?jobId='+encodeURIComponent(id))]),triggers=j.triggers||[];const triggerDetail=triggers.length?triggers.map(t=>{const c=t.config||{};return t.kind==='schedule'?esc(c.cron)+' · '+esc(c.timezone)+(t.nextRunAt?' · next '+new Date(t.nextRunAt).toLocaleString():''):t.kind==='webhook'?esc(c.provider)+' webhook':(c.sourceJobIds||[]).length+' lifecycle source(s)'}).join(' · '):'Manual only';root.innerHTML='

'+esc(j.name)+'

'+(triggers.length?triggers.map(t=>triggerBadge(t.kind)).join(''):triggerBadge('manual'))+(j.enabled?'':'Disabled')+'

'+triggerDetail+' · '+j.concurrencyLimit+' concurrent

Edit

Prompt template

'+esc(j.promptTemplate)+'

Defaults: '+esc(pairs(j.parameterDefaults)||'None')+'

Runs

'+(runs.items.length?'':'

No runs yet.

')+'
';$('#run').onclick=()=>runNow(j).catch(alert);$('#toggle').onclick=async()=>{await request('/api/jobs/'+encodeURIComponent(id)+'/'+(j.enabled?'disable':'enable'),{method:'POST'});load()};$('#delete').onclick=async()=>{if(confirm('Delete this job and its queued history?')){await request('/api/jobs/'+encodeURIComponent(id),{method:'DELETE'});location.href='/jobs'}}}load().catch(e=>root.innerHTML='

'+esc(e.message)+'

');`); export const jobRunPage = (viewer: { email: string }, runId: string) => shell("Run — Factorize", viewer, `

Loading run…

`, `${uiHelpers} const root=$('#run-detail'),id=root.dataset.id;request('/api/job-runs/'+encodeURIComponent(id)).then(r=>{const caps=r.capabilities||[],canOutput=caps.includes('output'),canStop=caps.includes('stop')&&['starting','running','blocked'].includes(r.state),trusted=typeof r.destination_url==='string'&&r.destination_url.startsWith('https://');root.innerHTML='← Job

Run '+esc(r.id.slice(0,8))+'

'+esc(r.backend_kind)+' · '+new Date(r.created_at).toLocaleString()+'

'+stateBadge(r.state)+(canStop?'':'')+'

Observation

'+(trusted?'Open '+esc(r.backend_kind)+' destination ↗':'

This backend has no external observation link.

')+'
'+(canOutput?'

Output

'+esc(r.result||'Output is not available yet.')+'
':'
Output is available only in the backend observation experience.
');if(canStop)$('#stop-run').onclick=async()=>{await request('/api/job-runs/'+encodeURIComponent(id)+'/stop',{method:'POST'});location.reload()}}).catch(e=>root.innerHTML='

'+esc(e.message)+'

');`); diff --git a/packages/app/test/flow-service.test.ts b/packages/app/test/flow-service.test.ts index 47f26b7f..e5a5a8a8 100644 --- a/packages/app/test/flow-service.test.ts +++ b/packages/app/test/flow-service.test.ts @@ -46,7 +46,7 @@ describe("FlowService", () => { requests.push(`${request.method} ${path}`); return Response.json({ ok: true }); }), { ...auth, scopes: ["flows:read", "flows:write", "runs:write"] }); - await service.createJob({ name: "Manual", promptTemplate: "{{context}}", parameterDefaults: {}, concurrencyLimit: 1, executionTargetId: "target-1", trigger: { kind: "manual", config: {} } }); + await service.createJob({ name: "Manual", promptTemplate: "{{context}}", parameterDefaults: {}, concurrencyLimit: 1, executionTargetId: "target-1", triggers: [] }); await service.invokeJob("job-1", { parameters: {}, idempotencyKey: "client-1" }); expect(requests).toEqual(["POST /v1/jobs", "POST /v1/jobs/job-1/invocations"]); }); @@ -66,8 +66,8 @@ 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 * * * *", timezone: "UTC" } } }); - expect(job.trigger.kind).toBe("schedule"); + const job = jobInputSchema.parse({ name: "Deploy", promptTemplate: "Deploy {{environment}}: {{context}}", parameterDefaults: { environment: "staging" }, concurrencyLimit: 2, executionTargetId: "exe-1", triggers: [{ kind: "schedule", config: { cron: "0 * * * *", timezone: "UTC" } }, { kind: "jobLifecycle", config: { sourceJobIds: ["worker"], states: ["succeeded", "failed"] } }] }); + expect(job.triggers.map(trigger => trigger.kind)).toEqual(["schedule", "jobLifecycle"]); expect(() => jobInputSchema.parse({ ...job, apiToken: "secret" })).toThrow(); expect(() => jobInputSchema.parse({ ...job, parameterDefaults: { context: "wrong" } })).toThrow(); expect(() => manualInvocationSchema.parse({ parameters: { context: "wrong" } })).toThrow(); diff --git a/packages/app/test/job-domain.test.ts b/packages/app/test/job-domain.test.ts index e95c1c74..5aab8ece 100644 --- a/packages/app/test/job-domain.test.ts +++ b/packages/app/test/job-domain.test.ts @@ -6,7 +6,7 @@ const job = (overrides: Partial = {}): Job => ({ parameterDefaults: { greeting: "Hello", name: "world" }, executionTarget: { connectionId: "exe-1", workspace: "triage", cwd: "/repo", agentKind: "codex" }, concurrencyLimit: 1, enabled: true, - trigger: { id: "trigger-1", jobId: "job-1", kind: "manual", config: {}, createdAt: "now", updatedAt: "now" }, + triggers: [], createdAt: "now", updatedAt: "now", ...overrides, }); @@ -44,10 +44,13 @@ describe("job invocation domain", () => { expect(await service.startIfCapacity(second.run)).toBeNull(); }); - it("defines exactly one trigger per job and durable claims in the clean schema", () => { - expect(JOB_SCHEMA).toContain("job_id TEXT NOT NULL UNIQUE"); + it("defines multiple triggers, per-trigger schedules, lifecycle claims, and coalescing state", () => { + expect(JOB_SCHEMA).toContain("kind IN ('schedule','webhook','jobLifecycle')"); + expect(JOB_SCHEMA).not.toContain("job_id TEXT NOT NULL UNIQUE REFERENCES jobs"); expect(JOB_SCHEMA).toContain("UNIQUE(job_id, claim_key)"); expect(JOB_SCHEMA).toContain("CREATE TABLE IF NOT EXISTS schedule_state"); + expect(JOB_SCHEMA).toContain("CREATE TABLE IF NOT EXISTS automatic_wakes"); + expect(JOB_SCHEMA).toContain("PRIMARY KEY(trigger_id,source_run_id,terminal_state)"); expect(JOB_SCHEMA).not.toContain("pipes"); }); });