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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/job-trigger-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ The available value beneath a slug is:

| Trigger | Fields |
| --- | --- |
| Manual | `prompt` |
| Manual | `prompt`, `data` |
| 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` |
Expand All @@ -30,3 +30,5 @@ Run inspection returns `context` as the complete persisted object and `invocatio
Every webhook trigger may also define `handlerCode` containing one synchronous `function handler(webhook)` declaration. Factorize runs it only after provider authentication and trigger scoping, inside an isolated Worker with no bindings or outbound network access. Returning `false` rejects the delivery, `true` retains the default value above, and a JSON-compatible object replaces that value beneath the stable trigger slug. Timeouts, exceptions, and invalid return values are recorded in webhook activity and never create a run. REST `POST /api/v1/job-handlers/test` and MCP `test_job_webhook_handler` exercise the same isolation boundary without creating an invocation.

Prompt and run-name templates render plain text: double-brace substitutions preserve URLs, quotes, Markdown, and code without HTML entity escaping. Triple-brace substitutions remain supported. Literal entity text in job context is preserved, not decoded. The web UI escapes rendered values when displaying them. This applies to new runs; existing persisted prompts are unchanged.

Object and array substitutions insert compact JSON, including nested values: `{{trigger-1}}` inserts the complete trigger context and `{{trigger-1.data}}` inserts the complete manual data object. Object keys are sorted recursively (integer keys follow JSON's numeric ordering); array order is preserved. Nested nulls render as JSON `null`; a directly interpolated null or missing value remains empty, as in Mustache. Primitive values remain raw text. Sections still use the original context for truthiness, object scopes, and array iteration.
28 changes: 27 additions & 1 deletion packages/app/src/text-template.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,32 @@
import Mustache from "mustache";

/**
* Compact JSON with recursively sorted object keys (integer keys retain JSON's
* numeric ordering), array order preserved, and nested nulls retained.
* Other values follow JSON.stringify's standard JSON conversion rules.
*/
function interpolationText(value: unknown): string {
if (value == null) return "";
if (typeof value !== "object") return String(value);
return JSON.stringify(value, (_key, entry) => {
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return entry;
return Object.fromEntries(Object.keys(entry).sort().map(key => [key, entry[key]]));
});
}

// Normalize only interpolations: section truthiness, iteration, and dotted
// lookups must continue to operate on the original structured context.
class TextWriter extends Mustache.Writer {
override unescapedValue(token: string[], context: Mustache.Context): string {
return interpolationText(context.lookup(token[1]));
}

override escapedValue(token: string[], context: Mustache.Context): string {
return this.unescapedValue(token, context);
}
}

/** Agent input and display names are plain text; HTML escaping belongs at the UI boundary. */
export function renderTextTemplate(template: string, context: Record<string, unknown>): string {
return Mustache.render(template, context, undefined, { escape: (value: string) => value });
return new TextWriter().render(template, context);
}
2 changes: 1 addition & 1 deletion packages/app/src/trigger-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const commonWebhook: ContextPath[] = [
export const triggerContextCatalog: Record<string, ContextPath[]> = {
manual: [
{ path: "prompt", type: "string", description: "Prompt supplied by the manual invocation.", example: "Review the failing build" },
{ path: "data", type: "object", description: "JSON data supplied by the manual invocation." },
{ path: "data", type: "object", description: "Complete manual JSON data; interpolate this path to insert the full object as JSON." },
],
schedule: [
{ path: "scheduled_at", type: "string", description: "Scheduled occurrence as an ISO 8601 timestamp.", example: "2026-09-16T09:00:00.000Z" },
Expand Down
6 changes: 3 additions & 3 deletions packages/app/src/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export const loginPage = (marketingOrigin = "https://factorize.sh") => `<!doctyp

const themeScript = `
const themeToggle=document.querySelector('#theme-toggle'),themeIcon=document.querySelector('#theme-icon');
const jobForm=document.querySelector('#job');if(jobForm&&!jobForm.elements.namedItem('runNameTemplate')){const label=document.createElement('label');label.className='label relative mt-5 min-w-0';label.innerHTML='Run name template<input class="field font-mono" name="runNameTemplate" maxlength="500" placeholder="Review {{trigger-2.issue.title}}"><span class="mt-2 block font-normal text-slate-500">Optional Mustache template; inactive triggers are false in conditional sections.</span>';jobForm.querySelector('[name="promptTemplate"]')?.parentElement?.before(label)}
const jobForm=document.querySelector('#job');if(jobForm&&!jobForm.elements.namedItem('runNameTemplate')){const label=document.createElement('label');label.className='label relative mt-5 min-w-0';label.innerHTML='Run name template<input class="field font-mono" name="runNameTemplate" maxlength="500" placeholder="Review {{trigger-2.issue.title}}"><span class="mt-2 block font-normal text-slate-500">Optional Mustache template; objects and arrays insert JSON. Inactive triggers are false in conditional sections.</span>';jobForm.querySelector('[name="promptTemplate"]')?.parentElement?.before(label)}
if(jobForm){const nativeFetch=window.fetch.bind(window);window.fetch=async(input,init)=>{if(init?.body&&new RegExp('^/api/v1/jobs(?:/|$)').test(String(input))){try{const body=JSON.parse(String(init.body));body.runNameTemplate=jobForm.elements.namedItem('runNameTemplate')?.value||'';init={...init,body:JSON.stringify(body)}}catch{}}return nativeFetch(input,init)}}
const syncThemeButton=()=>{const dark=document.documentElement.classList.contains('dark');themeIcon.textContent=dark?'☀':'☾';themeToggle.setAttribute('aria-label',dark?'Use light mode':'Use dark mode')};
themeToggle.addEventListener('click',()=>{const dark=!document.documentElement.classList.contains('dark');document.documentElement.classList.toggle('dark',dark);try{localStorage.setItem('factorize-theme',dark?'dark':'light')}catch{}syncThemeButton()});syncThemeButton();
Expand Down Expand Up @@ -131,8 +131,8 @@ let slugEdited=Boolean(jobId);const jobSlug=value=>value.trim().toLowerCase().re
const kinds={manual:'Manual',schedule:'Schedule',linear:'Linear',clickup:'ClickUp',github:'GitHub Issues',cloudflareTail:'Cloudflare Tail',jobLifecycle:'Job lifecycle'};
const providerKind=t=>t.kind==='webhook'?t.config.provider:t.kind;
const reflection=t=>t.reflection?.paths||contextCatalog[providerKind(t)]||[];
const triggerHints=()=>triggers.map(t=>({path:t.slug+'.*',type:'context',description:kinds[providerKind(t)]+' trigger context'}));
const contextPaths=()=>triggers.flatMap(t=>[{path:t.slug+'.*',type:'context',description:kinds[providerKind(t)]+' trigger context'},...reflection(t).filter(x=>x.path!=='*').map(x=>({path:t.slug+'.'+x.path,type:x.type,description:x.description}))]);
const triggerHints=()=>triggers.map(t=>({path:t.slug,type:'object',description:'Complete '+kinds[providerKind(t)]+' trigger context as JSON'}));
const contextPaths=()=>triggers.flatMap(t=>[{path:t.slug,type:'object',description:'Complete '+kinds[providerKind(t)]+' trigger context as JSON'},...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 simpleSchedule=c=>{if(c.timezone!=='UTC')return null;const cron=(c.cron||'').trim(),minutes=cron.match(/^\\*\\/(\\d+) \\* \\* \\* \\*$/),hours=cron.match(/^0 \\*\\/(\\d+) \\* \\* \\*$/);if(cron==='* * * * *')return {unit:'minutes',value:1};if(cron==='0 * * * *')return {unit:'hours',value:1};if(minutes&&Number(minutes[1])>=1&&Number(minutes[1])<=59)return {unit:'minutes',value:Number(minutes[1])};if(hours&&Number(hours[1])>=1&&Number(hours[1])<=23)return {unit:'hours',value:Number(hours[1])};return null};
function simpleCron(){const unit=triggerForm.elements.intervalUnit.value,value=Number(triggerForm.elements.intervalValue.value),max=unit==='minutes'?59:23;if(!Number.isInteger(value)||value<1||value>max)throw new Error('Enter an interval from 1 to '+max+' '+unit+'.');return unit==='minutes'?'*/'+value+' * * * *':'0 */'+value+' * * *'}
Expand Down
38 changes: 38 additions & 0 deletions packages/app/test/job-domain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,44 @@ describe("job invocation domain", () => {
expect(Mustache.render("{{value}}", { value: "<script>&" })).toBe("&lt;script&gt;&amp;");
});

it("renders complete contexts and nested JSON in prompts and run names", () => {
const data = { z: null, items: [{ b: 2, a: "<&" }, [true, null]], a: { y: 2, x: 1 } };
const context = { "trigger-1": { prompt: "go", data } };
const dataJson = '{"a":{"x":1,"y":2},"items":[{"a":"<&","b":2},[true,null]],"z":null}';
const cases = [
["trigger-1", '{"data":' + dataJson + ',"prompt":"go"}'],
["trigger-1.data", dataJson],
["trigger-1.data.a", '{"x":1,"y":2}'],
["trigger-1.data.items", '[{"a":"<&","b":2},[true,null]]'],
["trigger-1.data.items.0", '{"a":"<&","b":2}'],
["trigger-1.data.z", ""],
["trigger-1.missing", ""],
];
for (const [path, expected] of cases) {
for (const template of ["{{" + path + "}}", "{{{" + path + "}}}", "{{&" + path + "}}"]) {
expect(renderJobPrompt({ promptTemplate: "value:" + template }, context)).toBe("value:" + expected);
expect(renderRunName("value:" + template, context, "fallback")).toBe("value:" + expected);
}
}
expect(renderJobPrompt({ promptTemplate: "{{trigger-1.data}}" }, { "trigger-1": { data: { a: { x: 1, y: 2 }, items: data.items, z: null } } })).toBe(dataJson);
expect(context["trigger-1"].data).toBe(data);
});

it("preserves primitives, sections, array iteration, and empty collections", () => {
const context = { text: "<&", number: 0, yes: true, no: false, nil: null, empty: {}, list: [], rows: [{ name: "A" }, { name: "B" }] };
const template = "{{text}}|{{number}}|{{yes}}|{{no}}|{{nil}}|{{empty}}|{{list}}|{{#rows}}{{name}}:{{.}};{{/rows}}{{^nil}}nil{{/nil}}{{^list}}empty{{/list}}{{#empty}}object{{/empty}}";
const expected = '<&|0|true|false||{}|[]|A:{"name":"A"};B:{"name":"B"};nilemptyobject';
expect(renderJobPrompt({ promptTemplate: template }, context)).toBe(expected);
expect(renderRunName(template, context, "fallback")).toBe(expected);
});

it("preserves invalid-template errors and run-name fallbacks", () => {
expect(() => renderJobPrompt({ promptTemplate: "{{#broken}}" }, {})).toThrow("The job prompt is not valid Mustache.");
for (const template of ["", " ", "{{#broken}}", "{{missing}}", "{{nil}}"]) {
expect(renderRunName(template, { nil: null }, "fallback")).toBe("fallback");
}
});

it("encrypts and persists the original manual task text at invocation time", async () => {
const repository = new MemoryRepository();
repository.jobs.set("job-1", job({ promptTemplate: "<task>\n{{trigger-1.prompt}}\n</task>" }));
Expand Down
5 changes: 3 additions & 2 deletions packages/app/test/ui.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,10 +225,11 @@ describe("pages", () => {
expectInlineScriptsToParse(html);
});

it("shows synchronized wildcard trigger hints while retaining detailed autocomplete", () => {
it("shows complete JSON trigger hints while retaining detailed autocomplete", () => {
const html = jobPage({ email: "owner@example.com" }, "job-1");
expect(html).toContain("const triggerHints=()=>triggers.map");
expect(html).toContain("path:t.slug+'.*'");
expect(html).toContain("path:t.slug,type:'object'");
expect(html).toContain("trigger context as JSON");
expect(html).toContain('data-context-hint="');
expect(html).toContain("insertHint(hint.dataset.contextHint)");
expect(html).toContain("reflection(t).filter(x=>x.path!=='*')");
Expand Down
2 changes: 2 additions & 0 deletions packages/docs/concepts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,5 @@ Codex and Claude can show tool calls live from an execution stream; Pi uses its
An interactive tenant owner with `runs:write` can use `POST /api/v1/runs/{runId}/trace/replay` to reproject retained primary bytes or restore a retained native session. Supply a UUID `requestId` and `source` (`primary` or `native_session`). Preserve the request ID when retrying an interrupted operation. Replay is limited to 10 requests per tenant per minute. Results distinguish projected, already projected, skipped, and unrecoverable runs. Historical Codex tool calls can be recovered only if the native session artifact still exists. Replay preserves stored artifacts; expired or deleted bytes cannot be recovered.

See the [trace rollout and debugging runbook](https://github.com/GenerationSoftware/factorize/blob/main/docs/trace-rollout-runbook.md) for canary gates, retention, resumption, and rollback.

Object and array substitutions insert compact JSON, including nested values: `{{trigger-1}}` inserts the complete trigger context and `{{trigger-1.data}}` inserts the complete manual data object. Object keys are sorted recursively (integer keys follow JSON's numeric ordering); array order is preserved. Nested nulls render as JSON `null`; a directly interpolated null or missing value remains empty, as in Mustache. Primitive values remain raw text. Sections still use the original context for truthiness, object scopes, and array iteration.
Loading