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
2 changes: 2 additions & 0 deletions docs/job-trigger-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,5 @@ Manual invocation accepts an optional display `name`, `prompt`, JSON object `dat
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.

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.
5 changes: 3 additions & 2 deletions packages/app/src/job-domain.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Mustache from "mustache";
import { renderTextTemplate } from "./text-template";

export type TriggerKind = "manual" | "schedule" | "webhook" | "jobLifecycle";
export type InvocationSource = "manual" | TriggerKind;
Expand Down Expand Up @@ -88,7 +89,7 @@ export class InvocationError extends Error {
export function renderJobPrompt(job: Pick<Job, "promptTemplate">, context: Record<string, unknown>): string {
try {
Mustache.parse(job.promptTemplate);
return Mustache.render(job.promptTemplate, context);
return renderTextTemplate(job.promptTemplate, context);
} catch (error) {
if (error instanceof InvocationError) throw error;
throw new InvocationError("invalid_template", "The job prompt is not valid Mustache.");
Expand All @@ -99,7 +100,7 @@ export function renderRunName(template: string, context: Record<string, unknown>
if (!template.trim()) return fallback;
try {
Mustache.parse(template);
const name = Mustache.render(template, context).trim();
const name = renderTextTemplate(template, context).trim();
return name || fallback;
} catch {
return fallback;
Expand Down
4 changes: 2 additions & 2 deletions packages/app/src/linear-source.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Mustache from "mustache";
import { renderTextTemplate } from "./text-template";
import type { WorkItem } from "./types";

const object = (value: unknown): Record<string, any> => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, any> : {};
Expand Down Expand Up @@ -59,7 +59,7 @@ export function renderContextTemplate(template: string, payload: Record<string,
title: text(ticket.title) || "Untitled Linear issue", description: text(ticket.description).trim() || "No description provided.",
project, assignee, state, labels: labels.map((name, index) => ({ name, last: index === labels.length - 1 })),
};
return Mustache.render(template || DEFAULT_CONTEXT_TEMPLATE, { ...payload, ticket: normalizedTicket, flow: { name: flowName } });
return renderTextTemplate(template || DEFAULT_CONTEXT_TEMPLATE, { ...payload, ticket: normalizedTicket, flow: { name: flowName } });
}

export const linearTicketPrompt = (payload: Record<string, unknown>, flowName: string) => renderContextTemplate(DEFAULT_CONTEXT_TEMPLATE, payload, flowName);
6 changes: 6 additions & 0 deletions packages/app/src/text-template.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import Mustache from "mustache";

/** 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 });
}
22 changes: 22 additions & 0 deletions packages/app/test/job-domain.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest";
import Mustache from "mustache";
import { InvocationService, renderJobPrompt, renderRunName, type Invocation, type Job, type JobRepository, type JobRun } from "../src/job-domain";

const job = (overrides: Partial<Job> = {}): Job => ({
Expand All @@ -20,6 +21,27 @@ class MemoryRepository implements JobRepository {
}

describe("job invocation domain", () => {
it("preserves plain text without decoding literal entities or changing HTML renderers", () => {
const value = 'https://linear.app/generation/issue/GEN-2108/run-page?a=1&b=2\n{"title":"Fix it"} <script>alert("x")</script> `code` = &amp; &#x2F;';
const context = { "trigger-1": { prompt: value }, "trigger-2": false };
for (const substitution of ["{{trigger-1.prompt}}", "{{{trigger-1.prompt}}}", "{{&trigger-1.prompt}}"]) {
expect(renderJobPrompt({ promptTemplate: "{{#trigger-1}}<task>\n" + substitution + "\n</task>{{/trigger-1}}{{^trigger-2}} done{{/trigger-2}}" }, context))
.toBe("<task>\n" + value + "\n</task> done");
}
expect(renderRunName("Review {{trigger-1.prompt}}", context, "fallback")).toBe("Review " + value);
expect(Mustache.render("{{value}}", { value: "<script>&" })).toBe("&lt;script&gt;&amp;");
});

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>" }));
const service = new InvocationService(repository, async value => `encrypted:${value}`);
const prompt = 'https://linear.app/generation/issue/GEN-2108/run-page\n{"task":"Fix quotes & slashes"}';
const result = await service.invoke("job-1", { source: "manual", triggerId: "manual-1", claimKey: "plain-text", context: { "trigger-1": { prompt } } });
expect(result.run.encryptedPrompt).toBe(`encrypted:<task>\n${prompt}\n</task>`);
expect(repository.claims.get("job-1:plain-text")?.run.encryptedPrompt).toBe(result.run.encryptedPrompt);
});

it("renders run names with active and inactive trigger conditionals", () => {
expect(renderRunName("{{#trigger-2}}{{trigger-2.issue.identifier}}{{/trigger-2}}{{^trigger-2}}manual{{/trigger-2}}", { "trigger-1": { prompt: "go" }, "trigger-2": false }, "fallback")).toBe("manual");
expect(renderRunName("{{#trigger-2}}{{trigger-2.issue.identifier}}{{/trigger-2}}", { "trigger-1": false, "trigger-2": { issue: { identifier: "GEN-1" } } }, "fallback")).toBe("GEN-1");
Expand Down
7 changes: 7 additions & 0 deletions packages/app/test/ticket-prompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ Create \`WHOA.md\` with \`it works!\`.`);
expect(prompt).toBe("bug-fixes: GEN-1979 — Use `extra` context. (2026.09)");
});

it("preserves URLs and code in double-brace custom context templates", () => {
expect(renderContextTemplate("{{ticket.description}} {{custom.url}} {{flow.name}}", {
description: 'Use <tag> & "quotes".',
custom: { url: "https://example.com/a?x=1&y=2" },
}, "bugs & fixes")).toBe('Use <tag> & "quotes". https://example.com/a?x=1&y=2 bugs & fixes');
});

it("decodes HTML entities in ticket content before rendering the prompt", () => {
const prompt = linearTicketPrompt({
identifier: "GEN-2063", title: "Run prompt formatting",
Expand Down
2 changes: 2 additions & 0 deletions packages/docs/concepts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@ Templates are Mustache and render only against the firing trigger's stable slug,
Trigger kinds are `manual`, `schedule`, `webhook`, and `jobLifecycle`. Webhooks support Linear, ClickUp, GitHub, and Cloudflare Tail. A webhook handler is one synchronous `function handler(webhook)` declaration: `false` rejects, `true` keeps the default payload, and a JSON object replaces it. It runs after authentication/scoping in an isolated Worker with no network or bindings.

See the repository's [trigger context contract](https://github.com/GenerationSoftware/factorize/blob/main/docs/job-trigger-context.md) for the reflection paths exposed with every trigger.

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.
Loading