Automation Engine
The AI Trade Execution & Automation Engine — a richer, event-driven workflow system built alongside (not replacing) the AI Platform milestone's simpler ai_automations/risk_automation_rules engine. Lives at src/lib/automation/, sibling to src/lib/ai/.
Why two automation systems exist
ai_automations (4 trigger types, 4 actions) and risk_automation_rules (5 risk triggers, pause/lock/reduce/notify) still work exactly as before at /dashboard/automations — nothing about them changed. This milestone needed 18 trigger types, 17 condition types with AND/OR logic, 14 action types, real scheduling, natural-language authoring, and safety controls (dry-run, confirmation mode, rollback) none of the original engine was built to hold. Rather than redesign the existing, working engine, the new automation_workflows system was built as a genuine superset, reusing the original engine's action-execution code underneath: ActionExecutor (action-engine.ts) calls RiskAutomationService directly for pause/resume/stop/reduce/increase-risk/notify — the exact same CopyEngine.pause()/resume()/stopCopying() calls, not reimplemented.
Architecture
src/lib/automation/
types.ts Trigger/Condition/Action/Schedule discriminated unions
market-sessions.ts Real FX session windows (Sydney/Tokyo/London/NY, UTC)
asset-classifier.ts Real heuristic symbol -> asset class
trigger-engine.ts Pure: evaluateTrigger() — 18 types
condition-engine.ts Pure: evaluateConditions() — 17 types, AND/OR
scheduler.ts Pure: resolveSchedule() — once/daily/weekly/monthly/market_session
safety/
loop-guard.ts Cooldown + per-pass action cap (infinite-loop prevention)
conflict-detector.ts Opposing-action warnings between workflows
dry-run.ts Human-readable "would execute" descriptions
action-engine.ts ActionExecutor — routes all 14 action types to real systems
webhook-action.ts Real outbound POST for the execute_webhook action
workflow-engine.ts WorkflowEngine — the orchestrator (see below)
workflow-parser.ts WorkflowParser — natural language -> validated draft
ai-decision-service.ts AIDecisionService — 5 decisions, each with confidence + explanation
template-library-service.ts 9 seeded templates + instantiate/save-as-template
rollback-service.ts Reverses the subset of actions that have a real inverse
execution-log-service.ts Writes workflow_runs/workflow_logs (the Execution Log)
context-builder.ts Assembles SharedEvaluationContext from real account/trade data
sync-bridge.ts evaluateSyncEvent() — the request-scoped event hook (see docs/EVENT_ENGINE.md)
queries.ts Workflow/run/log/decision/alert-rule CRUD (thin Supabase reads)WorkflowEngine — the orchestrator
For each active workflow in a batch:
1. Cooldown check (safety/loop-guard.ts) — skip if still within cooldownSeconds of the last trigger. 2. Schedule gate (scheduler.ts) — if the workflow has a schedule, skip unless resolveSchedule() says now is a valid run time. 3. Trigger evaluation (trigger-engine.ts) — pure function against a TriggerContext derived from the batch's shared context. 4. Condition evaluation (condition-engine.ts) — pure, AND/OR across the workflow's condition list. 5. Confirmation mode — if set and this isn't a manual run, the run is recorded pending_confirmation and the user is notified; actions never execute until they explicitly confirm. 6. Action cap (safety/loop-guard.ts's RunCapGuard) — a hard per-batch ceiling (default 10) on how many workflows may actually execute actions in one pass. 7. Actions — each action's delaySeconds is honored for real up to 30s (a request-scoped process can't hold a longer delay — see docs/EXECUTION_SAFETY.md); dry-run workflows log a description instead of calling ActionExecutor; every step is logged to workflow_logs.
Performance property, directly tested (tests/automation-workflow-engine.test.ts): the shared context (risk snapshot, journal metrics, prop-firm status, etc.) is fetched once per batch, not once per workflow — context-builder.ts is the one place per evaluation pass that touches Supabase for context.
Action Engine — what's real behind each of the 14 actions
| Action | Implementation |
|---|---|
pause_copying / resume_copying / stop_copying | CopyEngine.pause()/.resume()/.stopCopying() on every active copy relationship (or one specific copyRelationshipId) |
reduce_risk / increase_risk | Scales copy_relationships.risk_value, snapshotting the previous value for rollback |
close_positions | withLiveConnector() — a real broker connection, fetches live positions (ConnectorPosition.positionId, since the mirrored positions table stores no broker-side id), calls closeOrder() |
send_notification | Insert into notifications |
send_email | sendEmailAlert() (the parameterized Alert Center channel sender) |
generate_ai_report | JournalReportService.generateReport() |
trigger_ai_analysis | CoachingService.generateCoaching() |
enable_strategy / disable_strategy | == resume/pause copying — this schema has no separate "strategy" entity, documented rather than invented |
execute_webhook | Real outbound POST (webhook-action.ts) |
create_journal_entry | Insert into ai_insights (insight_type: 'journal_entry') |
Reused, not duplicated
AIProviderManager, AIPromptManager/PROMPT_DEFAULTS, AIRecommendationEngine, checkAIRateLimit, sanitizeUserInput, getRiskSnapshot, calculateRiskScore, detectOvertrading/ detectRevengeTrading, getPropFirmAccountStatus, JournalReportService, CoachingService, calculateJournalMetrics, logAuditEvent, checkFeatureAccess, withLiveConnector, KpiCard/StatusBadge/ PaginationControls/BarChart — every one of these is called directly, none reimplemented. See docs/AI_ARCHITECTURE.md for what each already provided.
Database
Additive only — automation_workflows, workflow_runs, workflow_logs, workflow_templates, ai_decisions, alert_rules, one nullable notifications.workflow_run_id column, one widened alert_events.alert_type check constraint. Full column list in supabase/migrations/20260807210000_automation_engine.sql.
UI
/dashboard/workflows (Overview/Workflows/History/Alert Center/AI Decisions tabs), /dashboard/workflows/new and /[id]/edit (the guided wizard — see docs/AI_WORKFLOWS.md), /admin/automation/* (Overview/ Templates/Analytics/Failures).