Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(routines): gate event triggers on Jev yes/no conditions (#7572)
teo5616d5b644f8
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex b0631331c2..7acf1dfa63 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -3465,6 +3465,7 @@"crates/ip_extractor","crates/item_filter_index","crates/item_filters",+ "crates/jev","crates/kafka_util","crates/last_online_tracker","crates/lexical_client",@@ -4648,6 +4649,7 @@"crates/ip_extractor","crates/item_filter_index","crates/item_filters",+ "crates/jev","crates/kafka_util","crates/last_online_tracker","crates/lexical_client",@@ -7182,6 +7184,7 @@"crates/invite_email","crates/ip_extractor","crates/item_filters",+ "crates/jev","crates/kafka_util","crates/last_online_tracker","crates/lexical_client",@@ -7901,6 +7904,25 @@"crates/non_empty","crates/notification_state"],+ "jev": [+ "crates/ai_usage",+ "crates/bot_id",+ "crates/bot_token",+ "crates/cowlike",+ "crates/harness_id",+ "crates/harness_token",+ "crates/jev",+ "crates/macro_auth",+ "crates/macro_authorization",+ "crates/macro_env",+ "crates/macro_env_var",+ "crates/macro_user_id",+ "crates/macro_uuid",+ "crates/model-error-response",+ "crates/model_user",+ "crates/remote_env_var",+ "crates/workspace-hack"+ ],"kafka_util": ["crates/kafka_util","crates/macro_env",@@ -10357,6 +10379,7 @@"crates/invite_email","crates/ip_extractor","crates/item_filters",+ "crates/jev","crates/kafka_util","crates/last_online_tracker","crates/lexical_client",diff --git a/.sqlx/query-43a47fd4c20fc00da4007c746f6f8d363c7d6e5a2833fecf13beaafe5433e7ad.json b/.sqlx/query-43a47fd4c20fc00da4007c746f6f8d363c7d6e5a2833fecf13beaafe5433e7ad.jsonnew file mode 100644index 0000000000..523ed799da--- /dev/null+++ b/.sqlx/query-43a47fd4c20fc00da4007c746f6f8d363c7d6e5a2833fecf13beaafe5433e7ad.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE scheduled_action_event_run SET execution_record_id = $3\n WHERE action_id = $1 AND event_id = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "43a47fd4c20fc00da4007c746f6f8d363c7d6e5a2833fecf13beaafe5433e7ad"+}diff --git a/.sqlx/query-6ecf2a02f4d35e53471d07f6e6d3053ef183e28250a34491376aede6a238360a.json b/.sqlx/query-6ecf2a02f4d35e53471d07f6e6d3053ef183e28250a34491376aede6a238360a.jsonnew file mode 100644index 0000000000..ae46a81fb4--- /dev/null+++ b/.sqlx/query-6ecf2a02f4d35e53471d07f6e6d3053ef183e28250a34491376aede6a238360a.json@@ -0,0 +1,21 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO action_execution_record\n (id, action_id, resource_id, start_time, end_time, is_success, result, created_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Text",+ "Timestamptz",+ "Timestamptz",+ "Bool",+ "Jsonb",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "6ecf2a02f4d35e53471d07f6e6d3053ef183e28250a34491376aede6a238360a"+}diff --git a/.sqlx/query-d4e5c358f8bdef259dbb3aa6d7f45ae1bd6b202c7fa8a65efb5a114c6aa0fd6f.json b/.sqlx/query-d4e5c358f8bdef259dbb3aa6d7f45ae1bd6b202c7fa8a65efb5a114c6aa0fd6f.jsonnew file mode 100644index 0000000000..9f65a6e0fa--- /dev/null+++ b/.sqlx/query-d4e5c358f8bdef259dbb3aa6d7f45ae1bd6b202c7fa8a65efb5a114c6aa0fd6f.json@@ -0,0 +1,25 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE scheduled_action_event_run SET state = 'finished', finished_at = now(), outcome = $4\n WHERE action_id = $1 AND event_id = $2 AND configuration_revision = $3 AND state = 'pending'\n RETURNING event_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "event_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Int8",+ "Jsonb"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "d4e5c358f8bdef259dbb3aa6d7f45ae1bd6b202c7fa8a65efb5a114c6aa0fd6f"+}diff --git a/Cargo.lock b/Cargo.lockindex 0696705863..a01629cacf 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -10362,6 +10362,23 @@ version = "1.0.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"+[[package]]+name = "jev"+version = "0.1.0"+dependencies = [+ "ai_usage",+ "macro_env_var",+ "macro_user_id",+ "reqwest 0.13.4",+ "serde",+ "serde_json",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "wiremock",+ "workspace-hack",+]+[[package]]name = "jni"version = "0.21.1"@@ -16400,6 +16417,7 @@ dependencies = ["chrono","chrono-tz","connection_gateway_client",+ "crm","cron","database_env_vars","document_sub_type",@@ -16408,10 +16426,14 @@ dependencies = ["email","entity_access","entity_access_db_utils",+ "entity_access_management","entity_registry","entity_registry_db_utils",+ "frecency","futures",+ "jev","kafka_util",+ "lexical_client","macro_auth","macro_authorization","macro_aws_config",@@ -16427,6 +16449,7 @@ dependencies = ["macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","messages","model","model-entity",diff --git a/Cargo.toml b/Cargo.tomlindex f6a2782319..828af0021e 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -34,6 +34,7 @@ members = ["crates/crm","crates/cursor_api_key","crates/cursor_cloud_agents",+ "crates/jev","crates/claude_cloud_agents","crates/database_sql","crates/databases",diff --git a/apps/web/src/features/routines/components/routine-event-condition.tsx b/apps/web/src/features/routines/components/routine-event-condition.tsxnew file mode 100644index 0000000000..cf7bf9ddd5--- /dev/null+++ b/apps/web/src/features/routines/components/routine-event-condition.tsx@@ -0,0 +1,31 @@+import { TextField } from '@ui';+import {+ conditionPlaceholder,+ type EventTriggerDraft,+ MAX_CONDITION_CHARS,+} from '../core/routine-triggers';++/** Optional yes/no question each event must pass before the routine runs. */+export function RoutineEventCondition(props: {+ trigger: EventTriggerDraft;+ onChange: (condition: string | undefined) => void;+}) {+ return (+ <TextField+ class="mt-3"+ value={props.trigger.condition ?? ''}+ onChange={(value) => props.onChange(value.trim() ? value : undefined)}+ >+ <TextField.Label>Only run if</TextField.Label>+ <TextField.TextArea+ autoResize+ rows={2}+ maxLength={MAX_CONDITION_CHARS}+ placeholder={conditionPlaceholder(props.trigger)}+ />+ <TextField.Description>+ A yes/no question about each event. Events that answer no are skipped.+ </TextField.Description>+ </TextField>+ );+}diff --git a/apps/web/src/features/routines/components/routine-triggers.tsx b/apps/web/src/features/routines/components/routine-triggers.tsxindex 326cee2cf3..de3b6dd193 100644--- a/apps/web/src/features/routines/components/routine-triggers.tsx+++ b/apps/web/src/features/routines/components/routine-triggers.tsx@@ -47,6 +47,11 @@ type EventSlots = {trigger: Accessor<EventTriggerDraft>,change: (ids: string[] | undefined) => void) => JSX.Element;+ /** Absent where conditions are unavailable. */+ renderEventCondition?: (+ trigger: Accessor<EventTriggerDraft>,+ change: (condition: string | undefined) => void+ ) => JSX.Element;};function scheduleSummary(trigger: ScheduleTriggerDraft) {@@ -308,7 +313,9 @@ function TriggerChip(title={props.trigger?.kind === 'schedule'? `${label()} · ${props.trigger.timezone.replace(/_/g, ' ')}`- : label()+ : [label(), savedEvent()?.condition?.trim()]+ .filter(Boolean)+ .join(' · if ')}class={badgeTriggerClasses({variant: 'outline',@@ -324,6 +331,9 @@ function TriggerChip(<Show when={savedEvent()}>{(value) => <> · {props.renderEventLabel(value)}</>}</Show>+ <Show when={savedEvent()?.condition?.trim()}>+ {(condition) => <> · if {condition()}</>}+ </Show></span><Show when={props.trigger}><CaretDownIcon class="size-3" />@@ -387,6 +397,9 @@ function TriggerChip({props.renderEventScope(value, (ids) =>edit({ ...value(), ids }))}+ {props.renderEventCondition?.(value, (condition) =>+ edit({ ...value(), condition })+ )}</>)}</Show>@@ -440,6 +453,7 @@ export function RoutineTriggers(trigger={props.triggers.find((trigger) => trigger.id === id)}renderEventLabel={props.renderEventLabel}renderEventScope={props.renderEventScope}+ renderEventCondition={props.renderEventCondition}onSave={(value) =>props.onChange(props.triggers.map((trigger) =>@@ -458,6 +472,7 @@ export function RoutineTriggers(<TriggerChiprenderEventLabel={props.renderEventLabel}renderEventScope={props.renderEventScope}+ renderEventCondition={props.renderEventCondition}onSave={(trigger) => props.onChange([...props.triggers, trigger])}/></>diff --git a/apps/web/src/features/routines/core/history.ts b/apps/web/src/features/routines/core/history.tsindex aadd887264..1cef9a1b94 100644--- a/apps/web/src/features/routines/core/history.ts+++ b/apps/web/src/features/routines/core/history.ts@@ -1,8 +1,13 @@export type HistoryResource = { type: 'chat' | 'agent'; id: string };+/** Why a trigger's condition kept a run from starting. */+export type HistorySkip =+ | { reason: 'not_met'; probability: number }+ | { reason: 'unavailable' };export type HistoryRecord = {id?: string | null;resource?: HistoryResource;startedAt?: string | null;endedAt?: string | null;success?: boolean | null;+ skipped?: HistorySkip;};diff --git a/apps/web/src/features/routines/core/routine-triggers.ts b/apps/web/src/features/routines/core/routine-triggers.tsindex 9c462a87a6..c816ee2ad2 100644--- a/apps/web/src/features/routines/core/routine-triggers.ts+++ b/apps/web/src/features/routines/core/routine-triggers.ts@@ -1,4 +1,5 @@import { getDefaultTimezone } from '@core/util/cron';+import { match } from 'ts-pattern';import { z } from 'zod';export const scheduleTriggerSchema = z.object({@@ -37,6 +38,8 @@ export const routineTriggerSchema = z.discriminatedUnion('kind', [).min(1),ids: z.array(z.string().uuid()).optional(),+ /** Yes/no question the event's content must answer with yes. */+ condition: z.string().optional(),}),]);export type ScheduleTriggerDraft = z.infer<typeof scheduleTriggerSchema>;@@ -138,6 +141,17 @@ export function eventScopeKind(trigger: EventTriggerDraft) {return 'CHANNEL';}+export const MAX_CONDITION_CHARS = 500;++export function conditionPlaceholder(trigger: EventTriggerDraft) {+ return match(eventScopeKind(trigger))+ .with('THREAD', () => 'Is this email an invoice or a receipt?')+ .with('TASK', () => 'Is this task a bug report?')+ .with('DOCUMENT', () => 'Is this document meeting notes?')+ .with('CHANNEL', () => 'Is someone asking for help?')+ .exhaustive();+}+export function isGlobalEvent(events: readonly RoutineEventName[]) {return events.every((event) => event.endsWith('.created') || event === 'email.message_received'@@ -179,6 +193,19 @@ export function newScheduleTrigger(cron: '0 0 9 * * *',};}+function validateEventTrigger(+ trigger: EventTriggerDraft,+ creating: boolean+): string | null {+ if (!trigger.events.length) return 'Choose an activity event.';+ if (creating && trigger.ids?.length === 0)+ return 'Choose at least one item for this event trigger.';+ if ((trigger.ids?.length ?? 0) > 100)+ return 'Choose up to 100 items per event trigger.';+ if ([...(trigger.condition?.trim() ?? '')].length > MAX_CONDITION_CHARS)+ return `Keep the condition under ${MAX_CONDITION_CHARS} characters.`;+ return null;+}export function validateTriggers(triggers: RoutineTriggerDraft[],creating = false@@ -193,11 +220,8 @@ export function validateTriggers(return 'A routine can have up to 32 activity filters.';for (const trigger of triggers) {if (trigger.kind === 'event') {- if (!trigger.events.length) return 'Choose an activity event.';- if (creating && trigger.ids?.length === 0)- return 'Choose at least one item for this event trigger.';- if ((trigger.ids?.length ?? 0) > 100)- return 'Choose up to 100 items per event trigger.';+ const error = validateEventTrigger(trigger, creating);+ if (error) return error;continue;}if (trigger.frequency === 'once') {diff --git a/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts b/apps/web/src/features/routines/queries/routine-trigger-mapping.test.tsindex 5555bfd761..edb5c670f2 100644--- a/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts+++ b/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts@@ -132,6 +132,59 @@ describe('routine trigger mapping', () => {});});+describe('trigger conditions', () => {+ it('round trips a condition with its filter', () => {+ const config = {+ type: 'events' as const,+ filters: [+ {+ events: ['email.message_received' as const],+ condition: 'Is this email an invoice?',+ },+ ],+ };+ const triggers = parseRoutineTriggers(config)!;+ expect(triggers[0]).toMatchObject({+ kind: 'event',+ condition: 'Is this email an invoice?',+ });+ expect(routineTriggerSchema.safeParse(triggers[0]).success).toBe(true);+ expect(serializeTriggers(triggers)).toEqual(config);+ });++ it('trims conditions and drops blank ones', () => {+ const trigger = {+ id: 'trigger',+ kind: 'event' as const,+ events: ['task.created' as const],+ };+ expect(+ serializeTriggers([{ ...trigger, condition: ' Is it a bug? ' }])+ ).toEqual({+ type: 'events',+ filters: [{ events: ['task.created'], condition: 'Is it a bug?' }],+ });+ expect(serializeTriggers([{ ...trigger, condition: ' ' }])).toEqual({+ type: 'events',+ filters: [{ events: ['task.created'] }],+ });+ });++ it('rejects conditions longer than the backend accepts', () => {+ const trigger = {+ id: 'trigger',+ kind: 'event' as const,+ events: ['task.created' as const],+ };+ expect(+ validateTriggers([{ ...trigger, condition: 'é'.repeat(500) }])+ ).toBeNull();+ expect(+ validateTriggers([{ ...trigger, condition: 'é'.repeat(501) }])+ ).toMatch(/500 characters/);+ });+});+describe('completed routine classification', () => {it('recognizes exhausted multiple and custom schedules, but not Macro events', async () => {const { hasOnlyScheduledTriggers } = await import(diff --git a/apps/web/src/features/routines/queries/routine-trigger-mapping.ts b/apps/web/src/features/routines/queries/routine-trigger-mapping.tsindex 5e331fdff8..924674157c 100644--- a/apps/web/src/features/routines/queries/routine-trigger-mapping.ts+++ b/apps/web/src/features/routines/queries/routine-trigger-mapping.ts@@ -3,20 +3,25 @@ import { TZDate } from '@date-fns/tz';import type { ActionTrigger } from '@service-scheduled-action/generated/schemas';import { match } from 'ts-pattern';import {+ type EventTriggerDraft,newScheduleTrigger,type RoutineTriggerDraft,} from '../core/routine-triggers';+function serializeFilter(trigger: EventTriggerDraft) {+ const condition = trigger.condition?.trim();+ return {+ events: trigger.events,+ ...(trigger.ids === undefined ? {} : { ids: trigger.ids }),+ ...(condition ? { condition } : {}),+ };+}+export function serializeTrigger(trigger: RoutineTriggerDraft) {if (trigger.kind === 'event')return {type: 'events' as const,- filters: [- {- events: trigger.events,- ...(trigger.ids === undefined ? {} : { ids: trigger.ids }),- },- ],+ filters: [serializeFilter(trigger)],};const [hour, minute] = trigger.time.split(':').map(Number);if (trigger.frequency === 'once') {@@ -48,14 +53,7 @@ export function serializeTriggers(.filter((trigger) => trigger.kind === 'schedule').map(serializeTrigger);const filters = triggers.flatMap((trigger) =>- trigger.kind === 'event'- ? [- {- events: trigger.events,- ...(trigger.ids === undefined ? {} : { ids: trigger.ids }),- },- ]- : []+ trigger.kind === 'event' ? [serializeFilter(trigger)] : []);const values = [...schedules,@@ -79,6 +77,7 @@ export function parseRoutineTriggers(kind: 'event',events: filter.events,ids: filter.ids ?? undefined,+ condition: filter.condition ?? undefined,}));const draft = {...newScheduleTrigger('custom'),diff --git a/apps/web/src/features/routines/queries/run-resource.test.ts b/apps/web/src/features/routines/queries/run-resource.test.tsindex ff9cd65aed..b5e868358c 100644--- a/apps/web/src/features/routines/queries/run-resource.test.ts+++ b/apps/web/src/features/routines/queries/run-resource.test.ts@@ -4,7 +4,9 @@ import {decodeExecutionResult,getExecutionResource,getHistoryResource,+ getHistorySkip,resourcesMatch,+ toHistoryRecord,} from './run-resource';const chat = { type: 'chat', id: 'same-id' } as const;@@ -120,3 +122,46 @@ describe('versioned execution results', () => {).toBeUndefined();});});++describe('skipped runs', () => {+ const skipped = (condition: unknown) => ({+ version: 1,+ resource: null,+ error: null,+ condition,+ });++ it('decodes unmet and unavailable conditions', () => {+ expect(+ getHistorySkip({+ result: skipped({ status: 'not_met', probability: 0.12 }),+ })+ ).toEqual({ reason: 'not_met', probability: 0.12 });+ expect(+ getHistorySkip({ result: skipped({ status: 'unavailable' }) })+ ).toEqual({ reason: 'unavailable' });+ });++ it.for([null, 'chat-id', {}, skipped(null), skipped({ status: 'other' })])(+ 'treats %j as a run, not a skip',+ (result) => {+ expect(getHistorySkip({ result })).toBeUndefined();+ }+ );++ it('carries the skip into history records', () => {+ expect(+ toHistoryRecord({+ id: 'record',+ result: skipped({ status: 'not_met', probability: 0.2 }),+ resource_id: null,+ start_time: '2026-10-05T09:00:00Z',+ end_time: '2026-10-05T09:00:00Z',+ is_success: true,+ })+ ).toMatchObject({+ resource: undefined,+ skipped: { reason: 'not_met', probability: 0.2 },+ });+ });+});diff --git a/apps/web/src/features/routines/queries/run-resource.ts b/apps/web/src/features/routines/queries/run-resource.tsindex 2fe311c392..18afbdec33 100644--- a/apps/web/src/features/routines/queries/run-resource.ts+++ b/apps/web/src/features/routines/queries/run-resource.ts@@ -3,7 +3,7 @@ import type {ExecutionResult,} from '@service-scheduled-action/generated/schemas';import { z } from 'zod';-import type { HistoryRecord } from '../core/history';+import type { HistoryRecord, HistorySkip } from '../core/history';const resourceSchema = z.object({type: z.enum(['chat', 'agent']),@@ -15,6 +15,25 @@ const resultSchema = z.object({error: z.string().nullish(),});+const conditionSchema = z.discriminatedUnion('status', [+ z.object({ status: z.literal('not_met'), probability: z.number() }),+ z.object({ status: z.literal('unavailable') }),+]);++/** A run its trigger's condition skipped; old and unknown results are runs. */+export function getHistorySkip(record: {+ result: unknown;+}): HistorySkip | undefined {+ const result = record.result;+ if (typeof result !== 'object' || result === null || !('condition' in result))+ return undefined;+ const parsed = conditionSchema.safeParse(result.condition);+ if (!parsed.success) return undefined;+ return parsed.data.status === 'not_met'+ ? { reason: 'not_met', probability: parsed.data.probability }+ : { reason: 'unavailable' };+}+export function decodeExecutionResource(value: unknown): ExecutionResource | undefined {@@ -72,5 +91,6 @@ export function toHistoryRecord(record: {startedAt: record.start_time,endedAt: record.end_time,success: record.is_success,+ skipped: getHistorySkip(record),};}diff --git a/apps/web/src/features/routines/routine-creator.test.tsx b/apps/web/src/features/routines/routine-creator.test.tsxindex e13b92bb0f..d0ee647739 100644--- a/apps/web/src/features/routines/routine-creator.test.tsx+++ b/apps/web/src/features/routines/routine-creator.test.tsx@@ -27,6 +27,11 @@ const host = vi.hoisted(() => ({alert: vi.fn(),editorMount: vi.fn(),}));+vi.mock('@app/lib/analytics/posthog', () => ({+ useFeatureFlag: (flag: { key: string }) => () => ({+ enabled: flag.key === 'enable-routine-conditions',+ }),+}));vi.mock('@components/app/split-layout/layout', () => ({useSplitLayout: () => ({ openWithSplit: host.openWithSplit }),}));@@ -492,6 +497,45 @@ describe('routine composer execution selection', () => {});});+ it('saves an email trigger with an only-run-if condition', async () => {+ host.create.mockImplementation(async (body) => created(body));+ await mount();+ inputPrompt();+ fireEvent.click(screen.getByRole('button', { name: 'Add trigger' }));+ fireEvent.click(+ await screen.findByRole('button', { name: 'New email received' })+ );+ const condition = screen.getByRole('textbox', { name: 'Only run if' });+ expect(condition.getAttribute('placeholder')).toBe(+ 'Is this email an invoice or a receipt?'+ );+ fireEvent.input(condition, {+ target: { value: ' Is this email an invoice? ' },+ });+ fireEvent.click(+ within(screen.getByRole('dialog', { name: 'Add trigger' })).getByRole(+ 'button',+ { name: 'Add trigger' }+ )+ );+ expect(+ screen.getByTitle('New email received · if Is this email an invoice?')+ ).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: /Create routine/i }));+ await waitFor(() => expect(host.create).toHaveBeenCalledTimes(1));+ expect(host.create.mock.calls[0][0]).toMatchObject({+ trigger: {+ type: 'events',+ filters: [+ {+ events: ['email.message_received'],+ condition: 'Is this email an invoice?',+ },+ ],+ },+ });+ });+it('keeps trigger edits local until confirmed and leaves an add chip', async () => {await mount();const editor = inputPrompt();diff --git a/apps/web/src/features/routines/routine-triggers.tsx b/apps/web/src/features/routines/routine-triggers.tsxindex 00befd0c92..950b64acb6 100644--- a/apps/web/src/features/routines/routine-triggers.tsx+++ b/apps/web/src/features/routines/routine-triggers.tsx@@ -1,4 +1,7 @@+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { enableRoutineConditions } from '@core/constant/featureFlags';import { Show, Suspense } from 'solid-js';+import { RoutineEventCondition } from './components/routine-event-condition';import { RoutineTriggers as TriggerList } from './components/routine-triggers';import {eventScopeKind,@@ -14,9 +17,17 @@ export function RoutineTriggers(props: {triggers: RoutineTriggerDraft[];onChange: (triggers: RoutineTriggerDraft[]) => void;}) {+ const conditions = useFeatureFlag(enableRoutineConditions);return (<TriggerList{...props}+ renderEventCondition={+ conditions().enabled+ ? (trigger, onChange) => (+ <RoutineEventCondition trigger={trigger()} onChange={onChange} />+ )+ : undefined+ }renderEventLabel={(trigger) => (<Suspense fallback={<span>Selected items</span>}><RoutineEventScopeLabeldiff --git a/apps/web/src/features/routines/views/routine-history.test.tsx b/apps/web/src/features/routines/views/routine-history.test.tsxindex 8e535830ce..d47d49bdca 100644--- a/apps/web/src/features/routines/views/routine-history.test.tsx+++ b/apps/web/src/features/routines/views/routine-history.test.tsx@@ -288,3 +288,77 @@ describe('routine history', () => {expect(screen.queryByText('Load more runs')).toBeNull();});});++describe('skipped runs', () => {+ function skip(id: string, condition: unknown) {+ return record('agent', id, {+ id: `skip-${id}`,+ resource_id: null,+ result: { version: 1, resource: null, error: null, condition },+ });+ }++ it('shows why a lone run was skipped without loading a resource', () => {+ const source = sources();+ render(() => (+ <RoutineHistory+ {...source}+ isPending={false}+ records={[+ skip('a', { status: 'not_met', probability: 0.12 }),+ record('agent', 'ran'),+ skip('b', { status: 'unavailable' }),+ ]}+ />+ ));+ const unmet = screen.getByText('Condition not met').closest('[role]')!;+ expect(unmet.getAttribute('title')).toBe('12% likely yes');+ expect(+ within(unmet as HTMLElement)+ .getByText('Skipped')+ .classList.contains('text-failure')+ ).toBe(false);+ const unavailable = screen+ .getByText('Condition couldn’t be checked')+ .closest('[role]')!;+ expect(+ within(unavailable as HTMLElement)+ .getByText('Skipped')+ .classList.contains('text-failure')+ ).toBe(true);+ expect(source.createAgentMetadata.mock.calls).toEqual([['ran']]);+ });++ it('collapses consecutive skips between runs', () => {+ render(() => (+ <RoutineHistory+ {...sources()}+ isPending={false}+ records={[+ record('agent', 'newest'),+ skip('a', { status: 'not_met', probability: 0.1 }),+ skip('b', { status: 'not_met', probability: 0.2 }),+ skip('c', { status: 'not_met', probability: 0.3 }),+ record('agent', 'oldest'),+ ]}+ />+ ));+ expect(screen.queryByText('Condition not met')).toBeNull();+ const group = screen.getByRole('button', {+ name: /3 events skipped by the condition/,+ });+ expect(group.getAttribute('aria-expanded')).toBe('false');+ fireEvent.click(group);+ expect(screen.getAllByText('Condition not met')).toHaveLength(3);+ expect(+ screen.getAllByRole('listitem').map((item) => item.textContent)+ ).toEqual([+ expect.stringContaining('Agent newest'),+ expect.stringContaining('3 events skipped'),+ expect.stringContaining('Condition not met'),+ expect.stringContaining('Condition not met'),+ expect.stringContaining('Condition not met'),+ expect.stringContaining('Agent oldest'),+ ]);+ });+});diff --git a/apps/web/src/features/routines/views/routine-history.tsx b/apps/web/src/features/routines/views/routine-history.tsxindex 539efe39b0..48e22e352d 100644--- a/apps/web/src/features/routines/views/routine-history.tsx+++ b/apps/web/src/features/routines/views/routine-history.tsx@@ -11,7 +11,11 @@ import {Suspense,} from 'solid-js';-import type { HistoryRecord, HistoryResource } from '../core/history';+import type {+ HistoryRecord,+ HistoryResource,+ HistorySkip,+} from '../core/history';export type { HistoryRecord } from '../core/history';@@ -38,9 +42,11 @@ function RunOutcome(props: { record: HistoryRecord }) {const outcome = () =>!props.record.id? 'Running'- : props.record.success- ? 'Succeeded'- : 'Failed';+ : props.record.skipped+ ? 'Skipped'+ : props.record.success+ ? 'Succeeded'+ : 'Failed';const duration = () => {if (!props.record.startedAt || !props.record.endedAt) return undefined;const seconds = Math.max(@@ -58,7 +64,13 @@ function RunOutcome(props: { record: HistoryRecord }) {};return (<span class="inline-flex items-center gap-3 whitespace-nowrap text-xs text-ink-muted">- <span class={cn(outcome() === 'Failed' && 'text-failure')}>+ <span+ class={cn(+ (outcome() === 'Failed' ||+ props.record.skipped?.reason === 'unavailable') &&+ 'text-failure'+ )}+ >{outcome()}</span><Show when={duration()}>@@ -154,6 +166,83 @@ function ResourceHistoryRow(props: {);}+function skipLabel(skip: HistorySkip) {+ return skip.reason === 'not_met'+ ? 'Condition not met'+ : 'Condition couldn’t be checked';+}++function SkippedRow(props: { record: HistoryRecord; skip: HistorySkip }) {+ const confidence = () =>+ props.skip.reason === 'not_met'+ ? `${Math.round(props.skip.probability * 100)}% likely yes`+ : undefined;+ return (+ <div+ role="listitem"+ title={confidence()}+ class="soup-list-entity mx-1 flex min-h-11 items-center gap-2 rounded-xl px-2 text-sm text-ink-muted"+ >+ <span class="size-4 shrink-0">+ <EntityIcon targetType="routine" size="xs" />+ </span>+ <span class="min-w-0 flex-1 truncate">{skipLabel(props.skip)}</span>+ <RunOutcome record={props.record} />+ <span class="ml-2 text-xs text-ink-extra-muted">+ {props.record.startedAt+ ? formatDateAndTime(props.record.startedAt)+ : '—'}+ </span>+ </div>+ );+}++/** Consecutive skips collapse so a busy trigger doesn't bury real runs. */+function SkippedGroupToggle(props: {+ count: number;+ open: boolean;+ onToggle: () => void;+}) {+ return (+ <div role="listitem" class="mx-1">+ <button+ type="button"+ aria-expanded={props.open}+ class="flex min-h-11 w-full items-center gap-2 rounded-xl px-2 text-left text-sm text-ink-muted hover:bg-hover focus-visible:bg-hover outline-none"+ onClick={() => props.onToggle()}+ >+ <span class="size-4 shrink-0">+ <EntityIcon targetType="routine" size="xs" />+ </span>+ <span class="min-w-0 flex-1 truncate">+ {props.count} events skipped by the condition+ </span>+ <span class="text-xs text-ink-extra-muted">+ {props.open ? 'Hide' : 'Show'}+ </span>+ </button>+ </div>+ );+}++/** Where a skipped record sits in its run of consecutive skips. */+type SkipRun = { first: HistoryRecord; length: number };++function skipRuns(records: readonly HistoryRecord[]) {+ const runs = new Map<HistoryRecord, SkipRun>();+ let run: SkipRun | undefined;+ for (const record of records) {+ if (!record.skipped) {+ run = undefined;+ continue;+ }+ if (!run) run = { first: record, length: 0 };+ run.length += 1;+ runs.set(record, run);+ }+ return runs;+}+function ResolvedHistoryRow(props: {record: HistoryRecord;history: RoutineHistoryProps;@@ -199,6 +288,21 @@ function ResolvedHistoryRow(props: {export function RoutineHistory(props: RoutineHistoryProps): JSX.Element {const [visibleCount, setVisibleCount] = createSignal(50);const [listElement, setListElement] = createSignal<HTMLDivElement>();+ const visibleRecords = createMemo(() =>+ props.records.slice(0, visibleCount())+ );+ const runs = createMemo(() => skipRuns(visibleRecords()));+ // Keyed by the run's newest record id, which survives history refetches.+ const [expanded, setExpanded] = createSignal(new Set<string>());+ const toggle = (first: HistoryRecord | undefined) => {+ const id = first?.id;+ if (!id) return;+ setExpanded((current) => {+ const next = new Set(current);+ if (!next.delete(id)) next.add(id);+ return next;+ });+ };return (<div ref={setListElement} class="min-h-0 flex-1 overflow-y-auto py-3"><Show@@ -214,9 +318,38 @@ export function RoutineHistory(props: RoutineHistoryProps): JSX.Element {><ListLayoutProvider ref={listElement}><div role="list" aria-label="Routine runs">- <For each={props.records.slice(0, visibleCount())}>+ <For each={visibleRecords()}>{(record) => (- <ResolvedHistoryRow record={record} history={props} />+ <Show+ when={record.skipped}+ fallback={+ <ResolvedHistoryRow record={record} history={props} />+ }+ >+ {(skip) => {+ const run = () => runs().get(record);+ const grouped = () => (run()?.length ?? 1) > 1;+ const first = () => run()?.first === record;+ const open = () => {+ const id = run()?.first.id;+ return !!id && expanded().has(id);+ };+ return (+ <>+ <Show when={grouped() && first()}>+ <SkippedGroupToggle+ count={run()?.length ?? 0}+ open={open()}+ onToggle={() => toggle(run()?.first)}+ />+ </Show>+ <Show when={!grouped() || open()}>+ <SkippedRow record={record} skip={skip()} />+ </Show>+ </>+ );+ }}+ </Show>)}</For></div>diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex 352afb7ba0..bc4ad749d7 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -721,6 +721,15 @@ export const enableCodexAgents = defineFlag({env: 'ENABLE_CODEX_AGENTS',});+// Yes/no conditions on routine event triggers, checked by the Jev classifier+// before a run starts. The scheduled-action service rejects conditions until+// its TYPESAFE_API_KEY is set. Override with VITE_ENABLE_ROUTINE_CONDITIONS.+export const enableRoutineConditions = defineFlag({+ key: 'enable-routine-conditions',+ env: 'ENABLE_ROUTINE_CONDITIONS',+ default: onInDev,+});+// The Recent view: the touched-by-me feed (everything the viewer mutated,// newest own-touch first). Gates the view (the route redirects to the inbox// when off) and its sidebar entry. PostHog-gated with a dev-mode default;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/conditionResult.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/conditionResult.tsnew file mode 100644index 0000000000..bb92e167c0--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/conditionResult.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */+import type { ConditionResultOneOf } from './conditionResultOneOf';+import type { ConditionResultOneOfThree } from './conditionResultOneOfThree';++/**+ * Why an event-triggered run was skipped before it started.+ */+export type ConditionResult = ConditionResultOneOf | ConditionResultOneOfThree;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/conditionResultOneOf.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/conditionResultOneOf.tsnew file mode 100644index 0000000000..13bf34e8b0--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/conditionResultOneOf.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */+import type { ConditionResultOneOfStatus } from './conditionResultOneOfStatus';++/**+ * The triggering content answered the condition with no.+ */+export type ConditionResultOneOf = {+ /** The classifier's probability, from 0 to 1, that the answer was yes. */+ probability: number;+ status: ConditionResultOneOfStatus;+};diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/conditionResultOneOfStatus.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/conditionResultOneOfStatus.tsnew file mode 100644index 0000000000..f4a3b71cdf--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/conditionResultOneOfStatus.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */++export type ConditionResultOneOfStatus =+ (typeof ConditionResultOneOfStatus)[keyof typeof ConditionResultOneOfStatus];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const ConditionResultOneOfStatus = {+ not_met: 'not_met',+} as const;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/conditionResultOneOfThree.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/conditionResultOneOfThree.tsnew file mode 100644index 0000000000..2f46e41932--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/conditionResultOneOfThree.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */+import type { ConditionResultOneOfThreeStatus } from './conditionResultOneOfThreeStatus';++/**+ * The condition could not be checked before the retry window closed.+ */+export type ConditionResultOneOfThree = {+ status: ConditionResultOneOfThreeStatus;+};diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/conditionResultOneOfThreeStatus.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/conditionResultOneOfThreeStatus.tsnew file mode 100644index 0000000000..17d038094d--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/conditionResultOneOfThreeStatus.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */++export type ConditionResultOneOfThreeStatus =+ (typeof ConditionResultOneOfThreeStatus)[keyof typeof ConditionResultOneOfThreeStatus];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const ConditionResultOneOfThreeStatus = {+ unavailable: 'unavailable',+} as const;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilter.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilter.tsindex 8dadcd07af..90d01fe701 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilter.ts+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilter.ts@@ -5,14 +5,21 @@* API for managing scheduled actions* OpenAPI spec version: 0.1.0*/-+import type { EventFilterCondition } from './eventFilterCondition';import type { EventFilterIds } from './eventFilterIds';import type { EventName } from './eventName';/**- * An event name AND an entity ID must match within the same filter.+ * An event name AND an entity ID must match within the same filter. A+condition further requires the event's content to answer it with yes.*/export interface EventFilter {+ /**+ * Yes/no question about the triggering content, e.g. "Is this email an+invoice?". The routine runs only when the answer is yes.+ * @maxLength 500+ */+ condition?: EventFilterCondition;events: EventName[];ids?: EventFilterIds;}diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilterCondition.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilterCondition.tsnew file mode 100644index 0000000000..b4fa3216f0--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventFilterCondition.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */++/**+ * Yes/no question about the triggering content, e.g. "Is this email an+invoice?". The routine runs only when the answer is yes.+ * @maxLength 500+ */+export type EventFilterCondition = string | null;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/executionResult.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/executionResult.tsindex 8c50dc30ec..b0d95f9f0d 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/executionResult.ts+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/executionResult.ts@@ -5,6 +5,7 @@* API for managing scheduled actions* OpenAPI spec version: 0.1.0*/+import type { ExecutionResultCondition } from './executionResultCondition';import type { ExecutionResultError } from './executionResultError';import type { ExecutionResultResource } from './executionResultResource';@@ -13,6 +14,7 @@ import type { ExecutionResultResource } from './executionResultResource';Null/string column values predate this envelope and refer to legacy chats.*/export interface ExecutionResult {+ condition?: ExecutionResultCondition;error?: ExecutionResultError;resource?: ExecutionResultResource;/** @minimum 0 */diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/executionResultCondition.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/executionResultCondition.tsnew file mode 100644index 0000000000..a8676770a4--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/executionResultCondition.ts@@ -0,0 +1,10 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */+import type { ConditionResult } from './conditionResult';++export type ExecutionResultCondition = null | ConditionResult;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.tsindex 82667e9215..83645f79f8 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts@@ -28,15 +28,22 @@ export * from './agentTaskAgent';export * from './agentTaskAgentProperty';export * from './agentTaskModel';export * from './aiAdmissionErrorBody';+export * from './conditionResult';+export * from './conditionResultOneOf';+export * from './conditionResultOneOfStatus';+export * from './conditionResultOneOfThree';+export * from './conditionResultOneOfThreeStatus';export * from './createScheduledAction';export * from './emptyResponse';export * from './eventFilter';+export * from './eventFilterCondition';export * from './eventFilterIds';export * from './eventFilters';export * from './eventName';export * from './executionResource';export * from './executionResourceType';export * from './executionResult';+export * from './executionResultCondition';export * from './executionResultError';export * from './executionResultResource';export * from './inProgressExecution';diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.jsonindex 50a8dcb321..373779fff3 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json+++ b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json@@ -808,6 +808,38 @@}}},+ "ConditionResult": {+ "oneOf": [+ {+ "type": "object",+ "description": "The triggering content answered the condition with no.",+ "required": ["probability", "status"],+ "properties": {+ "probability": {+ "type": "number",+ "format": "float",+ "description": "The classifier's probability, from 0 to 1, that the answer was yes."+ },+ "status": {+ "type": "string",+ "enum": ["not_met"]+ }+ }+ },+ {+ "type": "object",+ "description": "The condition could not be checked before the retry window closed.",+ "required": ["status"],+ "properties": {+ "status": {+ "type": "string",+ "enum": ["unavailable"]+ }+ }+ }+ ],+ "description": "Why an event-triggered run was skipped before it started."+ },"CreateScheduledAction": {"oneOf": [{@@ -825,9 +857,14 @@},"EventFilter": {"type": "object",- "description": "An event name AND an entity ID must match within the same filter.",+ "description": "An event name AND an entity ID must match within the same filter. A\ncondition further requires the event's content to answer it with yes.","required": ["events"],"properties": {+ "condition": {+ "type": ["string", "null"],+ "description": "Yes/no question about the triggering content, e.g. \"Is this email an\ninvoice?\". The routine runs only when the answer is yes.",+ "maxLength": 500+ },"events": {"type": "array","items": {@@ -891,6 +928,17 @@"description": "Version 1 execution metadata stored in the existing JSON result column.\nNull/string column values predate this envelope and refer to legacy chats.","required": ["version"],"properties": {+ "condition": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/ConditionResult",+ "description": "Present when an event trigger's condition stopped the run from starting."+ }+ ]+ },"error": {"type": ["string", "null"]},diff --git a/crates/graphql_scheduled_action/src/objects.rs b/crates/graphql_scheduled_action/src/objects.rsindex ad91271ced..4637f19412 100644--- a/crates/graphql_scheduled_action/src/objects.rs+++ b/crates/graphql_scheduled_action/src/objects.rs@@ -70,6 +70,8 @@ pub(crate) struct GraphqlScheduledActionEventFilter {events: Vec<GraphqlScheduledActionEventName>,/// Entity ids that can satisfy this filter. Null matches every id; an empty list matches nothing.entity_ids: Option<Vec<ID>>,+ /// Yes/no question the triggering content must answer with yes before the routine runs.+ condition: Option<String>,}/// The agent task a routine runs.@@ -241,6 +243,9 @@ fn event_filters(entity_ids: filter.ids().map(|ids| ids.iter().map(|id| ID(id.to_string())).collect()),+ condition: filter+ .condition()+ .map(|condition| condition.as_str().to_owned()),}).collect(),}diff --git a/crates/jev/Cargo.toml b/crates/jev/Cargo.tomlnew file mode 100644index 0000000000..5033296366--- /dev/null+++ b/crates/jev/Cargo.toml@@ -0,0 +1,25 @@+[package]+edition = "2024"+name = "jev"+publish = false+version = "0.1.0"++[features]+default = []+outbound = ["dep:macro_env_var", "dep:reqwest", "dep:tokio"]++[dependencies]+ai_usage = { path = "../ai_usage" }+macro_env_var = { path = "../macro_env_var", optional = true }+reqwest = { workspace = true, optional = true }+serde = { workspace = true }+serde_json = { workspace = true }+thiserror = { workspace = true }+tokio = { workspace = true, optional = true, features = ["time"] }+tracing = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+macro_user_id = { path = "../macro_user_id" }+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }+wiremock = { workspace = true }diff --git a/crates/jev/src/domain.rs b/crates/jev/src/domain.rsnew file mode 100644index 0000000000..a45e548386--- /dev/null+++ b/crates/jev/src/domain.rs@@ -0,0 +1,13 @@+//! Jev domain: question and probability value objects, the provider port, and+//! the metered classification use case. No transport or infrastructure lives here.++pub mod models;+pub mod ports;+pub mod service;++pub use models::{+ Evaluation, JevError, MAX_QUESTION_CHARS, MAX_QUESTIONS, Probability, QuestionError,+ YesNoQuestion,+};+pub use ports::{JevProvider, YesNoClassifier};+pub use service::JevClassifier;diff --git a/crates/jev/src/domain/models.rs b/crates/jev/src/domain/models.rsnew file mode 100644index 0000000000..a5b4946bc7--- /dev/null+++ b/crates/jev/src/domain/models.rs@@ -0,0 +1,128 @@+//! Value objects for yes/no classification.++use std::fmt;++use serde::{Deserialize, Serialize};++#[cfg(test)]+mod test;++/// Longest question accepted, in characters.+pub const MAX_QUESTION_CHARS: usize = 500;+/// Most questions evaluated against one input in a single request.+pub const MAX_QUESTIONS: usize = 32;++/// A natural-language yes/no question, trimmed and bounded.+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]+#[serde(try_from = "String", into = "String")]+pub struct YesNoQuestion(String);++impl YesNoQuestion {+ /// The trimmed question text.+ pub fn as_str(&self) -> &str {+ &self.0+ }+}++impl TryFrom<String> for YesNoQuestion {+ type Error = QuestionError;++ fn try_from(value: String) -> Result<Self, Self::Error> {+ let trimmed = value.trim();+ if trimmed.is_empty() {+ return Err(QuestionError::Empty);+ }+ if trimmed.chars().count() > MAX_QUESTION_CHARS {+ return Err(QuestionError::TooLong);+ }+ Ok(Self(trimmed.to_owned()))+ }+}++impl TryFrom<&str> for YesNoQuestion {+ type Error = QuestionError;++ fn try_from(value: &str) -> Result<Self, Self::Error> {+ Self::try_from(value.to_owned())+ }+}++impl From<YesNoQuestion> for String {+ fn from(question: YesNoQuestion) -> Self {+ question.0+ }+}++impl fmt::Display for YesNoQuestion {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.write_str(&self.0)+ }+}++/// Why a question was rejected.+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+pub enum QuestionError {+ /// The question has no text after trimming.+ #[error("a question needs text")]+ Empty,+ /// The question is longer than [`MAX_QUESTION_CHARS`].+ #[error("a question can be at most {MAX_QUESTION_CHARS} characters")]+ TooLong,+}++/// The model's belief, from 0 to 1, that a question's answer is yes.+#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize)]+pub struct Probability(f32);++impl Probability {+ /// A probability, or `None` when the value is not finite or outside 0..=1.+ pub fn new(value: f32) -> Option<Self> {+ (value.is_finite() && (0.0..=1.0).contains(&value)).then_some(Self(value))+ }++ /// The probability as a number from 0 to 1.+ pub fn get(self) -> f32 {+ self.0+ }+}++/// One provider round trip: an answer per question, in question order, plus+/// the provider-reported token usage for metering.+#[derive(Debug, Clone, PartialEq)]+pub struct Evaluation {+ /// Probability of yes for each question, in the order asked.+ pub probabilities: Vec<Probability>,+ /// Input tokens the provider billed.+ pub input_tokens: u64,+ /// Output tokens the provider billed.+ pub output_tokens: u64,+}++/// Classification failures. Provider details stay in the adapter's logs.+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+pub enum JevError {+ /// No questions were asked.+ #[error("no questions to classify")]+ NoQuestions,+ /// More than [`MAX_QUESTIONS`] questions were asked at once.+ #[error("at most {MAX_QUESTIONS} questions can be classified at once")]+ TooManyQuestions,+ /// A timeout, connection failure, rate limit, overload or server error.+ /// Retrying later may succeed.+ #[error("the classifier is temporarily unavailable")]+ Unavailable,+ /// The provider refused the request, e.g. a bad credential or an input+ /// it cannot evaluate. Retrying the same request will not help.+ #[error("the classifier rejected the request")]+ Rejected,+ /// The provider answered, but not with one probability per question.+ #[error("the classifier returned an unusable response")]+ InvalidResponse,+}++impl JevError {+ /// Whether the same request may succeed later.+ pub fn is_transient(self) -> bool {+ matches!(self, Self::Unavailable)+ }+}diff --git a/crates/jev/src/domain/models/test.rs b/crates/jev/src/domain/models/test.rsnew file mode 100644index 0000000000..443b01290e--- /dev/null+++ b/crates/jev/src/domain/models/test.rs@@ -0,0 +1,53 @@+use super::*;++#[test]+fn questions_are_trimmed() {+ let question = YesNoQuestion::try_from(" Is this an invoice?\n").unwrap();+ assert_eq!(question.as_str(), "Is this an invoice?");+}++#[test]+fn blank_questions_are_rejected() {+ assert_eq!(YesNoQuestion::try_from(" \t "), Err(QuestionError::Empty));+}++#[test]+fn question_length_counts_characters_not_bytes() {+ let longest = "é".repeat(MAX_QUESTION_CHARS);+ assert!(YesNoQuestion::try_from(longest.as_str()).is_ok());+ let too_long = "é".repeat(MAX_QUESTION_CHARS + 1);+ assert_eq!(+ YesNoQuestion::try_from(too_long.as_str()),+ Err(QuestionError::TooLong)+ );+}++#[test]+fn questions_deserialize_through_validation() {+ let question: YesNoQuestion = serde_json::from_str(r#"" Urgent? ""#).unwrap();+ assert_eq!(question.as_str(), "Urgent?");+ assert!(serde_json::from_str::<YesNoQuestion>(r#""""#).is_err());+}++#[test]+fn probabilities_must_be_finite_and_between_zero_and_one() {+ assert_eq!(Probability::new(0.0).map(Probability::get), Some(0.0));+ assert_eq!(Probability::new(1.0).map(Probability::get), Some(1.0));+ assert!(Probability::new(-0.01).is_none());+ assert!(Probability::new(1.01).is_none());+ assert!(Probability::new(f32::NAN).is_none());+ assert!(Probability::new(f32::INFINITY).is_none());+}++#[test]+fn only_unavailability_is_transient() {+ assert!(JevError::Unavailable.is_transient());+ for error in [+ JevError::NoQuestions,+ JevError::TooManyQuestions,+ JevError::Rejected,+ JevError::InvalidResponse,+ ] {+ assert!(!error.is_transient(), "{error:?}");+ }+}diff --git a/crates/jev/src/domain/ports.rs b/crates/jev/src/domain/ports.rsnew file mode 100644index 0000000000..9a15ab2b32--- /dev/null+++ b/crates/jev/src/domain/ports.rs@@ -0,0 +1,34 @@+//! Ports: the use case exposed to callers and the capability it needs.++use std::future::Future;++use ai_usage::UsageContext;+use serde_json::Value;++use super::models::{Evaluation, JevError, Probability, YesNoQuestion};++/// External yes/no evaluation, implemented by outbound adapters.+pub trait JevProvider: Send + Sync + 'static {+ /// Model identifier used by the shared pricing and usage recorder.+ fn model_id(&self) -> &'static str;++ /// Ask every question about `input` in one round trip. Answers come back+ /// in question order, one per question.+ fn evaluate(+ &self,+ input: &Value,+ questions: &[YesNoQuestion],+ ) -> impl Future<Output = Result<Evaluation, JevError>> + Send;+}++/// Yes/no classification of any JSON input, metered as AI usage.+pub trait YesNoClassifier: Send + Sync + 'static {+ /// The probability that each question is true of `input`, in question+ /// order. Token usage is recorded against `usage`.+ fn classify(+ &self,+ usage: UsageContext,+ input: &Value,+ questions: &[YesNoQuestion],+ ) -> impl Future<Output = Result<Vec<Probability>, JevError>> + Send;+}diff --git a/crates/jev/src/domain/service.rs b/crates/jev/src/domain/service.rsnew file mode 100644index 0000000000..53a86b17de--- /dev/null+++ b/crates/jev/src/domain/service.rs@@ -0,0 +1,63 @@+//! The metered classification use case.++use std::sync::Arc;++use ai_usage::{UsageAmount, UsageContext, UsageRecorder};+use serde_json::Value;++use super::{+ models::{JevError, MAX_QUESTIONS, Probability, YesNoQuestion},+ ports::{JevProvider, YesNoClassifier},+};++#[cfg(test)]+mod test;++/// Classifies through a [`JevProvider`] and records each round trip's tokens.+pub struct JevClassifier<P> {+ provider: P,+ recorder: Arc<dyn UsageRecorder>,+}++impl<P: JevProvider> JevClassifier<P> {+ /// Build a classifier that meters usage through `recorder`.+ pub fn new(provider: P, recorder: Arc<dyn UsageRecorder>) -> Self {+ Self { provider, recorder }+ }+}++impl<P: JevProvider> YesNoClassifier for JevClassifier<P> {+ #[tracing::instrument(name = "jev.classify", skip_all, err, fields(+ jev.questions = questions.len(),+ ai.feature = ?usage.feature,+ ))]+ async fn classify(+ &self,+ usage: UsageContext,+ input: &Value,+ questions: &[YesNoQuestion],+ ) -> Result<Vec<Probability>, JevError> {+ if questions.is_empty() {+ return Err(JevError::NoQuestions);+ }+ if questions.len() > MAX_QUESTIONS {+ return Err(JevError::TooManyQuestions);+ }+ let evaluation = self.provider.evaluate(input, questions).await?;+ // The provider billed the call even if its answers are unusable.+ // Jev has no prompt cache, so every input token is uncached.+ self.recorder.record(usage.into_event(+ self.provider.model_id().to_owned(),+ UsageAmount::Tokens {+ input: evaluation.input_tokens,+ output: evaluation.output_tokens,+ cache_read: 0,+ cache_write: 0,+ },+ ));+ if evaluation.probabilities.len() != questions.len() {+ return Err(JevError::InvalidResponse);+ }+ Ok(evaluation.probabilities)+ }+}diff --git a/crates/jev/src/domain/service/test.rs b/crates/jev/src/domain/service/test.rsnew file mode 100644index 0000000000..a033ede158--- /dev/null+++ b/crates/jev/src/domain/service/test.rs@@ -0,0 +1,163 @@+use std::sync::{Arc, Mutex};++use ai_usage::{AiFeature, UsageAmount, UsageEvent};+use macro_user_id::user_id::MacroUserIdStr;+use serde_json::json;++use super::*;+use crate::domain::models::Evaluation;++struct FakeProvider {+ answers: Result<Vec<f32>, JevError>,+ seen: Mutex<Vec<(Value, Vec<String>)>>,+}++impl FakeProvider {+ fn answering(answers: &[f32]) -> Arc<Self> {+ Arc::new(Self {+ answers: Ok(answers.to_vec()),+ seen: Mutex::default(),+ })+ }++ fn failing(error: JevError) -> Arc<Self> {+ Arc::new(Self {+ answers: Err(error),+ seen: Mutex::default(),+ })+ }+}++impl JevProvider for Arc<FakeProvider> {+ fn model_id(&self) -> &'static str {+ "jev-test"+ }++ async fn evaluate(+ &self,+ input: &Value,+ questions: &[YesNoQuestion],+ ) -> Result<Evaluation, JevError> {+ self.seen.lock().unwrap().push((+ input.clone(),+ questions.iter().map(|q| q.as_str().to_owned()).collect(),+ ));+ let answers = self.answers.clone()?;+ Ok(Evaluation {+ probabilities: answers+ .iter()+ .map(|value| Probability::new(*value).unwrap())+ .collect(),+ input_tokens: 120,+ output_tokens: 4,+ })+ }+}++#[derive(Default)]+struct FakeRecorder(Mutex<Vec<UsageEvent>>);++impl UsageRecorder for FakeRecorder {+ fn record(&self, event: UsageEvent) {+ self.0.lock().unwrap().push(event);+ }+}++fn usage() -> UsageContext {+ UsageContext::new(+ AiFeature::Automation,+ MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap(),+ )+}++fn questions(texts: &[&str]) -> Vec<YesNoQuestion> {+ texts+ .iter()+ .map(|text| YesNoQuestion::try_from(*text).unwrap())+ .collect()+}++#[tokio::test]+async fn returns_answers_in_question_order_and_records_tokens() {+ let provider = FakeProvider::answering(&[0.9, 0.1]);+ let recorder = Arc::new(FakeRecorder::default());+ let classifier = JevClassifier::new(provider.clone(), recorder.clone());+ let input = json!({ "subject": "Invoice #42" });++ let answers = classifier+ .classify(usage(), &input, &questions(&["Invoice?", "Spam?"]))+ .await+ .unwrap();++ assert_eq!(+ answers.iter().map(|p| p.get()).collect::<Vec<_>>(),+ [0.9, 0.1]+ );+ assert_eq!(+ provider.seen.lock().unwrap().as_slice(),+ [(input, vec!["Invoice?".to_owned(), "Spam?".to_owned()])]+ );+ let events = recorder.0.lock().unwrap();+ assert_eq!(events.len(), 1);+ assert_eq!(events[0].feature, AiFeature::Automation);+ assert_eq!(events[0].model, "jev-test");+ assert!(matches!(+ events[0].amount,+ UsageAmount::Tokens {+ input: 120,+ output: 4,+ cache_read: 0,+ cache_write: 0,+ }+ ));+}++#[tokio::test]+async fn rejects_empty_and_oversized_question_lists_without_calling_the_provider() {+ let provider = FakeProvider::answering(&[]);+ let recorder = Arc::new(FakeRecorder::default());+ let classifier = JevClassifier::new(provider.clone(), recorder.clone());++ assert_eq!(+ classifier.classify(usage(), &json!({}), &[]).await,+ Err(JevError::NoQuestions)+ );+ let too_many = vec![YesNoQuestion::try_from("Yes?").unwrap(); MAX_QUESTIONS + 1];+ assert_eq!(+ classifier.classify(usage(), &json!({}), &too_many).await,+ Err(JevError::TooManyQuestions)+ );+ assert!(provider.seen.lock().unwrap().is_empty());+ assert!(recorder.0.lock().unwrap().is_empty());+}++#[tokio::test]+async fn provider_errors_record_no_usage() {+ let recorder = Arc::new(FakeRecorder::default());+ let classifier = JevClassifier::new(+ FakeProvider::failing(JevError::Unavailable),+ recorder.clone(),+ );++ assert_eq!(+ classifier+ .classify(usage(), &json!("text"), &questions(&["Urgent?"]))+ .await,+ Err(JevError::Unavailable)+ );+ assert!(recorder.0.lock().unwrap().is_empty());+}++#[tokio::test]+async fn a_missing_answer_is_invalid_but_still_metered() {+ let recorder = Arc::new(FakeRecorder::default());+ let classifier = JevClassifier::new(FakeProvider::answering(&[0.4]), recorder.clone());++ assert_eq!(+ classifier+ .classify(usage(), &json!({}), &questions(&["A?", "B?"]))+ .await,+ Err(JevError::InvalidResponse)+ );+ assert_eq!(recorder.0.lock().unwrap().len(), 1);+}diff --git a/crates/jev/src/lib.rs b/crates/jev/src/lib.rsnew file mode 100644index 0000000000..ad0ddd4492--- /dev/null+++ b/crates/jev/src/lib.rs@@ -0,0 +1,10 @@+//! Yes/no classification of arbitrary JSON input with TypeSafe's Jev model.+//!+//! Hexagonal layout: [`domain`] owns the question and probability value+//! objects, the provider port, and the metered classification use case;+//! [`outbound`] implements the port against the TypeSafe API.+#![deny(missing_docs)]++pub mod domain;+#[cfg(feature = "outbound")]+pub mod outbound;diff --git a/crates/jev/src/outbound.rs b/crates/jev/src/outbound.rsnew file mode 100644index 0000000000..e3a94d7963--- /dev/null+++ b/crates/jev/src/outbound.rs@@ -0,0 +1,5 @@+//! Outbound adapters implementing the Jev ports.++pub mod typesafe;++pub use typesafe::{TypesafeApiKey, TypesafeConfigError, TypesafeJev};diff --git a/crates/jev/src/outbound/typesafe.rs b/crates/jev/src/outbound/typesafe.rsnew file mode 100644index 0000000000..77435500c0--- /dev/null+++ b/crates/jev/src/outbound/typesafe.rs@@ -0,0 +1,265 @@+//! TypeSafe adapter for the [`JevProvider`] port.+//!+//! Every question goes out as a `noul` (yes/no) question in one+//! `POST /v1/systemone` request whose `state` is the caller's JSON input.+//! The adapter never logs the input, the questions, or response bodies.++use std::{collections::HashMap, time::Duration};++use macro_env_var::maybe_env_var;+use reqwest::{Client, StatusCode};+use serde::{Deserialize, Serialize};+use serde_json::Value;++use crate::domain::{Evaluation, JevError, JevProvider, Probability, YesNoQuestion};++#[cfg(test)]+mod test;++maybe_env_var! {+ /// TypeSafe API credential, injected as `TYPESAFE_API_KEY`. Hosts turn+ /// Jev-backed features off when it is unset.+ pub struct TypesafeApiKey;+}++const DEFAULT_BASE_URL: &str = "https://api.typesafe.ai";+const MODEL: &str = "jev-latest";+/// Per-attempt deadline. Jev answers in well under a second when healthy.+const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);+/// Waits before each retry of a timed-out, rate-limited, overloaded or+/// failed request. Rejections and malformed responses are not retried.+const RETRY_DELAYS: [Duration; 2] = [Duration::from_millis(250), Duration::from_secs(1)];+/// TypeSafe's "overloaded" status.+const OVERLOADED: u16 = 529;++/// Yes/no evaluation through TypeSafe's hosted Jev model.+pub struct TypesafeJev {+ client: Client,+ endpoint: String,+ api_key: String,+}++impl TypesafeJev {+ /// Construct once at startup against the public TypeSafe API.+ pub fn new(api_key: &str) -> Result<Self, TypesafeConfigError> {+ Self::with_base_url(api_key, DEFAULT_BASE_URL)+ }++ /// Construct against another API base, e.g. a test server.+ pub fn with_base_url(api_key: &str, base_url: &str) -> Result<Self, TypesafeConfigError> {+ let api_key = api_key.trim();+ if api_key.is_empty() {+ return Err(TypesafeConfigError::EmptyApiKey);+ }+ Ok(Self {+ client: Client::builder().timeout(REQUEST_TIMEOUT).build()?,+ endpoint: format!("{}/v1/systemone", base_url.trim_end_matches('/')),+ api_key: api_key.to_owned(),+ })+ }++ async fn send(&self, request: &EvaluateRequest<'_>) -> Result<EvaluateResponse, JevError> {+ let span = tracing::Span::current();+ let response = self+ .client+ .post(&self.endpoint)+ .bearer_auth(&self.api_key)+ .json(request)+ .send()+ .await+ .map_err(|error| {+ let kind = if error.is_timeout() {+ "timeout"+ } else if error.is_connect() {+ "connection"+ } else {+ "http"+ };+ span.record("error.type", kind);+ tracing::warn!(kind, "Jev request failed");+ JevError::Unavailable+ })?;+ let status = response.status();+ span.record("http.response.status_code", status.as_u16());+ if !status.is_success() {+ let error = status_error(status);+ span.record("error.type", status.as_str());+ tracing::warn!(status = status.as_u16(), "Jev request failed");+ return Err(error);+ }+ response.json().await.map_err(|error| {+ let kind = if error.is_timeout() {+ "timeout"+ } else {+ "invalid_response"+ };+ span.record("error.type", kind);+ tracing::warn!(kind, "Jev response unusable");+ if error.is_timeout() {+ JevError::Unavailable+ } else {+ JevError::InvalidResponse+ }+ })+ }+}++/// Startup failures for [`TypesafeJev::new`].+#[derive(Debug, thiserror::Error)]+pub enum TypesafeConfigError {+ /// The credential contains no usable key.+ #[error("TYPESAFE_API_KEY must not be empty")]+ EmptyApiKey,+ /// The HTTP client could not be constructed.+ #[error(transparent)]+ HttpClient(#[from] reqwest::Error),+}++impl JevProvider for TypesafeJev {+ fn model_id(&self) -> &'static str {+ MODEL+ }++ #[tracing::instrument(name = "classify jev-latest", skip_all, err, fields(+ otel.kind = "client",+ gen_ai.operation.name = "classify",+ gen_ai.provider.name = "typesafe",+ gen_ai.request.model = MODEL,+ gen_ai.response.model = tracing::field::Empty,+ gen_ai.usage.input_tokens = tracing::field::Empty,+ gen_ai.usage.output_tokens = tracing::field::Empty,+ jev.questions = questions.len(),+ jev.attempts = tracing::field::Empty,+ http.response.status_code = tracing::field::Empty,+ error.type = tracing::field::Empty,+ ))]+ async fn evaluate(+ &self,+ input: &Value,+ questions: &[YesNoQuestion],+ ) -> Result<Evaluation, JevError> {+ let span = tracing::Span::current();+ let request = EvaluateRequest::new(input, questions);+ let mut retries = RETRY_DELAYS.iter();+ let mut attempts = 1_u8;+ let response = loop {+ match self.send(&request).await {+ Err(JevError::Unavailable) => match retries.next() {+ Some(delay) => {+ tokio::time::sleep(*delay).await;+ attempts += 1;+ }+ None => {+ span.record("jev.attempts", attempts);+ return Err(JevError::Unavailable);+ }+ },+ result => {+ span.record("jev.attempts", attempts);+ break result?;+ }+ }+ };+ if let Some(model) = &response.model {+ span.record("gen_ai.response.model", model.as_str());+ }+ span.record("gen_ai.usage.input_tokens", response.usage.input_tokens);+ span.record("gen_ai.usage.output_tokens", response.usage.output_tokens);+ response.into_evaluation(questions.len()).inspect_err(|_| {+ span.record("error.type", "invalid_response");+ tracing::warn!(kind = "invalid_response", "Jev answers unusable");+ })+ }+}++fn status_error(status: StatusCode) -> JevError {+ if status == StatusCode::TOO_MANY_REQUESTS+ || status == StatusCode::REQUEST_TIMEOUT+ || status.as_u16() == OVERLOADED+ || status.is_server_error()+ {+ JevError::Unavailable+ } else {+ JevError::Rejected+ }+}++fn question_id(index: usize) -> String {+ format!("q{index}")+}++#[derive(Debug, Serialize)]+struct EvaluateRequest<'a> {+ model: &'static str,+ state: &'a Value,+ questions: HashMap<String, NoulQuestion<'a>>,+}++impl<'a> EvaluateRequest<'a> {+ fn new(input: &'a Value, questions: &'a [YesNoQuestion]) -> Self {+ Self {+ model: MODEL,+ state: input,+ questions: questions+ .iter()+ .enumerate()+ .map(|(index, question)| {+ (+ question_id(index),+ NoulQuestion {+ kind: "noul",+ instructions: question.as_str(),+ },+ )+ })+ .collect(),+ }+ }+}++#[derive(Debug, Serialize)]+struct NoulQuestion<'a> {+ #[serde(rename = "type")]+ kind: &'static str,+ instructions: &'a str,+}++#[derive(Debug, Deserialize)]+struct EvaluateResponse {+ model: Option<String>,+ answers: HashMap<String, Answer>,+ usage: Usage,+}++impl EvaluateResponse {+ fn into_evaluation(mut self, questions: usize) -> Result<Evaluation, JevError> {+ let probabilities = (0..questions)+ .map(|index| match self.answers.remove(&question_id(index)) {+ Some(Answer::Noul { noul }) => Probability::new(noul),+ Some(Answer::Other) | None => None,+ })+ .collect::<Option<Vec<_>>>()+ .ok_or(JevError::InvalidResponse)?;+ Ok(Evaluation {+ probabilities,+ input_tokens: self.usage.input_tokens,+ output_tokens: self.usage.output_tokens,+ })+ }+}++#[derive(Debug, Deserialize)]+#[serde(tag = "type", rename_all = "snake_case")]+enum Answer {+ Noul {+ noul: f32,+ },+ #[serde(other)]+ Other,+}++#[derive(Debug, Deserialize)]+struct Usage {+ input_tokens: u64,+ output_tokens: u64,+}diff --git a/crates/jev/src/outbound/typesafe/test.rs b/crates/jev/src/outbound/typesafe/test.rsnew file mode 100644index 0000000000..fd4a21b3d5--- /dev/null+++ b/crates/jev/src/outbound/typesafe/test.rs@@ -0,0 +1,165 @@+use serde_json::json;+use wiremock::matchers::{header, method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};++use super::*;++fn provider(server: &MockServer) -> TypesafeJev {+ TypesafeJev::with_base_url("test-key", &server.uri()).unwrap()+}++fn questions(texts: &[&str]) -> Vec<YesNoQuestion> {+ texts+ .iter()+ .map(|text| YesNoQuestion::try_from(*text).unwrap())+ .collect()+}++fn noul(value: f32) -> Value {+ json!({ "type": "noul", "noul": value })+}++#[tokio::test]+async fn sends_every_question_as_noul_with_the_input_as_state() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/v1/systemone"))+ .and(header("authorization", "Bearer test-key"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "model": "jev-1.13.0",+ "answers": { "q0": noul(0.92), "q1": noul(0.03) },+ "usage": { "input_tokens": 296, "output_tokens": 20 }+ })))+ .expect(1)+ .mount(&server)+ .await;+ let input = json!({ "email": { "subject": "Invoice #42" } });++ let evaluation = provider(&server)+ .evaluate(+ &input,+ &questions(&["Is this an invoice?", "Is this spam?"]),+ )+ .await+ .unwrap();++ assert_eq!(+ evaluation+ .probabilities+ .iter()+ .map(|p| p.get())+ .collect::<Vec<_>>(),+ [0.92, 0.03]+ );+ assert_eq!(+ (evaluation.input_tokens, evaluation.output_tokens),+ (296, 20)+ );+ let requests = server.received_requests().await.unwrap();+ let body: Value = serde_json::from_slice(&requests[0].body).unwrap();+ assert_eq!(+ body,+ json!({+ "model": "jev-latest",+ "state": input,+ "questions": {+ "q0": { "type": "noul", "instructions": "Is this an invoice?" },+ "q1": { "type": "noul", "instructions": "Is this spam?" }+ }+ })+ );+}++#[tokio::test]+async fn retries_overload_then_succeeds() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .respond_with(ResponseTemplate::new(529))+ .up_to_n_times(1)+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "answers": { "q0": noul(0.5) },+ "usage": { "input_tokens": 10, "output_tokens": 0 }+ })))+ .mount(&server)+ .await;++ let evaluation = provider(&server)+ .evaluate(&json!("text"), &questions(&["Yes?"]))+ .await+ .unwrap();++ assert_eq!(evaluation.probabilities.len(), 1);+ assert_eq!(server.received_requests().await.unwrap().len(), 2);+}++#[tokio::test]+async fn gives_up_after_bounded_retries() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .respond_with(ResponseTemplate::new(429))+ .mount(&server)+ .await;++ let result = provider(&server)+ .evaluate(&json!({}), &questions(&["Yes?"]))+ .await;++ assert_eq!(result, Err(JevError::Unavailable));+ assert_eq!(+ server.received_requests().await.unwrap().len(),+ RETRY_DELAYS.len() + 1+ );+}++#[tokio::test]+async fn rejections_are_not_retried() {+ for status in [401, 422] {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .respond_with(ResponseTemplate::new(status))+ .mount(&server)+ .await;++ let result = provider(&server)+ .evaluate(&json!({}), &questions(&["Yes?"]))+ .await;++ assert_eq!(result, Err(JevError::Rejected), "status {status}");+ assert_eq!(server.received_requests().await.unwrap().len(), 1);+ }+}++#[tokio::test]+async fn missing_or_out_of_range_answers_are_invalid() {+ for answers in [+ json!({ "q0": noul(0.5) }),+ json!({ "q0": noul(0.5), "q1": noul(1.5) }),+ json!({ "q0": noul(0.5), "q1": { "type": "score", "score": 3 } }),+ ] {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "answers": answers,+ "usage": { "input_tokens": 10, "output_tokens": 0 }+ })))+ .mount(&server)+ .await;++ let result = provider(&server)+ .evaluate(&json!({}), &questions(&["A?", "B?"]))+ .await;++ assert_eq!(result, Err(JevError::InvalidResponse), "{answers}");+ }+}++#[test]+fn rejects_blank_credentials() {+ assert!(matches!(+ TypesafeJev::new(" "),+ Err(TypesafeConfigError::EmptyApiKey)+ ));+}diff --git a/crates/macro_db_client/migrations/20261006034942_seed_jev_pricing.sql b/crates/macro_db_client/migrations/20261006034942_seed_jev_pricing.sqlnew file mode 100644index 0000000000..59e68497e5--- /dev/null+++ b/crates/macro_db_client/migrations/20261006034942_seed_jev_pricing.sql@@ -0,0 +1,8 @@+-- Seed pricing for TypeSafe's Jev yes/no classifier (USD per million tokens),+-- which gates event-triggered routines on a user-written condition. TypeSafe+-- charges $0.042 per million input tokens and nothing for output. Usage is+-- recorded under the requested model id, `jev-latest`. ON CONFLICT keeps any+-- price already set at runtime via the set_pricing endpoint.+INSERT INTO ai_pricing (model, price_per_million_in, price_per_million_out) VALUES+ ('jev-latest', 0.042, 0)+ON CONFLICT (model) DO NOTHING;diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.mdindex 694c706e49..7bcecd007e 100644--- a/docs/AGENT_GUIDE/navigation.md+++ b/docs/AGENT_GUIDE/navigation.md@@ -581,6 +581,15 @@ the same event. These are Macro events, not incoming HTTP webhooks. Bot-authoredor delegated changes do not retrigger routines. Saved legacy selectors remaineditable but are no longer offered in the new-trigger menu.+When `enable-routine-conditions` is on, every activity trigger panel has an+**Only run if** box for an optional yes/no question about each event, such as+**Is this email an invoice or a receipt?** Before a run starts, the event's+content (the email, channel message, document, or task, read as the routine+owner) is checked against it, and events answered no are skipped. The chip+shows the question after **· if**. Saving a condition fails with "trigger+conditions are not enabled" while the scheduled-action service has no+`TYPESAFE_API_KEY`.+A routine can combine up to sixteen trigger groups: each schedule is a group,and up to thirty-two activity filters share one event group;matching any trigger runs it. Open a trigger chip and choose **Remove trigger**@@ -595,7 +604,10 @@ The **Run options** dropdown contains**Enable routine** / **Disable routine** and **Copy prompt**, which copies thecurrent instructions, including unsaved edits. **Run History** uses full-widthSoup rows for past agent sessions, with each run's-outcome, duration, and time. Click a row or press Enter to open its session;+outcome, duration, and time. Runs a trigger's condition skipped show+**Condition not met** (hover for how likely the answer was yes) or **Condition+couldn’t be checked**, marked **Skipped**; consecutive skips collapse into one+**N events skipped by the condition** row that expands on click. Click a row or press Enter to open its session;Shift opens it in another split. **Back to routines** returns to the list in thesame pane.diff --git a/packages/sdk/generated/scheduled-action/index.ts b/packages/sdk/generated/scheduled-action/index.tsindex c44b139bb1..ba138a0047 100644--- a/packages/sdk/generated/scheduled-action/index.ts+++ b/packages/sdk/generated/scheduled-action/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, ActionTrigger, AgentTask, AgentTaskAgent, AiAdmissionErrorBody, ClientOptions, CreateScheduledAction, CreateScheduledActionData, CreateScheduledActionError, CreateScheduledActionErrors, CreateScheduledActionResponse, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionError, DeleteScheduledActionErrors, DeleteScheduledActionResponse, DeleteScheduledActionResponses, EmptyResponse, EventFilter, EventFilters, EventName, ExecuteScheduledActionNowData, ExecuteScheduledActionNowError, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponse, ExecuteScheduledActionNowResponses, ExecutionResource, ExecutionResourceType, ExecutionResult, GetScheduledActionData, GetScheduledActionError, GetScheduledActionErrors, GetScheduledActionResponse, GetScheduledActionResponses, InProgressExecution, LegacyActionConfiguration, ListScheduledActionHistoryData, ListScheduledActionHistoryError, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponse, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsError, ListScheduledActionsErrors, ListScheduledActionsResponse, ListScheduledActionsResponses, RoutineModelId, RoutineTrigger, RoutineTriggers, Schedule, ScheduledAction, ScheduledActionHealthData, ScheduledActionHealthResponse, ScheduledActionHealthResponses, ScheduledActionResponse, ScheduledActionUpdate, SetScheduledActionEnabled, SetScheduledActionEnabledData, SetScheduledActionEnabledError, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponse, SetScheduledActionEnabledResponses, UpdateScheduledAction, UpdateScheduledActionData, UpdateScheduledActionError, UpdateScheduledActionErrors, UpdateScheduledActionResponse, UpdateScheduledActionResponses } from './types.gen';+export type { ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, ActionTrigger, AgentTask, AgentTaskAgent, AiAdmissionErrorBody, ClientOptions, ConditionResult, CreateScheduledAction, CreateScheduledActionData, CreateScheduledActionError, CreateScheduledActionErrors, CreateScheduledActionResponse, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionError, DeleteScheduledActionErrors, DeleteScheduledActionResponse, DeleteScheduledActionResponses, EmptyResponse, EventFilter, EventFilters, EventName, ExecuteScheduledActionNowData, ExecuteScheduledActionNowError, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponse, ExecuteScheduledActionNowResponses, ExecutionResource, ExecutionResourceType, ExecutionResult, GetScheduledActionData, GetScheduledActionError, GetScheduledActionErrors, GetScheduledActionResponse, GetScheduledActionResponses, InProgressExecution, LegacyActionConfiguration, ListScheduledActionHistoryData, ListScheduledActionHistoryError, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponse, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsError, ListScheduledActionsErrors, ListScheduledActionsResponse, ListScheduledActionsResponses, RoutineModelId, RoutineTrigger, RoutineTriggers, Schedule, ScheduledAction, ScheduledActionHealthData, ScheduledActionHealthResponse, ScheduledActionHealthResponses, ScheduledActionResponse, ScheduledActionUpdate, SetScheduledActionEnabled, SetScheduledActionEnabledData, SetScheduledActionEnabledError, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponse, SetScheduledActionEnabledResponses, UpdateScheduledAction, UpdateScheduledActionData, UpdateScheduledActionError, UpdateScheduledActionErrors, UpdateScheduledActionResponse, UpdateScheduledActionResponses } from './types.gen';diff --git a/packages/sdk/generated/scheduled-action/types.gen.ts b/packages/sdk/generated/scheduled-action/types.gen.tsindex 76eff45dac..3d479113b9 100644--- a/packages/sdk/generated/scheduled-action/types.gen.ts+++ b/packages/sdk/generated/scheduled-action/types.gen.ts@@ -99,6 +99,19 @@ export type AiAdmissionErrorBody = {error: string;};+/**+ * Why an event-triggered run was skipped before it started.+ */+export type ConditionResult = {+ /**+ * The classifier's probability, from 0 to 1, that the answer was yes.+ */+ probability: number;+ status: 'not_met';+} | {+ status: 'unavailable';+};+/*** Exactly one representation is accepted, even if mixed fields agree or are null.*/@@ -112,9 +125,15 @@ export type EmptyResponse = {};/**- * An event name AND an entity ID must match within the same filter.+ * An event name AND an entity ID must match within the same filter. A+ * condition further requires the event's content to answer it with yes.*/export type EventFilter = {+ /**+ * Yes/no question about the triggering content, e.g. "Is this email an+ * invoice?". The routine runs only when the answer is yes.+ */+ condition?: string | null;events: Array<EventName>;ids?: Array<string> | null;};@@ -148,6 +167,7 @@ export type ExecutionResourceType = 'chat' | 'agent';* Null/string column values predate this envelope and refer to legacy chats.*/export type ExecutionResult = {+ condition?: null | ConditionResult;error?: string | null;resource?: null | ExecutionResource;version: number;diff --git a/packages/sdk/package.json b/packages/sdk/package.jsonindex 6966e7c7bc..339db4ed0c 100644--- a/packages/sdk/package.json+++ b/packages/sdk/package.json@@ -1,6 +1,6 @@{"name": "@macro-inc/sdk",- "version": "0.2.0",+ "version": "0.2.1","repository": {"type": "git","url": "git+https://github.com/macro-inc/macro.git",diff --git a/packages/sdk/specs/scheduled-action.json b/packages/sdk/specs/scheduled-action.jsonindex 50a8dcb321..373779fff3 100644--- a/packages/sdk/specs/scheduled-action.json+++ b/packages/sdk/specs/scheduled-action.json@@ -808,6 +808,38 @@}}},+ "ConditionResult": {+ "oneOf": [+ {+ "type": "object",+ "description": "The triggering content answered the condition with no.",+ "required": ["probability", "status"],+ "properties": {+ "probability": {+ "type": "number",+ "format": "float",+ "description": "The classifier's probability, from 0 to 1, that the answer was yes."+ },+ "status": {+ "type": "string",+ "enum": ["not_met"]+ }+ }+ },+ {+ "type": "object",+ "description": "The condition could not be checked before the retry window closed.",+ "required": ["status"],+ "properties": {+ "status": {+ "type": "string",+ "enum": ["unavailable"]+ }+ }+ }+ ],+ "description": "Why an event-triggered run was skipped before it started."+ },"CreateScheduledAction": {"oneOf": [{@@ -825,9 +857,14 @@},"EventFilter": {"type": "object",- "description": "An event name AND an entity ID must match within the same filter.",+ "description": "An event name AND an entity ID must match within the same filter. A\ncondition further requires the event's content to answer it with yes.","required": ["events"],"properties": {+ "condition": {+ "type": ["string", "null"],+ "description": "Yes/no question about the triggering content, e.g. \"Is this email an\ninvoice?\". The routine runs only when the answer is yes.",+ "maxLength": 500+ },"events": {"type": "array","items": {@@ -891,6 +928,17 @@"description": "Version 1 execution metadata stored in the existing JSON result column.\nNull/string column values predate this envelope and refer to legacy chats.","required": ["version"],"properties": {+ "condition": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/ConditionResult",+ "description": "Present when an event trigger's condition stopped the run from starting."+ }+ ]+ },"error": {"type": ["string", "null"]},diff --git a/services/scheduled_action/Cargo.toml b/services/scheduled_action/Cargo.tomlindex aa0f0991a0..b6d7d54d36 100644--- a/services/scheduled_action/Cargo.toml+++ b/services/scheduled_action/Cargo.toml@@ -31,18 +31,24 @@ agent_runtime_protocol = { path = "../../crates/agent_runtime_protocol", defaultagent_session = { path = "../../crates/agent_session", default-features = false, features = ["admission"] }bot_id = { path = "../../crates/bot_id" }channel_sender = { path = "../../crates/channel_sender" }-channels = { path = "../../crates/channels", default-features = false }-documents = { path = "../../crates/documents", default-features = false }+channels = { path = "../../crates/channels", default-features = false, features = ["outbound"] }+crm = { path = "../../crates/crm", default-features = false, features = ["ports"] }+documents = { path = "../../crates/documents", default-features = false, features = ["outbound", "ports"] }document_sub_type = { path = "../../crates/document_sub_type" }-email = { path = "../../crates/email", default-features = false }+email = { path = "../../crates/email", default-features = false, features = ["outbound"] }+entity_access_management = { path = "../../crates/entity_access_management" }+frecency = { path = "../../crates/frecency", features = ["postgres"] }+jev = { path = "../../crates/jev", features = ["outbound"] }+lexical_client = { path = "../../crates/lexical_client" }+mention_utils = { path = "../../crates/mention_utils" }entity_access = { path = "../../crates/entity_access", default-features = false, features = ["inbound", "outbound"] }entity_access_db_utils = { path = "../../crates/entity_access_db_utils" }kafka_util = { path = "../../crates/kafka_util" }macro_event_broker = { path = "../../crates/macro_event_broker", features = ["outbound"] }macro_event_topics = { path = "../../crates/macro_event_topics" }-messages = { path = "../../crates/messages", features = ["broker"] }+messages = { path = "../../crates/messages", features = ["broker", "outbound"] }models_properties = { path = "../../crates/models_properties" }-properties = { path = "../../crates/properties", default-features = false }+properties = { path = "../../crates/properties", default-features = false, features = ["outbound"] }system_properties = { path = "../../crates/system_properties" }rdkafka = { workspace = true }reqwest = { workspace = true }diff --git a/services/scheduled_action/src/bins/service.rs b/services/scheduled_action/src/bins/service.rsindex ccd226c070..9e6aad345c 100644--- a/services/scheduled_action/src/bins/service.rs+++ b/services/scheduled_action/src/bins/service.rs@@ -8,16 +8,18 @@ use connection_gateway_client::client::ConnectionGatewayClient;use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};use entity_registry::OwnerGrantPolicy;use entity_registry_db_utils::OwnedEntityRegistrar;+use jev::{domain::JevClassifier, outbound::TypesafeJev};use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_authorization::{InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationServiceImpl,MacroAuthorizationState, PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,};use macro_entrypoint::MacroEntrypoint;-use macro_service_urls::{AgentHarnessServiceUrl, ConnectionGatewayUrl};+use macro_service_urls::{AgentHarnessServiceUrl, ConnectionGatewayUrl, LexicalServiceUrl};use scheduled_action::config::Config;use scheduled_action::domain::event_runs::{- PageSize, admission::EventAdmissionService, dispatch::EventDispatchService,+ PageSize, admission::EventAdmissionService, condition::ConditionGate,+ dispatch::EventDispatchService,};use scheduled_action::domain::ports::ScheduledActionDispatcher;use scheduled_action::domain::service::ScheduledActionServiceImpl;@@ -31,6 +33,7 @@ use scheduled_action::inbound::kafka_consumer::run_scheduled_action_event_consumuse scheduled_action::outbound::agent_session_client::AgentSessionClient;use scheduled_action::outbound::conn_gateway_live_updates::ConnGatewayLiveUpdates;use scheduled_action::outbound::event_access::EventAccessAdapter;+use scheduled_action::outbound::event_content::EventContentAdapter;use scheduled_action::outbound::inprocess_executor::InProcessExecutor;use scheduled_action::outbound::pg_event_run_repo::PgEventRunRepo;use scheduled_action::outbound::pg_polling_dispatcher::{@@ -143,11 +146,37 @@ async fn main() -> Result<()> {// eventually block cron dispatch or its shutdown.drop(execution_rx);+ let typesafe = config+ .typesafe_api_key+ .value()+ .map(TypesafeJev::new)+ .transpose()+ .context("invalid TYPESAFE_API_KEY")?;+ let conditions_enabled = typesafe.is_some();+ let conditions = match typesafe {+ Some(provider) => Some(ConditionGate::new(+ Arc::new(event_content(+ &db,+ ®istrar,+ Arc::clone(&access),+ &config,+ )?),+ Arc::new(JevClassifier::new(+ provider,+ ai_usage::pg_recorder_with_enforcement(+ db.clone(),+ config.enable_ai_usage_enforcement,+ ),+ )),+ )),+ None => None,+ };let event_dispatch = EventDispatchService::new(Arc::clone(&event_repo),Arc::clone(&event_access),Arc::clone(&service_executor),- );+ )+ .with_conditions(Arc::new(conditions));let brokers = config.kafka_brokers.to_string();let intake_shutdown = lifecycle.stop_consumers.clone();start_event_tasks(@@ -181,6 +210,7 @@ async fn main() -> Result<()> {access.clone(),).with_event_management_enabled(config.event_routines_enabled)+ .with_conditions_enabled(conditions_enabled).with_target_validation(TargetValidation::new(sessions,config.routine_agents_enabled,@@ -205,6 +235,7 @@ async fn main() -> Result<()> {tracing::info!(event_routines_enabled = config.event_routines_enabled,routine_agents_enabled = config.routine_agents_enabled,+ routine_conditions_enabled = conditions_enabled,"scheduled_action service listening on {addr}");@@ -224,6 +255,61 @@ async fn main() -> Result<()> {.await}+/// Read-only views of the domains whose events can trigger a routine, for+/// condition checks. None of these reads notify, publish or enqueue.+fn event_content(+ db: &sqlx::PgPool,+ registrar: &OwnedEntityRegistrar<PgBotsRepo>,+ access: Arc<EntityAccessServiceImpl<PgAccessRepository>>,+ config: &Config,+) -> Result<impl scheduled_action::domain::event_runs::condition::EventContentReader + use<>> {+ Ok(EventContentAdapter::new(+ email::domain::service::EmailServiceImpl::new(+ email::outbound::EmailPgRepo::new(db.clone()),+ frecency::domain::services::FrecencyQueryServiceImpl::new(+ frecency::outbound::postgres::FrecencyPgStorage::new(db.clone()),+ ),+ email::domain::ports::NoOpEnqueuer,+ crm::domain::service::NoOpCrmService,+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(+ entity_access_management::outbound::PgRepository::new(db.clone()),+ ),+ 0,+ ),+ messages::domain::service::MessageService::new(+ messages::outbound::pg_message_repo::PgMessageRepository::new(db.clone()),+ messages::domain::ports::NoMessageEventPublisher,+ ),+ channels::domain::service::ChannelServiceImpl::new(+ channels::outbound::pg_channels_repo::PgChannelsRepo::new(db.clone()),+ ),+ documents::outbound::pg_document_repo::PgDocumentRepo::new(db.clone(), registrar.clone()),+ properties::PropertiesServiceImpl::new(+ properties::PropertiesPgRepo::new(db.clone()),+ Some(properties::PermissionServiceImpl::new(db.clone(), access)),+ None::<NoTaskNotifications>,+ ),+ lexical_client::LexicalClient::new(+ config.internal_api_key.to_string(),+ LexicalServiceUrl::new()?.to_string(),+ ),+ ))+}++/// Condition checks only read properties; they never assign tasks.+struct NoTaskNotifications;++impl properties::NotificationService for NoTaskNotifications {+ type Err = anyhow::Error;++ async fn send_task_assigned<'a>(+ &self,+ _: properties::domain::model::TaskAssignedNotification<'a>,+ ) -> Result<(), Self::Err> {+ Ok(())+ }+}+#[derive(Default)]struct ServiceLifecycle {stop_http: CancellationToken,diff --git a/services/scheduled_action/src/config.rs b/services/scheduled_action/src/config.rsindex bcc08d0cfe..fb6f161376 100644--- a/services/scheduled_action/src/config.rs+++ b/services/scheduled_action/src/config.rs@@ -57,6 +57,9 @@ pub struct Config {pub routine_agents_enabled: bool,/// The internal api keypub internal_api_key: InternalApiKey,+ /// TypeSafe credential for the Jev classifier behind trigger conditions.+ /// Optional: routines cannot save conditions while it is unset.+ pub typesafe_api_key: jev::outbound::TypesafeApiKey,}impl Config {diff --git a/services/scheduled_action/src/config/test.rs b/services/scheduled_action/src/config/test.rsindex d0a59b836f..f6d8bba1b5 100644--- a/services/scheduled_action/src/config/test.rs+++ b/services/scheduled_action/src/config/test.rs@@ -101,3 +101,13 @@ fn event_routines_require_an_explicit_boolean() {values["EVENT_ROUTINES_ENABLED"] = json!("enabled");assert!(serde_json::from_value::<Config>(values).is_err());}++#[test]+fn the_typesafe_key_is_optional() {+ let config: Config = serde_json::from_value(config_values()).unwrap();+ assert_eq!(config.typesafe_api_key.value(), None);+ let mut values = config_values();+ values["TYPESAFE_API_KEY"] = json!("ts-key");+ let config: Config = serde_json::from_value(values).unwrap();+ assert_eq!(config.typesafe_api_key.value(), Some("ts-key"));+}diff --git a/services/scheduled_action/src/domain/event_runs.rs b/services/scheduled_action/src/domain/event_runs.rsindex 900a546d82..2d2398353c 100644--- a/services/scheduled_action/src/domain/event_runs.rs+++ b/services/scheduled_action/src/domain/event_runs.rs@@ -18,6 +18,7 @@ use super::event_trigger::{use super::models::{ActionExecutionRecord, ScheduledAction};pub mod admission;+pub mod condition;pub mod dispatch;#[cfg(test)]@@ -126,7 +127,7 @@ pub enum RunContractError {/// Natural deduplication key. A matching event has at most one run per action,/// even if several filters matched or the source is redelivered.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]pub struct EventRunKey {pub action_id: Uuid,pub event_id: EventId,@@ -139,6 +140,10 @@ pub enum CancellationReason {Disabled,Superseded,NotUserOwned,+ /// The event's content answered every matching condition with no.+ ConditionNotMet,+ /// The condition could not be checked before the retry window closed.+ ConditionUnavailable,}/// All outcomes are terminal. In particular, failure and interruption never@@ -389,6 +394,17 @@ pub trait EventRunRepository: Send + Sync + 'static {reason: CancellationReason,) -> impl Future<Output = Result<(), Report>> + Send;+ /// Cancel like [`Self::cancel_pending`], and record the skipped run in the+ /// action's history in the same transaction. A run that is no longer+ /// pending at this revision is left alone and gets no history.+ fn skip_pending(+ &self,+ key: EventRunKey,+ revision: ConfigurationRevision,+ reason: CancellationReason,+ record: ActionExecutionRecord,+ ) -> impl Future<Output = Result<(), Report>> + Send;+/// Bounded cleanup of disabled/superseded pending rows, and expired started/// rows. Expired started rows become interrupted, never pending. Release/// only their own claim tokens. Return the number of affected rows.diff --git a/services/scheduled_action/src/domain/event_runs/condition.rs b/services/scheduled_action/src/domain/event_runs/condition.rsnew file mode 100644index 0000000000..500d501487--- /dev/null+++ b/services/scheduled_action/src/domain/event_runs/condition.rs@@ -0,0 +1,153 @@+//! Trigger conditions: before a matched event starts its run, the triggering+//! content must answer one of the matching filters' yes/no questions with yes.+//! Content is read as the routine owner, through the run's access receipt.++use std::sync::Arc;++use ai_usage::{AiFeature, UsageContext};+use jev::domain::{Probability, YesNoClassifier, YesNoQuestion};+use macro_user_id::user_id::MacroUserIdStr;+use rootcause::Report;+use serde_json::Value;++use super::AuthorizedEventRun;++#[cfg(test)]+mod test;++/// A condition is met when the classifier's probability of yes reaches this.+pub const CONDITION_THRESHOLD: f32 = 0.5;++/// Reads what a triggering event is about, as JSON for the classifier.+///+/// Read only what the run's access receipt covers. Content that no longer+/// exists (e.g. a deleted document) is described as such, not an error;+/// infrastructure failure is `Err` and is retried.+pub trait EventContentReader: Send + Sync + 'static {+ fn read(+ &self,+ owner: &MacroUserIdStr<'static>,+ run: &AuthorizedEventRun,+ ) -> impl Future<Output = Result<Value, Report>> + Send;+}++/// The answer to a run's conditions, with the highest probability of yes.+#[derive(Debug, Clone, Copy, PartialEq)]+pub enum ConditionVerdict {+ Met(Probability),+ NotMet(Probability),+}++#[derive(Debug)]+pub enum ConditionError {+ /// This host has no classifier configured.+ Unconfigured,+ /// Reading content or classifying failed; a later attempt may succeed.+ Transient(Report),+ /// The classifier refused this input; retrying will not help.+ Permanent(Report),+}++/// Decides whether a matched run's conditions hold.+pub trait EventConditionCheck: Send + Sync + 'static {+ fn check(+ &self,+ owner: &MacroUserIdStr<'static>,+ run: &AuthorizedEventRun,+ conditions: &[YesNoQuestion],+ ) -> impl Future<Output = Result<ConditionVerdict, ConditionError>> + Send;+}++/// For hosts without a classifier: no condition can be checked.+pub struct NoConditionCheck;++impl EventConditionCheck for NoConditionCheck {+ async fn check(+ &self,+ _: &MacroUserIdStr<'static>,+ _: &AuthorizedEventRun,+ _: &[YesNoQuestion],+ ) -> Result<ConditionVerdict, ConditionError> {+ Err(ConditionError::Unconfigured)+ }+}++/// A host-optional check: `None` means no classifier is configured.+impl<T: EventConditionCheck> EventConditionCheck for Option<T> {+ async fn check(+ &self,+ owner: &MacroUserIdStr<'static>,+ run: &AuthorizedEventRun,+ conditions: &[YesNoQuestion],+ ) -> Result<ConditionVerdict, ConditionError> {+ match self {+ Some(check) => check.check(owner, run, conditions).await,+ None => Err(ConditionError::Unconfigured),+ }+ }+}++/// Reads the triggering content and asks every condition about it in one+/// classifier call, metered against the routine owner.+pub struct ConditionGate<R, C> {+ content: Arc<R>,+ classifier: Arc<C>,+}++impl<R, C> ConditionGate<R, C> {+ pub fn new(content: Arc<R>, classifier: Arc<C>) -> Self {+ Self {+ content,+ classifier,+ }+ }+}++impl<R: EventContentReader, C: YesNoClassifier> EventConditionCheck for ConditionGate<R, C> {+ #[tracing::instrument(name = "routine.condition", skip_all, fields(+ action_id = %run.pending.action_id,+ event_name = run.pending.event.event_name().as_str(),+ conditions = conditions.len(),+ probability = tracing::field::Empty,+ ))]+ async fn check(+ &self,+ owner: &MacroUserIdStr<'static>,+ run: &AuthorizedEventRun,+ conditions: &[YesNoQuestion],+ ) -> Result<ConditionVerdict, ConditionError> {+ let input = self+ .content+ .read(owner, run)+ .await+ .map_err(ConditionError::Transient)?;+ let usage = UsageContext::new(AiFeature::Automation, owner.clone())+ .with_entity(Some(run.pending.action_id));+ let probabilities = self+ .classifier+ .classify(usage, &input, conditions)+ .await+ .map_err(|error| {+ let report = Report::new(error).into_dynamic();+ if error.is_transient() {+ ConditionError::Transient(report)+ } else {+ ConditionError::Permanent(report)+ }+ })?;+ let Some(best) = probabilities+ .into_iter()+ .max_by(|left, right| left.get().total_cmp(&right.get()))+ else {+ return Err(ConditionError::Permanent(rootcause::report!(+ "the classifier answered no conditions"+ )));+ };+ tracing::Span::current().record("probability", best.get());+ Ok(if best.get() >= CONDITION_THRESHOLD {+ ConditionVerdict::Met(best)+ } else {+ ConditionVerdict::NotMet(best)+ })+ }+}diff --git a/services/scheduled_action/src/domain/event_runs/condition/test.rs b/services/scheduled_action/src/domain/event_runs/condition/test.rsnew file mode 100644index 0000000000..61d5383504--- /dev/null+++ b/services/scheduled_action/src/domain/event_runs/condition/test.rs@@ -0,0 +1,173 @@+use std::sync::Mutex;++use ai_usage::UsageContext;+use jev::domain::JevError;+use serde_json::json;++use super::super::test_support::*;+use super::*;++pub struct Content(pub Result<Value, &'static str>);++impl EventContentReader for Content {+ async fn read(+ &self,+ _: &MacroUserIdStr<'static>,+ _: &AuthorizedEventRun,+ ) -> Result<Value, Report> {+ self.0+ .clone()+ .map_err(|message| rootcause::report!(message).into_dynamic())+ }+}++pub struct Classifier {+ pub answers: Result<Vec<f32>, JevError>,+ pub calls: Mutex<Vec<(UsageContext, Value, Vec<YesNoQuestion>)>>,+}++impl Classifier {+ pub fn answering(answers: &[f32]) -> Arc<Self> {+ Arc::new(Self {+ answers: Ok(answers.to_vec()),+ calls: Mutex::default(),+ })+ }++ pub fn failing(error: JevError) -> Arc<Self> {+ Arc::new(Self {+ answers: Err(error),+ calls: Mutex::default(),+ })+ }+}++impl YesNoClassifier for Classifier {+ async fn classify(+ &self,+ usage: UsageContext,+ input: &Value,+ questions: &[YesNoQuestion],+ ) -> Result<Vec<Probability>, JevError> {+ self.calls+ .lock()+ .unwrap()+ .push((usage, input.clone(), questions.to_vec()));+ self.answers.clone().map(|answers| {+ answers+ .into_iter()+ .map(|value| Probability::new(value).unwrap())+ .collect()+ })+ }+}++fn authorized() -> AuthorizedEventRun {+ let configuration = configuration();+ let pending = pending(&configuration);+ let access = capability(user(), &pending.event);+ AuthorizedEventRun::prepare(pending, &configuration, access).unwrap()+}++fn questions(texts: &[&str]) -> Vec<YesNoQuestion> {+ texts+ .iter()+ .map(|text| YesNoQuestion::try_from(*text).unwrap())+ .collect()+}++#[tokio::test]+async fn any_yes_meets_the_conditions_and_bills_the_owner() {+ let classifier = Classifier::answering(&[0.2, 0.7]);+ let gate = ConditionGate::new(+ Arc::new(Content(Ok(json!({ "title": "Q3 invoice" })))),+ classifier.clone(),+ );+ let run = authorized();++ let verdict = gate+ .check(&user(), &run, &questions(&["Invoice?", "Receipt?"]))+ .await+ .unwrap();++ assert_eq!(+ verdict,+ ConditionVerdict::Met(Probability::new(0.7).unwrap())+ );+ let calls = classifier.calls.lock().unwrap();+ let (usage, input, asked) = &calls[0];+ assert_eq!(usage.feature, AiFeature::Automation);+ assert_eq!(usage.user, user());+ assert_eq!(usage.entity, Some(run.pending.action_id));+ assert_eq!(input, &json!({ "title": "Q3 invoice" }));+ assert_eq!(asked, &questions(&["Invoice?", "Receipt?"]));+}++#[tokio::test]+async fn every_no_leaves_the_conditions_unmet() {+ let gate = ConditionGate::new(+ Arc::new(Content(Ok(json!("newsletter")))),+ Classifier::answering(&[0.1, 0.49]),+ );++ let verdict = gate+ .check(&user(), &authorized(), &questions(&["A?", "B?"]))+ .await+ .unwrap();++ assert_eq!(+ verdict,+ ConditionVerdict::NotMet(Probability::new(0.49).unwrap())+ );+}++#[tokio::test]+async fn the_threshold_itself_counts_as_yes() {+ let gate = ConditionGate::new(+ Arc::new(Content(Ok(json!({})))),+ Classifier::answering(&[CONDITION_THRESHOLD]),+ );++ let verdict = gate+ .check(&user(), &authorized(), &questions(&["A?"]))+ .await+ .unwrap();++ assert!(matches!(verdict, ConditionVerdict::Met(_)));+}++#[tokio::test]+async fn unreadable_content_is_transient_and_skips_the_classifier() {+ let classifier = Classifier::answering(&[1.0]);+ let gate = ConditionGate::new(Arc::new(Content(Err("db down"))), classifier.clone());++ let error = gate+ .check(&user(), &authorized(), &questions(&["A?"]))+ .await+ .unwrap_err();++ assert!(matches!(error, ConditionError::Transient(_)));+ assert!(classifier.calls.lock().unwrap().is_empty());+}++#[tokio::test]+async fn classifier_errors_keep_their_retryability() {+ for (error, transient) in [+ (JevError::Unavailable, true),+ (JevError::Rejected, false),+ (JevError::InvalidResponse, false),+ ] {+ let gate = ConditionGate::new(Arc::new(Content(Ok(json!({})))), Classifier::failing(error));++ let result = gate+ .check(&user(), &authorized(), &questions(&["A?"]))+ .await+ .unwrap_err();++ assert_eq!(+ matches!(result, ConditionError::Transient(_)),+ transient,+ "{error:?}"+ );+ }+}diff --git a/services/scheduled_action/src/domain/event_runs/dispatch.rs b/services/scheduled_action/src/domain/event_runs/dispatch.rsindex ef3522873b..c1581b653d 100644--- a/services/scheduled_action/src/domain/event_runs/dispatch.rs+++ b/services/scheduled_action/src/domain/event_runs/dispatch.rs@@ -4,8 +4,14 @@ use std::sync::Arc;use futures::FutureExt;+use super::condition::{ConditionError, ConditionVerdict, EventConditionCheck, NoConditionCheck};use super::*;-use crate::domain::models::MAX_ACTION_TIME;+use crate::domain::event_trigger::ConditionRequirement;+use crate::domain::models::{ConditionResult, MAX_ACTION_TIME};++/// How long after admission a condition that cannot be checked is retried+/// before the run is skipped as unavailable.+pub const CONDITION_RETRY_WINDOW: chrono::Duration = chrono::Duration::minutes(10);#[cfg(test)]mod test;@@ -34,23 +40,37 @@ pub trait EventRunDispatch: Send + Sync + 'static {) -> impl Future<Output = Result<DispatchResult, Report>> + Send;}-pub struct EventDispatchService<R, A, E> {+pub struct EventDispatchService<R, A, E, C = NoConditionCheck> {repository: Arc<R>,access: Arc<A>,executor: Arc<E>,+ conditions: Arc<C>,}impl<R, A, E> EventDispatchService<R, A, E> {+ /// Without [`Self::with_conditions`], conditional runs are skipped as unavailable.pub fn new(repository: Arc<R>, access: Arc<A>, executor: Arc<E>) -> Self {Self {repository,access,executor,+ conditions: Arc::new(NoConditionCheck),+ }+ }+}++impl<R, A, E, C> EventDispatchService<R, A, E, C> {+ pub fn with_conditions<D>(self, conditions: Arc<D>) -> EventDispatchService<R, A, E, D> {+ EventDispatchService {+ repository: self.repository,+ access: self.access,+ executor: self.executor,+ conditions,}}}-impl<R: EventRunRepository, A: CurrentOwnerAccess, E: EventExecutor> EventDispatchService<R, A, E> {+impl<R: EventRunRepository, A, E, C> EventDispatchService<R, A, E, C> {async fn cancel(&self,pending: &PendingEventRun,@@ -61,10 +81,26 @@ impl<R: EventRunRepository, A: CurrentOwnerAccess, E: EventExecutor> EventDispat.await?;Ok(DispatchResult::Cancelled(reason))}++ async fn skip(+ &self,+ pending: &PendingEventRun,+ condition: ConditionResult,+ ) -> Result<DispatchResult, Report> {+ let reason = match condition {+ ConditionResult::NotMet { .. } => CancellationReason::ConditionNotMet,+ ConditionResult::Unavailable => CancellationReason::ConditionUnavailable,+ };+ let record = ActionExecutionRecord::skipped(pending.action_id, Utc::now(), condition);+ self.repository+ .skip_pending(pending.key(), pending.revision, reason, record)+ .await?;+ Ok(DispatchResult::Cancelled(reason))+ }}-impl<R: EventRunRepository, A: CurrentOwnerAccess, E: EventExecutor> EventRunDispatch- for EventDispatchService<R, A, E>+impl<R: EventRunRepository, A: CurrentOwnerAccess, E: EventExecutor, C: EventConditionCheck>+ EventRunDispatch for EventDispatchService<R, A, E, C>{async fn pending(&self, limit: PageSize) -> Result<Vec<PendingEventRun>, Report> {self.repository.pending_runs(limit).await@@ -105,6 +141,35 @@ impl<R: EventRunRepository, A: CurrentOwnerAccess, E: EventExecutor> EventRunDisOk(run) => run,Err(reason) => return self.cancel(&pending, reason).await,};+ if let ConditionRequirement::AnyOf(conditions) =+ configuration.filters.condition_requirement(&pending.event)+ {+ match self.conditions.check(owner, &authorized, &conditions).await {+ Ok(ConditionVerdict::Met(_)) => {}+ Ok(ConditionVerdict::NotMet(probability)) => {+ let probability = probability.get();+ return self+ .skip(&pending, ConditionResult::NotMet { probability })+ .await;+ }+ // Unavailability leaves the run pending for a later attempt+ // until the window closes, like authorization above.+ Err(ConditionError::Transient(error))+ if Utc::now() < pending.admitted_at + CONDITION_RETRY_WINDOW =>+ {+ return Err(error);+ }+ Err(error) => {+ tracing::warn!(+ action_id = %pending.action_id,+ error = ?error,+ outcome = "condition_unavailable",+ "skipping event run whose condition could not be checked"+ );+ return self.skip(&pending, ConditionResult::Unavailable).await;+ }+ }+ }let mut cancellation = std::pin::pin!(cancellation);// Authorization may have been in flight when intake stopped. Do not// start a fresh claim after shutdown; already-started claims are terminal.diff --git a/services/scheduled_action/src/domain/event_runs/dispatch/test.rs b/services/scheduled_action/src/domain/event_runs/dispatch/test.rsindex 8c54bc185c..68518c0f11 100644--- a/services/scheduled_action/src/domain/event_runs/dispatch/test.rs+++ b/services/scheduled_action/src/domain/event_runs/dispatch/test.rs@@ -334,3 +334,199 @@ fn preparation_binds_receipt_to_authenticated_owner_entity_and_kind() {.is_ok());}++fn conditional(repo: &Repo, filters: serde_json::Value) {+ repo.0.lock().unwrap().configurations[0].filters = serde_json::from_value(filters).unwrap();+}++fn probability(value: f32) -> jev::domain::Probability {+ jev::domain::Probability::new(value).unwrap()+}++fn skipped_condition(repo: &Repo) -> serde_json::Value {+ let state = repo.0.lock().unwrap();+ assert_eq!(state.history.len(), 1);+ state.history[0].result["condition"].clone()+}++#[tokio::test]+async fn unmet_condition_skips_with_history_and_never_executes() {+ let (repo, access, executor, pending) = setup();+ conditional(+ &repo,+ json!([{"events":["document.updated"], "condition":"Is this urgent?"}]),+ );+ let conditions = Arc::new(Conditions::default());+ conditions+ .verdicts+ .lock()+ .unwrap()+ .push_back(Ok(ConditionVerdict::NotMet(probability(0.25))));+ let service = EventDispatchService::new(repo.clone(), access, executor.clone())+ .with_conditions(conditions.clone());++ assert_eq!(+ dispatch(&service, pending.clone()).await.unwrap(),+ DispatchResult::Cancelled(CancellationReason::ConditionNotMet)+ );++ assert!(executor.calls.lock().unwrap().is_empty());+ assert_eq!(+ conditions.calls.lock().unwrap().as_slice(),+ [vec![+ jev::domain::YesNoQuestion::try_from("Is this urgent?").unwrap()+ ]]+ );+ assert_eq!(+ skipped_condition(&repo),+ json!({"status": "not_met", "probability": 0.25})+ );+ let state = repo.0.lock().unwrap();+ assert!(state.pending.is_empty());+ assert!(state.history[0].is_success);+ assert_eq!(state.history[0].action_id, pending.action_id);+ assert_eq!(state.history[0].resource_id, None);+}++#[tokio::test]+async fn met_condition_runs_normally() {+ let (repo, access, executor, pending) = setup();+ conditional(+ &repo,+ json!([{"events":["document.updated"], "condition":"Is this urgent?"}]),+ );+ let conditions = Arc::new(Conditions::default());+ let service = EventDispatchService::new(repo.clone(), access, executor.clone())+ .with_conditions(conditions.clone());++ assert_eq!(+ dispatch(&service, pending).await.unwrap(),+ DispatchResult::Finished(FinalizationResult::Finalized)+ );++ assert_eq!(conditions.calls.lock().unwrap().len(), 1);+ assert_eq!(executor.calls.lock().unwrap().len(), 1);+ assert!(repo.0.lock().unwrap().history.is_empty());+}++#[tokio::test]+async fn a_matching_filter_without_a_condition_skips_the_check() {+ for filters in [+ json!([{"events":["document.updated", "channel.created"]}]),+ json!([+ {"events":["document.updated"], "condition":"Is this urgent?"},+ {"events":["document.updated"]}+ ]),+ // Only a filter that matches the event contributes its condition.+ json!([+ {"events":["document.updated"]},+ {"events":["channel.created"], "condition":"Is this urgent?"}+ ]),+ ] {+ let (repo, access, executor, pending) = setup();+ conditional(&repo, filters.clone());+ let conditions = Arc::new(Conditions::default());+ let service = EventDispatchService::new(repo, access, executor.clone())+ .with_conditions(conditions.clone());++ assert_eq!(+ dispatch(&service, pending).await.unwrap(),+ DispatchResult::Finished(FinalizationResult::Finalized),+ "{filters}"+ );+ assert!(conditions.calls.lock().unwrap().is_empty(), "{filters}");+ assert_eq!(executor.calls.lock().unwrap().len(), 1);+ }+}++#[tokio::test]+async fn every_matching_condition_is_asked_once() {+ let (repo, access, executor, pending) = setup();+ conditional(+ &repo,+ json!([+ {"events":["document.updated"], "condition":"Is this urgent?"},+ {"events":["document.updated", "channel.created"], "condition":"Is this urgent?"},+ {"events":["document.updated"], "condition":"Is it about billing?"}+ ]),+ );+ let conditions = Arc::new(Conditions::default());+ let service =+ EventDispatchService::new(repo, access, executor).with_conditions(conditions.clone());++ dispatch(&service, pending).await.unwrap();++ let asked = conditions.calls.lock().unwrap();+ assert_eq!(+ asked[0]+ .iter()+ .map(|question| question.as_str())+ .collect::<Vec<_>>(),+ ["Is it about billing?", "Is this urgent?"]+ );+}++#[tokio::test]+async fn unavailable_condition_retries_within_the_window_then_skips() {+ let (repo, access, executor, mut pending) = setup();+ conditional(+ &repo,+ json!([{"events":["document.updated"], "condition":"Is this urgent?"}]),+ );+ let conditions = Arc::new(Conditions::default());+ conditions.verdicts.lock().unwrap().extend([+ Err(ConditionError::Transient(rootcause::report!("jev down"))),+ Err(ConditionError::Transient(rootcause::report!("jev down"))),+ ]);+ let service = EventDispatchService::new(repo.clone(), access, executor.clone())+ .with_conditions(conditions);++ assert!(dispatch(&service, pending.clone()).await.is_err());+ assert_eq!(repo.0.lock().unwrap().pending.len(), 1);+ assert!(repo.0.lock().unwrap().history.is_empty());++ pending.admitted_at = Utc::now() - CONDITION_RETRY_WINDOW - chrono::Duration::seconds(1);+ repo.0.lock().unwrap().pending[0].admitted_at = pending.admitted_at;+ assert_eq!(+ dispatch(&service, pending).await.unwrap(),+ DispatchResult::Cancelled(CancellationReason::ConditionUnavailable)+ );+ assert!(executor.calls.lock().unwrap().is_empty());+ assert_eq!(skipped_condition(&repo), json!({"status": "unavailable"}));+ assert!(!repo.0.lock().unwrap().history[0].is_success);+}++#[tokio::test]+async fn rejected_or_unconfigured_conditions_skip_immediately() {+ for configured in [true, false] {+ let (repo, access, executor, pending) = setup();+ conditional(+ &repo,+ json!([{"events":["document.updated"], "condition":"Is this urgent?"}]),+ );+ let result = if configured {+ let conditions = Arc::new(Conditions::default());+ conditions+ .verdicts+ .lock()+ .unwrap()+ .push_back(Err(ConditionError::Permanent(rootcause::report!(+ "rejected"+ ))));+ let service = EventDispatchService::new(repo.clone(), access, executor.clone())+ .with_conditions(conditions);+ dispatch(&service, pending).await+ } else {+ let service = EventDispatchService::new(repo.clone(), access, executor.clone());+ dispatch(&service, pending).await+ };++ assert_eq!(+ result.unwrap(),+ DispatchResult::Cancelled(CancellationReason::ConditionUnavailable),+ "configured: {configured}"+ );+ assert!(executor.calls.lock().unwrap().is_empty());+ assert_eq!(skipped_condition(&repo), json!({"status": "unavailable"}));+ }+}diff --git a/services/scheduled_action/src/domain/event_runs/test_support.rs b/services/scheduled_action/src/domain/event_runs/test_support.rsindex 3282bfcc8e..94de043c26 100644--- a/services/scheduled_action/src/domain/event_runs/test_support.rs+++ b/services/scheduled_action/src/domain/event_runs/test_support.rs@@ -1,6 +1,7 @@//! In-memory ports for domain policy tests. PostgreSQL locking/fencing has its//! own integration coverage in the repository adapter.+use super::condition::{ConditionError, ConditionVerdict, EventConditionCheck};use super::*;use crate::domain::{event_trigger::{ActionTrigger, EventPayload},@@ -131,6 +132,7 @@ pub struct State {pub pending: Vec<PendingEventRun>,pub started: Vec<(PendingEventRun, ClaimToken, DateTime<Utc>)>,pub finished: Vec<(EventRunKey, EventRunOutcome)>,+ pub history: Vec<ActionExecutionRecord>,pub pages: Vec<Option<Uuid>>,pub fail_page: Option<usize>,pub fail_claim: bool,@@ -333,6 +335,27 @@ impl EventRunRepository for Repo {}Ok(())}+ async fn skip_pending(+ &self,+ key: EventRunKey,+ revision: ConfigurationRevision,+ reason: CancellationReason,+ record: ActionExecutionRecord,+ ) -> Result<(), Report> {+ let mut state = self.0.lock().unwrap();+ if let Some(index) = state+ .pending+ .iter()+ .position(|p| p.key() == key && p.revision == revision)+ {+ state.pending.remove(index);+ state+ .finished+ .push((key, EventRunOutcome::Cancelled { reason }));+ state.history.push(record);+ }+ Ok(())+ }async fn reconcile(&self, now: DateTime<Utc>, limit: PageSize) -> Result<u16, Report> {let mut state = self.0.lock().unwrap();let mut count = 0;@@ -379,6 +402,31 @@ impl EventExecutor for Executor {}}+/// Scripted condition answers; met when the script runs out.+#[derive(Default)]+pub struct Conditions {+ pub verdicts: Mutex<VecDeque<Result<ConditionVerdict, ConditionError>>>,+ pub calls: Mutex<Vec<Vec<jev::domain::YesNoQuestion>>>,+}+impl EventConditionCheck for Conditions {+ async fn check(+ &self,+ owner: &MacroUserIdStr<'static>,+ run: &AuthorizedEventRun,+ conditions: &[jev::domain::YesNoQuestion],+ ) -> Result<ConditionVerdict, ConditionError> {+ assert!(run.access.authorizes(owner, &run.pending.event));+ self.calls.lock().unwrap().push(conditions.to_vec());+ self.verdicts+ .lock()+ .unwrap()+ .pop_front()+ .unwrap_or(Ok(ConditionVerdict::Met(+ jev::domain::Probability::new(1.0).unwrap(),+ )))+ }+}+pub fn setup() -> (Arc<Repo>, Arc<Access>, Arc<Executor>, PendingEventRun) {let config = configuration();let pending = pending(&config);diff --git a/services/scheduled_action/src/domain/event_trigger.rs b/services/scheduled_action/src/domain/event_trigger.rsindex 477c8ee7c3..051c4974fb 100644--- a/services/scheduled_action/src/domain/event_trigger.rs+++ b/services/scheduled_action/src/domain/event_trigger.rs@@ -10,6 +10,7 @@ use chrono_tz::Tz;use document_sub_type::DocumentSubType;use documents::domain::events::DocumentTopicEvent;use email::domain::events::EmailTopicEvent;+use jev::domain::YesNoQuestion;use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;use messages::domain::{@@ -253,7 +254,8 @@ pub enum FilterValidationError {IdCount,}-/// An event name AND an entity ID must match within the same filter.+/// An event name AND an entity ID must match within the same filter. A+/// condition further requires the event's content to answer it with yes.#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, ToSchema)]#[serde(try_from = "FilterInput")]pub struct EventFilter {@@ -261,6 +263,11 @@ pub struct EventFilter {#[serde(skip_serializing_if = "Option::is_none")]#[schema(value_type = Option<Vec<String>>)]ids: Option<Vec<Uuid>>,+ /// Yes/no question about the triggering content, e.g. "Is this email an+ /// invoice?". The routine runs only when the answer is yes.+ #[serde(skip_serializing_if = "Option::is_none")]+ #[schema(value_type = Option<String>, max_length = 500)]+ condition: Option<YesNoQuestion>,}#[derive(Deserialize)]@@ -269,13 +276,15 @@ struct FilterInput {events: Vec<EventName>,#[serde(default)]ids: Option<Vec<Uuid>>,+ #[serde(default)]+ condition: Option<YesNoQuestion>,}impl TryFrom<FilterInput> for EventFilter {type Error = FilterValidationError;fn try_from(input: FilterInput) -> Result<Self, Self::Error> {- Self::new(input.events, input.ids)+ Ok(Self::new(input.events, input.ids)?.with_condition(input.condition))}}@@ -299,7 +308,16 @@ impl EventFilter {ids.sort_unstable();ids.dedup();}- Ok(Self { events, ids })+ Ok(Self {+ events,+ ids,+ condition: None,+ })+ }++ pub fn with_condition(mut self, condition: Option<YesNoQuestion>) -> Self {+ self.condition = condition;+ self}pub fn events(&self) -> &[EventName] {@@ -311,6 +329,10 @@ impl EventFilter {self.ids.as_deref()}+ pub fn condition(&self) -> Option<&YesNoQuestion> {+ self.condition.as_ref()+ }+pub fn accepts(&self, name: EventName, entity_id: Uuid) -> bool {(self.events.contains(&name)|| name@@ -358,6 +380,42 @@ impl EventFilters {.iter().any(|filter| filter.accepts(event.event_name, event.entity_id))}++ pub fn has_conditions(&self) -> bool {+ self.0.iter().any(|filter| filter.condition.is_some())+ }++ /// What a matching event must satisfy before its run starts. A matching+ /// filter without a condition runs unconditionally; otherwise any one of+ /// the matching filters' conditions is enough.+ pub fn condition_requirement(&self, event: &EventReference) -> ConditionRequirement {+ let mut conditions = Vec::new();+ for filter in self+ .0+ .iter()+ .filter(|filter| filter.accepts(event.event_name, event.entity_id))+ {+ match &filter.condition {+ None => return ConditionRequirement::Unconditional,+ Some(condition) => conditions.push(condition.clone()),+ }+ }+ conditions.sort_unstable();+ conditions.dedup();+ if conditions.is_empty() {+ ConditionRequirement::Unconditional+ } else {+ ConditionRequirement::AnyOf(conditions)+ }+ }+}++/// Conditions an event must meet before a matching routine runs.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum ConditionRequirement {+ Unconditional,+ /// Distinct, nonempty; one yes is enough.+ AnyOf(Vec<YesNoQuestion>),}/// A verified RFC UUIDv7 whose embedded publication timestamp is representable.diff --git a/services/scheduled_action/src/domain/models.rs b/services/scheduled_action/src/domain/models.rsindex 1799d25965..594998896a 100644--- a/services/scheduled_action/src/domain/models.rs+++ b/services/scheduled_action/src/domain/models.rs@@ -255,6 +255,8 @@ pub enum ActionPolicyError {NoFutureFirings,#[error("event-trigger management is not enabled")]EventManagementDisabled,+ #[error("trigger conditions are not enabled")]+ ConditionsDisabled,#[error("scheduled action changed or is running; reload before updating")]UpdateConflict,}@@ -340,6 +342,9 @@ pub struct ExecutionResult {pub version: u8,pub resource: Option<ExecutionResource>,pub error: Option<String>,+ /// Present when an event trigger's condition stopped the run from starting.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub condition: Option<ConditionResult>,}impl ExecutionResult {@@ -348,6 +353,53 @@ impl ExecutionResult {version: 1,resource,error,+ condition: None,+ }+ }++ /// A run its trigger's condition kept from starting. No agent ran.+ pub fn skipped(condition: ConditionResult) -> Self {+ let error = match condition {+ ConditionResult::NotMet { .. } => None,+ ConditionResult::Unavailable => Some(CONDITION_UNAVAILABLE_ERROR.to_owned()),+ };+ Self {+ condition: Some(condition),+ ..Self::new(None, error)+ }+ }+}++const CONDITION_UNAVAILABLE_ERROR: &str =+ "The trigger's condition couldn't be checked, so this run was skipped.";++/// Why an event-triggered run was skipped before it started.+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, ToSchema)]+#[serde(tag = "status", rename_all = "snake_case")]+pub enum ConditionResult {+ /// The triggering content answered the condition with no.+ NotMet {+ /// The classifier's probability, from 0 to 1, that the answer was yes.+ probability: f32,+ },+ /// The condition could not be checked before the retry window closed.+ Unavailable,+}++impl ActionExecutionRecord {+ /// History for a run that was skipped at `at` without starting an agent.+ pub fn skipped(action_id: Uuid, at: DateTime<Utc>, condition: ConditionResult) -> Self {+ let is_success = matches!(condition, ConditionResult::NotMet { .. });+ Self {+ id: None,+ action_id,+ resource_id: None,+ start_time: at,+ end_time: at,+ is_success,+ result: serde_json::to_value(ExecutionResult::skipped(condition))+ .expect("execution results serialize"),+ created_at: at,}}}diff --git a/services/scheduled_action/src/domain/service.rs b/services/scheduled_action/src/domain/service.rsindex 75d3d8f7c1..d3c93b8c1e 100644--- a/services/scheduled_action/src/domain/service.rs+++ b/services/scheduled_action/src/domain/service.rs@@ -34,6 +34,7 @@ pub struct ScheduledActionServiceImpl<Rpo, Exe, Grants, Targets = ModelOnlyTargegrants: Arc<Grants>,dispatcher_tx: Sender<DispatchEvent>,event_management_enabled: bool,+ conditions_enabled: bool,targets: Targets,}@@ -51,6 +52,7 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants> ScheduledActionServiceImpl<Rpo, Exe,grants,dispatcher_tx,event_management_enabled: false,+ conditions_enabled: false,targets: ModelOnlyTargets,}}@@ -69,6 +71,7 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>grants: self.grants,dispatcher_tx: self.dispatcher_tx,event_management_enabled: self.event_management_enabled,+ conditions_enabled: self.conditions_enabled,targets,}}@@ -78,6 +81,12 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>self}+ /// Accept trigger conditions only when dispatch can check them.+ pub fn with_conditions_enabled(mut self, enabled: bool) -> Self {+ self.conditions_enabled = enabled;+ self+ }+async fn load_granted<T: RequiredPermission>(&self,receipt: &EntityAccessReceipt<T>,@@ -107,6 +116,17 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>Ok(())}+ fn check_conditions(&self, trigger: &ActionTrigger) -> Result<()> {+ if trigger+ .event_filters()+ .is_some_and(|filters| filters.has_conditions())+ && !self.conditions_enabled+ {+ return Err(ActionPolicyError::ConditionsDisabled.into());+ }+ Ok(())+ }+async fn replace_configuration(&self,mut action: ScheduledAction,@@ -127,6 +147,7 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>if !disable_only {self.check_event_management(&action.trigger)?;self.check_event_management(&input.trigger)?;+ self.check_conditions(&input.trigger)?;}let now = Utc::now();if claim_blocks_replacement(&action, now) && !disable_only {@@ -255,6 +276,7 @@ where})?;let input = ActionConfiguration::from(input);self.check_event_management(&input.trigger)?;+ self.check_conditions(&input.trigger)?;self.targets.validate_task(&input.task, owner_user).await?;let now = Utc::now();let next_run_at = next_run(&input.trigger)?;diff --git a/services/scheduled_action/src/domain/service/test.rs b/services/scheduled_action/src/domain/service/test.rsindex a3718bfd72..bac17b527c 100644--- a/services/scheduled_action/src/domain/service/test.rs+++ b/services/scheduled_action/src/domain/service/test.rs@@ -1267,3 +1267,92 @@ async fn editing_an_overdue_one_off_keeps_its_unconsumed_firing() {.unwrap();assert_eq!(updated.next_run_at, None);}++fn conditional_configuration() -> ActionConfiguration {+ ActionConfiguration {+ trigger: serde_json::from_value(json!({+ "type": "events",+ "filters": [{"events": ["email.message_received"], "condition": "Is this an invoice?"}]+ }))+ .unwrap(),+ ..configuration(true)+ }+}++#[tokio::test]+async fn conditions_are_rejected_unless_the_host_can_check_them() {+ let without = service(true);+ assert_policy(+ without+ .create_action(+ &user_principal(),+ CreateScheduledAction::Canonical(conditional_configuration()),+ )+ .await,+ ActionPolicyError::ConditionsDisabled,+ );+ let plain = without+ .create_action(+ &user_principal(),+ CreateScheduledAction::Canonical(configuration(true)),+ )+ .await+ .unwrap();+ assert_policy(+ without+ .update_action(+ edit_receipt(plain.id.unwrap()),+ update(conditional_configuration()),+ )+ .await,+ ActionPolicyError::ConditionsDisabled,+ );++ let with = TestService::new(+ without.repo.clone(),+ without.executor.clone(),+ without.dispatcher_tx.clone(),+ grants(&without.repo),+ )+ .with_event_management_enabled(true)+ .with_conditions_enabled(true);+ let created = with+ .create_action(+ &user_principal(),+ CreateScheduledAction::Canonical(conditional_configuration()),+ )+ .await+ .unwrap();+ let filters = created.trigger.event_filters().unwrap();+ assert_eq!(+ filters.as_slice()[0].condition().map(|c| c.as_str()),+ Some("Is this an invoice?")+ );+}++#[test]+fn conditions_are_trimmed_bounded_and_round_trip() {+ let filters: crate::domain::event_trigger::EventFilters = serde_json::from_value(json!([+ {"events": ["email.message_received"], "condition": " Is this urgent? "}+ ]))+ .unwrap();+ assert_eq!(+ serde_json::to_value(&filters).unwrap(),+ json!([{"events": ["email.message_received"], "condition": "Is this urgent?"}])+ );+ for condition in [json!(""), json!(" "), json!("x".repeat(501)), json!(3)] {+ assert!(+ serde_json::from_value::<crate::domain::event_trigger::EventFilters>(json!([+ {"events": ["email.message_received"], "condition": condition}+ ]))+ .is_err(),+ "{condition}"+ );+ }+ let unconditional: crate::domain::event_trigger::EventFilters =+ serde_json::from_value(json!([{"events": ["document.created"]}])).unwrap();+ assert_eq!(+ serde_json::to_value(&unconditional).unwrap(),+ json!([{"events": ["document.created"]}])+ );+}diff --git a/services/scheduled_action/src/inbound/axum_router.rs b/services/scheduled_action/src/inbound/axum_router.rsindex ae6f27a0cb..157dea5056 100644--- a/services/scheduled_action/src/inbound/axum_router.rs+++ b/services/scheduled_action/src/inbound/axum_router.rs@@ -482,9 +482,9 @@ impl IntoResponse for ScheduledActionApiError {let status = match policy {ActionPolicyError::NotFound => StatusCode::NOT_FOUND,ActionPolicyError::UpdateConflict => StatusCode::CONFLICT,- ActionPolicyError::NoFutureFirings | ActionPolicyError::EventManagementDisabled => {- StatusCode::BAD_REQUEST- }+ ActionPolicyError::NoFutureFirings+ | ActionPolicyError::EventManagementDisabled+ | ActionPolicyError::ConditionsDisabled => StatusCode::BAD_REQUEST,};return (status, policy.to_string()).into_response();}diff --git a/services/scheduled_action/src/inbound/event_run_worker.rs b/services/scheduled_action/src/inbound/event_run_worker.rsindex 89d1306475..3becc3539d 100644--- a/services/scheduled_action/src/inbound/event_run_worker.rs+++ b/services/scheduled_action/src/inbound/event_run_worker.rs@@ -1,12 +1,16 @@//! Bounded continuous event dispatch. Shutdown signals active executors; the//! lifecycle drains the worker, then tracked executions and terminal bookkeeping.-use std::{sync::Arc, time::Duration};+use std::{+ collections::HashSet,+ sync::{Arc, Mutex},+ time::Duration,+};use tokio::sync::Semaphore;use tokio_util::{sync::CancellationToken, task::TaskTracker};-use crate::domain::event_runs::{PageSize, dispatch::EventRunDispatch};+use crate::domain::event_runs::{EventRunKey, PageSize, dispatch::EventRunDispatch};#[cfg(test)]mod test;@@ -33,6 +37,9 @@ async fn run() {let service = Arc::new(service);let permits = Arc::new(Semaphore::new(usize::from(limit.get())));+ // A run stays pending while its trigger condition is checked, so the next+ // poll can return it again. Never dispatch the same run twice at once.+ let in_flight = Arc::new(Mutex::new(HashSet::new()));loop {if shutdown.is_cancelled() {return;@@ -48,6 +55,9 @@ async fn run(match service.pending(page).await {Ok(pending) => {for pending in pending {+ let Some(claim) = InFlight::begin(&in_flight, pending.key()) else {+ continue;+ };let Ok(permit) = permits.clone().try_acquire_owned() else {break;};@@ -55,6 +65,7 @@ async fn run(let shutdown = shutdown.clone();executions.spawn(async move {let _permit = permit;+ let _claim = claim;if shutdown.is_cancelled() {return;}@@ -82,3 +93,30 @@ async fn run(}}}++/// Marks a run as being dispatched by this worker until dropped.+struct InFlight {+ keys: Arc<Mutex<HashSet<EventRunKey>>>,+ key: EventRunKey,+}++impl InFlight {+ fn begin(keys: &Arc<Mutex<HashSet<EventRunKey>>>, key: EventRunKey) -> Option<Self> {+ keys.lock()+ .expect("in-flight set lock")+ .insert(key)+ .then(|| Self {+ keys: Arc::clone(keys),+ key,+ })+ }+}++impl Drop for InFlight {+ fn drop(&mut self) {+ self.keys+ .lock()+ .expect("in-flight set lock")+ .remove(&self.key);+ }+}diff --git a/services/scheduled_action/src/inbound/event_run_worker/test.rs b/services/scheduled_action/src/inbound/event_run_worker/test.rsindex 1947cce137..763c0c3c1c 100644--- a/services/scheduled_action/src/inbound/event_run_worker/test.rs+++ b/services/scheduled_action/src/inbound/event_run_worker/test.rs@@ -216,3 +216,63 @@ async fn shutdown_signals_active_runs_and_awaits_completion_without_claiming_morassert_eq!(service.state.pending.lock().unwrap().len(), 23);assert!(executions.is_empty());}++/// Like the real queue, keeps returning a run until dispatch finishes it.+struct Requeueing {+ run: PendingEventRun,+ started: AtomicUsize,+ finish: tokio::sync::Notify,+ done: std::sync::atomic::AtomicBool,+}+impl EventRunDispatch for Arc<Requeueing> {+ async fn pending(&self, _: PageSize) -> Result<Vec<PendingEventRun>, Report> {+ Ok(if self.done.load(Ordering::SeqCst) {+ Vec::new()+ } else {+ vec![self.run.clone()]+ })+ }+ async fn reconcile(&self, _: PageSize) -> Result<u16, Report> {+ Ok(0)+ }+ async fn dispatch(+ &self,+ _: PendingEventRun,+ _: impl Future<Output = ()> + Send,+ ) -> Result<DispatchResult, Report> {+ self.started.fetch_add(1, Ordering::SeqCst);+ self.finish.notified().await;+ self.done.store(true, Ordering::SeqCst);+ Ok(DispatchResult::NotStarted)+ }+}++#[tokio::test]+async fn a_run_still_pending_during_dispatch_is_not_dispatched_again() {+ let queue = Arc::new(Requeueing {+ run: service(1, false).state.pending.lock().unwrap()[0].clone(),+ started: AtomicUsize::new(0),+ finish: tokio::sync::Notify::new(),+ done: Default::default(),+ });+ let shutdown = CancellationToken::new();+ let executions = TaskTracker::new();+ let worker = tokio::spawn(run(+ Arc::clone(&queue),+ shutdown.clone(),+ executions.clone(),+ page_size(),+ Duration::from_millis(1),+ ));+ wait_until(|| queue.started.load(Ordering::SeqCst) == 1).await;+ // Many polls return the same pending run while it is in flight.+ tokio::time::sleep(Duration::from_millis(50)).await;+ assert_eq!(queue.started.load(Ordering::SeqCst), 1);+ queue.finish.notify_waiters();+ wait_until(|| queue.done.load(Ordering::SeqCst)).await;+ shutdown.cancel();+ worker.await.unwrap();+ executions.close();+ executions.wait().await;+ assert_eq!(queue.started.load(Ordering::SeqCst), 1);+}diff --git a/services/scheduled_action/src/outbound.rs b/services/scheduled_action/src/outbound.rsindex d318615475..e520ac6f0d 100644--- a/services/scheduled_action/src/outbound.rs+++ b/services/scheduled_action/src/outbound.rs@@ -1,6 +1,7 @@pub mod agent_session_client;pub mod conn_gateway_live_updates;pub mod event_access;+pub mod event_content;pub mod inprocess_executor;pub mod pg_event_run_repo;pub mod pg_polling_dispatcher;diff --git a/services/scheduled_action/src/outbound/event_content.rs b/services/scheduled_action/src/outbound/event_content.rsnew file mode 100644index 0000000000..b8330c3418--- /dev/null+++ b/services/scheduled_action/src/outbound/event_content.rs@@ -0,0 +1,339 @@+//! Read a triggering event's content through each owning domain, as the+//! routine owner, and describe it as JSON for the condition classifier.+//!+//! Every read uses the run's access receipt or an id it covers. Nothing here+//! is logged: the content is the user's, and only the classifier sees it.++use channels::domain::{models::ChannelType, ports::ChannelService};+use documents::domain::ports::DocumentRepo;+use email::domain::{+ models::{ContactInfo, ParsedMessage},+ ports::EmailContentService,+};+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel, ViewOnly};+use lexical_client::{LexicalClient, parse_markdown::MarkdownTarget};+use macro_user_id::user_id::MacroUserIdStr;+use macro_uuid::Uuid;+use mention_utils::parse::{ParsedXmlText, PlainTextFormatter, XmlFormatter};+use messages::domain::{+ api::MessageReader, models::Message, ports::MessageError, service::MessageView,+};+use model::document::DocumentBasic;+use models_properties::service::{+ property_option::PropertyOptionValue, property_value::PropertyValue,+};+use properties::{EntityPropertyInfo, PropertiesService};+use rootcause::{Report, compat::IntoRootcause};+use serde_json::{Map, Value, json};++use crate::domain::{+ event_runs::{AuthorizedEventRun, EventAccessCapability, condition::EventContentReader},+ event_trigger::{EventName, EventReference},+};++#[cfg(test)]+mod test;++/// Longest text passed on per field, in characters. Jev reads up to 32k+/// tokens of state; a few fields at this size stay well inside it.+const MAX_TEXT_CHARS: usize = 8_000;+/// Messages per thread page searched for the triggering email, newest first.+const EMAIL_PAGE: i64 = 20;+const MARKDOWN_FILE_TYPE: &str = "md";++pub struct EventContentAdapter<E, M, C, D, P> {+ email: E,+ messages: M,+ channels: C,+ documents: D,+ properties: P,+ markdown: LexicalClient,+}++impl<E, M, C, D, P> EventContentAdapter<E, M, C, D, P> {+ pub fn new(+ email: E,+ messages: M,+ channels: C,+ documents: D,+ properties: P,+ markdown: LexicalClient,+ ) -> Self {+ Self {+ email,+ messages,+ channels,+ documents,+ properties,+ markdown,+ }+ }+}++impl<E, M, C, D, P> EventContentReader for EventContentAdapter<E, M, C, D, P>+where+ E: EmailContentService,+ M: MessageReader,+ C: ChannelService,+ D: DocumentRepo,+ P: PropertiesService,+{+ async fn read(+ &self,+ owner: &MacroUserIdStr<'static>,+ run: &AuthorizedEventRun,+ ) -> Result<Value, Report> {+ let event = &run.pending.event;+ let content = match &run.access {+ EventAccessCapability::EmailThread(receipt) => {+ json!({ "email": self.email(receipt.clone(), event).await? })+ }+ EventAccessCapability::Channel(receipt) => {+ self.channel(owner, receipt.clone(), event).await?+ }+ EventAccessCapability::Document(receipt) => {+ json!({ "item": self.document(receipt, event).await? })+ }+ };+ Ok(envelope(owner, event, content))+ }+}++impl<E, M, C, D, P> EventContentAdapter<E, M, C, D, P>+where+ E: EmailContentService,+ M: MessageReader,+ C: ChannelService,+ D: DocumentRepo,+ P: PropertiesService,+{+ async fn email(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ event: &EventReference,+ ) -> Result<Value, Report> {+ let messages = self+ .get_messages_parsed(receipt, 0, EMAIL_PAGE)+ .await+ .map_err(|error| Report::new(error).into_dynamic())?+ .unwrap_or_default();+ Ok(messages+ .iter()+ .find(|message| Some(message.db_id) == event.message_id())+ .map_or_else(+ || unavailable("the email is no longer available"),+ email_json,+ ))+ }++ async fn channel(+ &self,+ owner: &MacroUserIdStr<'static>,+ receipt: EntityAccessReceipt<ViewOnly>,+ event: &EventReference,+ ) -> Result<Value, Report> {+ let channel = self+ .channels+ .get_channel_metadata(event.entity_id(), owner.clone())+ .await+ .map_err(|error| Report::new(error).into_dynamic())?;+ let mut content = json!({+ "channel": {+ "name": channel.channel_name,+ "type": channel_type(channel.channel_type),+ }+ });+ let Some(message_id) = event.message_id() else {+ return Ok(content);+ };+ let access = receipt+ .try_into_requirement::<MessageView>()+ .map_err(|error| Report::new(error).into_dynamic())?;+ let Some(message) = self.message(access.clone(), message_id).await? else {+ content["message"] = unavailable("the message is no longer available");+ return Ok(content);+ };+ if let Some(root) = message.thread_id.filter(|root| *root != message.id)+ && let Some(parent) = self.message(access, root).await?+ {+ content["thread_parent"] = message_json(&parent);+ }+ content["message"] = message_json(&message);+ Ok(content)+ }++ /// None when the message, or the thread it was in, has been deleted.+ async fn message(+ &self,+ access: EntityAccessReceipt<MessageView>,+ id: Uuid,+ ) -> Result<Option<Message>, Report> {+ match self.messages.get(access, id).await {+ Ok(message) if message.deleted_at.is_none() => Ok(Some(message)),+ Ok(_) | Err(MessageError::NotFound) => Ok(None),+ Err(error) => Err(Report::new(error).into_dynamic()),+ }+ }++ async fn document(+ &self,+ receipt: &EntityAccessReceipt<ViewAccessLevel>,+ event: &EventReference,+ ) -> Result<Value, Report> {+ let id = event.entity_id().to_string();+ let document = self+ .documents+ .get_basic_document(&id)+ .await+ .map_err(|error| Into::<anyhow::Error>::into(error).into_rootcause())?;+ if document.deleted_at.is_some() || event.event_name() == EventName::DocumentDeleted {+ return Ok(document_json(&document, &[], None));+ }+ let properties = self+ .properties+ .get_entity_properties(receipt)+ .await+ .map_err(|error| Report::new(error).into_dynamic())?;+ // Lexical renders only Macro's own documents; tasks are among them.+ // The body is an excerpt: without it, the name and properties remain.+ let markdown = if document.file_type.as_deref() == Some(MARKDOWN_FILE_TYPE) {+ self.markdown+ .get_markdown(&id, MarkdownTarget::External)+ .await+ .inspect_err(|error| {+ tracing::warn!(error = ?error, "document body unavailable for condition");+ })+ .ok()+ } else {+ None+ };+ Ok(document_json(&document, &properties, markdown.as_deref()))+ }+}++/// What every condition can rely on: what happened, when, and to whom.+fn envelope(owner: &MacroUserIdStr<'static>, event: &EventReference, content: Value) -> Value {+ let mut value = json!({+ "event": event.event_name().as_str(),+ "occurred_at": event.published_at(),+ "routine_owner": owner.email_str(),+ });+ if let (Value::Object(target), Value::Object(content)) = (&mut value, content) {+ target.extend(content);+ }+ value+}++fn unavailable(note: &str) -> Value {+ json!({ "unavailable": note })+}++fn truncate(text: &str) -> String {+ match text.char_indices().nth(MAX_TEXT_CHARS) {+ Some((end, _)) => format!("{}…", &text[..end]),+ None => text.to_owned(),+ }+}++fn contact(contact: &ContactInfo) -> Value {+ json!({ "name": contact.name, "email": contact.email })+}++fn email_json(message: &ParsedMessage) -> Value {+ let body = message+ .body_parsed+ .as_deref()+ .or(message.body_text.as_deref())+ .or(message.snippet.as_deref())+ .map(truncate);+ json!({+ "subject": message.subject,+ "from": message.from.as_ref().map(contact),+ "to": message.to.iter().map(contact).collect::<Vec<_>>(),+ "cc": message.cc.iter().map(contact).collect::<Vec<_>>(),+ "received_at": message.internal_date_ts.or(message.sent_at),+ "labels": message.labels.iter().map(|label| &label.name).collect::<Vec<_>>(),+ "has_attachments": message.has_attachments,+ "body": body,+ })+}++fn channel_type(channel_type: ChannelType) -> &'static str {+ match channel_type {+ ChannelType::Public => "public",+ ChannelType::Private => "private",+ ChannelType::DirectMessage => "direct_message",+ ChannelType::Team => "team",+ }+}++fn message_json(message: &Message) -> Value {+ let sender = message+ .imported_author+ .as_ref()+ .map(|author| author.name.clone())+ .or_else(|| message.bot_profile.as_ref().map(|bot| bot.name.clone()))+ .or_else(|| {+ message+ .sender_id+ .as_user()+ .map(|user| user.email_str().to_owned())+ });+ let text = match ParsedXmlText::parse(&message.content) {+ Ok(parsed) => PlainTextFormatter::format_xml_text(parsed).0,+ Err(_) => message.content.clone(),+ };+ json!({+ "sender": sender,+ "sent_at": message.created_at,+ "edited": message.edited_at.is_some(),+ "attachments": message.attachments.len(),+ "text": truncate(&text),+ })+}++fn document_json(+ document: &DocumentBasic,+ properties: &[EntityPropertyInfo],+ markdown: Option<&str>,+) -> Value {+ let kind = match document.sub_type {+ Some(document_sub_type::DocumentSubType::Task) => "task",+ _ => "document",+ };+ let properties: Map<String, Value> = properties+ .iter()+ .filter_map(|property| {+ property_value(property).map(|value| (property.display_name.clone(), value))+ })+ .collect();+ json!({+ "kind": kind,+ "name": document.document_name,+ "file_type": document.file_type,+ "deleted": document.deleted_at.is_some(),+ "properties": properties,+ "content": markdown.map(truncate),+ })+}++/// A property's value as people read it: option labels rather than ids.+fn property_value(property: &EntityPropertyInfo) -> Option<Value> {+ match property.value.as_ref()? {+ PropertyValue::SelectOption(ids) => {+ let labels: Vec<Value> = ids+ .iter()+ .filter_map(|id| property.options.iter().find(|option| option.id == *id))+ .map(|option| match &option.value {+ PropertyOptionValue::String(text) => json!(text),+ PropertyOptionValue::Number(number) => json!(number),+ })+ .collect();+ (!labels.is_empty()).then(|| Value::Array(labels))+ }+ value => serde_json::to_value(value)+ .ok()+ .map(|value| value.get("value").cloned().unwrap_or(value)),+ }+}diff --git a/services/scheduled_action/src/outbound/event_content/test.rs b/services/scheduled_action/src/outbound/event_content/test.rsnew file mode 100644index 0000000000..0495cf24e9--- /dev/null+++ b/services/scheduled_action/src/outbound/event_content/test.rs@@ -0,0 +1,235 @@+use chrono::{TimeZone, Utc};+use document_sub_type::DocumentSubType;+use email::domain::models::ParsedLabel;+use messages::domain::models::{BotSenderProfile, MessageParent};+use model_owner::Owner;+use models_properties::{DataType, PropertyOwner};+use properties::PropertyOptionInfo;++use super::*;++fn owner() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()+}++fn event(name: &str, message_id: Option<Uuid>) -> EventReference {+ serde_json::from_value(json!({+ "event_id": macro_uuid::generate_uuid_v7(),+ "event_name": name,+ "entity_id": macro_uuid::generate_uuid_v7(),+ "message_id": message_id,+ }))+ .unwrap()+}++fn email() -> ParsedMessage {+ let at = Utc.with_ymd_and_hms(2026, 10, 5, 9, 30, 0).unwrap();+ ParsedMessage {+ db_id: Uuid::nil(),+ link_id: Uuid::nil(),+ thread_db_id: Uuid::nil(),+ subject: Some("Invoice #42".into()),+ snippet: Some("Please find attached".into()),+ from: Some(ContactInfo {+ email: "[email protected]".into(),+ name: Some("Vendor Billing".into()),+ photo_url: Some("https://example.com/p.png".into()),+ }),+ to: vec![ContactInfo {+ email: "[email protected]".into(),+ name: None,+ photo_url: None,+ }],+ cc: Vec::new(),+ bcc: vec![ContactInfo {+ email: "[email protected]".into(),+ name: None,+ photo_url: None,+ }],+ labels: vec![ParsedLabel {+ provider_id: "INBOX".into(),+ name: "Inbox".into(),+ }],+ body_parsed: Some("Your invoice for October is $420.".into()),+ body_text: Some("full text with quoted replies".into()),+ body_html_sanitized: None,+ body_macro: None,+ body_replyless: None,+ internal_date_ts: Some(at),+ sent_at: None,+ is_read: false,+ is_starred: false,+ is_sent: false,+ is_draft: false,+ has_attachments: true,+ created_at: at,+ updated_at: at,+ }+}++#[test]+fn emails_carry_headers_and_the_reply_free_body_but_not_bcc() {+ assert_eq!(+ email_json(&email()),+ json!({+ "subject": "Invoice #42",+ "from": {"name": "Vendor Billing", "email": "[email protected]"},+ "to": [{"name": null, "email": "[email protected]"}],+ "cc": [],+ "received_at": "2026-10-05T09:30:00Z",+ "labels": ["Inbox"],+ "has_attachments": true,+ "body": "Your invoice for October is $420.",+ })+ );+ let mut snippet_only = email();+ snippet_only.body_parsed = None;+ snippet_only.body_text = None;+ assert_eq!(email_json(&snippet_only)["body"], "Please find attached");+}++#[test]+fn envelope_names_the_event_and_the_owner() {+ let event = event("email.message_received", Some(Uuid::nil()));+ let value = envelope(&owner(), &event, json!({"email": {"subject": "Hi"}}));+ assert_eq!(value["event"], "email.message_received");+ assert_eq!(value["routine_owner"], "[email protected]");+ assert_eq!(value["email"], json!({"subject": "Hi"}));+ assert_eq!(+ value["occurred_at"],+ serde_json::to_value(event.published_at()).unwrap()+ );+}++#[test]+fn long_text_is_cut_on_a_character_boundary() {+ assert_eq!(truncate("short"), "short");+ let long = "é".repeat(MAX_TEXT_CHARS + 10);+ let cut = truncate(&long);+ assert_eq!(cut.chars().count(), MAX_TEXT_CHARS + 1);+ assert!(cut.ends_with('…'));+}++fn message(content: &str) -> Message {+ let at = Utc.with_ymd_and_hms(2026, 10, 5, 9, 30, 0).unwrap();+ Message {+ id: Uuid::nil(),+ parent: MessageParent::Channel(Uuid::nil()),+ thread_id: None,+ sender_id: "macro|[email protected]".to_owned().try_into().unwrap(),+ imported_author: None,+ bot_profile: None,+ mentions: Vec::new(),+ triggered_by: None,+ content: content.into(),+ created_at: at,+ updated_at: at,+ edited_at: None,+ deleted_at: None,+ attachments: Vec::new(),+ reactions: Vec::new(),+ }+}++#[test]+fn channel_messages_are_plain_text_from_their_sender() {+ let value = message_json(&message("Can someone review the Q3 plan?"));+ assert_eq!(value["sender"], "[email protected]");+ assert_eq!(value["text"], "Can someone review the Q3 plan?");+ assert_eq!(value["edited"], false);++ let mut bot = message("Deploy finished");+ bot.bot_profile = Some(BotSenderProfile {+ name: "CI".into(),+ avatar_url: None,+ });+ assert_eq!(message_json(&bot)["sender"], "CI");+}++fn task() -> DocumentBasic {+ DocumentBasic {+ document_id: Uuid::nil().to_string(),+ document_name: "Login page crashes on Safari".into(),+ owner: Owner::User(owner()),+ file_type: Some("md".into()),+ sub_type: Some(DocumentSubType::Task),+ branched_from_id: None,+ branched_from_version_id: None,+ document_family_id: None,+ project_id: None,+ deleted_at: None,+ }+}++fn select(name: &str, options: &[&str], selected: usize) -> EntityPropertyInfo {+ let options: Vec<_> = options+ .iter()+ .enumerate()+ .map(|(index, label)| PropertyOptionInfo {+ id: macro_uuid::generate_uuid_v7(),+ display_order: index as i32,+ value: PropertyOptionValue::String((*label).into()),+ })+ .collect();+ let value = options+ .get(selected)+ .map(|option| PropertyValue::SelectOption(vec![option.id]));+ EntityPropertyInfo {+ property_definition_id: macro_uuid::generate_uuid_v7(),+ owner: PropertyOwner::System,+ display_name: name.into(),+ data_type: DataType::SelectString,+ is_multi_select: false,+ is_system: true,+ value,+ options,+ }+}++#[test]+fn tasks_show_option_labels_and_skip_unset_properties() {+ let mut unset = select("Assignee", &["A"], 0);+ unset.value = None;+ let mut due = select("Due", &[], 0);+ due.data_type = DataType::Date;+ due.value = Some(PropertyValue::Date(+ Utc.with_ymd_and_hms(2026, 10, 9, 0, 0, 0).unwrap(),+ ));+ let properties = [+ select("Status", &["Todo", "In progress", "Done"], 1),+ select("Priority", &["Low", "High"], 1),+ unset,+ due,+ ];++ assert_eq!(+ document_json(+ &task(),+ &properties,+ Some("Steps: open login on Safari 17.")+ ),+ json!({+ "kind": "task",+ "name": "Login page crashes on Safari",+ "file_type": "md",+ "deleted": false,+ "properties": {+ "Status": ["In progress"],+ "Priority": ["High"],+ "Due": "2026-10-09T00:00:00Z",+ },+ "content": "Steps: open login on Safari 17.",+ })+ );+}++#[test]+fn deleted_documents_say_so_without_content() {+ let mut document = task();+ document.sub_type = None;+ document.deleted_at = Some(Utc::now());+ let value = document_json(&document, &[], None);+ assert_eq!(value["kind"], "document");+ assert_eq!(value["deleted"], true);+ assert_eq!(value["content"], Value::Null);+}diff --git a/services/scheduled_action/src/outbound/pg_event_run_repo.rs b/services/scheduled_action/src/outbound/pg_event_run_repo.rsindex fcdc6924e3..fe1a802416 100644--- a/services/scheduled_action/src/outbound/pg_event_run_repo.rs+++ b/services/scheduled_action/src/outbound/pg_event_run_repo.rs@@ -16,7 +16,7 @@ use crate::domain::event_runs::{EventRunRepository, FinalizationResult, FinalizeEventRun, PageSize, PendingEventRun,};use crate::domain::event_trigger::{ActionTrigger, EventReference};-use crate::domain::models::{MAX_ACTION_TIME, ScheduledAction};+use crate::domain::models::{ActionExecutionRecord, MAX_ACTION_TIME, ScheduledAction};#[cfg(test)]mod test;@@ -501,6 +501,73 @@ impl EventRunRepository for PgEventRunRepo {Ok(())}+ async fn skip_pending(+ &self,+ key: EventRunKey,+ revision: ConfigurationRevision,+ reason: CancellationReason,+ record: ActionExecutionRecord,+ ) -> Result<(), Report> {+ if record.action_id != key.action_id {+ bail!("execution record belongs to another action");+ }+ let mut tx = self.pool.begin().await?;+ sqlx::query_scalar!(+ "SELECT id FROM scheduled_action WHERE id = $1 FOR UPDATE",+ key.action_id,+ )+ .fetch_optional(&mut *tx)+ .await?;+ let skipped = sqlx::query_scalar!(+ r#"+ UPDATE scheduled_action_event_run SET state = 'finished', finished_at = now(), outcome = $4+ WHERE action_id = $1 AND event_id = $2 AND configuration_revision = $3 AND state = 'pending'+ RETURNING event_id+ "#,+ key.action_id,+ key.event_id.as_uuid(),+ revision.get(),+ serde_json::to_value(EventRunOutcome::Cancelled { reason })?,+ )+ .fetch_optional(&mut *tx)+ .await?;+ if skipped.is_none() {+ tx.rollback().await?;+ return Ok(());+ }+ let id = generate_uuid_v7();+ sqlx::query!(+ r#"+ INSERT INTO action_execution_record+ (id, action_id, resource_id, start_time, end_time, is_success, result, created_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)+ "#,+ id,+ key.action_id,+ record.resource_id,+ record.start_time,+ record.end_time,+ record.is_success,+ record.result,+ record.created_at,+ )+ .execute(&mut *tx)+ .await?;+ sqlx::query!(+ r#"+ UPDATE scheduled_action_event_run SET execution_record_id = $3+ WHERE action_id = $1 AND event_id = $2+ "#,+ key.action_id,+ key.event_id.as_uuid(),+ id,+ )+ .execute(&mut *tx)+ .await?;+ tx.commit().await?;+ Ok(())+ }+async fn reconcile(&self, now: DateTime<Utc>, limit: PageSize) -> Result<u16, Report> {let candidates = sqlx::query!(r#"diff --git a/services/scheduled_action/src/outbound/pg_event_run_repo/test.rs b/services/scheduled_action/src/outbound/pg_event_run_repo/test.rsindex a7b0b99ed4..b96e4b3ff7 100644--- a/services/scheduled_action/src/outbound/pg_event_run_repo/test.rs+++ b/services/scheduled_action/src/outbound/pg_event_run_repo/test.rs@@ -964,3 +964,113 @@ async fn property_changes_match_general_selectors_without_duplicate_runs(pool: P}assert_eq!(repo.pending_runs(page(100)).await.unwrap().len(), 2);}++fn skipped_record(action_id: Uuid) -> ActionExecutionRecord {+ ActionExecutionRecord::skipped(+ action_id,+ Utc::now(),+ crate::domain::models::ConditionResult::NotMet { probability: 0.25 },+ )+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn skipping_finishes_pending_run_and_links_its_history(pool: PgPool) {+ let (repo, id, event) = setup(&pool).await;+ admit(&repo, id, &event).await;+ let pending = repo.pending_runs(page(1)).await.unwrap().remove(0);++ repo.skip_pending(+ pending.key(),+ ConfigurationRevision::INITIAL,+ CancellationReason::ConditionNotMet,+ skipped_record(id),+ )+ .await+ .unwrap();++ let (state, outcome, record_id) = state(&pool, pending.key()).await;+ assert_eq!(state, "finished");+ assert_eq!(+ outcome,+ Some(json!({"type": "cancelled", "reason": "condition_not_met"}))+ );+ let record = sqlx::query!(+ "SELECT action_id, resource_id, is_success, result FROM action_execution_record WHERE id = $1",+ record_id.expect("skipped runs link their history"),+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(record.action_id, id);+ assert_eq!(record.resource_id, None);+ assert!(record.is_success);+ assert_eq!(+ record.result["condition"],+ json!({"status": "not_met", "probability": 0.25})+ );+ assert!(repo.pending_runs(page(1)).await.unwrap().is_empty());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn skipping_leaves_started_or_superseded_runs_without_history(pool: PgPool) {+ let (repo, id, event) = setup(&pool).await;+ admit(&repo, id, &event).await;+ let pending = repo.pending_runs(page(1)).await.unwrap().remove(0);+ let key = pending.key();++ repo.skip_pending(+ key,+ ConfigurationRevision::INITIAL.next().unwrap(),+ CancellationReason::ConditionNotMet,+ skipped_record(id),+ )+ .await+ .unwrap();+ assert_eq!(state(&pool, key).await.0, "pending");++ claim(&repo, pending).await.unwrap();+ repo.skip_pending(+ key,+ ConfigurationRevision::INITIAL,+ CancellationReason::ConditionNotMet,+ skipped_record(id),+ )+ .await+ .unwrap();++ assert_eq!(state(&pool, key).await.0, "started");+ let records = sqlx::query_scalar!(+ "SELECT COUNT(*) FROM action_execution_record WHERE action_id = $1",+ id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(records, Some(0));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn conditions_do_not_change_candidate_matching(pool: PgPool) {+ let id = action(+ &pool,+ json!([{"events": ["document.updated"], "condition": "Is this urgent?"}]),+ )+ .await;+ let repo = PgEventRunRepo::new(pool.clone());+ let event = new_event(generate_uuid_v7());++ let page = repo+ .candidate_actions(&event, None, page(10))+ .await+ .unwrap();++ assert_eq!(+ page.configurations+ .iter()+ .map(|configuration| configuration.action_id)+ .collect::<Vec<_>>(),+ [id]+ );+ assert!(page.configurations[0].filters.has_conditions());+ admit(&repo, id, &event).await;+}diff --git a/static_assets/schema.graphql b/static_assets/schema.graphqlindex 46e45123a6..de74fc8d8e 100644--- a/static_assets/schema.graphql+++ b/static_assets/schema.graphql@@ -4764,6 +4764,10 @@ type GraphqlScheduledActionEventFilter {Entity ids that can satisfy this filter. Null matches every id; an empty list matches nothing."""entityIds: [ID!]+ """+ Yes/no question the triggering content must answer with yes before the routine runs.+ """+ condition: String}"""