// R-P12c DoD 7 — forward-executor tests: RLS-imitating stateful store, // duplicate-claim (parallelism), recovery (retry/backoff + resume), delay, // condition branching, SSRF fail-closed and duplicate-mail protection. import { describe, expect, test, vi } from "vitest"; import { AUTOMATION_CONDITION_BRANCHES_CONFIG_KEY } from "./automation-graph.js"; import { AutomationActionPermanentError, planNextStep, renderAutomationTemplate, resolveDelayMs, runAutomationExecutionJob, validateAutomationStepOutput, type AutomationExecutorDeps, } from "./automation-executor.server.js"; const TENANT = "tenant-a"; const OWNER = "user-owner"; const NOW = new Date("2026-07-19T12:00:00.000Z"); type StepSeed = { id: string; stepKey: string; stepKind: string; nodeType: string; sortOrder: number; status?: string; input?: Record; output?: Record; startedAt?: Date | null; ruleStepId?: string; config?: Record; parentStepIds?: string[]; }; /** Stateful in-memory execution store bound to one tenant (RLS imitation). */ function makeHarness(options: { steps: StepSeed[]; executionStatus?: string; attempt?: number; nextRetryAt?: Date | null; resumeFromStepId?: string | null; triggerPayload?: Record; createdByUserId?: string | null; tasks?: Array>; kontakte?: Array>; leads?: Array>; leadAntiSpamConfig?: Record; tags?: Array>; tagAssignments?: Array>; tenantUsers?: Array>; projektKontakte?: Array>; kwpMaterialPositionen?: Array>; projektTermine?: Array>; fetchImpl?: AutomationExecutorDeps["fetchOutboundHttp"]; sendChatImpl?: AutomationExecutorDeps["sendChatMessage"]; failTaskCreateTimes?: number; /** null models a tenant without a slug - the notification deeplink is dropped then. */ tenantSlug?: string | null; }) { const state = { execution: { id: "exec-1", tenantId: TENANT, status: options.executionStatus ?? "queued", attempt: options.attempt ?? 1, nextRetryAt: options.nextRetryAt ?? null, dryRun: false, resumeFromStepId: options.resumeFromStepId ?? null, triggerPayload: options.triggerPayload ?? { kontaktId: "k-1" }, createdByUserId: options.createdByUserId === undefined ? OWNER : options.createdByUserId, ruleId: "rule-1", startedAt: null as Date | null, queuedAt: NOW, summaryText: "", errorText: null as string | null, endedAt: null as Date | null, durationMs: null as number | null, }, steps: options.steps.map((step) => ({ executionId: "exec-1", tenantId: TENANT, startedAt: null, input: {}, output: {}, ruleStepId: step.id, parentStepIds: step.parentStepIds ?? [], config: step.config ?? {}, status: "queued", summaryText: "", errorText: null as string | null, ...step, })), tasks: options.tasks ?? [], kontakte: options.kontakte ?? [], leads: options.leads ?? [], leadAntiSpamConfig: options.leadAntiSpamConfig ?? { tenantId: TENANT, lostAutoDeleteDays: 0 }, tags: options.tags ?? [], tagAssignments: options.tagAssignments ?? [], tenantUsers: options.tenantUsers ?? [{ id: "membership-owner", tenantId: TENANT, userId: OWNER, status: 2, user: { active: true } }], projektKontakte: options.projektKontakte ?? [], kwpMaterialPositionen: options.kwpMaterialPositionen ?? [], projektTermine: options.projektTermine ?? [], outbox: [] as Array>, notifications: [] as Array>, activities: [] as Array>, chatMessages: [] as Array>, }; let taskCreateFailuresLeft = options.failTaskCreateTimes ?? 0; const matches = (row: Record, where: Record): boolean => { for (const [key, value] of Object.entries(where)) { if (key === "tenantId") { if (value !== TENANT) throw new Error(`RLS violation: query for tenant ${String(value)}`); continue; } if (value && typeof value === "object" && "in" in (value as Record)) { if (!((value as { in: unknown[] }).in as unknown[]).includes(row[key])) return false; continue; } if (value && typeof value === "object" && ["gt", "gte", "lt", "lte"].some((operator) => operator in (value as Record))) { const range = value as { gt?: Date; gte?: Date; lt?: Date; lte?: Date }; const candidate = row[key] as Date; if ((range.gt && !(candidate > range.gt)) || (range.gte && !(candidate >= range.gte))) return false; if ((range.lt && !(candidate < range.lt)) || (range.lte && !(candidate <= range.lte))) return false; continue; } if (value && typeof value === "object") continue; // ignore other operators for this harness if (row[key] !== value) return false; } return true; }; const tx = { automationExecution: { findFirst: vi.fn(async () => ({ ...state.execution, rule: { steps: state.steps.map((step) => ({ id: step.ruleStepId, stepKey: step.stepKey, stepKind: step.stepKind, nodeType: step.nodeType, parentStepIds: step.parentStepIds, config: step.config, sortOrder: step.sortOrder, summaryText: step.summaryText, })), }, stepExecutions: state.steps.map((s) => ({ ...s })), })), updateMany: vi.fn(async (args: { where: Record; data: Record }) => { if (!matches(state.execution as never, args.where)) return { count: 0 }; Object.assign(state.execution, args.data); return { count: 1 }; }), }, automationStepExecution: { findMany: vi.fn(async (args: { where: Record }) => state.steps.filter((s) => matches(s as never, args.where)).map((s) => ({ ...s }))), updateMany: vi.fn(async (args: { where: Record; data: Record }) => { let count = 0; for (const step of state.steps) { if (matches(step as never, args.where)) { Object.assign(step, args.data); count += 1; } } return { count }; }), createMany: vi.fn(async (args: { data: Array> }) => { for (const row of args.data) { state.steps.push({ id: `dynamic-step-${state.steps.length + 1}`, parentStepIds: [], config: {}, errorText: null, startedAt: null, ...row, } as never); } return { count: args.data.length }; }), }, task: { create: vi.fn(async (args: { data: Record }) => { if (taskCreateFailuresLeft > 0) { taskCreateFailuresLeft -= 1; throw new Error("transient db hiccup"); } const task = { id: `task-${state.tasks.length + 1}`, archivedAt: null, ...args.data }; state.tasks.push(task); return task; }), findMany: vi.fn(async (args: { where: Record; take?: number }) => state.tasks.filter((task) => matches(task, args.where)).slice(0, args.take) ), findFirst: vi.fn(async (args: { where: Record }) => state.tasks.find((t) => matches(t, args.where)) ?? null), update: vi.fn(async (args: { where: { id: string }; data: Record }) => { const task = state.tasks.find((t) => t.id === args.where.id); if (task) Object.assign(task, args.data); return task; }), }, kontakt: { findFirst: vi.fn(async (args: { where: Record }) => state.kontakte.find((k) => matches(k, args.where)) ?? null), update: vi.fn(async (args: { where: { id: string }; data: Record }) => { const kontakt = state.kontakte.find((k) => k.id === args.where.id); if (kontakt) Object.assign(kontakt, args.data); return kontakt; }), }, inboxLead: { findFirst: vi.fn(async (args: { where: Record }) => state.leads.find((lead) => matches(lead, args.where)) ?? null), update: vi.fn(async (args: { where: { id: string }; data: Record }) => { const lead = state.leads.find((row) => row.id === args.where.id); if (lead) Object.assign(lead, args.data, { updatedAt: NOW }); return lead; }), }, leadAntiSpamConfig: { upsert: vi.fn(async () => state.leadAntiSpamConfig), }, tag: { findFirst: vi.fn(async (args: { where: Record }) => state.tags.find((tag) => matches(tag, args.where)) ?? null), }, tagAssignment: { findFirst: vi.fn(async (args: { where: Record }) => state.tagAssignments.find((row) => matches(row, args.where)) ?? null), upsert: vi.fn(async (args: { create: Record }) => { const existing = state.tagAssignments.find( (row) => row.tagId === args.create.tagId && row.entityType === args.create.entityType && row.entityId === args.create.entityId ); if (existing) return existing; const created = { id: `tag-assignment-${state.tagAssignments.length + 1}`, ...args.create }; state.tagAssignments.push(created); return created; }), deleteMany: vi.fn(async (args: { where: Record }) => { const before = state.tagAssignments.length; state.tagAssignments = state.tagAssignments.filter((row) => !matches(row, args.where)); return { count: before - state.tagAssignments.length }; }), }, tenantUser: { findFirst: vi.fn(async (args: { where: Record }) => state.tenantUsers.find((row) => matches(row, args.where)) ?? null), }, projektKontakt: { findMany: vi.fn(async (args: { where: Record; take?: number }) => state.projektKontakte.filter((row) => matches(row, args.where)).slice(0, args.take) ), }, kwpMaterialPosition: { findMany: vi.fn(async (args: { where: Record; take?: number }) => state.kwpMaterialPositionen.filter((row) => matches(row, args.where)).slice(0, args.take) ), }, projektTermin: { findMany: vi.fn(async (args: { where: Record; take?: number }) => state.projektTermine.filter((row) => matches(row, args.where)).slice(0, args.take) ), }, tenant: { findFirst: vi.fn(async (args: { where: { id: string } }) => { if (args.where.id !== TENANT) throw new Error(`RLS violation: query for tenant ${args.where.id}`); const slug = options.tenantSlug === undefined ? "betrieb-nord" : options.tenantSlug; return { slug }; }), }, user: { findFirst: vi.fn(async (args: { where: { id: string } }) => args.where.id === OWNER ? { id: OWNER, email: "owner@betrieb.de", firstName: "Otto", lastName: "Owner" } : null ), }, outboxEvent: { create: vi.fn(async (args: { data: Record }) => { const key = args.data.dispatchKey; if (key && state.outbox.some((row) => row.dispatchKey === key)) { const err = new Error("unique") as Error & { code: string }; err.code = "P2002"; throw err; } state.outbox.push(args.data); return args.data; }), findUnique: vi.fn(async (args: { where: { dispatchKey: string } }) => state.outbox.find((row) => row.dispatchKey === args.where.dispatchKey) ?? null), }, }; const deps: AutomationExecutorDeps = { runInTenantTx: (fn) => fn(tx as never), notify: async (input) => { state.notifications.push(input); return {}; }, logActivity: async (input) => { state.activities.push(input); return {}; }, fetchOutboundHttp: options.fetchImpl ?? (async () => { throw new Error("no http expected"); }), sendChatMessage: options.sendChatImpl ?? (async (input) => { state.chatMessages.push(input); return { messageId: `message-${state.chatMessages.length}`, replayed: false }; }), now: () => clock.now, }; const clock = { now: NOW }; return { state, deps, tx, clock }; } function triggerStep(overrides: Partial = {}): StepSeed { return { id: "rs-t", stepKey: "trigger", stepKind: "trigger", nodeType: "forms.submitted", sortOrder: 0, ...overrides }; } describe("runAutomationExecutionJob", () => { test("happy path: trigger -> task.create -> notification.send with reverse-compatible outputs", async () => { const { state, deps } = makeHarness({ steps: [ triggerStep(), { id: "rs-1", stepKey: "create-task", stepKind: "action", nodeType: "task.create", sortOrder: 1, parentStepIds: ["trigger"], config: { titel: "Rueckruf", faelligkeit: "einTag", prioritaet: "hoch" }, }, { id: "rs-2", stepKey: "notify", stepKind: "action", nodeType: "notification.send", sortOrder: 2, parentStepIds: ["create-task"], config: { betreff: "Neu", nachricht: "Die Aufgabe wurde angelegt." }, }, ], }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("completed"); expect(state.execution.status).toBe("success"); expect(state.tasks).toHaveLength(1); expect(state.tasks[0]).toMatchObject({ source: "automation", priority: "high", assignedToUserId: OWNER }); const taskStep = state.steps.find((s) => s.stepKey === "create-task"); expect(taskStep?.status).toBe("success"); expect(taskStep?.output).toMatchObject({ taskId: "task-1", createdTaskId: "task-1" }); expect(state.notifications).toHaveLength(1); const notifyStep = state.steps.find((s) => s.stepKey === "notify"); expect((notifyStep?.output as { recipients: unknown[] }).recipients).toHaveLength(1); }); test("renders trigger placeholders in action text", async () => { const { state, deps } = makeHarness({ triggerPayload: { vorname: "Kim", projekt: { nummer: "P-42" } }, steps: [ triggerStep(), { id: "rs-1", stepKey: "create-task", stepKind: "action", nodeType: "task.create", sortOrder: 1, parentStepIds: ["trigger"], config: { titel: "Rückruf {{Vorname}} für {{projekt.nummer}}" }, }, { id: "rs-2", stepKey: "notify", stepKind: "action", nodeType: "notification.send", sortOrder: 2, parentStepIds: ["create-task"], config: { betreff: "Neue Aufgabe für {{VORNAME}}", nachricht: "{{vorname}} wurde eingeplant." }, }, ], }); await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(state.tasks[0]?.title).toBe("Rückruf Kim für P-42"); expect(state.notifications[0]?.payloadMetadata).toMatchObject({ betreff: "Neue Aufgabe für Kim", nachricht: "Kim wurde eingeplant." }); }); test("task.assign notifies the configured previous and new responsibilities", async () => { const { state, deps } = makeHarness({ tasks: [ { id: "task-1", tenantId: TENANT, archivedAt: null, createdByUserId: OWNER, assignedToUserId: "user-previous", assignedToGroupId: null, }, ], steps: [ triggerStep(), { id: "rs-1", stepKey: "assign", stepKind: "action", nodeType: "task.assign", sortOrder: 1, parentStepIds: ["trigger"], config: { aufgabe: "bestimmteAufgabe", taskId: "task-1", zustaendig: "erstellerDerAufgabe", benachrichtigungAn: "beide" }, }, ], }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("completed"); expect(state.tasks[0]).toMatchObject({ assignedToUserId: OWNER, assignedToGroupId: null }); expect(state.notifications.map((notification) => notification.userId)).toEqual([OWNER, "user-previous"]); expect(state.steps.find((step) => step.stepKey === "assign")?.output).toMatchObject({ notifiedUserIds: [OWNER, "user-previous"] }); }); test("task.create rejects an unsupported assignee instead of silently using the owner", async () => { const { state, deps } = makeHarness({ steps: [ triggerStep(), { id: "rs-1", stepKey: "create-task", stepKind: "action", nodeType: "task.create", sortOrder: 1, parentStepIds: ["trigger"], config: { titel: "Nachfassen", zustaendig: "vertriebsteam" }, }, ], }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("failed"); expect(state.execution.summaryText).toBe("automation.execution.taskCreateInvalidAssignee"); expect(state.tasks).toEqual([]); }); test("task.assign sends no notification when the optional setting is omitted", async () => { const { state, deps } = makeHarness({ tasks: [ { id: "task-1", tenantId: TENANT, archivedAt: null, createdByUserId: OWNER, assignedToUserId: "user-previous", assignedToGroupId: null, }, ], steps: [ triggerStep(), { id: "rs-1", stepKey: "assign", stepKind: "action", nodeType: "task.assign", sortOrder: 1, parentStepIds: ["trigger"], config: { aufgabe: "bestimmteAufgabe", taskId: "task-1", zustaendig: "erstellerDerAufgabe" }, }, ], }); await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(state.notifications).toEqual([]); }); test("crm.create_note does not claim unenforced per-note visibility", async () => { const { state, deps } = makeHarness({ triggerPayload: { projectId: "project-1" }, steps: [ triggerStep(), { id: "rs-1", stepKey: "create-note", stepKind: "action", nodeType: "crm.create_note", sortOrder: 1, parentStepIds: ["trigger"], config: { datensatz: "projektAusAusloeser", notiztext: "Angebot geprüft", sichtbarkeit: "nurIch" }, }, ], }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("completed"); expect(state.activities).toHaveLength(1); expect(state.activities[0]).toMatchObject({ subjectType: "project", subjectId: "project-1", summaryText: "Angebot geprüft" }); expect(state.activities[0]?.metadata).toEqual({ executionId: "exec-1", stepKey: "create-note" }); }); test("crm.update_kontakt resolves the linked contact emitted by a lead trigger", async () => { const { state, deps } = makeHarness({ triggerPayload: { verknuepfterKontaktId: "k-1" }, kontakte: [ { id: "k-1", tenantId: TENANT, archivedAt: null, kontaktStatus: "kontakt", vorname: "Kim", nachname: "Klein", orgName: null, primaerEmail: null, primaerTelefon: null, language: "de", }, ], steps: [ triggerStep(), { id: "rs-u", stepKey: "update", stepKind: "action", nodeType: "crm.update_kontakt", sortOrder: 1, parentStepIds: ["trigger"], config: { kontakt: "ausloeser", feld: "kontaktStatus", wert: "kunde" }, }, ], }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("completed"); expect(state.kontakte[0]?.kontaktStatus).toBe("kunde"); }); test("notification carries a deeplink to the run that produced it", async () => { const { state, deps } = makeHarness({ steps: [ triggerStep(), { id: "rs-1", stepKey: "notify", stepKind: "action", nodeType: "notification.send", sortOrder: 1, parentStepIds: ["trigger"], config: { betreff: "Neu", nachricht: "Der Lauf ist abgeschlossen." }, }, ], }); await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); const metadata = state.notifications[0]?.payloadMetadata as Record; expect(metadata.deeplink).toBe("/betrieb-nord/automations/rule-1/executions/exec-1"); }); test("notification.send rejects an unsupported recipient instead of notifying the owner", async () => { const { state, deps } = makeHarness({ steps: [ triggerStep(), { id: "rs-1", stepKey: "notify", stepKind: "action", nodeType: "notification.send", sortOrder: 1, parentStepIds: ["trigger"], config: { kanal: "intern", empfaenger: "kontaktAusAusloeser" }, }, ], }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("failed"); expect(state.execution.summaryText).toBe("automation.execution.notificationInvalidRecipient"); expect(state.notifications).toEqual([]); }); test("notification.send rejects empty content instead of reporting a false success", async () => { const { state, deps } = makeHarness({ steps: [ triggerStep(), { id: "rs-1", stepKey: "notify", stepKind: "action", nodeType: "notification.send", sortOrder: 1, parentStepIds: ["trigger"], config: { kanal: "intern", empfaenger: "besitzerDerAutomation" }, }, ], }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("failed"); expect(state.execution.summaryText).toBe("automation.execution.notificationMissingContent"); expect(state.notifications).toEqual([]); }); test("notification stays unlinked when the tenant has no slug to address the route with", async () => { const { state, deps } = makeHarness({ tenantSlug: null, steps: [ triggerStep(), { id: "rs-1", stepKey: "notify", stepKind: "action", nodeType: "notification.send", sortOrder: 1, parentStepIds: ["trigger"], config: { betreff: "Neu", nachricht: "Der Lauf ist abgeschlossen." }, }, ], }); await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); const metadata = state.notifications[0]?.payloadMetadata as Record; expect(metadata).not.toHaveProperty("deeplink"); }); test("duplicate claim: a second worker on the same execution is a no-op (parallelism)", async () => { const { deps } = makeHarness({ steps: [triggerStep()], executionStatus: "running" }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result).toMatchObject({ status: "skipped", detail: "running" }); }); test("transient adapter failure schedules a bounded backoff retry and re-publishes the continuation (recovery)", async () => { const { state, deps, clock } = makeHarness({ steps: [triggerStep(), { id: "rs-1", stepKey: "create-task", stepKind: "action", nodeType: "task.create", sortOrder: 1, parentStepIds: ["trigger"] }], failTaskCreateTimes: 1, }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("retry_scheduled"); expect(state.execution).toMatchObject({ status: "retrying", attempt: 2 }); expect(state.execution.nextRetryAt).toEqual(new Date(NOW.getTime() + 60_000)); expect(state.steps.find((s) => s.stepKey === "create-task")?.status).toBe("queued"); expect(state.outbox.some((row) => row.dispatchKey === "automation-exec:exec-1:retry:2")).toBe(true); // Continuation fires at scheduledAt: advance the clock past nextRetryAt. clock.now = new Date(NOW.getTime() + 61_000); const second = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(second.status).toBe("completed"); expect(state.tasks).toHaveLength(1); }); test("exhausted retries fail the execution with Klartext error", async () => { const { state, deps } = makeHarness({ steps: [triggerStep(), { id: "rs-1", stepKey: "create-task", stepKind: "action", nodeType: "task.create", sortOrder: 1, parentStepIds: ["trigger"] }], attempt: 3, failTaskCreateTimes: 1, }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("failed"); expect(state.execution.status).toBe("failed"); expect(state.steps.find((s) => s.stepKey === "create-task")?.status).toBe("failed"); }); test("delay.wait parks the run durably and completes after the wait elapsed", async () => { const { state, deps, clock } = makeHarness({ steps: [ triggerStep(), { id: "rs-w", stepKey: "wait", stepKind: "flow_control", nodeType: "delay.wait", sortOrder: 1, parentStepIds: ["trigger"], config: { dauer: "2", dauerEinheit: "stunden" }, }, { id: "rs-2", stepKey: "notify", stepKind: "action", nodeType: "notification.send", sortOrder: 2, parentStepIds: ["wait"], config: { betreff: "Weiter", nachricht: "Die Wartezeit ist abgelaufen." }, }, ], }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("waiting"); expect(state.execution.status).toBe("waiting"); const waitStep = state.steps.find((s) => s.stepKey === "wait"); expect(waitStep?.status).toBe("waiting"); const continuation = state.outbox.find((row) => String(row.dispatchKey).startsWith("automation-exec:exec-1:wait:wait")); expect(continuation).toBeDefined(); expect(continuation?.scheduledAt).toEqual(new Date(NOW.getTime() + 2 * 60 * 60_000)); // Simulate the scheduled continuation firing after the wait elapsed. clock.now = new Date(NOW.getTime() + 2 * 60 * 60_000 + 1_000); const second = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(second.status).toBe("completed"); expect(state.steps.find((s) => s.stepKey === "wait")?.status).toBe("success"); expect(state.notifications).toHaveLength(1); }); test("condition.if_else false skips the dependent branch", async () => { const { state, deps } = makeHarness({ triggerPayload: { status: "verloren" }, steps: [ triggerStep(), { id: "rs-c", stepKey: "check", stepKind: "condition", nodeType: "condition.if_else", sortOrder: 1, parentStepIds: ["trigger"], config: { feld: "status", vergleich: "istGleich", wert: "gewonnen" }, }, { id: "rs-2", stepKey: "create-task", stepKind: "action", nodeType: "task.create", sortOrder: 2, parentStepIds: ["check"] }, ], }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("completed"); expect(state.steps.find((s) => s.stepKey === "check")?.output).toMatchObject({ matched: false }); expect(state.steps.find((s) => s.stepKey === "create-task")?.status).toBe("skipped"); expect(state.tasks).toHaveLength(0); }); test("condition.if_else executes only the matching true or false edge", async () => { const { state, deps } = makeHarness({ triggerPayload: { status: "verloren" }, steps: [ triggerStep(), { id: "rs-c", stepKey: "check", stepKind: "condition", nodeType: "condition.if_else", sortOrder: 1, parentStepIds: ["trigger"], config: { feld: "status", vergleich: "istGleich", wert: "gewonnen" }, }, { id: "rs-true", stepKey: "true-task", stepKind: "action", nodeType: "task.create", sortOrder: 2, parentStepIds: ["check"], config: { titel: "Gewonnen", [AUTOMATION_CONDITION_BRANCHES_CONFIG_KEY]: { check: "true" } }, }, { id: "rs-false", stepKey: "false-task", stepKind: "action", nodeType: "task.create", sortOrder: 3, parentStepIds: ["check"], config: { titel: "Verloren nachbearbeiten", [AUTOMATION_CONDITION_BRANCHES_CONFIG_KEY]: { check: "false" } }, }, ], }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("completed"); expect(state.steps.find((step) => step.stepKey === "true-task")?.status).toBe("skipped"); expect(state.steps.find((step) => step.stepKey === "false-task")?.status).toBe("success"); expect(state.tasks.map((task) => task.title)).toEqual(["Verloren nachbearbeiten"]); }); test("condition.if_else maps the configured quote value to the emitted order volume", async () => { const { state, deps } = makeHarness({ triggerPayload: { orderVolume: "12500.50" }, steps: [ triggerStep(), { id: "rs-c", stepKey: "check", stepKind: "condition", nodeType: "condition.if_else", sortOrder: 1, parentStepIds: ["trigger"], config: { feld: "angebotswert", vergleich: "istGroesserAls", wert: "10000" }, }, { id: "rs-2", stepKey: "create-task", stepKind: "action", nodeType: "task.create", sortOrder: 2, parentStepIds: ["check"], config: { titel: "Angebot nachfassen" }, }, ], }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("completed"); expect(state.steps.find((step) => step.stepKey === "check")?.output).toMatchObject({ matched: true, actual: "12500.50" }); expect(state.tasks).toHaveLength(1); }); test("flow.parallel fans out and flow.merge waits for every branch", async () => { const { state, deps } = makeHarness({ steps: [ triggerStep(), { id: "rs-split", stepKey: "parallel", stepKind: "flow_control", nodeType: "flow.parallel", sortOrder: 1, parentStepIds: ["trigger"], }, { id: "rs-a", stepKey: "task-a", stepKind: "action", nodeType: "task.create", sortOrder: 2, parentStepIds: ["parallel"], config: { titel: "Zweig A" }, }, { id: "rs-b", stepKey: "task-b", stepKind: "action", nodeType: "task.create", sortOrder: 3, parentStepIds: ["parallel"], config: { titel: "Zweig B" }, }, { id: "rs-merge", stepKey: "merge", stepKind: "flow_control", nodeType: "flow.merge", sortOrder: 4, parentStepIds: ["task-a", "task-b"], }, { id: "rs-notify", stepKey: "notify", stepKind: "action", nodeType: "notification.send", sortOrder: 5, parentStepIds: ["merge"], config: { betreff: "Beide fertig", nachricht: "Die Zweige wurden zusammengeführt." }, }, ], }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("completed"); expect(state.tasks.map((task) => task.title)).toEqual(["Zweig A", "Zweig B"]); expect(state.steps.find((step) => step.stepKey === "parallel")?.output).toEqual({ continued: true }); expect(state.steps.find((step) => step.stepKey === "merge")?.output).toEqual({ continued: true }); expect(state.notifications).toHaveLength(1); expect(state.steps.find((step) => step.stepKey === "notify")?.status).toBe("success"); }); test("resumeFromStepId skips earlier steps and runs from the resume point", async () => { const { state, deps } = makeHarness({ resumeFromStepId: "rs-2", steps: [ triggerStep(), { id: "rs-1", stepKey: "create-task", stepKind: "action", nodeType: "task.create", sortOrder: 1, parentStepIds: ["trigger"] }, { id: "rs-2", stepKey: "notify", stepKind: "action", nodeType: "notification.send", sortOrder: 2, parentStepIds: ["create-task"], config: { betreff: "Fortgesetzt", nachricht: "Der Lauf wurde fortgesetzt." }, }, ], }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("completed"); expect(state.steps.find((s) => s.stepKey === "create-task")?.status).toBe("skipped"); expect(state.tasks).toHaveLength(0); expect(state.notifications).toHaveLength(1); }); test("SSRF-blocked http.request fails closed without retry", async () => { const ssrfError = Object.assign(new Error("blocked host"), { name: "OutboundHttpUrlValidationError" }); const { state, deps } = makeHarness({ steps: [ triggerStep(), { id: "rs-h", stepKey: "hook", stepKind: "action", nodeType: "http.request", sortOrder: 1, parentStepIds: ["trigger"], config: { url: "http://10.0.0.1/x", methode: "post" }, }, ], fetchImpl: async () => { throw ssrfError; }, }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("failed"); expect(state.execution.summaryText).toBe("automation.execution.httpBlockedUrl"); expect(state.outbox.filter((row) => String(row.dispatchKey ?? "").startsWith("automation-exec:exec-1:retry"))).toHaveLength(0); }); test("http.request renders placeholders before the guarded outbound call", async () => { let request: { url: string; method: string; body?: string } | null = null; const { deps } = makeHarness({ triggerPayload: { host: "hooks.example.com", project: { id: "project-42" } }, steps: [ triggerStep(), { id: "rs-h", stepKey: "hook", stepKind: "action", nodeType: "http.request", sortOrder: 1, parentStepIds: ["trigger"], config: { url: "https://{{host}}/projects/{{project.id}}", methode: "post", koerper: '{"projectId":"{{project.id}}"}' }, }, ], fetchImpl: async (input) => { request = input; return { status: 202, ok: true }; }, }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("completed"); expect(request).toEqual({ url: "https://hooks.example.com/projects/project-42", method: "POST", body: '{"projectId":"project-42"}' }); }); test("chat.post_message uses the idempotent chat service and renders step placeholders", async () => { const calls: Array> = []; const { state, deps } = makeHarness({ triggerPayload: { chatId: "chat-42", project: { number: "P-42" } }, steps: [ triggerStep(), { id: "rs-c", stepKey: "chat", stepKind: "action", nodeType: "chat.post_message", sortOrder: 1, parentStepIds: ["trigger"], config: { chatId: "{{chatId}}", nachricht: "Projekt {{project.number}} ist bereit." }, }, ], sendChatImpl: async (input) => { calls.push(input); return { messageId: "message-42", replayed: false }; }, }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("completed"); expect(calls).toEqual([ { tenantId: TENANT, userId: OWNER, chatId: "chat-42", requestId: "automation:exec-1:rs-c", clientMessageId: "automation:exec-1:rs-c", body: "Projekt P-42 ist bereit.", }, ]); expect(state.steps.find((step) => step.stepKey === "chat")?.output).toEqual({ chatId: "chat-42", messageId: "message-42", replayed: false }); }); test("email.send_transactional publishes exactly one mail per step (duplicate-mail protection)", async () => { const seed = { steps: [ triggerStep(), { id: "rs-m", stepKey: "mail", stepKind: "action", nodeType: "email.send_transactional", sortOrder: 1, parentStepIds: ["trigger"], config: { an: "kunde@firma.de", betreff: "Hallo", nachricht: "Ihre Anfrage ist da." }, }, ], }; const { state, deps } = makeHarness(seed); await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); const mails = state.outbox.filter((row) => row.eventType === "mail.transactional.send"); expect(mails).toHaveLength(1); expect(mails[0]).toMatchObject({ dispatchKey: "automation-mail:rs-m" }); // Re-processing the same step (e.g. crash after send, retry) collapses on // the dispatchKey instead of sending a second mail. const step = state.steps.find((s) => s.stepKey === "mail")!; step.status = "queued"; state.execution.status = "queued"; await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(state.outbox.filter((row) => row.eventType === "mail.transactional.send")).toHaveLength(1); }); test("later actions can render outputs from their completed ancestor steps", async () => { const { state, deps } = makeHarness({ triggerPayload: { email: "kunde@firma.de" }, steps: [ triggerStep(), { id: "rs-task", stepKey: "create-task", stepKind: "action", nodeType: "task.create", sortOrder: 1, parentStepIds: ["trigger"], config: { titel: "Rückruf", zustaendig: "besitzerDerAutomation", prioritaet: "normal" }, }, { id: "rs-mail", stepKey: "mail", stepKind: "action", nodeType: "email.send_transactional", sortOrder: 2, parentStepIds: ["create-task"], config: { an: "{{email}}", betreff: "Aufgabe {{steps.create-task.taskId}} angelegt", nachricht: "Titel: {{steps.create-task.title}}", }, }, ], }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("completed"); expect(state.outbox.find((row) => row.eventType === "mail.transactional.send")?.payload).toMatchObject({ to: [{ email: "kunde@firma.de" }], subject: "Aufgabe task-1 angelegt", text: "Titel: Rückruf", }); }); test("crm.update_kontakt stores the reverse-consumable before snapshot", async () => { const { state, deps } = makeHarness({ kontakte: [ { id: "k-1", tenantId: TENANT, archivedAt: null, kontaktStatus: "kontakt", vorname: "Kim", nachname: "Klein", orgName: null, primaerEmail: null, primaerTelefon: null, language: "de", }, ], steps: [ triggerStep(), { id: "rs-u", stepKey: "update", stepKind: "action", nodeType: "crm.update_kontakt", sortOrder: 1, parentStepIds: ["trigger"], config: { kontakt: "ausloeser", feld: "kontaktStatus", wert: "kunde" }, }, ], }); await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); const step = state.steps.find((s) => s.stepKey === "update"); expect(step?.output).toMatchObject({ kontaktId: "k-1", before: { kontaktStatus: "kontakt" } }); expect(state.kontakte[0].kontaktStatus).toBe("kunde"); }); test("CRM tag actions add and remove a tenant tag idempotently", async () => { const { state, deps } = makeHarness({ kontakte: [{ id: "k-1", tenantId: TENANT, archivedAt: null }], tags: [{ id: "tag-1", tenantId: TENANT, name: "VIP" }], steps: [ triggerStep(), { id: "rs-add-tag", stepKey: "add-tag", stepKind: "action", nodeType: "crm.add_tag", sortOrder: 1, parentStepIds: ["trigger"], config: { kontakt: "ausloeser", tagId: "tag-1" }, }, { id: "rs-remove-tag", stepKey: "remove-tag", stepKind: "action", nodeType: "crm.remove_tag", sortOrder: 2, parentStepIds: ["add-tag"], config: { kontakt: "ausloeser", tagId: "tag-1" }, }, ], }); expect((await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps)).status).toBe("completed"); expect(state.tagAssignments).toEqual([]); expect(state.steps.find((step) => step.stepKey === "add-tag")?.output).toMatchObject({ kontaktId: "k-1", tagId: "tag-1", changed: true }); expect(state.steps.find((step) => step.stepKey === "remove-tag")?.output).toMatchObject({ kontaktId: "k-1", tagId: "tag-1", changed: true }); expect(state.activities.map((activity) => activity.activityType)).toEqual(["tag_added", "tag_removed"]); }); test("crm.assign_kontakt assigns only an active user of the tenant", async () => { const { state, deps } = makeHarness({ kontakte: [{ id: "k-1", tenantId: TENANT, archivedAt: null, zustaendigerUserId: null }], tenantUsers: [{ id: "membership-assignee", tenantId: TENANT, userId: "user-assignee", status: 2, user: { active: true } }], steps: [ triggerStep(), { id: "rs-assign-contact", stepKey: "assign-contact", stepKind: "action", nodeType: "crm.assign_kontakt", sortOrder: 1, parentStepIds: ["trigger"], config: { kontakt: "ausloeser", userId: "user-assignee" }, }, ], }); expect((await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps)).status).toBe("completed"); expect(state.kontakte[0]?.zustaendigerUserId).toBe("user-assignee"); expect(state.steps.find((step) => step.stepKey === "assign-contact")?.output).toMatchObject({ kontaktId: "k-1", assignedToUserId: "user-assignee", before: { zustaendigerUserId: null }, }); expect(state.activities).toEqual([expect.objectContaining({ activityType: "owner_changed", subjectId: "k-1" })]); }); test("lead.assign and lead.set_status mutate the typed lead and emit domain events", async () => { const { state, deps } = makeHarness({ triggerPayload: { leadId: "lead-1" }, leads: [ { id: "lead-1", tenantId: TENANT, archivedAt: null, quelle: "form", sourceId: "source-1", status: "new", weiterverarbeitungFreigabe: "unklar", zustaendigerUserId: null, konvertiertProjektId: null, verknuepfterKontaktId: null, spamScore: 0, isQuarantined: false, convertedAt: null, lostAt: null, spamMarkedAt: null, autoDeleteAt: null, }, ], tenantUsers: [{ id: "membership-assignee", tenantId: TENANT, userId: "user-assignee", status: 2, user: { active: true } }], steps: [ triggerStep({ nodeType: "lead.captured" }), { id: "rs-assign-lead", stepKey: "assign-lead", stepKind: "action", nodeType: "lead.assign", sortOrder: 1, parentStepIds: ["trigger"], config: { lead: "ausloeser", userId: "user-assignee" }, }, { id: "rs-qualify-lead", stepKey: "qualify-lead", stepKind: "action", nodeType: "lead.set_status", sortOrder: 2, parentStepIds: ["assign-lead"], config: { lead: "ausloeser", status: "qualified" }, }, ], }); expect((await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps)).status).toBe("completed"); expect(state.leads[0]).toMatchObject({ zustaendigerUserId: "user-assignee", status: "qualified", weiterverarbeitungFreigabe: "ja" }); expect(state.steps.find((step) => step.stepKey === "assign-lead")?.output).toMatchObject({ leadId: "lead-1", assignedToUserId: "user-assignee", changed: true, before: { zustaendigerUserId: null }, }); expect(state.steps.find((step) => step.stepKey === "qualify-lead")?.output).toMatchObject({ leadId: "lead-1", status: "qualified", changed: true, before: { status: "new", weiterverarbeitungFreigabe: "unklar" }, }); expect(state.outbox.filter((row) => row.eventType === "workflow.trigger.event").map((row) => (row.payload as Record).event)).toEqual([ "lead.assigned", "lead.qualified", ]); expect(state.activities.map((activity) => activity.activityType)).toEqual(["assignee_changed", "lead_qualified"]); }); test("lead.set_status rejects an invalid transition without changing the lead", async () => { const { state, deps } = makeHarness({ triggerPayload: { leadId: "lead-1" }, leads: [ { id: "lead-1", tenantId: TENANT, archivedAt: null, quelle: "form", sourceId: null, status: "lost", weiterverarbeitungFreigabe: "unklar", zustaendigerUserId: null, konvertiertProjektId: null, verknuepfterKontaktId: null, spamScore: 0, isQuarantined: false, convertedAt: null, lostAt: NOW, spamMarkedAt: null, autoDeleteAt: null, }, ], steps: [ triggerStep({ nodeType: "lead.captured" }), { id: "rs-status-lead", stepKey: "status-lead", stepKind: "action", nodeType: "lead.set_status", sortOrder: 1, parentStepIds: ["trigger"], config: { lead: "ausloeser", status: "qualified" }, }, ], }); expect((await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps)).status).toBe("failed"); expect(state.execution.summaryText).toBe("automation.execution.leadStatusInvalidTransition"); expect(state.leads[0]?.status).toBe("lost"); expect(state.outbox.filter((row) => row.eventType === "workflow.trigger.event")).toHaveLength(0); }); test("loop.for_each fans out its descendant DAG once per collection item", async () => { const { state, deps } = makeHarness({ triggerPayload: { projectId: "project-1" }, tasks: [ { id: "source-task-1", tenantId: TENANT, createdAt: new Date("2026-07-01T08:00:00.000Z"), archivedAt: null, linkedEntityType: "project", linkedEntityId: "project-1", status: "open", priority: "normal", title: "Heizung prüfen", description: null, deadline: null, assignedToUserId: OWNER, assignedToGroupId: null, }, { id: "source-task-2", tenantId: TENANT, createdAt: new Date("2026-07-02T08:00:00.000Z"), archivedAt: null, linkedEntityType: "project", linkedEntityId: "project-1", status: "blocked", priority: "high", title: "Material klären", description: null, deadline: null, assignedToUserId: OWNER, assignedToGroupId: null, }, ], steps: [ triggerStep(), { id: "rs-l", stepKey: "loop", stepKind: "flow_control", nodeType: "loop.for_each", sortOrder: 1, parentStepIds: ["trigger"], config: { liste: "offeneAufgabenDesProjekts", maxDurchlaeufe: "10" }, }, { id: "rs-c", stepKey: "create-follow-up", stepKind: "action", nodeType: "task.create", sortOrder: 2, parentStepIds: ["loop"], config: { titel: "Nachfassen: {{loop.item.title}}", zustaendig: "besitzerDerAutomation", prioritaet: "normal" }, }, { id: "rs-n", stepKey: "notify", stepKind: "action", nodeType: "notification.send", sortOrder: 3, parentStepIds: ["create-follow-up"], config: { betreff: "Element {{loop.position}}/{{loop.count}}", nachricht: "{{loop.item.title}} wurde eingeplant." }, }, ], }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("completed"); expect(state.steps.find((step) => step.stepKey === "loop")?.output).toMatchObject({ count: 2, truncated: false }); expect(state.steps.find((step) => step.stepKey === "create-follow-up")?.status).toBe("skipped"); const createdTasks = state.tasks.filter((task) => task.source === "automation"); expect(createdTasks.map((task) => task.title)).toEqual(["Nachfassen: Heizung prüfen", "Nachfassen: Material klären"]); expect(state.notifications).toHaveLength(2); expect(state.notifications.map((notification) => notification.payloadMetadata)).toEqual([ expect.objectContaining({ betreff: "Element 1/2", nachricht: "Heizung prüfen wurde eingeplant." }), expect.objectContaining({ betreff: "Element 2/2", nachricht: "Material klären wurde eingeplant." }), ]); expect(state.steps.filter((step) => step.stepKey.startsWith("create-follow-up::loop:")).every((step) => step.status === "success")).toBe(true); expect(state.steps.filter((step) => step.stepKey.startsWith("notify::loop:")).every((step) => step.status === "success")).toBe(true); }); test.each([ { name: "project contacts", collectionKey: "kontakteDesProjekts", itemField: "kontaktId", expectedTitle: "Element kontakt-1", maxIterations: "1", expectedTruncated: true, source: { projektKontakte: [ { id: "pk-1", tenantId: TENANT, projektId: "project-1", createdAt: new Date("2026-07-01T08:00:00.000Z"), kontaktId: "kontakt-1", rolle: "kunde", primaer: true }, { id: "pk-2", tenantId: TENANT, projektId: "project-1", createdAt: new Date("2026-07-02T08:00:00.000Z"), kontaktId: "kontakt-2", rolle: "ansprechpartner", primaer: false }, { id: "pk-other", tenantId: TENANT, projektId: "project-2", createdAt: new Date("2026-07-03T08:00:00.000Z"), kontaktId: "kontakt-other" }, ], }, }, { name: "quote positions", collectionKey: "positionenDesAngebots", itemField: "text", expectedTitle: "Element Wärmepumpe", maxIterations: "10", expectedTruncated: false, source: { kwpMaterialPositionen: [ { id: "position-1", tenantId: TENANT, projektId: "project-1", archivedAt: null, externalId: "ext-1", positionNumber: 1, text: "Wärmepumpe", longText: null, quantity: "1", unit: "Stk", unitPrice: "12000", totalPrice: "12000", }, { id: "position-archived", tenantId: TENANT, projektId: "project-1", archivedAt: NOW, text: "Archiviert" }, ], }, }, { name: "appointments in the current week", collectionKey: "termineDieserWoche", itemField: "titel", expectedTitle: "Element Montage", maxIterations: "10", expectedTruncated: false, source: { projektTermine: [ { id: "termin-1", tenantId: TENANT, projektId: "project-1", archivedAt: null, titel: "Montage", beschreibung: null, startAt: new Date("2026-07-18T08:00:00.000Z"), endAt: new Date("2026-07-18T10:00:00.000Z"), status: "confirmed", typ: "installation", assignedToUserId: OWNER, assignedToGroupId: null, }, { id: "termin-next-week", tenantId: TENANT, projektId: "project-1", archivedAt: null, titel: "Nächste Woche", startAt: new Date("2026-07-20T08:00:00.000Z"), endAt: null, }, ], }, }, ])("loop.for_each reads $name and exposes each item to descendant templates", async (fixture) => { const { state, deps } = makeHarness({ triggerPayload: { projectId: "project-1" }, ...fixture.source, steps: [ triggerStep(), { id: "rs-loop", stepKey: "loop", stepKind: "flow_control", nodeType: "loop.for_each", sortOrder: 1, parentStepIds: ["trigger"], config: { liste: fixture.collectionKey, maxDurchlaeufe: fixture.maxIterations }, }, { id: "rs-task", stepKey: "create-task", stepKind: "action", nodeType: "task.create", sortOrder: 2, parentStepIds: ["loop"], config: { titel: `Element {{loop.item.${fixture.itemField}}}`, zustaendig: "besitzerDerAutomation", prioritaet: "normal" }, }, ], }); const result = await runAutomationExecutionJob({ tenantId: TENANT, executionId: "exec-1" }, deps); expect(result.status).toBe("completed"); expect(state.steps.find((step) => step.stepKey === "loop")?.output).toMatchObject({ count: 1, truncated: fixture.expectedTruncated }); expect(state.tasks.filter((task) => task.source === "automation").map((task) => task.title)).toEqual([fixture.expectedTitle]); }); }); describe("output contracts", () => { test("rejects incomplete reverse-critical outputs fail-closed", () => { expect(() => validateAutomationStepOutput("task.create", {})).toThrow(AutomationActionPermanentError); expect(() => validateAutomationStepOutput("task.assign", { taskId: "t", before: { assignedToUserId: "a", assignedToGroupId: "g" } })).toThrow( /user AND group/ ); expect(() => validateAutomationStepOutput("crm.update_kontakt", { kontaktId: "k", before: {} })).toThrow(AutomationActionPermanentError); expect(() => validateAutomationStepOutput("lead.assign", { leadId: "l", assignedToUserId: "u", changed: true, before: {} })).toThrow( AutomationActionPermanentError ); expect(() => validateAutomationStepOutput("lead.set_status", { leadId: "l", status: "qualified", changed: true, before: { status: "new" } })).toThrow( AutomationActionPermanentError ); expect(() => validateAutomationStepOutput("notification.send", { recipients: [] })).toThrow(AutomationActionPermanentError); expect(() => validateAutomationStepOutput("chat.post_message", { chatId: "c", messageId: "m" })).toThrow(AutomationActionPermanentError); expect(() => validateAutomationStepOutput("task.create", { taskId: "t-1" })).not.toThrow(); }); }); describe("renderAutomationTemplate", () => { test("supports case-insensitive nested payload keys and clears missing values", () => { expect(renderAutomationTemplate("Hallo {{Vorname}} · {{project.number}} · {{missing}}", { vorname: "Mia", project: { number: 17 } })).toBe( "Hallo Mia · 17 · " ); }); }); describe("planNextStep / resolveDelayMs", () => { test("resolveDelayMs converts units and caps at 30 days", () => { expect(resolveDelayMs({ dauer: "2", dauerEinheit: "stunden" })).toBe(2 * 60 * 60_000); expect(resolveDelayMs({ dauer: "9999", dauerEinheit: "wochen" })).toBe(30 * 24 * 60 * 60_000); expect(() => resolveDelayMs({ dauer: "-1", dauerEinheit: "tage" })).toThrow(AutomationActionPermanentError); expect(() => resolveDelayMs({ dauer: "2", dauerEinheit: "jahre" })).toThrow(/delayInvalidUnit/); }); test("marks queued steps behind a failed ancestor as unreachable", () => { const configs = new Map([ ["rs-1", { config: {}, parentStepIds: [] as readonly string[] }], ["rs-2", { config: {}, parentStepIds: ["a"] as readonly string[] }], ]); const plan = planNextStep( [ { id: "s1", stepKey: "a", stepKind: "action", nodeType: "task.create", sortOrder: 0, status: "failed", output: {}, startedAt: null, ruleStepId: "rs-1", }, { id: "s2", stepKey: "b", stepKind: "action", nodeType: "task.assign", sortOrder: 1, status: "queued", output: {}, startedAt: null, ruleStepId: "rs-2", }, ], configs as never, NOW ); expect(plan).toMatchObject({ kind: "skip_steps", summaryKey: "automation.execution.stepSkippedUnreachable" }); }); });