// R-P12c DoD 7 — trigger-bus tests. The fake tx imitates the RLS policy // (AGENTS.md §RLS): it is BOUND to one tenant and refuses to return or write // rows of any other tenant, so a missing tenant filter surfaces as a test // failure instead of being hidden by an answer-everything mock. import { describe, expect, test, vi } from "vitest"; import { AUTOMATION_DOMAIN_EVENT_TRIGGER_MAP, buildAutomationExecutionRequestedOutboxEvent, queueAutomationExecutionsForDomainEventWithTx, recordAutomationTriggerVolumeWithTx, } from "./automation-forward.server.js"; const TENANT = "tenant-a"; const OTHER_TENANT = "tenant-b"; const OWNER = "user-owner"; const NOW = new Date("2026-07-19T12:00:00.000Z"); type RuleSeed = { id: string; tenantId?: string; triggerKey?: string; status?: string; enabled?: boolean; createdByUserId?: string | null; steps?: Array<{ id: string; stepKey: string; stepKind: string; nodeType: string; config?: Record; parentStepIds: string[]; sortOrder: number; summaryText: string; }>; }; function defaultSteps() { return [ { id: "rs-1", stepKey: "trigger", stepKind: "trigger", nodeType: "forms.submitted", parentStepIds: [], sortOrder: 0, summaryText: "t" }, { id: "rs-2", stepKey: "create-task", stepKind: "action", nodeType: "task.create", parentStepIds: ["trigger"], sortOrder: 1, summaryText: "a" }, ]; } function makeTx(options: { boundTenantId?: string; rules?: RuleSeed[]; existingIdempotencyKeys?: string[]; ownerPermissions?: string[]; ownerActive?: boolean; tenantActive?: boolean; frozen?: boolean; meterCount?: number; }) { const bound = options.boundTenantId ?? TENANT; const assertTenant = (where: { tenantId?: string } | undefined, model: string) => { if (where?.tenantId && where.tenantId !== bound) { throw new Error(`RLS violation: ${model} queried for ${where.tenantId} on a tx bound to ${bound}`); } }; const createdExecutions: Array> = []; const outboxRows: Array> = []; const ruleUpdates: Array> = []; const ruleFindMany = vi.fn(async (args: { where: { tenantId: string; triggerKey: string; id?: string } }) => { assertTenant(args.where, "automationRule"); return (options.rules ?? []) .filter((rule) => (rule.tenantId ?? TENANT) === bound) .filter((rule) => !args.where.id || rule.id === args.where.id) .filter((rule) => rule.triggerKey === args.where.triggerKey && (rule.status ?? "active") === "active" && (rule.enabled ?? true)) .map((rule) => ({ id: rule.id, createdByUserId: rule.createdByUserId === undefined ? OWNER : rule.createdByUserId, steps: rule.steps ?? defaultSteps(), })); }); const tx = { tenant: { findFirst: vi.fn(async () => options.tenantActive === false ? { active: false, subscription: null } : { active: true, subscription: options.frozen ? { status: "frozen", frozenAt: NOW } : { status: "active", frozenAt: null } } ), }, automationRule: { findMany: ruleFindMany, update: vi.fn(async (args: Record) => { ruleUpdates.push(args); return {}; }), }, automationExecution: { findFirst: vi.fn(async (args: { where: { tenantId: string; idempotencyKey: string } }) => { assertTenant(args.where, "automationExecution"); return (options.existingIdempotencyKeys ?? []).includes(args.where.idempotencyKey) ? { id: "existing" } : null; }), create: vi.fn(async (args: { data: Record }) => { assertTenant(args.data as { tenantId?: string }, "automationExecution.create"); createdExecutions.push(args.data); return { id: `exec-${createdExecutions.length}`, status: args.data.status }; }), }, tenantUser: { findFirst: vi.fn(async (args: { where: { tenantId: string } }) => { assertTenant(args.where, "tenantUser"); return options.ownerActive === false ? null : { id: "tu-1" }; }), }, permission: { findMany: vi.fn(async () => (options.ownerPermissions ?? ["automation.run"]).map((name) => ({ name }))), }, automationTriggerMeter: { upsert: vi.fn(async () => ({ count: options.meterCount ?? 1 })), update: vi.fn(async () => ({})), }, outboxEvent: { create: vi.fn(async (args: { data: Record }) => { outboxRows.push(args.data); return args.data; }), findUnique: vi.fn(async () => null), }, }; return { tx: tx as never, createdExecutions, outboxRows, ruleUpdates, ruleFindMany }; } describe("AUTOMATION_DOMAIN_EVENT_TRIGGER_MAP", () => { test("maps the v1 emitter set onto registry trigger keys", () => { expect(AUTOMATION_DOMAIN_EVENT_TRIGGER_MAP["form.submitted"]).toBe("forms.submitted"); expect(AUTOMATION_DOMAIN_EVENT_TRIGGER_MAP["lead.created"]).toBe("lead.captured"); expect(AUTOMATION_DOMAIN_EVENT_TRIGGER_MAP["deal.won"]).toBe("sales.project_won"); expect(AUTOMATION_DOMAIN_EVENT_TRIGGER_MAP["kontakt.created"]).toBe("crm.kontakt_created"); expect(AUTOMATION_DOMAIN_EVENT_TRIGGER_MAP["email.inbound_received"]).toBe("email.inbound_received"); expect(AUTOMATION_DOMAIN_EVENT_TRIGGER_MAP["email.campaign_bounced"]).toBe("email.campaign_bounced"); expect(AUTOMATION_DOMAIN_EVENT_TRIGGER_MAP["booking.appointment_booked"]).toBe("booking.appointment_booked"); expect(AUTOMATION_DOMAIN_EVENT_TRIGGER_MAP["booking.appointment_cancelled"]).toBe("booking.appointment_cancelled"); expect(AUTOMATION_DOMAIN_EVENT_TRIGGER_MAP["calendar.event_created"]).toBe("calendar.event_created"); expect(AUTOMATION_DOMAIN_EVENT_TRIGGER_MAP["projects.deadline_soon"]).toBe("projects.deadline_soon"); expect(AUTOMATION_DOMAIN_EVENT_TRIGGER_MAP["time.schedule"]).toBe("time.schedule"); expect(AUTOMATION_DOMAIN_EVENT_TRIGGER_MAP["portal.status_mail_sent"]).toBeUndefined(); }); }); describe("queueAutomationExecutionsForDomainEventWithTx", () => { const baseInput = { tenantId: TENANT, domainEvent: "form.submitted", payload: { formId: "f-1" }, sourceEventId: "outbox-1", now: NOW, }; test("creates a queued execution with step snapshots and publishes the executor dispatch atomically", async () => { const { tx, createdExecutions, outboxRows } = makeTx({ rules: [{ id: "rule-1", triggerKey: "forms.submitted" }] }); const result = await queueAutomationExecutionsForDomainEventWithTx(tx, baseInput); expect(result).toMatchObject({ matched: 1, queued: 1, deduplicated: 0 }); expect(result.executionIds).toEqual(["exec-1"]); expect(createdExecutions).toHaveLength(1); expect(createdExecutions[0]).toMatchObject({ tenantId: TENANT, triggerKey: "forms.submitted", status: "queued", createdByUserId: OWNER }); expect((createdExecutions[0].stepExecutions as { create: unknown[] }).create).toHaveLength(2); expect(outboxRows).toHaveLength(1); expect(outboxRows[0]).toMatchObject({ eventType: "automation.execution.requested", tenantId: TENANT }); }); test("queues only rules whose persisted trigger filter matches the event payload", async () => { const steps = (formId: string) => [{ ...defaultSteps()[0]!, config: { formId } }, defaultSteps()[1]!]; const { tx, createdExecutions } = makeTx({ rules: [ { id: "rule-matching", triggerKey: "forms.submitted", steps: steps("f-1") }, { id: "rule-other-form", triggerKey: "forms.submitted", steps: steps("f-2") }, ], }); const result = await queueAutomationExecutionsForDomainEventWithTx(tx, baseInput); expect(result).toMatchObject({ matched: 1, queued: 1 }); expect(createdExecutions).toHaveLength(1); expect(createdExecutions[0]).toMatchObject({ ruleId: "rule-matching", triggerPayload: { formId: "f-1" } }); }); test("routes scheduler events only to the rule whose lead-time calculation produced them", async () => { const steps = [{ ...defaultSteps()[0]!, nodeType: "time.schedule", config: { wiederholung: "taeglich", uhrzeit: "08:00" } }, defaultSteps()[1]!]; const { tx, createdExecutions, ruleFindMany } = makeTx({ rules: [ { id: "rule-due", triggerKey: "time.schedule", steps }, { id: "rule-not-due", triggerKey: "time.schedule", steps }, ], }); const result = await queueAutomationExecutionsForDomainEventWithTx(tx, { ...baseInput, domainEvent: "time.schedule", payload: { automationRuleId: "rule-due", wiederholung: "taeglich", uhrzeit: "08:00" }, }); expect(result).toMatchObject({ matched: 1, queued: 1 }); expect(createdExecutions).toHaveLength(1); expect(createdExecutions[0]).toMatchObject({ ruleId: "rule-due" }); expect(ruleFindMany).toHaveBeenCalledWith(expect.objectContaining({ where: expect.objectContaining({ id: "rule-due" }) })); }); test("duplicate source events dedup on the idempotency key and publish nothing", async () => { const first = makeTx({ rules: [{ id: "rule-1", triggerKey: "forms.submitted" }] }); await queueAutomationExecutionsForDomainEventWithTx(first.tx, baseInput); const usedKey = (first.createdExecutions[0] as { idempotencyKey: string }).idempotencyKey; const second = makeTx({ rules: [{ id: "rule-1", triggerKey: "forms.submitted" }], existingIdempotencyKeys: [usedKey] }); const result = await queueAutomationExecutionsForDomainEventWithTx(second.tx, baseInput); expect(result).toMatchObject({ matched: 1, queued: 0, deduplicated: 1 }); expect(second.createdExecutions).toHaveLength(0); expect(second.outboxRows).toHaveLength(0); }); test("rejects rules whose owner lost the automation.run permission", async () => { const { tx, createdExecutions } = makeTx({ rules: [{ id: "rule-1", triggerKey: "forms.submitted" }], ownerPermissions: [] }); const result = await queueAutomationExecutionsForDomainEventWithTx(tx, baseInput); expect(result.rejected).toEqual([{ ruleId: "rule-1", reason: "owner_missing_automation_run_permission" }]); expect(createdExecutions).toHaveLength(0); }); test("rejects rules without an active owner membership", async () => { const { tx } = makeTx({ rules: [{ id: "rule-1", triggerKey: "forms.submitted" }], ownerActive: false }); const result = await queueAutomationExecutionsForDomainEventWithTx(tx, baseInput); expect(result.rejected[0]?.reason).toBe("owner_not_active_member"); }); test("pauses the rule and parks the execution when the trigger volume anomaly fires", async () => { const { tx, createdExecutions, outboxRows, ruleUpdates } = makeTx({ rules: [{ id: "rule-1", triggerKey: "forms.submitted" }], meterCount: 2000, }); const result = await queueAutomationExecutionsForDomainEventWithTx(tx, baseInput); expect(result.queued).toBe(0); expect(result.rejected[0]?.reason).toBe("trigger_volume_paused"); expect(createdExecutions[0]).toMatchObject({ status: "paused" }); expect(outboxRows).toHaveLength(0); expect(ruleUpdates).toHaveLength(1); }); test("pauses the rule fail-closed when the persisted graph contains a cycle", async () => { const cyclicSteps = [ { id: "rs-1", stepKey: "a", stepKind: "action", nodeType: "task.create", parentStepIds: ["b"], sortOrder: 0, summaryText: "a" }, { id: "rs-2", stepKey: "b", stepKind: "action", nodeType: "task.assign", parentStepIds: ["a"], sortOrder: 1, summaryText: "b" }, ]; const { tx, createdExecutions } = makeTx({ rules: [{ id: "rule-1", triggerKey: "forms.submitted", steps: cyclicSteps }] }); const result = await queueAutomationExecutionsForDomainEventWithTx(tx, baseInput); expect(result.rejected[0]?.reason).toBe("loop_guard_paused"); expect(createdExecutions[0]).toMatchObject({ status: "paused", summaryText: "automation.execution.loopGuardPaused" }); }); test("does nothing for inactive or frozen tenants", async () => { for (const opts of [{ tenantActive: false }, { frozen: true }]) { const { tx, createdExecutions } = makeTx({ rules: [{ id: "rule-1", triggerKey: "forms.submitted" }], ...opts }); const result = await queueAutomationExecutionsForDomainEventWithTx(tx, baseInput); expect(result).toEqual({ matched: 0, queued: 0, deduplicated: 0, rejected: [] }); expect(createdExecutions).toHaveLength(0); } }); test("ignores domain events without an automation mapping", async () => { const { tx } = makeTx({ rules: [] }); const result = await queueAutomationExecutionsForDomainEventWithTx(tx, { ...baseInput, domainEvent: "portal.user_created" }); expect(result).toEqual({ matched: 0, queued: 0, deduplicated: 0, rejected: [] }); }); test("a tx bound to another tenant refuses the query (RLS imitation)", async () => { const { tx } = makeTx({ boundTenantId: OTHER_TENANT, rules: [] }); await expect(queueAutomationExecutionsForDomainEventWithTx(tx, baseInput)).rejects.toThrow(/RLS violation/); }); }); describe("recordAutomationTriggerVolumeWithTx", () => { test("pauses at the hard window limit and reports a translatable key", async () => { const { tx } = makeTx({ meterCount: 2000 }); const result = await recordAutomationTriggerVolumeWithTx(tx, { tenantId: TENANT, triggerKey: "forms.submitted", now: NOW }); expect(result.action).toBe("pause"); // The summary is rendered in the run list, so it has to stay a key - the // English sentence this used to carry leaked straight into the UI. expect(result.summaryKey).toBe("automation.execution.triggerVolumePaused"); }); test("below the limit the queued key is reported, never prose", async () => { const { tx } = makeTx({ meterCount: 3 }); const result = await recordAutomationTriggerVolumeWithTx(tx, { tenantId: TENANT, triggerKey: "forms.submitted", now: NOW }); expect(result.action).toBe("allow"); expect(result.summaryKey).toBe("automation.execution.queued"); }); }); describe("buildAutomationExecutionRequestedOutboxEvent", () => { test("builds a deduplicatable dispatch with optional scheduling", () => { const event = buildAutomationExecutionRequestedOutboxEvent({ tenantId: TENANT, executionId: "exec-1", phase: "retry:2", scheduledAt: NOW }); expect(event).toMatchObject({ type: "automation.execution.requested", tenantId: TENANT, dispatchKey: "automation-exec:exec-1:retry:2", scheduledAt: NOW, }); expect(buildAutomationExecutionRequestedOutboxEvent({ tenantId: TENANT, executionId: "exec-1" }).dispatchKey).toBe("automation-exec:exec-1:initial"); }); });