From bba2c5474bc15682da7ec81f80368d95acb9fb9d Mon Sep 17 00:00:00 2001 From: Brendan Date: Wed, 16 Sep 2026 20:24:21 +0000 Subject: [PATCH] GEN-2009 add structured trigger context --- README.md | 2 +- docs/execution-boundaries.md | 12 +- docs/job-trigger-context.md | 27 ++++ packages/app/src/flow-schemas.ts | 25 ++-- packages/app/src/job-domain.ts | 43 +++---- packages/app/src/protected-api.ts | 2 +- packages/app/src/schedule.ts | 2 - packages/app/src/tenant.ts | 147 +++++++++++++++------- packages/app/src/ui.ts | 16 +-- packages/app/src/webhook-trigger.ts | 13 +- packages/app/test/flow-service.test.ts | 12 +- packages/app/test/job-domain.test.ts | 21 ++-- packages/app/test/run-inspection.test.ts | 25 +++- packages/app/test/webhook-trigger.test.ts | 4 +- 14 files changed, 213 insertions(+), 138 deletions(-) create mode 100644 docs/job-trigger-context.md diff --git a/README.md b/README.md index a1003786..5a1ea702 100644 --- a/README.md +++ b/README.md @@ -150,7 +150,7 @@ curl -X POST -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ https://app.factorize.sh/api/v1/runs/RUN_ID/stop ``` -Flow CRUD is available at `/flows` and `/flows/:id`; supporting collections are `/projects`, `/flow-options`, `/runs`, and `/flow-events`. Run and event collections return `{ "items": [...], "nextCursor": "..." }`; pass `nextCursor` back as the `cursor` query parameter. Runs can be filtered by `jobId`, `state`, and `contextQuery`; context queries use case-insensitive literal substring matching and matching items contain a bounded `context_excerpt`, never the full context. `GET /runs/:runId` returns the full triggered `context` and its invocation metadata (`source`, parameters, schedule occurrence, claim key, and timestamp). Legacy runs return `null` for `context` and `invocation`. Errors consistently use `{ "error": { "code": "...", "message": "..." } }`. +Flow CRUD is available at `/flows` and `/flows/:id`; supporting collections are `/projects`, `/flow-options`, `/runs`, and `/flow-events`. Run and event collections return `{ "items": [...], "nextCursor": "..." }`; pass `nextCursor` back as the `cursor` query parameter. Runs can be filtered by `jobId`, `state`, and `contextQuery`; context queries use case-insensitive literal substring matching and matching items contain a bounded `context_excerpt`, never the full context. `GET /runs/:runId` returns the complete structured trigger `context` and invocation metadata, including the firing `trigger_id`. Legacy runs return `null` for `context` and `invocation`. The canonical Job prompt contract is documented in [docs/job-trigger-context.md](docs/job-trigger-context.md). Errors consistently use `{ "error": { "code": "...", "message": "..." } }`. ## MCP clients diff --git a/docs/execution-boundaries.md b/docs/execution-boundaries.md index 03040314..9382d6c9 100644 --- a/docs/execution-boundaries.md +++ b/docs/execution-boundaries.md @@ -35,16 +35,16 @@ state and request/response receipt. ## Job invocation boundary -A `Job` owns a Mustache prompt template, string parameter defaults, an execution +A `Job` owns a Mustache prompt template, an execution 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` records. Stored triggers are `manual`, `schedule`, `webhook`, or +`jobLifecycle`. 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, +canonical request carries the source, firing trigger ID, structured context, a +durable claim key, and optional occurrence metadata. The invocation boundary +validates and renders the prompt, 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 diff --git a/docs/job-trigger-context.md b/docs/job-trigger-context.md new file mode 100644 index 00000000..75fa52e0 --- /dev/null +++ b/docs/job-trigger-context.md @@ -0,0 +1,27 @@ +# Job trigger context + +Every Job trigger has a server-generated immutable slug (`trigger-1`, `trigger-2`, …). The slug is returned by REST and MCP and is preserved when a Job is edited, reordered, enabled, or disabled. New triggers receive the next unused number. A manual trigger is created for every Job. + +Job prompts are Mustache templates rendered only against the firing trigger's structured context. Missing paths render as an empty string. For example: + +```mustache +{{trigger-1.prompt}} +{{trigger-2.issue.title}} +{{trigger-3.pull_request.number}} +``` + +The available value beneath a slug is: + +| Trigger | Fields | +| --- | --- | +| Manual | `prompt` | +| Schedule | `scheduled_at`, `cron`, `timezone` | +| Linear webhook | Complete Linear delivery, plus `provider`, `event`, `delivery_id` | +| GitHub webhook | Complete GitHub delivery, plus `provider`, `event`, `delivery_id` | +| Cloudflare Tail | Complete sanitized Tail delivery, plus `provider`, `event`, `delivery_id` | +| Custom webhook | Complete submitted JSON delivery, plus `provider`, `event`, `delivery_id` | +| Job lifecycle | `source_job_id`, `source_run_id`, `final_state`, `transitioned_at`, `observation_destination` | + +Manual invocation accepts `{ "prompt": "...", "idempotencyKey": "..." }`. Parameter defaults and invocation, schedule, or webhook parameter overrides are not accepted. + +Run inspection returns `context` as the complete persisted object and `invocation.trigger_id` as the trigger that fired. Parameter-era stored Jobs are migrated: old context and parameters are retained beneath `legacy_context` and `legacy_parameters` in the corresponding trigger context. They are not used as global template variables. diff --git a/packages/app/src/flow-schemas.ts b/packages/app/src/flow-schemas.ts index 4432da21..adb56f48 100644 --- a/packages/app/src/flow-schemas.ts +++ b/packages/app/src/flow-schemas.ts @@ -31,10 +31,7 @@ export const listEventsSchema = z.object({ flowId: z.string().min(1), limit: z.coerce.number().int().min(1).max(100).default(50), cursor: z.string().min(1).optional(), }); -const stringRecordSchema = z.record(z.string(), z.string()); -const webhookCommonSchema = z.object({ - context: z.string().max(50_000).optional(), parameters: stringRecordSchema.default({}), -}); +const webhookCommonSchema = z.object({}); export const webhookTriggerConfigSchema = z.discriminatedUnion("provider", [ webhookCommonSchema.extend({ provider: z.literal("linear"), projectId: z.string().min(1), matchRules: z.array(matchRuleSchema).min(1) }).strict(), webhookCommonSchema.extend({ provider: z.literal("github"), installationId: z.number().int().positive(), repositoryId: z.number().int().positive(), event: z.string().min(1).default("pull_request"), action: z.string().min(1).default("dequeued") }).strict(), @@ -42,33 +39,27 @@ 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({ id: z.string().min(1).optional(), kind: z.literal("schedule"), enabled: z.boolean().default(true), config: z.object({ + z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^trigger-[1-9][0-9]*$/).optional(), kind: z.literal("manual"), enabled: z.boolean().default(true), config: z.object({}).strict().default({}) }).strict(), + z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^trigger-[1-9][0-9]*$/).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({ 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({ + z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^trigger-[1-9][0-9]*$/).optional(), kind: z.literal("webhook"), enabled: z.boolean().default(true), config: webhookTriggerConfigSchema }).strict(), + z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^trigger-[1-9][0-9]*$/).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), promptTemplate: z.string().min(1).max(50_000), - parameterDefaults: stringRecordSchema.default({}), concurrencyLimit: z.number().int().min(1).max(50).default(1), executionTargetId: z.string().min(1), 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" }); -}); +}).strict(); export const jobIdSchema = z.object({ jobId: z.string().min(1) }); export const manualInvocationSchema = z.object({ - context: z.string().max(50_000).optional(), - parameters: stringRecordSchema.default({}), + prompt: z.string().max(50_000).default(""), idempotencyKey: z.string().trim().min(1).max(200).optional(), -}).strict().superRefine((value, ctx) => { - if (Object.prototype.hasOwnProperty.call(value.parameters, "context")) ctx.addIssue({ code: "custom", path: ["parameters", "context"], message: "context must use the reserved context field" }); -}); +}).strict(); export type FlowInput = z.infer; export type JobInput = z.infer; diff --git a/packages/app/src/job-domain.ts b/packages/app/src/job-domain.ts index 1f471b8f..8efc133c 100644 --- a/packages/app/src/job-domain.ts +++ b/packages/app/src/job-domain.ts @@ -1,6 +1,6 @@ import Mustache from "mustache"; -export type TriggerKind = "schedule" | "webhook" | "jobLifecycle"; +export type TriggerKind = "manual" | "schedule" | "webhook" | "jobLifecycle"; export type InvocationSource = "manual" | TriggerKind; export type JobRunState = "queued" | "running" | "succeeded" | "failed" | "stopped"; @@ -15,6 +15,7 @@ export interface Trigger { id: string; jobId: string; kind: TriggerKind; + slug: string; enabled: boolean; config: Record; createdAt: string; @@ -25,7 +26,6 @@ export interface Job { id: string; name: string; promptTemplate: string; - parameterDefaults: Record; executionTarget: ExecutionTarget; concurrencyLimit: number; enabled: boolean; @@ -36,8 +36,8 @@ export interface Job { export interface InvocationRequest { source: InvocationSource; - context?: string; - parameters?: Record; + triggerId: string; + context: Record; /** Stable, source-owned key used to claim this occurrence exactly once. */ claimKey: string; occurrence?: { occurredAt?: string; externalId?: string; metadata?: Record }; @@ -48,8 +48,8 @@ export interface Invocation { jobId: string; source: InvocationSource; claimKey: string; - context?: string; - parameters: Record; + triggerId: string; + context: Record; occurrence?: InvocationRequest["occurrence"]; createdAt: string; } @@ -80,22 +80,10 @@ export class InvocationError extends Error { constructor(public code: "job_not_found" | "job_disabled" | "invalid_invocation" | "invalid_template", message: string) { super(message); } } -const recordOfStrings = (value: unknown, name: string): Record => { - if (value === undefined) return {}; - if (!value || typeof value !== "object" || Array.isArray(value) || Object.values(value).some(item => typeof item !== "string")) { - throw new InvocationError("invalid_invocation", `${name} must contain only string values.`); - } - return value as Record; -}; - -export function renderJobPrompt(job: Pick, request: Pick): string { - const defaults = recordOfStrings(job.parameterDefaults, "Job parameter defaults"); - if (Object.prototype.hasOwnProperty.call(defaults, "context")) throw new InvocationError("invalid_template", "context is reserved and cannot be a job parameter."); - const overrides = recordOfStrings(request.parameters, "Invocation parameters"); - if (Object.prototype.hasOwnProperty.call(overrides, "context")) throw new InvocationError("invalid_invocation", "context is reserved and must be supplied through the context field."); +export function renderJobPrompt(job: Pick, context: Record): string { try { Mustache.parse(job.promptTemplate); - return Mustache.render(job.promptTemplate, { ...defaults, ...overrides, context: request.context ?? "" }); + return Mustache.render(job.promptTemplate, context); } catch (error) { if (error instanceof InvocationError) throw error; throw new InvocationError("invalid_template", "The job prompt is not valid Mustache."); @@ -121,10 +109,10 @@ export class InvocationService { const existing = await this.repository.findInvocation(jobId, input.claimKey); if (existing) return { ...existing, duplicate: true }; - const parameters = recordOfStrings(input.parameters, "Invocation parameters"); + if (!input.triggerId || !input.context || typeof input.context !== "object" || Array.isArray(input.context)) throw new InvocationError("invalid_invocation", "A trigger and structured context are required."); const createdAt = this.clock(); - const invocation: Invocation = { id: this.makeId(), jobId, source: input.source, claimKey: input.claimKey, ...(input.context === undefined ? {} : { context: input.context }), parameters, ...(input.occurrence ? { occurrence: input.occurrence } : {}), createdAt }; - const run: JobRun = { id: this.makeId(), jobId, invocationId: invocation.id, state: "queued", encryptedPrompt: await this.encryptPrompt(renderJobPrompt(job, input)), createdAt, updatedAt: createdAt }; + const invocation: Invocation = { id: this.makeId(), jobId, source: input.source, claimKey: input.claimKey, triggerId: input.triggerId, context: input.context, ...(input.occurrence ? { occurrence: input.occurrence } : {}), createdAt }; + const run: JobRun = { id: this.makeId(), jobId, invocationId: invocation.id, state: "queued", encryptedPrompt: await this.encryptPrompt(renderJobPrompt(job, input.context)), createdAt, updatedAt: createdAt }; if (!await this.repository.insertInvocationAndRun(invocation, run)) { const winner = await this.repository.findInvocation(jobId, input.claimKey); if (!winner) throw new Error("Invocation claim was lost without a persisted winner."); @@ -145,19 +133,20 @@ export class InvocationService { export const JOB_SCHEMA = ` CREATE TABLE IF NOT EXISTS jobs ( id TEXT PRIMARY KEY, name TEXT NOT NULL, encrypted_prompt_template TEXT NOT NULL, - parameter_defaults TEXT NOT NULL, execution_target TEXT NOT NULL, + execution_target TEXT NOT NULL, concurrency_limit INTEGER NOT NULL CHECK (concurrency_limit >= 1), enabled INTEGER NOT NULL, 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 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 + kind TEXT NOT NULL CHECK (kind IN ('manual','schedule','webhook','jobLifecycle')), slug TEXT NOT NULL, enabled INTEGER NOT NULL DEFAULT 1, config TEXT NOT NULL, + created_at TEXT NOT NULL, updated_at TEXT NOT NULL, + UNIQUE(job_id, slug) ); 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','jobLifecycle')), claim_key TEXT NOT NULL, - context TEXT, parameters TEXT NOT NULL, occurrence TEXT, created_at TEXT NOT NULL, + trigger_id TEXT NOT NULL, context TEXT NOT NULL, occurrence TEXT, created_at TEXT NOT NULL, UNIQUE(job_id, claim_key) ); CREATE TABLE IF NOT EXISTS job_runs ( diff --git a/packages/app/src/protected-api.ts b/packages/app/src/protected-api.ts index 35f6d1f3..49ab5165 100644 --- a/packages/app/src/protected-api.ts +++ b/packages/app/src/protected-api.ts @@ -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", "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("invoke_job", "Invoke a job's manual trigger with a prompt exposed beneath that trigger's stable slug. Manual invocations are never coalesced.", 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/schedule.ts b/packages/app/src/schedule.ts index 260b9435..663bcda9 100644 --- a/packages/app/src/schedule.ts +++ b/packages/app/src/schedule.ts @@ -3,8 +3,6 @@ import { CronExpressionParser } from "cron-parser"; export interface ScheduleConfig { cron: string; timezone: string; - context?: string; - parameters?: Record; } export function validateScheduleConfig(value: unknown): ScheduleConfig { diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index d5ef68e1..5ad7e439 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -90,7 +90,17 @@ 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.ensureColumn("triggers", "slug", "TEXT"); + this.ensureColumn("invocations", "trigger_id", "TEXT"); + for (const job of this.rows("SELECT id FROM jobs")) { + let index = 1; + for (const trigger of this.rows("SELECT id,slug FROM triggers WHERE job_id=? ORDER BY created_at,id", job.id)) { + if (!trigger.slug) this.ctx.storage.sql.exec("UPDATE triggers SET slug=? WHERE id=?", `trigger-${index}`, trigger.id); + index++; + } + } this.migrateSingularJobTriggers(); + this.migrateStructuredTriggerContext(); } /** Rebuild v1 Job tables because SQLite cannot drop UNIQUE/CHECK constraints in place. */ @@ -105,10 +115,12 @@ export class Tenant extends DurableObject { 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 triggers(id,job_id,kind,slug,enabled,config,created_at,updated_at) + SELECT id,job_id,kind,'trigger-1',1,config,created_at,updated_at FROM triggers_v1 WHERE kind IN ('schedule','webhook'); + INSERT INTO triggers(id,job_id,kind,slug,enabled,config,created_at,updated_at) + SELECT lower(hex(randomblob(16))),j.id,'manual','trigger-2',1,'{}',j.created_at,j.updated_at FROM jobs j; + INSERT INTO invocations(id,job_id,source,claim_key,trigger_id,context,occurrence,created_at) + SELECT i.id,i.job_id,i.source,i.claim_key,t.id,json_object(t.slug,json_object('legacy_context',COALESCE(i.context,''),'legacy_parameters',i.parameters)),i.occurrence,i.created_at FROM invocations_v1 i JOIN triggers t ON t.job_id=i.job_id AND (t.kind=i.source OR (i.source NOT IN ('manual','schedule','webhook') AND t.kind='manual')); 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) @@ -123,6 +135,34 @@ export class Tenant extends DurableObject { `); } + /** Upgrade parameter-era Job rows to the trigger-keyed structured context contract. */ + private migrateStructuredTriggerContext(): void { + const table = this.one("SELECT sql FROM sqlite_master WHERE type='table' AND name='triggers'") as Row | undefined; + if (String(table?.sql ?? "").includes("'manual'")) 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_parameters; + ALTER TABLE job_runs RENAME TO job_runs_parameters; + ALTER TABLE invocations RENAME TO invocations_parameters; + ALTER TABLE triggers RENAME TO triggers_parameters; + ${JOB_SCHEMA} + INSERT INTO triggers(id,job_id,kind,slug,enabled,config,created_at,updated_at) + SELECT id,job_id,kind,COALESCE(slug,'trigger-' || row_number() OVER (PARTITION BY job_id ORDER BY created_at,id)),enabled,config,created_at,updated_at FROM triggers_parameters; + INSERT INTO triggers(id,job_id,kind,slug,enabled,config,created_at,updated_at) + SELECT lower(hex(randomblob(16))),j.id,'manual','trigger-' || (1 + (SELECT count(*) FROM triggers t WHERE t.job_id=j.id)),1,'{}',j.created_at,j.updated_at FROM jobs j; + INSERT INTO invocations(id,job_id,source,claim_key,trigger_id,context,occurrence,created_at) + SELECT i.id,i.job_id,i.source,i.claim_key,COALESCE(i.trigger_id,t.id),json_object(COALESCE(t.slug,'trigger-1'),json_object('legacy_context',COALESCE(i.context,''),'legacy_parameters',i.parameters)),i.occurrence,i.created_at + FROM invocations_parameters i LEFT JOIN triggers t ON t.job_id=i.job_id AND t.kind=i.source; + INSERT INTO job_runs SELECT * FROM job_runs_parameters; + INSERT INTO schedule_state SELECT * FROM schedule_state_parameters; + DROP TABLE schedule_state_parameters; + DROP TABLE job_runs_parameters; + DROP TABLE invocations_parameters; + DROP TABLE triggers_parameters; + `); + } + async fetch(request: Request): Promise { const url = new URL(request.url); try { @@ -350,8 +390,7 @@ export class Tenant extends DurableObject { private async publicJob(row: Row): Promise> { 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 */ } + let executionTarget: Record = {}; try { executionTarget = JSON.parse(String(row.execution_target)); } catch { /* malformed internal state is presented safely */ } 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 => { @@ -359,14 +398,14 @@ export class Tenant extends DurableObject { 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, + return { id: trigger.id, slug: trigger.slug, 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), + concurrencyLimit: Number(row.concurrency_limit), executionTargetId: `${executionTarget.backendKind === "amp" ? "amp:" : ""}${String(executionTarget.connectionId ?? "")}`, triggers: publicTriggers, enabled: Boolean(row.enabled), createdAt: row.created_at, updatedAt: row.updated_at, @@ -387,12 +426,24 @@ 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 (!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"); + if (!Array.isArray(input.triggers) || input.triggers.some((trigger: any) => !["manual", "schedule", "webhook", "jobLifecycle"].includes(trigger?.kind))) throw new Error("Job triggers are invalid"); Mustache.parse(input.promptTemplate); for (const trigger of input.triggers) if (trigger.kind === "schedule") validateScheduleConfig(trigger.config); } + private normalizedTriggers(input: any[], existing: Map = new Map()): any[] { + const triggers = input.some(trigger => trigger.kind === "manual") ? [...input] : [{ kind: "manual", enabled: true, config: {} }, ...input]; + const used = new Set([...existing.values()].map(row => String(row.slug || "")).filter(Boolean)); + let next = 1; + return triggers.map(trigger => { + const prior = typeof trigger.id === "string" ? existing.get(trigger.id) : undefined; + if (prior?.slug) return { ...trigger, slug: String(prior.slug) }; + while (used.has(`trigger-${next}`)) next++; + const slug = `trigger-${next++}`; used.add(slug); + return { ...trigger, slug }; + }); + } + 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); @@ -409,9 +460,10 @@ export class Tenant extends DurableObject { private async createJob(input: any): Promise { this.validateJobInput(input); 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); - 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); + const triggers = this.normalizedTriggers(input.triggers); + this.validateLifecycleGraph(jobId, triggers); + this.ctx.storage.sql.exec("INSERT INTO jobs (id,name,encrypted_prompt_template,execution_target,concurrency_limit,enabled,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)", jobId, input.name, await encrypt(input.promptTemplate, this.env.CREDENTIAL_ENCRYPTION_KEY), JSON.stringify(target), input.concurrencyLimit, 1, timestamp, timestamp); + for (const trigger of triggers) this.ctx.storage.sql.exec("INSERT INTO triggers (id,job_id,kind,slug,enabled,config,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)", trigger.id ?? id(), jobId, trigger.kind, trigger.slug, 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)); } @@ -424,15 +476,16 @@ 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); const existing = new Map(this.triggersFor(jobId).map(trigger => [String(trigger.id), trigger])); + const triggers = this.normalizedTriggers(input.triggers, existing); + this.validateLifecycleGraph(jobId, triggers); + const target = await this.jobTarget(input.executionTargetId), timestamp = now(); + this.ctx.storage.sql.exec("UPDATE jobs SET name=?,encrypted_prompt_template=?,execution_target=?,concurrency_limit=?,updated_at=? WHERE id=?", input.name, await encrypt(input.promptTemplate, this.env.CREDENTIAL_ENCRYPTION_KEY), JSON.stringify(target), input.concurrencyLimit, timestamp, jobId); const retained = new Set(); - for (const trigger of input.triggers) { + for (const trigger of 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); + else this.ctx.storage.sql.exec("INSERT INTO triggers (id,job_id,kind,slug,enabled,config,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)", triggerId, jobId, trigger.kind, trigger.slug, 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); @@ -475,21 +528,23 @@ export class Tenant extends DurableObject { const job = this.one("SELECT enabled FROM jobs WHERE id=?", jobId) as Row | undefined; if (!job) return new Response("Not found", { status: 404 }); if (!Boolean(job.enabled)) return Response.json({ error: "Job is disabled" }, { status: 409 }); - const result = await this.invokeCanonicalJob(jobId, "manual", input.idempotencyKey ? `manual:${input.idempotencyKey}` : `manual:${id()}`, input.context, object(input.parameters)); + const trigger = this.one("SELECT id,slug FROM triggers WHERE job_id=? AND kind='manual' AND enabled=1 ORDER BY created_at,id LIMIT 1", jobId) as Row | undefined; + if (!trigger) return Response.json({ error: "The manual trigger is disabled" }, { status: 409 }); + const result = await this.invokeCanonicalJob(jobId, "manual", String(trigger.id), input.idempotencyKey ? `manual:${input.idempotencyKey}` : `manual:${id()}`, { [String(trigger.slug)]: { prompt: String(input.prompt ?? "") } }); if (!result) return Response.json({ error: "Job is disabled" }, { status: 409 }); return json(result); } /** 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> { + private async invokeCanonicalJob(jobId: string, source: "manual" | "schedule" | "webhook" | "jobLifecycle", triggerId: string, claimKey: string, context: 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; if (existing) return { invocationId: existing.invocation_id, runId: existing.run_id, state: existing.state, duplicate: true }; const job = await this.publicJob(row); - const prompt = renderJobPrompt({ promptTemplate: String(job.promptTemplate), parameterDefaults: job.parameterDefaults as Record }, { context, parameters }); + const prompt = renderJobPrompt({ promptTemplate: String(job.promptTemplate) }, context); const invocationId = id(), runId = id(), timestamp = now(); - 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); + this.ctx.storage.sql.exec("INSERT OR IGNORE INTO invocations (id,job_id,source,claim_key,trigger_id,context,occurrence,created_at) VALUES (?,?,?,?,?,?,?,?)", invocationId, jobId, source, claimKey, triggerId, JSON.stringify(context), occurrence ? JSON.stringify(occurrence) : null, timestamp); const winner = this.one("SELECT id FROM invocations WHERE job_id=? AND claim_key=?", jobId, claimKey) as Row; if (winner.id !== invocationId) { const duplicate = this.one("SELECT id,state FROM job_runs WHERE invocation_id=?", winner.id) as Row; @@ -506,13 +561,13 @@ 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> { + private async signalAutomaticJob(jobId: string, source: "schedule" | "webhook" | "jobLifecycle", triggerId: string, claimKey: string, context: 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); + if (!active) return this.invokeCanonicalJob(jobId, source, triggerId, claimKey, context, 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); + this.ctx.storage.sql.exec("INSERT OR IGNORE INTO invocations (id,job_id,source,claim_key,trigger_id,context,occurrence,created_at) VALUES (?,?,?,?,?,?,?,?)", invocationId, jobId, source, claimKey, triggerId, JSON.stringify(context), 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 */ } @@ -526,9 +581,10 @@ export class Tenant extends DurableObject { 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 trigger = this.one("SELECT id,slug,kind FROM triggers WHERE job_id=? AND kind!='manual' ORDER BY created_at,id LIMIT 1", jobId) as Row | undefined; + if (trigger) await this.invokeCanonicalJob(jobId, String(trigger.kind) as any, String(trigger.id), `trailing:${sourceRunId}:${transitionedAt}`, { [String(trigger.slug)]: { coalesced: true, summary: JSON.parse(String(wake.summary)) } }, { 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"); + const subscribers = this.rows("SELECT t.id,t.slug,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; @@ -536,26 +592,26 @@ export class Tenant extends DurableObject { 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 } }); + const context = { [String(trigger.slug)]: { source_job_id: jobId, source_run_id: sourceRunId, final_state: terminalState, transitioned_at: transitionedAt, observation_destination: destination } }; + await this.signalAutomaticJob(String(trigger.job_id), "jobLifecycle", String(trigger.id), `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.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); + const due = this.rows("SELECT s.job_id,s.trigger_id,s.next_run_at,t.slug,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), String(row.trigger_id), occurredAt, config); + await this.enqueueScheduledJob(String(row.job_id), String(row.trigger_id), String(row.slug), 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, triggerId: string, occurredAt: string, config: ScheduleConfig): Promise { - await this.signalAutomaticJob(jobId, "schedule", `schedule:${triggerId}:${occurredAt}`, config.context, config.parameters ?? {}, { occurredAt, metadata: { triggerId } }); + private async enqueueScheduledJob(jobId: string, triggerId: string, slug: string, occurredAt: string, config: ScheduleConfig): Promise { + await this.signalAutomaticJob(jobId, "schedule", triggerId, `schedule:${triggerId}:${occurredAt}`, { [slug]: { scheduled_at: occurredAt, cron: config.cron, timezone: config.timezone } }, { occurredAt, metadata: { triggerId } }); } private deletePipe(pipeId: string): Response { @@ -694,19 +750,20 @@ export class Tenant extends DurableObject { private async getRun(runId: string): Promise { const run = this.one(`SELECT r.id, r.pipe_id AS job_id, r.issue_id, r.issue_url, r.agent_name, r.workspace_name, r.agent_kind, r.state, r.provider, r.execution_backend_kind AS backend_kind, r.execution_capabilities AS capabilities, r.destination_url, r.result, r.exec_status, r.exec_exit_code, r.recovery_last_action, r.created_at, r.updated_at, - i.id AS invocation_id, i.job_id AS invocation_job_id, i.source AS invocation_source, i.claim_key AS invocation_claim_key, i.context, i.parameters AS invocation_parameters, i.occurrence AS invocation_occurrence, i.created_at AS invocation_created_at + i.id AS invocation_id, i.job_id AS invocation_job_id, i.source AS invocation_source, i.claim_key AS invocation_claim_key, i.trigger_id AS invocation_trigger_id, i.context, i.occurrence AS invocation_occurrence, i.created_at AS invocation_created_at FROM runs r LEFT JOIN job_runs jr ON jr.id = r.id LEFT JOIN invocations i ON i.id = jr.invocation_id WHERE r.id = ?`, runId); if (!run) return new Response("Not found", { status: 404 }); if (run.invocation_id) { - let parameters: unknown = {}, occurrence: unknown = null; - try { parameters = JSON.parse(String(run.invocation_parameters || "{}")); } catch { /* Persisted invocation remains readable if metadata is malformed. */ } + let context: unknown = {}, occurrence: unknown = null; + try { context = JSON.parse(String(run.context || "{}")); } catch { context = { legacy: String(run.context ?? "") }; } try { occurrence = run.invocation_occurrence == null ? null : JSON.parse(String(run.invocation_occurrence)); } catch { /* Persisted invocation remains readable if metadata is malformed. */ } - run.invocation = { id: run.invocation_id, job_id: run.invocation_job_id, source: run.invocation_source, claim_key: run.invocation_claim_key, parameters, occurrence, created_at: run.invocation_created_at }; + run.context = context; + run.invocation = { id: run.invocation_id, job_id: run.invocation_job_id, source: run.invocation_source, trigger_id: run.invocation_trigger_id, claim_key: run.invocation_claim_key, context, occurrence, created_at: run.invocation_created_at }; } else { run.context = null; run.invocation = null; } - for (const key of ["invocation_id", "invocation_job_id", "invocation_source", "invocation_claim_key", "invocation_parameters", "invocation_occurrence", "invocation_created_at"]) delete run[key]; + for (const key of ["invocation_id", "invocation_job_id", "invocation_source", "invocation_trigger_id", "invocation_claim_key", "invocation_occurrence", "invocation_created_at"]) delete run[key]; if (run.state !== "ignored" && typeof run.result === "string" && run.result) run.result = await decrypt(run.result, this.env.CREDENTIAL_ENCRYPTION_KEY); run.activity = this.rows("SELECT action, detail, created_at FROM run_activity WHERE run_id = ? ORDER BY created_at, id", runId); this.presentExecution(run); @@ -773,9 +830,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; 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 webhookJobs(provider: WebhookProvider): Array<{ job: Row; triggerId: string; triggerSlug: string; config: WebhookTriggerConfig }> { + return this.rows("SELECT j.*,t.id AS trigger_id,t.slug AS trigger_slug,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), triggerSlug: String(job.trigger_slug), config }] : []; } catch { return []; } }) as any; } private recordJobEvent(jobId: string, provider: string, deliveryId: string, outcome: string, detail: string): void { @@ -783,10 +840,10 @@ export class Tenant extends DurableObject { } private async invokeWebhookJobs(provider: WebhookProvider, deliveryId: string, payload: Record, eventName?: string): Promise { - for (const { job, triggerId, config } of this.webhookJobs(provider)) { + for (const { job, triggerId, triggerSlug, config } of this.webhookJobs(provider) as any[]) { 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.signalAutomaticJob(String(job.id), "webhook", `webhook:${triggerId}:${invocation.claimKey}`, invocation.context, invocation.parameters, { ...invocation.occurrence, metadata: { ...invocation.occurrence?.metadata, triggerId } }); + const result = await this.signalAutomaticJob(String(job.id), "webhook", triggerId, `webhook:${triggerId}:${invocation.claimKey}`, { [triggerSlug]: invocation.payload }, { ...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."); } } @@ -977,7 +1034,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.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 job = pipe ? undefined : this.one("SELECT j.*,t.id AS trigger_id,t.slug AS trigger_slug,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; @@ -999,7 +1056,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.signalAutomaticJob(String(job.id), "webhook", `webhook:${String(job.trigger_id)}:${invocation.claimKey}`, invocation.context, invocation.parameters, invocation.occurrence); + if (invocation) await this.signalAutomaticJob(String(job.id), "webhook", String(job.trigger_id), `webhook:${String(job.trigger_id)}:${invocation.claimKey}`, { [String((job as any).trigger_slug)]: invocation.payload }, 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; } diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 4cfd20b4..c486ce69 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -207,24 +207,24 @@ ${dashboardHead("Jobs", "Create reusable agent work and choose exactly how it st

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-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.")}
-
+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 structured trigger values through stable Mustache paths.")}
+

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;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')});`); +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.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'}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.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'))};if(kind==='webhook'){const provider=d.get('provider'),base={provider};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')),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))]),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)+'

');`); +async function runNow(job){const value=prompt('Prompt for this manual run:','');if(value===null)return;const x=await request('/api/jobs/'+encodeURIComponent(id)+'/invocations',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({prompt:value})});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))]),triggers=j.triggers||[];const triggerDetail=triggers.map(t=>esc(t.slug)+' · '+esc(t.kind)).join(' · ');root.innerHTML='

'+esc(j.name)+'

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

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

Edit

Prompt template

'+esc(j.promptTemplate)+'

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/src/webhook-trigger.ts b/packages/app/src/webhook-trigger.ts index b15978c5..fc7ea8af 100644 --- a/packages/app/src/webhook-trigger.ts +++ b/packages/app/src/webhook-trigger.ts @@ -3,18 +3,15 @@ import type { MatchRule } from "./types"; export type WebhookProvider = "linear" | "github" | "cloudflareTail" | "custom"; export type WebhookTriggerConfig = { - provider: WebhookProvider; context?: string; parameters?: Record; + provider: WebhookProvider; projectId?: string; matchRules?: MatchRule[]; installationId?: number; repositoryId?: number; event?: string; action?: string; signingSecret?: string; secret?: string; handlerCode?: string; }; export interface WebhookInvocation { - claimKey: string; context: string; parameters: Record; + claimKey: string; payload: Record; occurrence: { externalId: string; metadata: Record }; } -const strings = (value: unknown): Record => value && typeof value === "object" && !Array.isArray(value) - ? Object.fromEntries(Object.entries(value).filter((entry): entry is [string, string] => typeof entry[1] === "string")) : {}; - /** Pure provider adapter: matching and normalization only; it never launches execution. */ export function adaptWebhook(config: WebhookTriggerConfig, provider: WebhookProvider, deliveryId: string, payload: Record, eventName?: string): WebhookInvocation | null { if (config.provider !== provider) return null; @@ -27,10 +24,12 @@ export function adaptWebhook(config: WebhookTriggerConfig, provider: WebhookProv if ((eventName ?? "") !== (config.event ?? "pull_request") || payload.action !== (config.action ?? "dequeued")) return null; } const normalizedProvider = provider === "cloudflareTail" ? "cloudflare" : provider; + const providerAliases = provider === "linear" + ? { issue: payload.data?.issue ?? (payload.type === "Issue" ? payload.data : undefined) } + : {}; return { claimKey: `webhook:${normalizedProvider}:${deliveryId}`, - context: config.context ?? JSON.stringify(payload), - parameters: { ...strings(config.parameters), provider: normalizedProvider, event: eventName ?? String(payload.type ?? "webhook"), deliveryId }, + payload: { ...payload, ...providerAliases, provider: normalizedProvider, event: eventName ?? payload.type ?? "webhook", delivery_id: deliveryId }, occurrence: { externalId: deliveryId, metadata: { provider: normalizedProvider, event: eventName ?? payload.type ?? "webhook", action: payload.action ?? null } }, }; } diff --git a/packages/app/test/flow-service.test.ts b/packages/app/test/flow-service.test.ts index e5a5a8a8..d3cccdd6 100644 --- a/packages/app/test/flow-service.test.ts +++ b/packages/app/test/flow-service.test.ts @@ -46,8 +46,8 @@ 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", triggers: [] }); - await service.invokeJob("job-1", { parameters: {}, idempotencyKey: "client-1" }); + await service.createJob({ name: "Manual", promptTemplate: "{{trigger-1.prompt}}", concurrencyLimit: 1, executionTargetId: "target-1", triggers: [] }); + await service.invokeJob("job-1", { prompt: "go", idempotencyKey: "client-1" }); expect(requests).toEqual(["POST /v1/jobs", "POST /v1/jobs/job-1/invocations"]); }); }); @@ -66,11 +66,11 @@ 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", triggers: [{ kind: "schedule", config: { cron: "0 * * * *", timezone: "UTC" } }, { kind: "jobLifecycle", config: { sourceJobIds: ["worker"], states: ["succeeded", "failed"] } }] }); + const job = jobInputSchema.parse({ name: "Deploy", promptTemplate: "Deploy {{trigger-1.prompt}}", 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(); - expect(manualInvocationSchema.parse({ context: "ticket", parameters: { environment: "prod" } })).toMatchObject({ context: "ticket" }); + expect(() => jobInputSchema.parse({ ...job, parameterDefaults: {} })).toThrow(); + expect(() => manualInvocationSchema.parse({ parameters: {} })).toThrow(); + expect(manualInvocationSchema.parse({ prompt: "ticket" })).toMatchObject({ prompt: "ticket" }); }); }); diff --git a/packages/app/test/job-domain.test.ts b/packages/app/test/job-domain.test.ts index 5aab8ece..e662f266 100644 --- a/packages/app/test/job-domain.test.ts +++ b/packages/app/test/job-domain.test.ts @@ -2,8 +2,7 @@ import { describe, expect, it } from "vitest"; import { InvocationService, JOB_SCHEMA, renderJobPrompt, type Invocation, type Job, type JobRepository, type JobRun } from "../src/job-domain"; const job = (overrides: Partial = {}): Job => ({ - id: "job-1", name: "Triage", promptTemplate: "{{greeting}}, {{name}}!\n{{context}}", - parameterDefaults: { greeting: "Hello", name: "world" }, + id: "job-1", name: "Triage", promptTemplate: "{{trigger-1.prompt}} · {{trigger-2.issue.title}}", executionTarget: { connectionId: "exe-1", workspace: "triage", cwd: "/repo", agentKind: "codex" }, concurrencyLimit: 1, enabled: true, triggers: [], @@ -20,32 +19,32 @@ class MemoryRepository implements JobRepository { } describe("job invocation domain", () => { - it("applies defaults, overrides, and the reserved context", () => { - expect(renderJobPrompt(job(), { parameters: { name: "Ada" }, context: "Fix GEN-2000" })).toBe("Hello, Ada!\nFix GEN-2000"); - expect(() => renderJobPrompt(job({ parameterDefaults: { context: "not allowed" } }), {})).toThrow(/reserved/); - expect(() => renderJobPrompt(job(), { parameters: { context: "not allowed" } })).toThrow(/reserved/); + it("renders structured trigger paths and empty missing values", () => { + expect(renderJobPrompt(job(), { "trigger-1": { prompt: "Fix it" }, "trigger-2": { issue: { title: "Bug" } } })).toBe("Fix it · Bug"); + expect(renderJobPrompt(job(), { "trigger-1": { prompt: "Fix it" } })).toBe("Fix it · "); }); it("queues one encrypted run for a claim regardless of source retries", async () => { const repository = new MemoryRepository(); let ids = 0; const service = new InvocationService(repository, async value => `encrypted:${value}`, () => `id-${++ids}`, () => "2026-09-16T00:00:00.000Z"); - const request = { source: "webhook" as const, claimKey: "delivery-7", context: "Issue payload", parameters: { greeting: "Hi" }, occurrence: { externalId: "evt-7", metadata: { provider: "linear" } } }; + const request = { source: "webhook" as const, triggerId: "webhook-1", claimKey: "delivery-7", context: { "trigger-2": { issue: { title: "Issue payload" } } }, occurrence: { externalId: "evt-7", metadata: { provider: "linear" } } }; const first = await service.invoke("job-1", request), retry = await service.invoke("job-1", request); expect(first.duplicate).toBe(false); expect(retry.duplicate).toBe(true); - expect(retry.run.id).toBe(first.run.id); expect(first.run.encryptedPrompt).toBe("encrypted:Hi, world!\nIssue payload"); + expect(retry.run.id).toBe(first.run.id); expect(first.run.encryptedPrompt).toBe("encrypted: · Issue payload"); expect(JSON.stringify(first)).not.toContain('"prompt":"Hi'); }); it("starts queued runs only while the job has capacity", async () => { const repository = new MemoryRepository(); const service = new InvocationService(repository, async value => value, undefined, () => "then"); - const first = await service.invoke("job-1", { source: "manual", claimKey: "one" }); - const second = await service.invoke("job-1", { source: "schedule", claimKey: "two", occurrence: { occurredAt: "2026-09-16T01:00:00Z" } }); + const first = await service.invoke("job-1", { source: "manual", triggerId: "manual-1", claimKey: "one", context: { "trigger-1": { prompt: "go" } } }); + const second = await service.invoke("job-1", { source: "schedule", triggerId: "schedule-1", claimKey: "two", context: { "trigger-3": { scheduled_at: "2026-09-16T01:00:00Z" } }, occurrence: { occurredAt: "2026-09-16T01:00:00Z" } }); expect((await service.startIfCapacity(first.run))?.state).toBe("running"); expect(await service.startIfCapacity(second.run)).toBeNull(); }); it("defines multiple triggers, per-trigger schedules, lifecycle claims, and coalescing state", () => { - expect(JOB_SCHEMA).toContain("kind IN ('schedule','webhook','jobLifecycle')"); + expect(JOB_SCHEMA).toContain("kind IN ('manual','schedule','webhook','jobLifecycle')"); + expect(JOB_SCHEMA).toContain("UNIQUE(job_id, slug)"); 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"); diff --git a/packages/app/test/run-inspection.test.ts b/packages/app/test/run-inspection.test.ts index a9c72b72..f68e0196 100644 --- a/packages/app/test/run-inspection.test.ts +++ b/packages/app/test/run-inspection.test.ts @@ -11,6 +11,21 @@ function tenantWithRows(rows: (query: string, ...params: unknown[]) => Record { + it("preserves trigger slugs across edits and reordering", () => { + const tenant = Object.create(Tenant.prototype) as Tenant; + const existing = new Map([ + ["manual", { id: "manual", slug: "trigger-1" }], + ["schedule", { id: "schedule", slug: "trigger-2" }], + ["webhook", { id: "webhook", slug: "trigger-3" }], + ]); + const triggers = (tenant as any).normalizedTriggers([ + { id: "webhook", kind: "webhook", config: { provider: "custom" } }, + { id: "manual", kind: "manual", config: {} }, + { kind: "schedule", config: { cron: "0 * * * *", timezone: "UTC" } }, + ], existing); + expect(triggers.map((trigger: any) => trigger.slug)).toEqual(["trigger-3", "trigger-1", "trigger-4"]); + }); + it("combines literal context search with run filters and returns only a bounded excerpt", async () => { let statement = ""; let bindings: unknown[] = []; @@ -38,15 +53,15 @@ describe("run invocation inspection", () => { it("returns full canonical invocation metadata and nulls for a legacy run", async () => { const canonical = tenantWithRows((query) => query.includes("FROM runs r") ? [{ id: "run-1", job_id: "job-1", state: "queued", backend_kind: "amp", capabilities: "[]", result: null, - context: "Exact Triggered Context", invocation_id: "inv-1", invocation_job_id: "job-1", invocation_source: "schedule", - invocation_claim_key: "schedule:occurrence-1", invocation_parameters: '{"region":"west"}', + context: '{"trigger-2":{"scheduled_at":"2026-09-16T12:00:00Z"}}', invocation_id: "inv-1", invocation_job_id: "job-1", invocation_source: "schedule", invocation_trigger_id: "schedule-1", + invocation_claim_key: "schedule:occurrence-1", invocation_occurrence: '{"occurredAt":"2026-09-16T12:00:00Z"}', invocation_created_at: "2026-09-16T12:00:01Z", }] : []); const canonicalBody = await ((canonical as any).getRun("run-1") as Promise).then((response: Response) => response.json()) as any; - expect(canonicalBody.context).toBe("Exact Triggered Context"); + expect(canonicalBody.context).toEqual({ "trigger-2": { scheduled_at: "2026-09-16T12:00:00Z" } }); expect(canonicalBody.invocation).toEqual({ - id: "inv-1", job_id: "job-1", source: "schedule", claim_key: "schedule:occurrence-1", - parameters: { region: "west" }, occurrence: { occurredAt: "2026-09-16T12:00:00Z" }, created_at: "2026-09-16T12:00:01Z", + id: "inv-1", job_id: "job-1", source: "schedule", trigger_id: "schedule-1", claim_key: "schedule:occurrence-1", + context: { "trigger-2": { scheduled_at: "2026-09-16T12:00:00Z" } }, occurrence: { occurredAt: "2026-09-16T12:00:00Z" }, created_at: "2026-09-16T12:00:01Z", }); const legacy = tenantWithRows((query) => query.includes("FROM runs r") ? [{ id: "legacy-1", job_id: "flow-1", state: "done", backend_kind: "exe-herdr", capabilities: "[]", result: null }] : []); diff --git a/packages/app/test/webhook-trigger.test.ts b/packages/app/test/webhook-trigger.test.ts index d1aac423..ff2001d2 100644 --- a/packages/app/test/webhook-trigger.test.ts +++ b/packages/app/test/webhook-trigger.test.ts @@ -3,9 +3,9 @@ import { adaptWebhook, publicWebhookConfig } from "../src/webhook-trigger"; describe("webhook Job trigger adapters", () => { it("matches Linear and derives a stable claim plus string invocation inputs", () => { - const config = { provider: "linear" as const, projectId: "p1", matchRules: [{ type: "status" as const, targetId: "done" }], parameters: { mode: "fix" } }; + const config = { provider: "linear" as const, projectId: "p1", matchRules: [{ type: "status" as const, targetId: "done" }] }; const payload = { type: "Issue", action: "update", data: { id: "i1", project: { id: "p1" }, state: { id: "done" } }, updatedFrom: { stateId: "todo" } }; - expect(adaptWebhook(config, "linear", "linear:d1", payload)).toMatchObject({ claimKey: "webhook:linear:linear:d1", parameters: { mode: "fix", provider: "linear", deliveryId: "linear:d1" }, occurrence: { externalId: "linear:d1" } }); + expect(adaptWebhook(config, "linear", "linear:d1", payload)).toMatchObject({ claimKey: "webhook:linear:linear:d1", payload: { data: { id: "i1" }, provider: "linear", delivery_id: "linear:d1" }, occurrence: { externalId: "linear:d1" } }); }); it("matches GitHub installation, repository, event, and action", () => {