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
20 changes: 19 additions & 1 deletion docs/execution-boundaries.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Execution boundaries

Factorize separates an incoming event from the system that executes its task:
Factorize separates an incoming trigger from the system that executes its job:

```text
provider webhook -> SourceAdapter -> WorkItem -> prompt renderer
Expand All @@ -24,3 +24,21 @@ Launch and prompt delivery are deliberately separate operations. An existing
harness proves only that launch reconciliation succeeded. It never proves that
the run's prompt was accepted. Prompt delivery therefore has its own persisted
state and request/response receipt.

## Job invocation boundary

A `Job` owns a Mustache prompt template, string parameter defaults, an execution
target, a positive concurrency limit, enabled state, and exactly one `Trigger`.
Triggers have one of three domain kinds: `manual`, `schedule`, or `webhook`.

Trigger adapters do only source-specific authentication and normalization. They
then call the same `InvocationService.invoke(jobId, request)` operation. Its
canonical request carries the source, optional reserved `context`, string
parameter overrides, a durable claim key, and optional occurrence metadata.
The invocation boundary validates and renders the prompt, applies defaults,
encrypts the rendered prompt, and atomically persists an `Invocation` plus its
queued `JobRun`. The `(job_id, claim_key)` constraint makes retries idempotent.

Queue consumers call `startIfCapacity`; concurrency is counted by job, never by
trigger source. Provider adapters must not render prompts, insert runs, claim
capacity, or launch execution backends themselves.
170 changes: 170 additions & 0 deletions packages/app/src/job-domain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import Mustache from "mustache";

export type TriggerKind = "manual" | "schedule" | "webhook";
export type InvocationSource = TriggerKind;
export type JobRunState = "queued" | "running" | "succeeded" | "failed" | "cancelled";

export interface ExecutionTarget {
connectionId: string;
workspace: string;
cwd: string;
agentKind: string;
}

export interface Trigger {
id: string;
jobId: string;
kind: TriggerKind;
config: Record<string, unknown>;
createdAt: string;
updatedAt: string;
}

export interface Job {
id: string;
name: string;
promptTemplate: string;
parameterDefaults: Record<string, string>;
executionTarget: ExecutionTarget;
concurrencyLimit: number;
enabled: boolean;
trigger: Trigger;
createdAt: string;
updatedAt: string;
}

export interface InvocationRequest {
source: InvocationSource;
context?: string;
parameters?: Record<string, string>;
/** Stable, source-owned key used to claim this occurrence exactly once. */
claimKey: string;
occurrence?: { occurredAt?: string; externalId?: string; metadata?: Record<string, unknown> };
}

export interface Invocation {
id: string;
jobId: string;
source: InvocationSource;
claimKey: string;
context?: string;
parameters: Record<string, string>;
occurrence?: InvocationRequest["occurrence"];
createdAt: string;
}

export interface JobRun {
id: string;
jobId: string;
invocationId: string;
state: JobRunState;
/** Persisted form is encrypted; repositories decrypt only at an authorized read boundary. */
encryptedPrompt: string;
createdAt: string;
updatedAt: string;
startedAt?: string;
}

export interface InvocationResult { invocation: Invocation; run: JobRun; duplicate: boolean; }

export interface JobRepository {
getJob(id: string): Promise<Job | null>;
findInvocation(jobId: string, claimKey: string): Promise<{ invocation: Invocation; run: JobRun } | null>;
insertInvocationAndRun(invocation: Invocation, run: JobRun): Promise<boolean>;
countActiveRuns(jobId: string): Promise<number>;
markRunRunning(runId: string, startedAt: string): Promise<JobRun>;
}

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<string, string> => {
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<string, string>;
};

export function renderJobPrompt(job: Pick<Job, "promptTemplate" | "parameterDefaults">, request: Pick<InvocationRequest, "context" | "parameters">): 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.");
try {
Mustache.parse(job.promptTemplate);
return Mustache.render(job.promptTemplate, { ...defaults, ...overrides, context: request.context ?? "" });
} catch (error) {
if (error instanceof InvocationError) throw error;
throw new InvocationError("invalid_template", "The job prompt is not valid Mustache.");
}
}

/** The only operation trigger adapters call after normalizing an occurrence. */
export class InvocationService {
constructor(
private repository: JobRepository,
private encryptPrompt: (prompt: string) => Promise<string>,
private makeId: () => string = () => crypto.randomUUID(),
private clock: () => string = () => new Date().toISOString(),
) {}

async invoke(jobId: string, input: InvocationRequest): Promise<InvocationResult> {
if (!input.claimKey?.trim()) throw new InvocationError("invalid_invocation", "An invocation claim key is required.");
if (!(["manual", "schedule", "webhook"] as const).includes(input.source)) throw new InvocationError("invalid_invocation", "Invocation source is invalid.");
const job = await this.repository.getJob(jobId);
if (!job) throw new InvocationError("job_not_found", "Job not found.");
if (!job.enabled) throw new InvocationError("job_disabled", "Job is disabled.");

const existing = await this.repository.findInvocation(jobId, input.claimKey);
if (existing) return { ...existing, duplicate: true };

const parameters = recordOfStrings(input.parameters, "Invocation parameters");
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 };
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.");
return { ...winner, duplicate: true };
}
return { invocation, run, duplicate: false };
}

async startIfCapacity(run: JobRun): Promise<JobRun | null> {
const job = await this.repository.getJob(run.jobId);
if (!job || !job.enabled || run.state !== "queued") return null;
if (await this.repository.countActiveRuns(job.id) >= job.concurrencyLimit) return null;
return this.repository.markRunRunning(run.id, this.clock());
}
}

/** Fresh v2 Durable Object schema. There are deliberately no legacy Flow migrations. */
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,
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 UNIQUE REFERENCES jobs(id) ON DELETE CASCADE,
kind TEXT NOT NULL CHECK (kind IN ('manual','schedule','webhook')), config TEXT NOT NULL,
created_at TEXT NOT NULL, updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS invocations (
id TEXT PRIMARY KEY, job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
source TEXT NOT NULL CHECK (source IN ('manual','schedule','webhook')), claim_key TEXT NOT NULL,
context TEXT, parameters TEXT NOT NULL, occurrence TEXT, created_at TEXT NOT NULL,
UNIQUE(job_id, claim_key)
);
CREATE TABLE IF NOT EXISTS job_runs (
id TEXT PRIMARY KEY, job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
invocation_id TEXT NOT NULL UNIQUE REFERENCES invocations(id) ON DELETE CASCADE,
state TEXT NOT NULL CHECK (state IN ('queued','running','succeeded','failed','cancelled')),
encrypted_prompt TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, started_at TEXT
);
CREATE INDEX IF NOT EXISTS job_runs_queue ON job_runs(state, created_at);
CREATE INDEX IF NOT EXISTS job_runs_active ON job_runs(job_id, state);
`;
2 changes: 2 additions & 0 deletions packages/app/src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { sanitizeTailEvent, suppressTailEvent, tailFingerprint, verifyTailDelive
import { ExeHerdrBackend } from "./exe-herdr-backend";
import { DEFAULT_CONTEXT_TEMPLATE, LinearSourceAdapter, linearTicketPrompt, renderContextTemplate } from "./linear-source";
import { renderSourcePrompt } from "./source-lifecycle";
import { JOB_SCHEMA } from "./job-domain";

export { DEFAULT_CONTEXT_TEMPLATE, linearTicketPrompt, renderContextTemplate } from "./linear-source";

Expand All @@ -33,6 +34,7 @@ export class Tenant extends DurableObject<Env> {
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
this.ctx.storage.sql.exec(`
${JOB_SCHEMA}
CREATE TABLE IF NOT EXISTS connections (kind TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS members (user_id TEXT PRIMARY KEY, email TEXT NOT NULL, role TEXT NOT NULL, session_version INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS pipes (id TEXT PRIMARY KEY, name TEXT NOT NULL, project_id TEXT NOT NULL, team_id TEXT NOT NULL,
Expand Down
52 changes: 52 additions & 0 deletions packages/app/test/job-domain.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
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> = {}): Job => ({
id: "job-1", name: "Triage", promptTemplate: "{{greeting}}, {{name}}!\n{{context}}",
parameterDefaults: { greeting: "Hello", name: "world" },
executionTarget: { connectionId: "exe-1", workspace: "triage", cwd: "/repo", agentKind: "codex" },
concurrencyLimit: 1, enabled: true,
trigger: { id: "trigger-1", jobId: "job-1", kind: "manual", config: {}, createdAt: "now", updatedAt: "now" },
createdAt: "now", updatedAt: "now", ...overrides,
});

class MemoryRepository implements JobRepository {
jobs = new Map([["job-1", job()]]); claims = new Map<string, { invocation: Invocation; run: JobRun }>(); active = 0;
async getJob(id: string) { return this.jobs.get(id) ?? null; }
async findInvocation(jobId: string, claimKey: string) { return this.claims.get(`${jobId}:${claimKey}`) ?? null; }
async insertInvocationAndRun(invocation: Invocation, run: JobRun) { const key = `${invocation.jobId}:${invocation.claimKey}`; if (this.claims.has(key)) return false; this.claims.set(key, { invocation, run }); return true; }
async countActiveRuns() { return this.active; }
async markRunRunning(runId: string, startedAt: string) { const value = [...this.claims.values()].find(entry => entry.run.id === runId)!; value.run = { ...value.run, state: "running", startedAt, updatedAt: startedAt }; this.active++; return value.run; }
}

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("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 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(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" } });
expect((await service.startIfCapacity(first.run))?.state).toBe("running");
expect(await service.startIfCapacity(second.run)).toBeNull();
});

it("defines exactly one trigger per job and durable claims in the clean schema", () => {
expect(JOB_SCHEMA).toContain("job_id TEXT NOT NULL UNIQUE");
expect(JOB_SCHEMA).toContain("UNIQUE(job_id, claim_key)");
expect(JOB_SCHEMA).not.toContain("pipes");
});
});