From b904464eead5b9fef49f2f6a6ec45f155eab94d4 Mon Sep 17 00:00:00 2001 From: Brendan Date: Wed, 16 Sep 2026 21:20:00 +0000 Subject: [PATCH] Add trigger context reflection and autocomplete --- docs/job-trigger-context.md | 2 + packages/app/src/tenant.ts | 3 +- packages/app/src/trigger-context.ts | 62 +++++++++++++++++++++++ packages/app/src/ui.ts | 16 ++++-- packages/app/test/trigger-context.test.ts | 20 ++++++++ packages/app/test/ui.test.ts | 5 ++ 6 files changed, 103 insertions(+), 5 deletions(-) create mode 100644 packages/app/src/trigger-context.ts create mode 100644 packages/app/test/trigger-context.test.ts diff --git a/docs/job-trigger-context.md b/docs/job-trigger-context.md index 37c3b198..dcdc2bcd 100644 --- a/docs/job-trigger-context.md +++ b/docs/job-trigger-context.md @@ -22,6 +22,8 @@ The available value beneath a slug is: | 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` | +Every trigger returned by `GET /api/v1/jobs` and `GET /api/v1/jobs/:id` (and the corresponding MCP `list_jobs` and `get_job` tools) includes a `reflection` object. It contains the stable `slug`, trigger kind/provider, whether the result is dynamic, and a flat `paths` list with nested path, basic value type, description, and occasional example. The Job editor consumes this same canonical contract for Mustache autocomplete. A custom webhook, or any webhook with a replacing handler, reports `dynamic: true` and an explicit `*`/`unknown` fallback because arbitrary handler output cannot be inferred safely. + 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/tenant.ts b/packages/app/src/tenant.ts index 2656f4ea..2b5ad3d4 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -19,6 +19,7 @@ import { JOB_SCHEMA, renderJobPrompt } from "./job-domain"; import { normalizeExecutionState, type RunHandle } from "./execution"; import { catchUpOccurrence, nextOccurrence, validateScheduleConfig, type ScheduleConfig } from "./schedule"; import { adaptWebhook, publicWebhookConfig, validateWebhookHandler, type WebhookProvider, type WebhookTriggerConfig } from "./webhook-trigger"; +import { reflectTriggerContext } from "./trigger-context"; export { DEFAULT_CONTEXT_TEMPLATE, linearTicketPrompt, renderContextTemplate } from "./linear-source"; @@ -400,7 +401,7 @@ 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, slug: trigger.slug, 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, reflection: reflectTriggerContext({ ...trigger, 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 } : {}) }; }); diff --git a/packages/app/src/trigger-context.ts b/packages/app/src/trigger-context.ts new file mode 100644 index 00000000..82b9f14d --- /dev/null +++ b/packages/app/src/trigger-context.ts @@ -0,0 +1,62 @@ +export type ContextValueType = "string" | "number" | "boolean" | "object" | "array" | "unknown"; +export interface ContextPath { path: string; type: ContextValueType; description: string; example?: unknown; } +export interface TriggerContextReflection { slug: string; kind: string; provider?: string; dynamic: boolean; paths: ContextPath[]; } + +const commonWebhook: ContextPath[] = [ + { path: "provider", type: "string", description: "Normalized webhook provider name." }, + { path: "event", type: "string", description: "Provider event name." }, + { path: "delivery_id", type: "string", description: "Stable delivery identifier used for deduplication." }, +]; + +export const triggerContextCatalog: Record = { + manual: [{ path: "prompt", type: "string", description: "Prompt supplied by the manual invocation.", example: "Review the failing build" }], + schedule: [ + { path: "scheduled_at", type: "string", description: "Scheduled occurrence as an ISO 8601 timestamp.", example: "2026-09-16T09:00:00.000Z" }, + { path: "cron", type: "string", description: "Configured cron expression.", example: "0 9 * * *" }, + { path: "timezone", type: "string", description: "Configured IANA timezone.", example: "UTC" }, + ], + linear: [...commonWebhook, + { path: "issue", type: "object", description: "Complete Linear issue from the authenticated delivery." }, + { path: "issue.id", type: "string", description: "Linear issue UUID." }, + { path: "issue.identifier", type: "string", description: "Human-readable issue identifier.", example: "GEN-2019" }, + { path: "issue.title", type: "string", description: "Issue title." }, + { path: "issue.description", type: "string", description: "Issue description, when present." }, + { path: "issue.url", type: "string", description: "Canonical Linear issue URL." }, + { path: "issue.state.name", type: "string", description: "Current workflow state name." }, + { path: "issue.project.name", type: "string", description: "Project name, when present." }, + ], + github: [...commonWebhook, + { path: "action", type: "string", description: "GitHub webhook action." }, + { path: "pull_request", type: "object", description: "Complete GitHub pull request payload." }, + { path: "pull_request.number", type: "number", description: "Pull request number.", example: 42 }, + { path: "pull_request.title", type: "string", description: "Pull request title." }, + { path: "pull_request.html_url", type: "string", description: "Pull request URL." }, + { path: "pull_request.base.ref", type: "string", description: "Base branch name." }, + { path: "pull_request.head.ref", type: "string", description: "Head branch name." }, + { path: "repository.full_name", type: "string", description: "Owner and repository name.", example: "acme/widgets" }, + ], + cloudflareTail: [...commonWebhook, + { path: "outcome", type: "string", description: "Sanitized Worker invocation outcome." }, + { path: "scriptName", type: "string", description: "Worker script that emitted the Tail event." }, + { path: "eventTimestamp", type: "number", description: "Event timestamp in milliseconds." }, + { path: "logs", type: "array", description: "Sanitized console log records." }, + { path: "exceptions", type: "array", description: "Sanitized exception records." }, + ], + custom: [...commonWebhook, { path: "*", type: "unknown", description: "Additional submitted JSON fields are dynamic and may be nested." }], + jobLifecycle: [ + { path: "source_job_id", type: "string", description: "Job whose run reached a final state." }, + { path: "source_run_id", type: "string", description: "Run that reached a final state." }, + { path: "final_state", type: "string", description: "Observed final state: succeeded, failed, or stopped." }, + { path: "transitioned_at", type: "string", description: "State transition as an ISO 8601 timestamp." }, + { path: "observation_destination", type: "string", description: "Backend observation URL, when available." }, + ], +}; + +export function reflectTriggerContext(trigger: { slug?: unknown; kind?: unknown; config?: any }): TriggerContextReflection { + const kind = String(trigger.kind ?? ""), provider = kind === "webhook" ? String(trigger.config?.provider ?? "custom") : undefined; + const key = provider ?? kind, handler = kind === "webhook" && typeof trigger.config?.handlerCode === "string" && trigger.config.handlerCode.trim().length > 0; + return { + slug: String(trigger.slug ?? ""), kind, ...(provider ? { provider } : {}), dynamic: key === "custom" || handler, + paths: handler ? [{ path: "*", type: "unknown", description: "The custom handler replaces context with a dynamic JSON object; inspect the handler contract." }] : (triggerContextCatalog[key] ?? [{ path: "*", type: "unknown", description: "Context shape is not known." }]), + }; +} diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 4e5f749f..452c3e1b 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -1,4 +1,5 @@ /** Framework-light pages; Tailwind is compiled locally into public/styles.css. */ +import { triggerContextCatalog } from "./trigger-context"; type Viewer = { email: string } | null; const escapeHtml = (value: string) => value.replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]!); @@ -212,7 +213,7 @@ async function load(){const jobs=await request('/api/jobs');const root=$('#jobs' export const jobPage = (viewer: { email: string }, jobId?: string) => shell(`${jobId ? "Edit" : "Create"} job — Factorize`, viewer, `
← Jobs
${dashboardHead(jobId ? "Edit job" : "Create a job", "Every prompt input comes from an explicit trigger row with a stable context slug.")}

Step 1

Job details

Name this job and set how many runs it can process at once.

Step 2

Triggers

Choose the events that start this job and expose prompt context.

Context slugTypeConfigurationEnabledActions
-

Step 3

Prompt and context

Write the instructions for each run using context supplied by your triggers.

+

Step 3

Prompt and context

Write the instructions for each run using context supplied by your triggers.

Step 4

Execution target

Select the connected environment that will run this job.

Add trigger

Provider credentials stay managed by Factorize.

@@ -220,16 +221,23 @@ export const jobPage = (viewer: { email: string }, jobId?: string) => shell(`${j
`, `${uiHelpers} -const jobId=${JSON.stringify(jobId ?? null)},form=$('#job'),dialog=$('#trigger-dialog'),triggerForm=$('#trigger-form');let triggers=[],editing=-1,resources={projects:[],options:{statuses:[],users:[],labels:[]},installations:[],repositories:new Map(),jobs:[]},clientId=0,reservedSlugs=new Set(); +const jobId=${JSON.stringify(jobId ?? null)},contextCatalog=${JSON.stringify(triggerContextCatalog)},form=$('#job'),dialog=$('#trigger-dialog'),triggerForm=$('#trigger-form');let triggers=[],editing=-1,resources={projects:[],options:{statuses:[],users:[],labels:[]},installations:[],repositories:new Map(),jobs:[]},clientId=0,reservedSlugs=new Set(); const kinds={manual:'Manual',schedule:'Schedule',linear:'Linear',github:'GitHub',cloudflareTail:'Cloudflare Tail',custom:'Custom webhook',jobLifecycle:'Job lifecycle'}; const providerKind=t=>t.kind==='webhook'?t.config.provider:t.kind; -const contextHint=t=>{const k=providerKind(t),s=t.slug;return k==='manual'?s+'.prompt':k==='schedule'?s+'.scheduled_at':k==='linear'?s+'.issue.title':k==='github'?s+'.pull_request.number':k==='cloudflareTail'?s+'.outcome':k==='custom'?s+'.delivery_id':s+'.source_run_id'}; +const reflection=t=>t.reflection?.paths||contextCatalog[providerKind(t)]||[]; +const contextPaths=()=>triggers.flatMap(t=>reflection(t).filter(x=>x.path!=='*').map(x=>({path:t.slug+'.'+x.path,type:x.type,description:x.description}))); const nameOf=(items,id)=>items.find(x=>String(x.id)===String(id))?.name||String(id||'Not selected'); const ruleLabels={status:'Status',label:'Label',assignee:'Assignee',creator:'Creator',owner:'Owner'}; const ruleOptions=type=>type==='status'?resources.options.statuses:type==='label'?resources.options.labels:resources.options.users; const ruleSummary=rule=>ruleLabels[rule.type]+' is '+nameOf(ruleOptions(rule.type),rule.targetId); function summary(t){const c=t.config||{},k=providerKind(t);if(k==='manual')return 'Prompt entered when run';if(k==='schedule')return c.cron+' · '+c.timezone;if(k==='linear')return nameOf(resources.projects,c.projectId)+' · '+(c.matchRules||[]).map(ruleSummary).join(' + ');if(k==='github'){const i=resources.installations.find(x=>String(x.installationId)===String(c.installationId));const repos=resources.repositories.get(String(c.installationId))||[];return (i?.accountLogin||c.installationId)+' · '+(repos.find(x=>String(x.id)===String(c.repositoryId))?.fullName||c.repositoryId)+' · '+c.event+'/'+c.action}if(k==='cloudflareTail')return 'Managed signed Tail endpoint'+(c.handlerCode?' · handler':'');if(k==='custom')return 'Managed custom endpoint'+(c.handlerCode?' · handler':'');return (c.sourceJobIds||[]).map(id=>resources.jobs.find(j=>j.id===id)?.name||id).join(', ')+' · '+(c.states||[]).join(', ')} -function render(){const rows=$('#trigger-rows');rows.innerHTML=triggers.map((t,i)=>''+esc(t.slug)+''+esc(kinds[providerKind(t)])+''+esc(summary(t))+'
').join('');$('#trigger-empty').classList.toggle('hidden',triggers.length>0);$('#context-paths').innerHTML=triggers.length?'Available context: '+triggers.map(t=>'{{'+esc(contextHint(t))+'}}').join(' · '):'Add a trigger to expose structured context.'} +function render(){const rows=$('#trigger-rows');rows.innerHTML=triggers.map((t,i)=>''+esc(t.slug)+''+esc(kinds[providerKind(t)])+''+esc(summary(t))+'
').join('');$('#trigger-empty').classList.toggle('hidden',triggers.length>0);const paths=contextPaths();$('#context-paths').innerHTML=paths.length?'Available context: '+paths.slice(0,6).map(x=>'{{'+esc(x.path)+'}}').join(' · ')+(paths.length>6?' · '+(paths.length-6)+' more':''):'Add a trigger to expose structured context.';updateSuggestions()} +const promptEditor=form.elements.promptTemplate,suggestionMenu=$('#context-suggestions');let matches=[],activeSuggestion=0,expression=null; +function currentExpression(){const end=promptEditor.selectionStart,start=promptEditor.value.lastIndexOf('{{',end);if(start<0||promptEditor.value.slice(start+2,end).includes('}}'))return null;const raw=promptEditor.value.slice(start+2,end);if(!/^\\s*[A-Za-z0-9_.-]*$/.test(raw))return null;return {start,end,query:raw.trim()}} +function closeSuggestions(){matches=[];expression=null;suggestionMenu.classList.add('hidden');suggestionMenu.replaceChildren();promptEditor.setAttribute('aria-expanded','false');promptEditor.removeAttribute('aria-activedescendant')} +function updateSuggestions(){expression=currentExpression();if(!expression)return closeSuggestions();matches=contextPaths().filter(x=>x.path.toLowerCase().includes(expression.query.toLowerCase())).slice(0,12);if(!matches.length)return closeSuggestions();activeSuggestion=Math.min(activeSuggestion,matches.length-1);suggestionMenu.innerHTML=matches.map((x,i)=>'').join('');suggestionMenu.classList.remove('hidden');promptEditor.setAttribute('aria-expanded','true');promptEditor.setAttribute('aria-activedescendant','context-option-'+activeSuggestion);$('#context-announcement').textContent=matches.length+' context suggestions available. '+matches[activeSuggestion].path+' selected.'} +function selectSuggestion(index=activeSuggestion){const choice=matches[index];if(!choice||!expression)return;const before=promptEditor.value.slice(0,expression.start+2),after=promptEditor.value.slice(expression.end),closing=after.startsWith('}}')?'':'}}';promptEditor.value=before+choice.path+closing+after;const caret=before.length+choice.path.length+closing.length;promptEditor.setSelectionRange(caret,caret);closeSuggestions();promptEditor.focus();promptEditor.dispatchEvent(new Event('input',{bubbles:true}))} +promptEditor.addEventListener('input',()=>{activeSuggestion=0;updateSuggestions()});promptEditor.addEventListener('click',updateSuggestions);promptEditor.addEventListener('keyup',e=>{if(!['ArrowDown','ArrowUp','Escape','Tab'].includes(e.key))updateSuggestions()});promptEditor.addEventListener('keydown',e=>{if(suggestionMenu.classList.contains('hidden'))return;if(e.key==='ArrowDown'||e.key==='ArrowUp'){e.preventDefault();activeSuggestion=(activeSuggestion+(e.key==='ArrowDown'?1:-1)+matches.length)%matches.length;updateSuggestions()}else if(e.key==='Tab'||e.key==='Enter'){e.preventDefault();selectSuggestion()}else if(e.key==='Escape'){e.preventDefault();closeSuggestions()}});suggestionMenu.addEventListener('mousedown',e=>e.preventDefault());suggestionMenu.addEventListener('click',e=>{const option=e.target.closest('[data-suggestion]');if(option)selectSuggestion(Number(option.dataset.suggestion))});promptEditor.addEventListener('blur',()=>setTimeout(closeSuggestions,100)); function nextSlug(){let n=1;while(reservedSlugs.has('trigger-'+n))n++;const slug='trigger-'+n;reservedSlugs.add(slug);return slug} async function repositories(installationId){const key=String(installationId);if(resources.repositories.has(key))return resources.repositories.get(key);const response=await fetch('/api/github/installations/'+encodeURIComponent(key)+'/repositories');const items=response.ok?await response.json():[];resources.repositories.set(key,items);return items} function options(select,items,label,value='id'){select.replaceChildren(...items.map(x=>new Option(x[label]||x.name,String(x[value]))))} diff --git a/packages/app/test/trigger-context.test.ts b/packages/app/test/trigger-context.test.ts new file mode 100644 index 00000000..27e54184 --- /dev/null +++ b/packages/app/test/trigger-context.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from "vitest"; +import { reflectTriggerContext, triggerContextCatalog } from "../src/trigger-context"; + +describe("trigger context reflection", () => { + it("defines typed nested paths for every built-in kind and provider", () => { + expect(Object.keys(triggerContextCatalog)).toEqual(expect.arrayContaining(["manual", "schedule", "linear", "github", "cloudflareTail", "custom", "jobLifecycle"])); + for (const paths of Object.values(triggerContextCatalog)) { + expect(paths.length).toBeGreaterThan(0); + expect(paths.every(path => path.path && path.type && path.description)).toBe(true); + } + expect(triggerContextCatalog.linear).toContainEqual(expect.objectContaining({ path: "issue.title", type: "string" })); + expect(triggerContextCatalog.github).toContainEqual(expect.objectContaining({ path: "pull_request.number", type: "number" })); + }); + + it("preserves the slug and explicitly marks unknown handler output", () => { + const reflected = reflectTriggerContext({ slug: "trigger-7", kind: "webhook", config: { provider: "linear", handlerCode: "function handler() { return {}; }" } }); + expect(reflected).toMatchObject({ slug: "trigger-7", provider: "linear", dynamic: true }); + expect(reflected.paths).toEqual([{ path: "*", type: "unknown", description: expect.any(String) }]); + }); +}); diff --git a/packages/app/test/ui.test.ts b/packages/app/test/ui.test.ts index 8b47e2ce..e4b00f9a 100644 --- a/packages/app/test/ui.test.ts +++ b/packages/app/test/ui.test.ts @@ -213,6 +213,11 @@ describe("pages", () => { expect(editor).not.toContain("Order rows"); expect(editor).toContain("multiple size=\"4\""); expect(editor).toContain("Available context"); + expect(editor).toContain('role="listbox"'); + expect(editor).toContain("contextCatalog"); + expect(editor).toContain("e.key==='Tab'"); + expect(editor).toContain("e.key==='ArrowDown'"); + expect(editor).toContain("e.key==='Escape'"); expect(editor).not.toContain("Additional triggers (JSON array)"); expect(editor).not.toContain('name="triggerKind"'); expect(editor).toContain("/api/schedules/preview");