Skip to content
MSO CloudDocumentation

ADR 0057 — Alert workflows: Signals → Alert as a designable decision graph

On this page
  • Status: Accepted (2026-10-24). Amended 2026-11-02, 2026-11-23 and 2026-11-25.
  • Date: 2026-10-24
  • Owners: Platform / decision-intelligence (packages/alerts/src/workflow).
  • Related: ADR 0035 (Morning Brief per org type), ADR 0036 (detection operators), §65 (one predicate grammar), §117 (signal ledger), §136 (notification delivery), §79 (audience), §57/§58/§60d (planes).

Context#

A Morning Brief alert rule is one detection over one series with an optional gate. A finding that needs structure ("spend continued, results stopped; escalate when it repeats; stay quiet in the first week of a flight") cannot be stated as one rule, and its routing lives in code. An org admin needs to design that structure, see why a morning was quiet, and replay a past morning.

Decisions#

D1 — A workflow is a directed acyclic graph drawn on a canvas

Stored in the React Flow shape (nodes[{id, type, position, data}], edges[{id, source, sourceHandle, target}], schemaVersion: 1). Node kinds: trigger (one measure address + brand + optional cooldown), detect, condition, switch, and the terminals alert (severity, optional title) and silence (closed reason list). The graph hash is stableHash over a canonical projection without positions or labels, so a layout change is not a behaviour change.

D2 — No new language

detect evaluates one of the two existing detection vocabularies: a domain signal type (signal-types.ts, with its sufficiency floors) or a brief detection operator (signal-conditions.ts). condition and switch cases are §65 predicates evaluated by evaluatePredicate (strong Kleene). Every output port is explicit: fired | quiet | unknown, true | false | unknown, switch cases + unknown + default. An unknown is never folded into a false or a default branch.

D3 — Facts are a declared catalog

Predicate leaves read facts: a measure's latest and previous value, the calendar position from the series' own ICT label, the workflow's alert history from the ledger, and the magnitude of a detection already evaluated. Each fact is registered with a label and a unit; save-time validation refuses an unregistered one. A missing fact is unknown, never zero.

D4 — Plane isolation by construction

The trigger's measure address fixes the domain and plane; every series a node reads must be a measure of the same domain. eCom measures read agg_org_day through the metric value-column helper (NMV by the org's definition); a ratio is computed from its summed numerator and denominator.

D5 — One ledger

Each evaluation writes one signal_events row (type = 'workflow', binding_hash = graph hash, trace = the path taken with every fact as read). A silenced or cooled-down run is recorded with its reason. Workflow rows are excluded from signal_stats and from the binding path's history.

D6 — Runtime is the daily brief job, in the worker

processBriefingJob evaluates active workflows after the brief is generated, with the worker's ledger writer. An alert outcome writes alert_events and is delivered through the same path as a tenant-dataset rule (§136), deduplicated per rule and period, with the notification type workflow.alert_fired. Playbooks subscribed to the workflow's alert rule fire through the existing alert trigger. The 15-minute alert job and web paths never evaluate workflows.

D6a — Evaluation period

The trigger chooses a period: day, ISO week (Monday to Sunday) or calendar month, labelled in ICT. A day workflow judges the as-of day. A week or month workflow judges the newest period that has closed: it runs on the first morning after the close (Monday, the 1st) and retries on later mornings while that period's data is incomplete, recording insufficient and never alerting on a partial period. A day series rolls up to a week or month only for an additive level, and only when every day is present; a ratio, share or plan variance is judged at day grain only; a tenant-dataset measure is month only. Which periods a measure supports comes from the catalog, and validation refuses the rest. Ledger rows, alert deduplication, cooldown and history count periods of the workflow's own period.

D7 — Versions are immutable

Publishing writes a new alert_workflow_versions row and moves the head pointer in one transaction; the head owns its alert_rules row (enable, mute, snooze, per-person preferences). Versions are append-only.

D8 — The editor simulates before it publishes

Test run evaluates the draft over the last 14 days, 8 closed weeks or 6 closed months of real data (by the workflow's period) with one read per measure and no writes, seeded with the real alert history, and paints the path each step took.

Consequences#

  • Shipped rule packs keep running unchanged; any shipped rule compiles to an equivalent workflow (ruleToWorkflow, equivalence-tested), which seeds templates.
  • The decision engine reads the same trace, fact catalog and versions; a replay of any run is a pure function of the stored graph version and inputs.
  • Rollback: pause workflows; the migration is additive and nothing else depends on it.

Amendment 1 (2026-11-02) — the brief's alerts are the Alerts section#

Operator decision: every alert a brief or the bell shows is a rule the org can see, switch and draw. Plan and inventory: batches B0-B5.

D10 — The brief's alerts are the Alerts section

Every alert the Morning Brief shows is an alert_events row of an enabled, org-visible alert_rules row, filtered by the §79 audience fence and the reader's mute and snooze; the bullet's kind is the rule's slug. A detection that is not such a row never becomes a brief bullet. Facts (GMV and media headlines, domain statements, estimate context) are not alerts and stay.

D11 — Nothing runs until an admin configures it

No org ever configured an alert: the shipped default rules were authored by us, not chosen by a tenant (prod 2026-11-02: 0 alert audit rows, 0 mute/snooze states). So every org-visible rule no human configured is switched off, and the worker no longer creates org-visible rules. Platform rules stay on for the super-admin operations view only (§79). Alerts come from a template catalog grouped by data type, each method industry-cited or relative to the org's own baseline or target; an admin picks a template, and its workflow starts paused until enabled. The only defaults switched on are identity tests whose value is certain (spend with zero results, a results signal that stopped while spend continues, negative contribution margin, data that stopped arriving), and only for an org that has that data. A demo org (pinned clock) keeps its demonstration rules unchanged.

D12 — One evaluator per rule

A rule row owned by a non-archived workflow is evaluated only by the workflow runtime; the 15-minute job skips it. Rules the runtime cannot read (entity grain, intraday critical) stay operational in the 15-minute job and are listed in Alerts with an org on/off switch and a read-only drawing. Platform-audience rules are visible to super admins only (§79).

D13 — Workflows run before the brief

The daily brief job evaluates workflows, then writes the brief, for the same data-day. This replaces "after the brief is generated" in D6.

D14 — Seeded alerts keep their identity

An adopted rule keeps its notification type, link, mute states and playbook subscriptions; its bullet is rendered from the event's trace payload.

Rollback: pause the workflows (nothing fires) or archive them (the 15-minute job takes the rule back); the seed_key migration is additive; switched-off rules are switched back on per rule in Alerts.

Out of scope#

Migrating the shipped packs (superseded by D11: they become catalog templates, never auto-enabled); executing agents or playbooks from inside a workflow (the alert → playbook trigger is the hand-off); per-person routing inside a workflow.

Amendment 2 (2026-11-23) — the Alerts page shows what runs and every threshold is editable#

Operator: "I cannot see any alerts in use and cannot see how to configure them." Prod MSO Demo had 12 rules on, 0 workflows and 0 alert events ever, and nothing on the page said so.

D15 — Overview first

/settings/alerts opens on what the org runs: on/off counts, firings in the last 30 days and the last firing (from alert_events, under the audience and brand fences), then one row per workflow, rule and reminder with its condition and threshold in words, its cadence and its firing history. The template library and the reader's own mute/snooze are separate tabs (?tab=templates|mine); the mute tab lists the silenceable pack rules and every active workflow the reader can see, keyed by its alert rule, which the workflow runtime reads. A condition names its signal by the alerts or metric-catalogue label, never the slug.

D16 — The 15-minute rules read the thresholds stored on their row

evaluateDefaultRules takes its numbers from each enabled rule's condition (@yng/alerts/operational-thresholds): GMV floor/ceiling vs the 7-day baseline, return rate, contribution-margin floor, creator score, price-gap count. A missing or out-of-range value is the shipped default, so no org's behaviour changed until an admin edits it (alerts.setRuleThresholds, audited alert.rule.update). The save is refused as rule_changed when the stored values differ from the ones the editor opened with, and the UPDATE is predicated on the condition it merged into (updated_at cannot be the lock: a JS Date drops its microseconds). The stock-out cover and the brief-pack rules are tuned through D18.

D17 — A threshold edit publishes a version and keeps the on/off

The editor's Thresholds tab lists every detect, condition and switch node as one form, runs the D8 test run, and applies through publish({ keepStatus: true }): a new immutable version (D7) whose status is the one the workflow had. Creating from a template opens that tab. The tab edits operators and bounds only; which facts a step compares, how many, and switch cases stay on the canvas.

D18 — A brief rule is tuned by becoming the workflow that runs it

Outside a frozen demo org nothing evaluated the discussion and marketing rules: their class is workflow (D12), yet no workflow owned the rows, so the org switch changed a flag and nothing else (prod 2026-11-24: one such rule switched on, no workflow, no event). "Chỉnh ngưỡng", a click on a numbered step of the drawing, and switching the row on all call alertWorkflows.adoptRule: under an advisory lock it binds a workflow drawn by ruleToWorkflow to the org's existing rule row (no second row, so events, mute states and playbooks keep their key, D14), publishes v1 with the row's on/off, and opens its Thresholds tab. A second call returns the same workflow. The row then shows the workflow's active graph. A frozen demo org's inline brief pass skips rules a workflow runs or an admin switched off, so a rule never reports twice and the org switch means what it says; a rule with no row yet keeps running there, the one deliberate exception to D11, so a demo brief does not go quiet before anyone opened the page (configurePackRules). Market estimate rules are workflow-class too: their catalog series is one point per captured window, so their workflow judges the native series (day period) and the pack's "3 periods" stay 3 windows (workflowPeriodOfRule). The stock-out cover (5 days) becomes an editable 15-minute threshold (days_of_supply.coverDays).

Amendment 3 (2026-11-25) — lifecycle actions, lazily created rule rows, one link target#

D19 — A restore is a new version; a copy is a draft; "Chạy ngay" is a worker job

alertWorkflows.rollback publishes a NEW version whose graph equals an earlier one and sets the draft to it (D7: published versions stay immutable); the workflow keeps the on/off it had, an archived one refuses, and the audit row records the source version. clone inserts a paused draft copy with the same plane and measure and no version, so nothing runs until its owner publishes. runNow enqueues a durable briefing job (reason: workflow_run, one workflowId) for an active workflow; the worker evaluates only that workflow with the same evaluator and ledger key as the morning run (D5, D6), writes no brief and no brief-run row, and the web never evaluates (§66c/§133). A repeat dedupes on the ledger.

D20 — A pack rule has no row until an admin acts on it

Reading the catalog or the Alerts page inserts nothing. ensurePackRuleRow creates the rule row under its derived id on the first switch-on, threshold edit or adoptRule (D18); until then a member's mute and snooze are disabled ("Quy tắc chưa bật"). The earlier read-time insertion of disabled rows is gone. A dataset rule is edited in place (updateDatasetRule, same id), so mutes, fired events and playbook subscriptions keep their key (D14). Dataset rules of deleted brands are not listed.

D21 — A workflow alert links to the brief, not the editor

Every member in the audience is notified, so the notification and the resolved notice link to /briefing#alert-<event id>, which any recipient can read, instead of the admin-only run tab (workflowAlertHref). A day workflow judges the newest closed day, so its test-run window ends yesterday (workflow/period.ts).

D22 — Super-admin reach

/admin/orgs/[slug]/alerts (Rules) and /alerts/workflows (list and editor) render the same components as the organization's Settings pages with the admin route base, for an organization that runs a briefable plane; "Thông báo của tôi" is not shown there. Organization managers reach the flow list as the settings tab "Luồng cảnh báo".