Metrics
A Metric is a single tracked number in a simulation — cash balance, EBITDA margin, customer satisfaction, whatever your simulation needs to move over time. Metrics are what triggers react to, what the player dashboard charts, and what a facilitator or an AI conversation can push up or down as the story unfolds.
There are three metric component types, and they share one config shape (BaseMetricComponentConfig in frontend/src/hooks/use-form-simulation-builder.ts) plus type-specific fields on top:
- Static Metric (
STATIC_METRIC) — a plain number that only changes when something explicitly changes it (a trigger action, a facilitator, an AI conversation outcome). - Time-Based Metric (
TIME_BASED_METRIC) — a number that grows or shrinks on its own, on a fixed clock (every minute/hour/day/week/month), independent of anything else happening in the simulation. - Formula Metric (
FORMULA_METRIC) — a read-only, derived number computed from other metrics and/or Data Resource columns via a formula. You never set it directly; it recalculates whenever its inputs change.
Shared fields
Every metric has:
id— a stable UUID. Formulas, triggers, and dependency graphs reference metrics by this id, not by name — renaming a metric in the builder never breaks anything that points at it.visibility—public(every participant sees it),team_only(only the owning team), orhidden(not shown to participants — used for intermediate/internal calculations, see Hidden calculation metrics below).displaySettings— controls how the number renders on the player dashboard (see Display settings).initialValue— the value the metric starts at when a simulation instance is created (Formula Metrics compute their own value instead, but can still be seeded viaoverrideInitialValue).
Static Metric
The simplest kind — a number that sits still until something changes it. Typical uses: starting cash, a headcount, a satisfaction score a facilitator adjusts by hand.
Static Metrics are changed by trigger actions:
| Action | What it does |
|---|---|
set_metric | Overwrites the value (can be a constant, or { source: 'metric_ref', metricId, property: 'current_value' } to copy another metric’s live value). |
increase_metric / decrease_metric | Adds/subtracts an amount, or applies it as a percentage of the current value (unit: 'percent'). |
multiply_metric | Multiplies by a factor. |
apply_percentage_change | Grows or shrinks by a percentage (direction: 'increase' | 'decrease'). |
reset_metric | Resets to initialValue. |
A metric that a Formula Metric depends on (see below) is protected: the engine rejects any action that tries to write to a metric id currently used as a formula input, with Cannot modify read-only formula metric '<id>'.
Time-Based Metric
Grows or shrinks automatically on a schedule, with no trigger needed. Configured with:
changeDirection—growthorshrink.growthType—fixed(add/subtractchangeValueeach tick) orpercentage(multiply by1 ± changeValue/100each tick).frequency—minute,hour,day,week,month, orcustom(paired withcustomFrequencyin minutes).changeValue— the amount or percentage applied on every tick.minimumValue/maximumValue(optional) — clamps applied after each tick, so a metric never drifts below a floor or above a ceiling (e.g. a satisfaction score staying within 0–100).
The backend’s timer service (backend/src/engine/timer-service.ts) schedules a recurring timer per Time-Based Metric for the life of the instance and applies the tick server-side — this keeps running even if no participant has the page open.
Formula Metric
A derived, read-only value recalculated from a formula (formulaAst) whenever any of its inputs change. Because it’s computed, it has no initialValue of its own (overrideInitialValue can still seed a starting value before the first real recalculation — see the engine section below) and can’t be targeted by set_metric/increase_metric/etc.
Writing a formula
In the builder, formulas are typed as text and parsed into a formulaAst tree (frontend/src/lib/metric-formula.ts, parseFormulaText):
[Metric Name]— reference another metric by name (resolved to its id).{Resource.Row.Column}— a single cell from a Data Resource.SUM({Resource.Column}),AVG(...),MIN(...),MAX(...),COUNT(...)— an aggregate over a whole column of a Data Resource.- Arithmetic:
+ - * / % ^, parentheses, and functionsSUM/AVG/MIN/MAX/ROUND/IF/COUNT/ABS/CEILING/FLOORfor combining metric values (as opposed to the data-resource aggregation functions above, which only take a{Resource.Column}argument).
Example: SUM({Dark Stores.net_profit}) / SUM({Dark Stores.sales_revenue}) — net profit across every row of a Data Resource, divided by revenue across the same rows.
Dependency rules (enforced on save)
The backend validator (backend/src/service/business/simulation-template-definition.ts) checks every Formula Metric’s formulaAst (not just its dependencies list — the AST is walked directly, so a stale reference the UI never recorded in dependencies is still caught):
- Every metric id and data-resource id referenced in the formula must exist as a component somewhere in the template. A dangling reference — most commonly caused by importing a template exported from a different instance, where a Data Resource was re-created with a new id — fails validation with
Formula Metric '<id>' formula references data resource '<id>', which does not exist.The builder’s JSON import flow now detects this automatically and offers a repair dialog to remap the missing id to an existing Data Resource before you save. - Scope access — a formula can only reference a metric or resource that’s attached at its own scope or an ancestor scope (task → subround → round → simulation). Referencing a sibling task’s metric fails with a “from an unrelated branch” error.
- No circular dependencies —
Adepending onBdepending onAis rejected both in the builder (buildMetricDependencyGraph/wouldCreateCircularDependencyinmetric-formula.ts) and at runtime (topologicalSortinbackend/src/engine/formula-engine.tsthrowsCircular dependency detected among formula metricsif one slips through).
How it’s computed at runtime
On every trigger fire (or simulation tick), the engine:
- Topologically sorts all Formula Metrics by their dependency graph (
topologicalSort), so a formula is only evaluated after everything it depends on. - Evaluates each one (
evaluateFormula) against the team’s current metric values and Data Resource rows, walking the AST node by node —constant,metric(looks up another metric’s current value),data_resource(a single cell),data_resource_aggregate(SUM/AVG/MIN/MAX/COUNT over a column),binary, andfunction. - Data Resource columns are parsed leniently (
parseNumericValue) — currency symbols, thousands separators, percent signs, and unit suffixes are stripped before parsing, so a column formatted as"₹1,20,000"or"10.2 hrs"still aggregates correctly instead of silently dropping the row. - Writes the new value into the team’s
runtime_state.metrics, and reports which formula metrics actually changed (a >0.001 delta) so downstream triggers keyed on “metric changed” only fire when something real happened.
This is a separate implementation from the builder’s own evaluateFormulaAst in frontend/src/lib/metric-formula.ts — that one only powers the live preview while editing a formula in the builder; it’s never used once a simulation is actually running.
Hidden calculation metrics
A common pattern in existing templates: a hidden Formula Metric does the raw calculation, and a public Static Metric mirrors its value for display, kept in sync by a set_metric action with { source: 'metric_ref', metricId: <formula metric id>, property: 'current_value' } on a simulation_started (or other) trigger. This is useful when you want participants to see a friendly, editable-looking number while the real computation stays internal — but it means the visible metric’s displaySettings won’t automatically match the formula’s semantics. If the formula computes a raw fraction (e.g. net_profit / revenue = 0.0223), the mirrored Static Metric needs its own correctly-scaled formula/format to display as a percentage — see below.
Display settings
displaySettings controls only rendering, never the stored value — the raw number is always what’s saved and evaluated. Rendering happens in formatMetricValue() (frontend/src/components/player/components/MetricCard.tsx, mirrored in frontend/src/components/dashboard/MetricsOverview.tsx):
format | Rendering | Notes |
|---|---|---|
number | Locale-formatted number (toLocaleString) with decimalPlaces digits. | Default. |
currency | Intl.NumberFormat currency, using currencyCode (e.g. INR, USD). | |
percentage | value.toFixed(decimalPlaces) + '%' | Does not multiply by 100. If the underlying value is a fraction (0.0223), it renders as "0.02%", not "2.23%" — the formula itself must produce the already-scaled number (... * 100) if you want the % sign to read naturally. |
custom_unit | The number followed by unitSymbol, with unitName as a label elsewhere in the UI. |
Watch decimalPlaces on small values. A metric holding a fraction or a small ratio with decimalPlaces: 0 rounds to "0" on screen — correct arithmetic, misleading display. This is the most common “why does my metric show 0/looks wrong” report; before assuming the formula or engine is broken, check whether the raw value is just too small for the configured decimal places (and, for percentages, whether it needs * 100 in the formula as above).
Tips
- Give every metric a clear, specific name —
formulaAstToText()and the builder’s dependency/broken-reference UIs display metrics by name, and a vague name like “Margin 2” makes formulas hard to audit later. - Keep Formula Metric inputs at the same scope or a shared ancestor scope; if you find yourself needing a metric from an unrelated branch, promote it (or a copy of it) to a shared parent scope instead.
- When mirroring a hidden Formula Metric into a visible Static Metric for display, double-check the two components’
displaySettingsagree on scale (fraction vs. percent) — the mirroring trigger copies the raw number verbatim, with no unit conversion. - Exporting a template to JSON and importing it into another instance can leave Formula Metrics pointing at Data Resource ids that no longer exist there; the import flow’s repair dialog handles this, but it’s worth re-checking formulas after any cross-instance import regardless.