@datarails-ai/dr-appspace-cli 0.12.61 → 0.12.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +1191 -234
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -13,7 +13,7 @@ import { fileURLToPath as fileURLToPath6 } from "url";
13
13
  // package.json
14
14
  var package_default = {
15
15
  name: "@datarails-ai/dr-appspace-cli",
16
- version: "0.12.61",
16
+ version: "0.12.63",
17
17
  description: "Datarails App Space CLI \u2014 build, try, push and publish App Space apps",
18
18
  type: "module",
19
19
  engines: {
@@ -57,7 +57,7 @@ var package_default = {
57
57
  };
58
58
 
59
59
  // src/buildInfo.ts
60
- var BUILD_TIME = "2026-11-01T20:35:20.518Z";
60
+ var BUILD_TIME = "2026-11-02T15:28:06.153Z";
61
61
  function formatBuildTime(iso) {
62
62
  if (iso === "") return "";
63
63
  const d = new Date(iso);
@@ -6159,7 +6159,8 @@ function metricsOf(pages) {
6159
6159
  const embedded = embeddedContractOf(page);
6160
6160
  if (embedded === null) continue;
6161
6161
  const metrics = embedded.data?.metrics;
6162
- return isPlainObject(metrics) ? { metrics } : {};
6162
+ const model = embedded.data?.model;
6163
+ return { ...isPlainObject(metrics) ? { metrics } : {}, ...isPlainObject(model) ? { model } : {} };
6163
6164
  }
6164
6165
  return {};
6165
6166
  }
@@ -6764,7 +6765,8 @@ function dataSection(app, manifest, spec, elements, describe7, problems) {
6764
6765
  // Only when there are any: a contract written before sources existed
6765
6766
  // reads back byte for byte as it always did.
6766
6767
  ...Object.keys(sources).length > 0 ? { sources } : {},
6767
- // The same for declared metrics, which only an app's pages carry.
6768
+ // The same for declared metrics and the planning model, which only an
6769
+ // app's pages carry.
6768
6770
  ...isApp ? metricsOf(app.pages) : {}
6769
6771
  };
6770
6772
  if (describe7) {
@@ -7526,7 +7528,7 @@ var contract_schema_default = {
7526
7528
  min: { type: "number", description: "OPTIONAL. slider/number only." },
7527
7529
  max: { type: "number", description: "OPTIONAL. slider/number only." },
7528
7530
  step: { type: "number", description: "OPTIONAL. slider/number only." },
7529
- default: { description: "OPTIONAL. The kind decides the shape: a number for slider/number, a string for select/period/month, a bool for toggle, a list for multi." },
7531
+ default: { description: 'OPTIONAL. The kind decides the shape: a number for slider/number, a string for select/period/month, a bool for toggle, a list for multi. A slider or number may instead name a driver data.metrics declares, "@<key>": the page opens on the starting value ship bound for it in this company (its baseline), so the unadjusted page is a Datarails figure; where none is bound the param has no default.' },
7530
7532
  values: { type: "array", items: { type: "string" }, description: "OPTIONAL. select/multi only; absent means the values come from the source's catalog op at serve time." },
7531
7533
  max_selected: { type: "integer", description: "OPTIONAL. multi only." }
7532
7534
  },
@@ -7534,8 +7536,8 @@ var contract_schema_default = {
7534
7536
  { properties: { kind: { const: "period" }, default: { type: "string" } } },
7535
7537
  { properties: { kind: { const: "multi" }, default: { type: "array", items: { type: "string" } } } },
7536
7538
  { properties: { kind: { const: "select" }, default: { type: "string" } } },
7537
- { properties: { kind: { const: "slider" }, default: { type: "number" } } },
7538
- { properties: { kind: { const: "number" }, default: { type: "number" } } },
7539
+ { properties: { kind: { const: "slider" }, default: { anyOf: [{ type: "number" }, { type: "string", pattern: "^@[a-z][a-z0-9_]*$" }] } } },
7540
+ { properties: { kind: { const: "number" }, default: { anyOf: [{ type: "number" }, { type: "string", pattern: "^@[a-z][a-z0-9_]*$" }] } } },
7539
7541
  { properties: { kind: { const: "toggle" }, default: { type: "boolean" } } },
7540
7542
  { properties: { kind: { const: "month" }, default: { type: "string" } } },
7541
7543
  { properties: { kind: { const: "text" }, default: { type: "string" } } },
@@ -7833,12 +7835,22 @@ var contract_schema_default = {
7833
7835
  order: { enum: ["source", "declared"], description: "OPTIONAL, shape breakdown only (this schema has no conditional keyword, so the shape rule is the compiler's: source_shape refuses order on a breakdown source outside this enum). The order the items are answered in: declared is the labels listed in items, over any read; source keeps the rows' own order, which holds only where something promises one: a transform, or an app-table read that states order_by. Absent, the items are sorted by size. A waterfall card over a breakdown source needs one, with top: null." },
7834
7836
  items: { type: "array", items: { type: "string", minLength: 1 }, minItems: 1, description: `OPTIONAL, shape breakdown with order: declared only; on any other shape the compiler refuses it (source_shape). The breakdown's labels, each once, in the order they are drawn (a bridge's steps: ["Opening ARR", "New", ...]). A label the rows do not carry is left out; one they carry and the list does not name follows, in row order.` },
7835
7837
  top: { type: ["integer", "null"], minimum: 1, description: "OPTIONAL. On a breakdown source (the only shape whose top the compiler holds), how many items are drawn (default 5; the rest is one Other figure, other_value), or null to draw every one; a waterfall card over a breakdown source needs null. An app-table read is also capped by limit (default 200 rows), so a total over a bigger table needs limit set above its row count." },
7838
+ shaped: {
7839
+ type: "object",
7840
+ additionalProperties: false,
7841
+ required: ["step", "label"],
7842
+ description: `OPTIONAL, beside a transform over Datarails reads: the transform names the one step the app takes on Datarails figures, so the card says it in a sentence and the compiler reports a named app-shaped figure (app_shaped_figure) instead of an unlabelled app computation (app_computed). step: fy (a year total), split (a formula Datarails refused, evaluated from its parts), solve (a search over Datarails evaluations) or custom:<name> (a method of the app's own, cohort_retention_v2). label: the sentence the card says ("Produced in this app by a cohort retention model"). Said, never refused; the figure is still not a Datarails figure.`,
7843
+ properties: {
7844
+ step: { type: "string", pattern: "^(fy|split|solve|custom:[a-z][a-z0-9_]*)$" },
7845
+ label: { type: "string", minLength: 1, maxLength: 300 }
7846
+ }
7847
+ },
7836
7848
  requiresRole: { type: "array", items: { type: "string" }, description: "OPTIONAL. The app roles that may read this source, any of them: written as its handler's requiresRole, so the server refuses anyone else with 403. Absent means the roles of the pages whose components read it (pages[].roles), and every role as soon as one of those pages is open to every role." }
7837
7849
  }
7838
7850
  }
7839
7851
  },
7840
7852
  metrics: {
7841
- $comment: "Present only for kind: app, and only when the contract declares any (docs/appspace/research/2026-10-25-datarails-calc-layer/06-design-contract-declared-metrics.md \xA72). The package carries it in the contract its pages embed. The key pattern and the per-kind rules are the compiler's (this schema has no propertyNames and no conditional keyword): metric_decl, metric_kind_later, metric_formula, metric_base, metric_format.",
7853
+ $comment: "Present only for kind: app, and only when the contract declares any (docs/appspace/research/2026-10-25-datarails-calc-layer/06-design-contract-declared-metrics.md \xA72). The package carries it in the contract its pages embed. The key pattern and the per-kind rules are the compiler's (this schema has no propertyNames and no conditional keyword): metric_decl, metric_formula, metric_base, metric_format, metric_driver.",
7842
7854
  type: "object",
7843
7855
  description: `the Datarails metrics this app reads, declared rather than addressed by id, keyed by a local name: a lowercase letter, then lowercase letters, digits or _ (revenue_mom), never sent to Datarails. A source reads one with from.financeos.metric "@<key>" and a CALC formula with [@<key>]. \`app-space ship\` binds each key in the company it ships to: it reuses the company's metric with the same definition, or the one with the same name when reuse is "name", and creates it otherwise (create), as the person shipping; a metric with the declared name and another definition is refused, never suffixed. So the contract names no company's metric, and every figure stays a Datarails metric read, the same number MCP and DR.METRIC give. A declaration with no definition binds the company's own metric by name: {"name": "Revenue", "reuse": "name", "create": false}.`,
7844
7856
  additionalProperties: {
@@ -7847,7 +7859,7 @@ var contract_schema_default = {
7847
7859
  additionalProperties: false,
7848
7860
  properties: {
7849
7861
  name: { type: "string", minLength: 1, maxLength: 128, description: `the metric's name in Datarails, which finance users, MCP and DR.METRIC see, so a name a finance team would use ("Revenue MoM growth"), never an app id: at most 128 characters, no ' [ or ] (a CALC formula's reference delimiters), not starting with @, and not DAYS_IN_PERIOD or PERIODS_IN_YEAR (Datarails reserves both)` },
7850
- kind: { enum: ["base", "calc", "driver"], description: "base (a table's value field aggregated by its date field) or calc (a formula over other declared metrics). driver is reserved: the compiler refuses it (metric_kind_later) until driver declarations ship. Absent only on a declaration with no definition (create: false, reuse: name)" },
7862
+ kind: { enum: ["base", "calc", "driver"], description: "base (a table's value field aggregated by its date field), calc (a formula over other declared metrics) or driver (an assumption whose values people enter, per scenario context: no table and no formula; its starting value is baseline or baseline_from). Absent only on a declaration with no definition (create: false, reuse: name)" },
7851
7863
  formula: { type: "string", description: "calc only: the metric in Datarails' CALC syntax: numbers, + - * / and parentheses over operands, each [@<key>] (another metric this block declares) or a system variable written bare, PERIODS_IN_YEAR or DAYS_IN_PERIOD. An operand may carry one modifier: .SHIFT(unit, offset), unit year, quarter, month, day or consumption_period and offset 0 to -1200, or .AS_OF(anchor), anchor year_end, quarter_end or month_end. A window function avg|min|max([@<key>], unit, periods), unit year, quarter or month and periods 1 to 120, compiles with a warning (metric_window): Datarails evaluates it only where the company has scenario_bound_calculations on. Never a metric's name, quoted or bracketed ('Revenue', [Revenue]): the contract names no company's metric. No scenario pin (| Budget), at least one [@<key>], at most 5000 characters, and no declaration that reads itself, however far round. ([@revenue] - [@revenue].SHIFT(month, -1)) / [@revenue].SHIFT(month, -1)" },
7852
7864
  table: {
7853
7865
  type: "object",
@@ -7880,7 +7892,67 @@ var contract_schema_default = {
7880
7892
  format: { type: "string", description: `OPTIONAL: the metric's display in Datarails (its Metric page, MCP, Excel), one of the 180 strings the metric editor writes: an optional currency prefix ("$" quoted, or \u20AC \xA3 \u20AA), #,### or ####, optional decimals .# to .####, an optional scale [kilo]k or [mega]M, and an optional % suffix (never with a currency): #,### "$"#,###.## ####.#%. A card keeps its own format` },
7881
7893
  description: { type: "string", description: "OPTIONAL: what the metric is, in words, for its page in Datarails" },
7882
7894
  reuse: { enum: ["definition", "name"], description: "OPTIONAL. definition (the default): bind only a company metric whose definition matches this one. name: bind the company's metric of this name whatever its definition, so a finance team's own Revenue wins; created from this definition when the company has none" },
7883
- create: { type: "boolean", description: "OPTIONAL. true (the default): create the metric when the company has none to bind. false: bind only, never create; a declaration with no definition says false" }
7895
+ create: { type: "boolean", description: "OPTIONAL. true (the default): create the metric when the company has none to bind. false: bind only, never create; a declaration with no definition says false" },
7896
+ calculations: { type: "object", additionalProperties: { type: "string" }, description: `OPTIONAL, calc only: a formula per scenario, keyed by the scenario's name ("Forecast", "Budget"), which Datarails stores as the metric's scenario-bound calculation (MetricCalculation) for that scenario in every cycle; formula stays the Actuals one. The same CALC syntax as formula, and one thing more: an operand may be pinned to Actuals, [@<key>] | Actuals, before its modifier ([@revenue] | Actuals.SHIFT(year, -1) * (1 + [@growth])), and the metric may read itself only so pinned. No other pin, and no entry keyed Actuals. Datarails evaluates these only where the company has scenario_bound_calculations and the Planning product on (metric_window's advisory names it).` },
7897
+ unit: { type: "string", maxLength: 32, description: 'OPTIONAL, driver only: what one value counts, in words ("procedures", "%", "USD")' },
7898
+ additive: { type: "boolean", description: "OPTIONAL, driver only: true (the default) when months add up to a quarter or year (volume, cost); false when they do not (a rate, a price, a percentage)" },
7899
+ min: { type: ["number", "null"], description: "OPTIONAL, driver only: the lowest value it may take; null for none" },
7900
+ max: { type: ["number", "null"], description: "OPTIONAL, driver only: the highest value it may take; null for none" },
7901
+ baseline: { type: "number", description: "OPTIONAL, driver only, never beside baseline_from: the starting value as the author types it, labelled author on the card; the compiler warns (driver_baseline_typed) where the contract declares a metric it could have been read from" },
7902
+ baseline_from: {
7903
+ type: "object",
7904
+ additionalProperties: false,
7905
+ required: ["rule"],
7906
+ description: "OPTIONAL, driver only, never beside baseline: the starting value read from Datarails at ship, over the last 12 closed months before the plan's first open month (data.model.plan; the last 12 complete months when there is no plan), written into the driver in Datarails and stamped on the app's binding with its window and the months found. rule l12m_mean: the mean of metric's months. l12m_ratio: ratio [a, b], the sum of a over the sum of b in the same months (never a mean of monthly ratios). l12m_growth: metric's 12 months against the 12 before them, as a fraction (0.08 is 8%).",
7907
+ properties: {
7908
+ metric: { type: "string", pattern: "^@[a-z][a-z0-9_]*$", description: 'l12m_mean and l12m_growth: the declared metric it is read from, "@<key>"' },
7909
+ ratio: { type: "array", minItems: 2, items: { type: "string", pattern: "^@[a-z][a-z0-9_]*$" }, description: 'l12m_ratio: [numerator, denominator], each a declared metric "@<key>"' },
7910
+ rule: { enum: ["l12m_mean", "l12m_ratio", "l12m_growth"] }
7911
+ }
7912
+ }
7913
+ }
7914
+ }
7915
+ },
7916
+ model: {
7917
+ $comment: "Present only for kind: app, and only when the contract declares a planning model (docs/appspace/research/2026-11-01-trusted-forecast-models.md \xA75.2). The package carries it in the contract its pages embed, beside data.metrics, and the platform stores it with the contract. The cross-reference rules (a line or result that names no declared metric, a scenario version that is not a calc) are the compiler's: model_decl.",
7918
+ type: "object",
7919
+ additionalProperties: false,
7920
+ description: "the parts of a forecast that are neither a metric nor a page: the planning context every read runs under, the lines that are its results, each line's year-total rule, and what a saved scenario writes",
7921
+ properties: {
7922
+ plan: {
7923
+ type: "object",
7924
+ additionalProperties: false,
7925
+ required: ["module", "cycle"],
7926
+ description: `the planning context: module forecast or budget, the cycle as Datarails names it ("4+8": four closed months and eight forecast) or "favourite" (the company's favourite cycle), and the plan's year. A cycle of the form <closed>+<open> also says where the closed months end, and so the window baseline_from reads`,
7927
+ properties: {
7928
+ module: { enum: ["forecast", "budget"] },
7929
+ cycle: { type: "string", minLength: 1, maxLength: 64 },
7930
+ year: { type: "integer", minimum: 2e3 }
7931
+ }
7932
+ },
7933
+ results: { type: "array", items: { type: "string", pattern: "^@[a-z][a-z0-9_]*$" }, description: `the declared metrics that are the model's results, each "@<key>"` },
7934
+ lines: {
7935
+ type: "object",
7936
+ description: 'per declared metric, keyed "@<key>": its year-total rule and a sentence a reader understands',
7937
+ additionalProperties: {
7938
+ type: "object",
7939
+ additionalProperties: false,
7940
+ properties: {
7941
+ fy: { enum: ["sum", "last", "average"], description: "OPTIONAL. How the year total is made from its months: sum, last (the year's last month, a balance or a headcount) or average (a rate or a price). Declared, never inferred; a line with none takes the metric's own time aggregation" },
7942
+ plain_english: { type: "string", maxLength: 500, description: "OPTIONAL. What the line is, in a sentence" }
7943
+ }
7944
+ }
7945
+ },
7946
+ scenarios: {
7947
+ type: "object",
7948
+ additionalProperties: false,
7949
+ required: ["kind"],
7950
+ description: "what a saved scenario writes: planning_scenario (the drivers' rows under the plan's scenario and cycle, by name; Data Managers and admins) or app_plan (assumptions in an app table with an owner; figures always from what-if)",
7951
+ properties: {
7952
+ kind: { enum: ["planning_scenario", "app_plan"] },
7953
+ names: { anyOf: [{ const: "user" }, { type: "array", minItems: 1, items: { type: "string", minLength: 1, maxLength: 64 } }], description: 'OPTIONAL. user (the default: the viewer names it) or a fixed list ["Base", "Upside", "Downside"]' },
7954
+ versions: { type: "array", items: { type: "string", pattern: "^@[a-z][a-z0-9_]*$" }, description: "OPTIONAL. The declared calc lines a save binds as a Forecast calculation of that metric" }
7955
+ }
7884
7956
  }
7885
7957
  }
7886
7958
  },
@@ -12007,7 +12079,10 @@ var OPERATOR_RE = /\s*([+\-*/])\s*/g;
12007
12079
  var SENTINEL = "\uE000";
12008
12080
  var STASH_RE = /(\d+)/g;
12009
12081
  var REF_WITH_MOD_RE = /\[([^[\]]+)\](\.(?:SHIFT|AS_OF)\([^)]*\))?/g;
12082
+ var PINNED_REF_RE = /\[([^[\]]+)\](\s*\|\s*Actuals\b)?(\.(?:SHIFT|AS_OF)\([^)]*\))?/g;
12010
12083
  var WINDOW_RE = new RegExp(String.raw`\b(${WINDOW_FUNCTIONS.join("|")})\(\s*\[([^[\]]+)\]\s*,\s*(\w+)\s*,\s*([+-]?\d+)\s*\)`, "g");
12084
+ var PINNED_WINDOW_RE = new RegExp(String.raw`\b(${WINDOW_FUNCTIONS.join("|")})\(\s*\[([^[\]]+)\](\s*\|\s*Actuals\b)?\s*,\s*(\w+)\s*,\s*([+-]?\d+)\s*\)`, "g");
12085
+ var CALCULATION_PIN = "Actuals";
12011
12086
  var SYSTEM_VARIABLE_RE = new RegExp(`\\b(?:${SYSTEM_VARIABLES.join("|")})\\b`, "g");
12012
12087
  var SHIFT_RE = /^\.SHIFT\(\s*(\w+)\s*,\s*([+-]?\d+)\s*\)$/;
12013
12088
  var AS_OF_RE = /^\.AS_OF\(\s*(\w+)\s*\)$/;
@@ -12056,8 +12131,9 @@ function declaredKey(inner, declared) {
12056
12131
  }
12057
12132
  function spelledEntry(entry) {
12058
12133
  if (entry.kind === "token") return entry.token;
12059
- if (entry.kind === "window") return `${entry.fn}([@${entry.key}], ${entry.unit}, ${entry.periods})`;
12060
- return `[@${entry.key}]${entry.mod}`;
12134
+ const pin = entry.pinned ? ` | ${CALCULATION_PIN}` : "";
12135
+ if (entry.kind === "window") return `${entry.fn}([@${entry.key}]${pin}, ${entry.unit}, ${entry.periods})`;
12136
+ return `[@${entry.key}]${pin}${entry.mod}`;
12061
12137
  }
12062
12138
  function arithmeticProblem(skeleton, stash) {
12063
12139
  const tokens = [];
@@ -12106,14 +12182,16 @@ function arithmeticProblem(skeleton, stash) {
12106
12182
  }
12107
12183
  return null;
12108
12184
  }
12109
- function scan(formula, declared) {
12185
+ function scan(formula, declared, pinned = false) {
12110
12186
  if (typeof formula !== "string") refuse(`is ${JSON.stringify(formula ?? null)}, not text`);
12111
12187
  if (formula.trim() === "") refuse("must be non-empty");
12112
12188
  if (formula.length > MAX_FORMULA_LENGTH) {
12113
12189
  refuse(`is ${formula.length} characters, over the server maximum of ${MAX_FORMULA_LENGTH}; shorten the formula`);
12114
12190
  }
12115
12191
  if (formula.includes(SENTINEL)) refuse("contains an unsupported character (U+E000)");
12116
- if (formula.includes("|")) refuse("pins a scenario (|); a scenario pin is not accepted in a declared metric's formula \u2014 read the scenario on the source instead (from.financeos.scenario)");
12192
+ if (!pinned && formula.includes("|")) {
12193
+ refuse("pins a scenario (|); a scenario pin is not accepted in a declared metric's formula \u2014 read the scenario on the source instead (from.financeos.scenario), or state a per-scenario formula in calculations, where | Actuals is read");
12194
+ }
12117
12195
  if (formula.includes("'")) {
12118
12196
  const quoted3 = /'[^']*'/.exec(formula);
12119
12197
  if (quoted3) refuse(namedItself(quoted3[0]));
@@ -12124,7 +12202,7 @@ function scan(formula, declared) {
12124
12202
  stash.push(entry);
12125
12203
  return `${SENTINEL}${stash.length - 1}${SENTINEL}`;
12126
12204
  };
12127
- let working = formula.replace(WINDOW_RE, (_m, fn, inner, unit, periods) => {
12205
+ const windowAt = (fn, inner, pin, unit, periods) => {
12128
12206
  if (SYSTEM_VARIABLES.includes(inner)) refuse(`has a window over the reserved token "${inner}"; a window function reads a [@key] operand`);
12129
12207
  const key = declaredKey(inner, declared);
12130
12208
  if (!WINDOW_UNITS.includes(unit.toLowerCase())) refuse(`has an invalid window unit "${unit}" in ${fn}() (valid: ${WINDOW_UNITS.join(", ")})`);
@@ -12132,17 +12210,23 @@ function scan(formula, declared) {
12132
12210
  if (!Number.isInteger(count) || count < 1 || count > MAX_WINDOW_PERIODS) {
12133
12211
  refuse(`has a window of ${periods} periods in ${fn}(); a window spans 1 to ${MAX_WINDOW_PERIODS} periods`);
12134
12212
  }
12135
- return put({ kind: "window", fn, key, unit: unit.toLowerCase(), periods: String(count) });
12136
- });
12137
- working = working.replace(REF_WITH_MOD_RE, (_m, inner, mod) => {
12213
+ return put({ kind: "window", fn, key, unit: unit.toLowerCase(), periods: String(count), pinned: Boolean(pin) });
12214
+ };
12215
+ let working = pinned ? formula.replace(PINNED_WINDOW_RE, (_m, fn, inner, pin, unit, periods) => windowAt(fn, inner, pin, unit, periods)) : formula.replace(WINDOW_RE, (_m, fn, inner, unit, periods) => windowAt(fn, inner, void 0, unit, periods));
12216
+ const refAt = (inner, pin, mod) => {
12138
12217
  if (SYSTEM_VARIABLES.includes(inner)) {
12139
12218
  if (mod) refuse(modifierOnSystemVariable(inner));
12219
+ if (pin) refuse(`pins the reserved token "${inner}" to a scenario; a pin reads a [@key] operand`);
12140
12220
  return put({ kind: "token", token: inner });
12141
12221
  }
12142
12222
  const key = declaredKey(inner, declared);
12143
12223
  if (mod) checkModifier(mod);
12144
- return put({ kind: "ref", key, mod: mod ?? "" });
12145
- });
12224
+ return put({ kind: "ref", key, mod: mod ?? "", pinned: Boolean(pin) });
12225
+ };
12226
+ working = pinned ? working.replace(PINNED_REF_RE, (_m, inner, pin, mod) => refAt(inner, pin, mod)) : working.replace(REF_WITH_MOD_RE, (_m, inner, mod) => refAt(inner, void 0, mod));
12227
+ if (pinned && working.includes("|")) {
12228
+ refuse(`pins a scenario other than ${CALCULATION_PIN}, or pins no operand; a calculation pins an operand to ${CALCULATION_PIN} only, written [@key] | ${CALCULATION_PIN} before its modifier ([@revenue] | ${CALCULATION_PIN}.SHIFT(year, -1))`);
12229
+ }
12146
12230
  working = working.replace(SYSTEM_VARIABLE_RE, (token, offset, whole) => {
12147
12231
  if (/^\s*\.(?:SHIFT|AS_OF)\(/i.test(whole.slice(offset + token.length))) refuse(modifierOnSystemVariable(token));
12148
12232
  return put({ kind: "token", token });
@@ -12176,20 +12260,23 @@ function scan(formula, declared) {
12176
12260
  if (!stash.some((entry) => entry.kind !== "token")) refuse("must read at least one declared metric, e.g. [@revenue]");
12177
12261
  return { padded, stash };
12178
12262
  }
12179
- function metricFormulaProblems(formula, declared) {
12263
+ function metricFormulaProblems(formula, declared, { pinned = false, self = null } = {}) {
12180
12264
  try {
12181
- const { stash } = scan(formula, Array.isArray(declared) ? declared.filter((one) => typeof one === "string") : []);
12182
- const operands = [...new Set(stash.filter((entry) => entry.kind !== "token").map((entry) => entry.key))].sort();
12183
- const windows = stash.filter((entry) => entry.kind === "window").map((entry) => `${entry.fn}([@${entry.key}], ${entry.unit}, ${entry.periods})`);
12184
- return { problems: [], operands, windows };
12265
+ const { stash } = scan(formula, Array.isArray(declared) ? declared.filter((one) => typeof one === "string") : [], pinned);
12266
+ const refs = stash.filter((entry) => entry.kind !== "token");
12267
+ const operands = [...new Set(refs.map((entry) => entry.key))].sort();
12268
+ const windows = stash.filter((entry) => entry.kind === "window").map(spelledEntry);
12269
+ const unpinned = [...new Set(refs.filter((entry) => !entry.pinned).map((entry) => entry.key))].sort();
12270
+ const selfUnpinned = self !== null && unpinned.includes(self);
12271
+ return { problems: [], operands, unpinned, windows, selfUnpinned };
12185
12272
  } catch (error) {
12186
12273
  if (!(error instanceof MetricFormulaError)) throw error;
12187
- return { problems: [error.message], operands: [], windows: [] };
12274
+ return { problems: [error.message], operands: [], unpinned: [], windows: [], selfUnpinned: false };
12188
12275
  }
12189
12276
  }
12190
- function wireFormula(formula, names) {
12277
+ function wireFormula(formula, names, { pinned = false } = {}) {
12191
12278
  const known = names !== null && typeof names === "object" ? names : {};
12192
- const { padded, stash } = scan(formula, Object.keys(known));
12279
+ const { padded, stash } = scan(formula, Object.keys(known), pinned);
12193
12280
  const nameOf5 = (key) => {
12194
12281
  const name = known[key];
12195
12282
  if (typeof name !== "string" || name.trim() === "" || /['[\]]/.test(name)) {
@@ -12200,8 +12287,9 @@ function wireFormula(formula, names) {
12200
12287
  const wire = padded.replace(STASH_RE, (_m, index) => {
12201
12288
  const entry = stash[Number(index)];
12202
12289
  if (entry.kind === "token") return `'${entry.token}'`;
12203
- if (entry.kind === "window") return `${entry.fn}('${nameOf5(entry.key)}', ${entry.unit}, ${entry.periods})`;
12204
- return `'${nameOf5(entry.key)}'${entry.mod}`;
12290
+ const pin = entry.pinned ? ` | ${CALCULATION_PIN}` : "";
12291
+ if (entry.kind === "window") return `${entry.fn}('${nameOf5(entry.key)}'${pin}, ${entry.unit}, ${entry.periods})`;
12292
+ return `'${nameOf5(entry.key)}'${pin}${entry.mod}`;
12205
12293
  });
12206
12294
  if (wire.length > MAX_FORMULA_LENGTH) {
12207
12295
  refuse(`is ${wire.length} characters with the company's metric names written in, over the server maximum of ${MAX_FORMULA_LENGTH}; shorten the formula or the names`);
@@ -12242,6 +12330,159 @@ function metricFormatProblem(format) {
12242
12330
  return `is ${JSON.stringify(format)}, which the metric editor never writes${meant ? ` (did you mean ${JSON.stringify(meant)}?)` : ""}; build it from these parts, in this order: an optional currency prefix ("$" quoted, or \u20AC \xA3 \u20AA, never with %), #,### or ####, optional decimals .# to .####, an optional scale [kilo]k or [mega]M, and an optional % suffix`;
12243
12331
  }
12244
12332
 
12333
+ // ../flows/insights-builder/kit/contract/figures.mjs
12334
+ var APP_COMPUTED = "app_computed";
12335
+ var APP_SHAPED = "app_shaped_figure";
12336
+ var FY_INFERRED = "fy_inferred";
12337
+ var APP_ROWS = "app_rows";
12338
+ var APP_RECORDS = "app_records";
12339
+ var KINDS = [APP_COMPUTED, APP_SHAPED, FY_INFERRED, APP_ROWS, APP_RECORDS];
12340
+ var SHAPED_STEP_RE = /^(fy|split|solve|custom:[a-z][a-z0-9_]*)$/;
12341
+ var SHAPED_LABEL_MAX = 300;
12342
+ var FY_WORDS = { sum: "the sum of its months", last: "its last month", average: "the average of its months" };
12343
+ var FIGURE_PARTS = /* @__PURE__ */ new Set(["widget", "stat", "chart", "callout", "variance_table", "scenario_columns", "progress"]);
12344
+ var ALTERNATIVE = "Get the figure from Datarails instead: a metric (declared in data.metrics), a tier-3 formula (expr over from Datarails reads), or a direct FinanceOS read";
12345
+ var isObject4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
12346
+ var rowsOf = (table) => isObject4(table) ? Object.entries(table).filter(([, row]) => isObject4(row)) : [];
12347
+ var byName = ([a], [b]) => a < b ? -1 : a > b ? 1 : 0;
12348
+ var present = (value) => value !== void 0 && value !== null;
12349
+ function hookName(value) {
12350
+ const name = isObject4(value) ? value.$callable : void 0;
12351
+ return typeof name === "string" && name !== "" ? name.split(".").at(-1) : null;
12352
+ }
12353
+ function transformName(value) {
12354
+ if (typeof value === "string" && value !== "") return value;
12355
+ return hookName(value) ?? "a transform";
12356
+ }
12357
+ function dashboardWhy(row) {
12358
+ if (present(row.compute)) {
12359
+ const name = hookName(row.compute);
12360
+ return name ? `computed by its compute hook ${name}` : "computed by its compute hook";
12361
+ }
12362
+ if (present(row.transform)) return `drawn through ${transformName(row.transform)}`;
12363
+ return null;
12364
+ }
12365
+ function origins(rows2, name, seen = /* @__PURE__ */ new Set()) {
12366
+ if (seen.has(name)) return /* @__PURE__ */ new Set();
12367
+ seen.add(name);
12368
+ const origin = rows2[name]?.from;
12369
+ if (Array.isArray(origin)) {
12370
+ const out = /* @__PURE__ */ new Set();
12371
+ for (const one of origin) if (typeof one === "string") for (const kind of origins(rows2, one, seen)) out.add(kind);
12372
+ return out;
12373
+ }
12374
+ if (isObject4(origin)) {
12375
+ if ("table" in origin) return /* @__PURE__ */ new Set(["app_table"]);
12376
+ if ("financeos" in origin || "call" in origin) return /* @__PURE__ */ new Set(["datarails"]);
12377
+ }
12378
+ return /* @__PURE__ */ new Set();
12379
+ }
12380
+ function appTables(rows2, name, seen = /* @__PURE__ */ new Set()) {
12381
+ if (seen.has(name)) return [];
12382
+ seen.add(name);
12383
+ const origin = rows2[name]?.from;
12384
+ if (isObject4(origin) && typeof origin.table === "string") return [origin.table];
12385
+ const out = [];
12386
+ if (Array.isArray(origin)) {
12387
+ for (const one of origin) {
12388
+ if (typeof one !== "string") continue;
12389
+ for (const table of appTables(rows2, one, seen)) if (!out.includes(table)) out.push(table);
12390
+ }
12391
+ }
12392
+ return out;
12393
+ }
12394
+ function shapedOf(row) {
12395
+ const shaped = isObject4(row) ? row.shaped : void 0;
12396
+ if (!isObject4(shaped)) return null;
12397
+ const { step, label } = shaped;
12398
+ if (typeof step !== "string" || !SHAPED_STEP_RE.test(step)) return null;
12399
+ if (typeof label !== "string" || label.trim() === "" || label.length > SHAPED_LABEL_MAX) return null;
12400
+ return { step, label };
12401
+ }
12402
+ function declaredKeyOf(row) {
12403
+ const origin = row.from;
12404
+ const read = isObject4(origin) && isObject4(origin.financeos) ? origin.financeos : null;
12405
+ const metric = read === null ? null : read.metric;
12406
+ return typeof metric === "string" && /^@[a-z][a-z0-9_]*$/.test(metric) ? metric.slice(1) : null;
12407
+ }
12408
+ function yearTotalFinding(card, row, model) {
12409
+ if (!isObject4(model) || row.shape !== "kpi" || present(row.transform)) return null;
12410
+ const key = declaredKeyOf(row);
12411
+ if (key === null) return null;
12412
+ const ref = `@${key}`;
12413
+ const lines = isObject4(model.lines) ? model.lines : {};
12414
+ const line2 = Object.hasOwn(lines, ref) && isObject4(lines[ref]) ? lines[ref] : null;
12415
+ const fy = line2 === null ? void 0 : line2.fy;
12416
+ if (typeof fy === "string" && Object.hasOwn(FY_WORDS, fy)) {
12417
+ return { card, kind: APP_SHAPED, step: "fy", why: `year total of ${ref}: ${FY_WORDS[fy]} (declared)` };
12418
+ }
12419
+ const results = Array.isArray(model.results) ? model.results : [];
12420
+ if (line2 !== null || results.includes(ref)) {
12421
+ return { card, kind: FY_INFERRED, why: `a year total of ${ref}, a line of the model with no fy declared: Datarails' own roll-up of the metric, which the model never chose` };
12422
+ }
12423
+ return null;
12424
+ }
12425
+ function sourceFinding(card, row, rows2, readers, model) {
12426
+ const figure2 = typeof row.shape === "string" && row.shape !== "rows" || readers.some((part) => FIGURE_PARTS.has(part));
12427
+ const from = origins(rows2, card);
12428
+ const transform = row.transform;
12429
+ if (present(transform) && transform !== false && transform !== "") {
12430
+ const through = transformName(transform);
12431
+ if (from.has("datarails")) {
12432
+ if (!figure2) return { card, kind: APP_ROWS, why: `rows shaped by ${through}` };
12433
+ const shaped = shapedOf(row);
12434
+ return shaped === null ? { card, kind: APP_COMPUTED, why: `drawn through ${through}` } : { card, kind: APP_SHAPED, step: shaped.step, why: `${shaped.label} (step ${shaped.step}, through ${through})` };
12435
+ }
12436
+ if (from.size === 1 && from.has("app_table")) {
12437
+ return { card, kind: APP_RECORDS, why: `${through} over ${appTables(rows2, card).join(", ")}, the app's own records` };
12438
+ }
12439
+ return null;
12440
+ }
12441
+ const origin = row.from;
12442
+ if (isObject4(origin) && typeof origin.table === "string" && figure2) {
12443
+ return { card, kind: APP_RECORDS, why: `a figure over ${origin.table}, the app's own records` };
12444
+ }
12445
+ return yearTotalFinding(card, row, model);
12446
+ }
12447
+ function classify2({ widgets, sources, summaries, readers, model } = {}) {
12448
+ const found = [];
12449
+ for (const [card, row] of rowsOf(widgets).sort(byName)) {
12450
+ if (card.startsWith("_")) continue;
12451
+ const why = dashboardWhy(row);
12452
+ if (why !== null) found.push({ card, kind: APP_COMPUTED, why });
12453
+ }
12454
+ const rows2 = Object.fromEntries(rowsOf(sources));
12455
+ for (const [card, row] of Object.entries(rows2).sort(byName)) {
12456
+ const finding = sourceFinding(card, row, rows2, isObject4(readers) && readers[card] || [], model);
12457
+ if (finding !== null) found.push(finding);
12458
+ }
12459
+ for (const [card, row] of rowsOf(summaries).sort(byName)) {
12460
+ if (row.role !== "summary") continue;
12461
+ const named13 = typeof row.table === "string" ? ` of ${row.table}` : "";
12462
+ found.push({ card, kind: APP_RECORDS, why: `counts and sums${named13}, the app's own records` });
12463
+ }
12464
+ const order2 = (kind) => KINDS.indexOf(kind);
12465
+ return found.sort((a, b) => order2(a.kind) - order2(b.kind) || (a.card < b.card ? -1 : a.card > b.card ? 1 : 0));
12466
+ }
12467
+ function readersOf(elements) {
12468
+ const out = {};
12469
+ if (!isObject4(elements)) return out;
12470
+ for (const element of Object.values(elements)) {
12471
+ if (!isObject4(element) || typeof element.type !== "string") continue;
12472
+ const props = isObject4(element.props) ? element.props : {};
12473
+ const inner = isObject4(props.props) ? props.props : {};
12474
+ const source = "source" in props ? props.source : inner.source;
12475
+ if (typeof source === "string") (out[source] ??= []).push(element.type);
12476
+ }
12477
+ return out;
12478
+ }
12479
+ function figuresOf(contract) {
12480
+ if (!isObject4(contract)) return [];
12481
+ const data = isObject4(contract.data) ? contract.data : {};
12482
+ const app = isObject4(data.app) ? data.app : {};
12483
+ return classify2({ widgets: data.widgets, sources: data.sources, summaries: app.handlers, readers: readersOf(contract.elements), model: data.model });
12484
+ }
12485
+
12245
12486
  // ../flows/insights-builder/kit/contract/compileApp.mjs
12246
12487
  var RUNTIME = "dr-app-runtime@1.13.5";
12247
12488
  var UI_KIT2 = "ui-kit/v4";
@@ -12868,10 +13109,43 @@ function reaches2(sources, start, target, seen, isFormula) {
12868
13109
  if (!isFormula(row) || !Array.isArray(row.from)) return false;
12869
13110
  return row.from.filter(named5).some((one) => reaches2(sources, one, target, seen, isFormula));
12870
13111
  }
12871
- var METRIC_DECL_KEYS = ["name", "kind", "formula", "table", "value", "date", "aggregate", "time_aggregation", "filters", "format", "description", "reuse", "create"];
12872
- var METRIC_KINDS = ["base", "calc"];
12873
- var METRIC_CALC_KEYS = ["formula"];
13112
+ var METRIC_DECL_KEYS = [
13113
+ "name",
13114
+ "kind",
13115
+ "formula",
13116
+ "calculations",
13117
+ "table",
13118
+ "value",
13119
+ "date",
13120
+ "aggregate",
13121
+ "time_aggregation",
13122
+ "filters",
13123
+ "unit",
13124
+ "additive",
13125
+ "min",
13126
+ "max",
13127
+ "baseline",
13128
+ "baseline_from",
13129
+ "format",
13130
+ "description",
13131
+ "reuse",
13132
+ "create"
13133
+ ];
13134
+ var METRIC_KINDS = ["base", "calc", "driver"];
13135
+ var METRIC_CALC_KEYS = ["formula", "calculations"];
12874
13136
  var METRIC_BASE_KEYS = ["table", "value", "date", "aggregate", "time_aggregation", "filters"];
13137
+ var METRIC_DRIVER_KEYS = ["unit", "additive", "min", "max", "baseline", "baseline_from"];
13138
+ var METRIC_KIND_KEYS = { calc: METRIC_CALC_KEYS, base: METRIC_BASE_KEYS, driver: METRIC_DRIVER_KEYS };
13139
+ var BASELINE_RULES = { l12m_mean: "metric", l12m_ratio: "ratio", l12m_growth: "metric" };
13140
+ var BASELINE_FROM_KEYS = ["metric", "ratio", "rule"];
13141
+ var CALCULATION_SCENARIO_RE = /^[A-Za-z][A-Za-z0-9 _+&-]{0,63}$/;
13142
+ var DRIVER_UNIT_MAX = 32;
13143
+ var METRIC_REF_RE = /^@([a-z][a-z0-9_]*)$/;
13144
+ var KIND_WORDS = {
13145
+ base: `"base" (a table's field, aggregated)`,
13146
+ calc: '"calc" (a formula over declared metrics)',
13147
+ driver: '"driver" (an assumption people enter, with baseline or baseline_from)'
13148
+ };
12875
13149
  var METRIC_AGGREGATES = ["sum", "count", "cumulative_sum", "cumulative_count"];
12876
13150
  var METRIC_TIME_AGGREGATIONS = ["sum", "eop", "avg"];
12877
13151
  var METRIC_REUSE = ["definition", "name"];
@@ -12912,6 +13186,69 @@ function metricReaches(operandsOf2, start, target, seen) {
12912
13186
  seen.add(start);
12913
13187
  return (operandsOf2.get(start) ?? []).some((one) => metricReaches(operandsOf2, one, target, seen));
12914
13188
  }
13189
+ function baselineRefs(from) {
13190
+ if (!isPlainObject8(from)) return [];
13191
+ const out = [];
13192
+ if (typeof from.metric === "string" && METRIC_REF_RE.test(from.metric)) out.push(["metric", from.metric]);
13193
+ if (Array.isArray(from.ratio)) from.ratio.forEach((one, index) => typeof one === "string" && METRIC_REF_RE.test(one) && out.push([`ratio/${index}`, one]));
13194
+ return out;
13195
+ }
13196
+ function driverDeclProblems(key, decl, at) {
13197
+ const problems = [];
13198
+ const say = (field, message) => problems.push({ code: "metric_driver", pointer: at(key, field), message: `metric "${key}" ${message}` });
13199
+ const finite = (value) => typeof value === "number" && Number.isFinite(value);
13200
+ if (decl.unit !== void 0 && (typeof decl.unit !== "string" || decl.unit.length > DRIVER_UNIT_MAX)) say("unit", `states unit ${JSON.stringify(decl.unit)}; a unit is what one value counts, in words, at most ${DRIVER_UNIT_MAX} characters ("procedures", "%")`);
13201
+ if (decl.additive !== void 0 && typeof decl.additive !== "boolean") say("additive", `states additive ${JSON.stringify(decl.additive)}; additive is true (months add up: a volume, a cost) or false (a rate, a price)`);
13202
+ for (const field of ["min", "max"]) {
13203
+ if (decl[field] !== void 0 && decl[field] !== null && !finite(decl[field])) say(field, `states ${field} ${JSON.stringify(decl[field])}; ${field} is a finite number, or null for none`);
13204
+ }
13205
+ if (finite(decl.min) && finite(decl.max) && decl.min > decl.max) say("min", `has min ${decl.min} above max ${decl.max}`);
13206
+ if (decl.baseline !== void 0 && decl.baseline_from !== void 0) {
13207
+ say("baseline", "states both baseline and baseline_from; a starting value is typed (baseline) or read from Datarails (baseline_from), not both");
13208
+ return problems;
13209
+ }
13210
+ if (decl.baseline !== void 0) {
13211
+ if (!finite(decl.baseline)) say("baseline", `states baseline ${JSON.stringify(decl.baseline)}; a typed baseline is a finite number`);
13212
+ else if (finite(decl.min) && decl.baseline < decl.min || finite(decl.max) && decl.baseline > decl.max) {
13213
+ problems.push({
13214
+ code: "driver_bounds",
13215
+ pointer: at(key, "baseline"),
13216
+ message: `metric "${key}" starts at ${decl.baseline}, outside its own bounds [${finite(decl.min) ? decl.min : "\u2026"}, ${finite(decl.max) ? decl.max : "\u2026"}]; Datarails stores it as typed, and every scenario opens outside them`,
13217
+ advisory: true
13218
+ });
13219
+ }
13220
+ } else if (decl.baseline_from !== void 0) {
13221
+ const from = decl.baseline_from;
13222
+ const rules = Object.keys(BASELINE_RULES);
13223
+ if (!isPlainObject8(from)) {
13224
+ say("baseline_from", `states baseline_from ${JSON.stringify(from)}; it is {"metric": "@<key>", "rule": "l12m_mean"}, {"ratio": ["@<a>", "@<b>"], "rule": "l12m_ratio"} or {"metric": "@<key>", "rule": "l12m_growth"}`);
13225
+ return problems;
13226
+ }
13227
+ const extra = Object.keys(from).filter((one) => !BASELINE_FROM_KEYS.includes(one)).sort(natural3);
13228
+ if (extra.length > 0) say(`baseline_from/${escapePointer3(extra[0])}`, `states baseline_from.${extra[0]}, which baseline_from does not take; it takes ${either3(BASELINE_FROM_KEYS)}`);
13229
+ if (!rules.includes(from.rule)) {
13230
+ say("baseline_from/rule", `reads its baseline by rule ${JSON.stringify(from.rule ?? null)}; the rule is ${either3(rules)}`);
13231
+ return problems;
13232
+ }
13233
+ const wants = BASELINE_RULES[from.rule];
13234
+ const other = wants === "metric" ? "ratio" : "metric";
13235
+ if (from[other] !== void 0) say(`baseline_from/${other}`, `reads its baseline by ${from.rule}, which takes ${wants === "metric" ? "one metric" : "a ratio"}, and states ${other}; drop it`);
13236
+ if (wants === "metric" && !(typeof from.metric === "string" && METRIC_REF_RE.test(from.metric))) {
13237
+ say("baseline_from/metric", `reads its baseline by ${from.rule} from ${JSON.stringify(from.metric ?? null)}; name the declared metric it is read from, "@<key>"`);
13238
+ }
13239
+ if (wants === "ratio" && !(Array.isArray(from.ratio) && from.ratio.length === 2 && from.ratio.every((one) => typeof one === "string" && METRIC_REF_RE.test(one)))) {
13240
+ say("baseline_from/ratio", `reads its baseline by l12m_ratio from ${JSON.stringify(from.ratio ?? null)}; a ratio is [numerator, denominator], each a declared metric "@<key>"`);
13241
+ }
13242
+ } else {
13243
+ problems.push({
13244
+ code: "driver_no_baseline",
13245
+ pointer: at(key),
13246
+ message: `metric "${key}" is a driver with no starting value: every scenario opens on an empty driver until someone enters one. Read it from Datarails ("baseline_from": {"metric": "@<key>", "rule": "l12m_mean"}), or type one ("baseline": <n>)`,
13247
+ advisory: true
13248
+ });
13249
+ }
13250
+ return problems;
13251
+ }
12915
13252
  function calcShaped(node) {
12916
13253
  if (node[0] === "num" || node[0] === "name") return true;
12917
13254
  if (node[0] === "neg") return calcShaped(node[1]);
@@ -12930,6 +13267,8 @@ function metricProblems(metrics, sources) {
12930
13267
  const keys2 = Object.keys(declared).sort(natural3);
12931
13268
  const declaredKeys = keys2.filter((key) => METRIC_KEY_RE.test(key));
12932
13269
  const formulas = /* @__PURE__ */ new Map();
13270
+ const drivers = /* @__PURE__ */ new Map();
13271
+ const calculations = [];
12933
13272
  for (const key of keys2) {
12934
13273
  const decl = declared[key];
12935
13274
  if (!METRIC_KEY_RE.test(key)) {
@@ -12964,9 +13303,9 @@ function metricProblems(metrics, sources) {
12964
13303
  }
12965
13304
  const kind = decl.kind;
12966
13305
  if (kind === void 0) {
12967
- const defining = [...METRIC_CALC_KEYS, ...METRIC_BASE_KEYS].filter((field) => decl[field] !== void 0);
13306
+ const defining = [...METRIC_CALC_KEYS, ...METRIC_BASE_KEYS, ...METRIC_DRIVER_KEYS].filter((field) => decl[field] !== void 0);
12968
13307
  if (defining.length > 0) {
12969
- say("metric_decl", at(key, "kind"), `metric "${key}" states ${defining.join(", ")} and no kind; state "kind": "base" (a table's field, aggregated) or "calc" (a formula over declared metrics)`);
13308
+ say("metric_decl", at(key, "kind"), `metric "${key}" states ${defining.join(", ")} and no kind; state "kind": ${KIND_WORDS.base}, ${KIND_WORDS.calc} or ${KIND_WORDS.driver}`);
12970
13309
  } else if (decl.create !== false) {
12971
13310
  say(
12972
13311
  "metric_decl",
@@ -12982,20 +13321,19 @@ function metricProblems(metrics, sources) {
12982
13321
  }
12983
13322
  continue;
12984
13323
  }
12985
- if (kind === "driver") {
12986
- say(
12987
- "metric_kind_later",
12988
- at(key, "kind"),
12989
- `metric "${key}" is kind "driver", which is reserved: driver declarations are not compiled yet. Declare a base or calc metric, or create the driver in Datarails and bind it with {"name": "<its name>", "reuse": "name", "create": false}`
12990
- );
12991
- continue;
12992
- }
12993
13324
  if (!METRIC_KINDS.includes(kind)) {
12994
- say("metric_decl", at(key, "kind"), `metric "${key}" is kind ${JSON.stringify(kind)}; a declared metric is "base" (a table's field, aggregated) or "calc" (a formula over declared metrics)`);
13325
+ say("metric_decl", at(key, "kind"), `metric "${key}" is kind ${JSON.stringify(kind)}; a declared metric is ${KIND_WORDS.base}, ${KIND_WORDS.calc} or ${KIND_WORDS.driver}`);
12995
13326
  continue;
12996
13327
  }
12997
- for (const field of kind === "calc" ? METRIC_BASE_KEYS : METRIC_CALC_KEYS) {
12998
- if (decl[field] !== void 0) say("metric_decl", at(key, field), `metric "${key}" is a ${kind} metric and states ${field}, which only a ${kind === "calc" ? "base" : "calc"} metric takes`);
13328
+ for (const other of METRIC_KINDS.filter((one) => one !== kind)) {
13329
+ for (const field of METRIC_KIND_KEYS[other]) {
13330
+ if (decl[field] !== void 0) say("metric_decl", at(key, field), `metric "${key}" is a ${kind} metric and states ${field}, which only a ${other} metric takes`);
13331
+ }
13332
+ }
13333
+ if (kind === "driver") {
13334
+ drivers.set(key, decl);
13335
+ problems.push(...driverDeclProblems(key, decl, at));
13336
+ continue;
12999
13337
  }
13000
13338
  if (kind === "calc") {
13001
13339
  if (decl.formula === void 0) {
@@ -13003,6 +13341,22 @@ function metricProblems(metrics, sources) {
13003
13341
  } else {
13004
13342
  formulas.set(key, decl.formula);
13005
13343
  }
13344
+ if (decl.calculations !== void 0) {
13345
+ if (!isPlainObject8(decl.calculations)) {
13346
+ say("metric_decl", at(key, "calculations"), `metric "${key}" states calculations ${JSON.stringify(decl.calculations)}; calculations is an object of formulas keyed by a scenario's name ({"Forecast": "[@revenue] | Actuals.SHIFT(year, -1) * (1 + [@growth])"})`);
13347
+ } else {
13348
+ for (const scenario of Object.keys(decl.calculations).sort(natural3)) {
13349
+ const pointer2 = at(key, `calculations/${escapePointer3(scenario)}`);
13350
+ if (!CALCULATION_SCENARIO_RE.test(scenario)) {
13351
+ say("metric_decl", pointer2, `metric "${key}" states a calculation for ${JSON.stringify(scenario)}, which is not a scenario's name (a letter, then letters, digits, spaces, _ + & or -, at most 64)`);
13352
+ } else if (scenario.toLowerCase() === "actuals") {
13353
+ say("metric_decl", pointer2, `metric "${key}" states a calculation for ${scenario}; the Actuals formula is formula itself \u2014 a calculation is for another scenario ("Forecast", "Budget")`);
13354
+ } else {
13355
+ calculations.push({ key, scenario, formula: decl.calculations[scenario], pointer: pointer2 });
13356
+ }
13357
+ }
13358
+ }
13359
+ }
13006
13360
  continue;
13007
13361
  }
13008
13362
  if (decl.table === void 0) {
@@ -13040,6 +13394,8 @@ function metricProblems(metrics, sources) {
13040
13394
  }
13041
13395
  }
13042
13396
  const operandsOf2 = /* @__PURE__ */ new Map();
13397
+ const baselineReads = /* @__PURE__ */ new Set();
13398
+ const calculationReads = /* @__PURE__ */ new Map();
13043
13399
  for (const key of [...formulas.keys()].sort(natural3)) {
13044
13400
  const { problems: wrong, operands, windows } = metricFormulaProblems(formulas.get(key), declaredKeys);
13045
13401
  for (const one of wrong) say("metric_formula", at(key, "formula"), `metric "${key}"'s formula ${one}`);
@@ -13053,6 +13409,47 @@ function metricProblems(metrics, sources) {
13053
13409
  );
13054
13410
  }
13055
13411
  }
13412
+ for (const { key, scenario, formula, pointer: pointer2 } of calculations) {
13413
+ const { problems: wrong, operands, unpinned, windows, selfUnpinned } = metricFormulaProblems(formula, declaredKeys, { pinned: true, self: key });
13414
+ for (const one of wrong) say("metric_formula", pointer2, `metric "${key}"'s ${scenario} calculation ${one}`);
13415
+ if (wrong.length > 0) continue;
13416
+ calculationReads.set(key, [...calculationReads.get(key) ?? [], ...operands]);
13417
+ if (operandsOf2.has(key)) operandsOf2.set(key, [.../* @__PURE__ */ new Set([...operandsOf2.get(key), ...unpinned.filter((one) => one !== key)])].sort(natural3));
13418
+ if (selfUnpinned) {
13419
+ advise(
13420
+ "metric_self_read",
13421
+ pointer2,
13422
+ `metric "${key}"'s ${scenario} calculation reads [@${key}] without a pin; Datarails refuses a ${scenario} formula that reads its own ${scenario} (a loop) \u2014 read its Actuals, [@${key}] | Actuals`
13423
+ );
13424
+ }
13425
+ advise(
13426
+ "metric_scenario_bound",
13427
+ pointer2,
13428
+ `metric "${key}" states a ${scenario} calculation${windows.length > 0 ? ` (and calls ${windows.join(" and ")})` : ""}, which Datarails stores and evaluates only where the company has scenario_bound_calculations and the Planning product on, and refuses to create elsewhere`
13429
+ );
13430
+ }
13431
+ for (const [key, decl] of [...drivers.entries()].sort(([a], [b]) => natural3(a, b))) {
13432
+ for (const [field, ref] of baselineRefs(decl.baseline_from)) {
13433
+ const pointer2 = at(key, `baseline_from/${field}`);
13434
+ const target = ref.slice(1);
13435
+ if (!declaredKeys.includes(target)) {
13436
+ say("metric_driver", pointer2, `metric "${key}" reads its baseline from "${ref}", which data.metrics does not declare (it declares ${declaredKeys.length > 0 ? declaredKeys.map((one) => `"@${one}"`).join(", ") : "none"}); declare it there, or read one it declares`);
13437
+ } else if (declared[target]?.kind === "driver") {
13438
+ say("metric_driver", pointer2, `metric "${key}" reads its baseline from "${ref}", another driver, which has no Actuals to read; read a base or calc metric, or a company metric bound by name`);
13439
+ } else {
13440
+ baselineReads.add(target);
13441
+ }
13442
+ }
13443
+ }
13444
+ const readable = declaredKeys.filter((one) => isPlainObject8(declared[one]) && declared[one].kind !== "driver");
13445
+ for (const [key, decl] of [...drivers.entries()].sort(([a], [b]) => natural3(a, b))) {
13446
+ if (decl.baseline === void 0 || decl.baseline_from !== void 0 || readable.length === 0) continue;
13447
+ advise(
13448
+ "driver_baseline_typed",
13449
+ at(key, "baseline"),
13450
+ `metric "${key}" starts at a typed ${JSON.stringify(decl.baseline)} (labelled author on its card), and the contract declares metrics Datarails holds Actuals for (${readable.map((one) => `"@${one}"`).join(", ")}); read the starting value from them with baseline_from ({"metric": "@<key>", "rule": "l12m_mean"}), so the starting value in Datarails is an Actuals figure, not a typed one`
13451
+ );
13452
+ }
13056
13453
  for (const key of [...operandsOf2.keys()].sort(natural3)) {
13057
13454
  for (const dep of operandsOf2.get(key)) {
13058
13455
  if (metricReaches(operandsOf2, dep, key, /* @__PURE__ */ new Set())) {
@@ -13099,8 +13496,10 @@ function metricProblems(metrics, sources) {
13099
13496
  if (used.has(key)) return;
13100
13497
  used.add(key);
13101
13498
  for (const one of operandsOf2.get(key) ?? []) visit(one);
13499
+ for (const one of calculationReads.get(key) ?? []) visit(one);
13102
13500
  };
13103
13501
  for (const key of read) visit(key);
13502
+ for (const key of baselineReads) visit(key);
13104
13503
  for (const key of declaredKeys) {
13105
13504
  if (used.has(key)) continue;
13106
13505
  advise(
@@ -13134,6 +13533,160 @@ function metricProblems(metrics, sources) {
13134
13533
  }
13135
13534
  return problems;
13136
13535
  }
13536
+ function shapedProblems(sources) {
13537
+ const problems = [];
13538
+ for (const name of Object.keys(sources ?? {}).sort(natural3)) {
13539
+ const row = sources[name];
13540
+ if (!isPlainObject8(row) || row.shaped === void 0) continue;
13541
+ const pointer2 = `/data/sources/${escapePointer3(name)}/shaped`;
13542
+ if (shapedOf(row) === null) {
13543
+ problems.push({
13544
+ code: "source_shaped",
13545
+ pointer: pointer2,
13546
+ message: `source "${name}" states shaped ${JSON.stringify(row.shaped)}; shaped is {"step": "<step>", "label": "<the card's sentence>"}, step one of fy, split, solve or custom:<name> (${SHAPED_STEP_RE.source}) and label at most ${SHAPED_LABEL_MAX} characters, with nothing else`
13547
+ });
13548
+ } else if (Object.keys(row.shaped).some((key) => key !== "step" && key !== "label")) {
13549
+ problems.push({ code: "source_shaped", pointer: pointer2, message: `source "${name}"'s shaped states ${Object.keys(row.shaped).filter((key) => key !== "step" && key !== "label").sort(natural3).join(", ")}, which it does not take; it takes step and label` });
13550
+ } else if (typeof row.transform !== "string" || row.transform === "") {
13551
+ problems.push({ code: "source_shaped", pointer: pointer2, message: `source "${name}" labels a step (shaped) and has no transform, so the label names nothing the app does; drop shaped, or state the transform that takes the step` });
13552
+ }
13553
+ }
13554
+ return problems;
13555
+ }
13556
+ var MODEL_KEYS = ["plan", "results", "lines", "scenarios"];
13557
+ var MODEL_PLAN_KEYS = ["module", "cycle", "year"];
13558
+ var MODEL_MODULES = ["forecast", "budget"];
13559
+ var MODEL_LINE_KEYS = ["fy", "plain_english"];
13560
+ var MODEL_FY_RULES = ["sum", "last", "average"];
13561
+ var MODEL_SCENARIO_KEYS = ["kind", "names", "versions"];
13562
+ var MODEL_SCENARIO_KINDS = ["planning_scenario", "app_plan"];
13563
+ function planModelProblems(model, metrics) {
13564
+ const problems = [];
13565
+ if (model === void 0 || model === null) return problems;
13566
+ const say = (pointer2, message) => problems.push({ code: "model_decl", pointer: `/data/model${pointer2}`, message: `data.model ${message}` });
13567
+ if (!isPlainObject8(model)) {
13568
+ say("", `is ${JSON.stringify(model)}; it is an object: {"plan": {...}, "results": [...], "lines": {...}, "scenarios": {...}}`);
13569
+ return problems;
13570
+ }
13571
+ const declared = isPlainObject8(metrics) ? metrics : {};
13572
+ const known = (ref) => {
13573
+ const match = typeof ref === "string" ? METRIC_REF_RE.exec(ref) : null;
13574
+ return match !== null && Object.hasOwn(declared, match[1]) ? match[1] : null;
13575
+ };
13576
+ const refSentence = (ref) => `${JSON.stringify(ref ?? null)}, which is not a metric data.metrics declares, written "@<key>" (it declares ${Object.keys(declared).length > 0 ? Object.keys(declared).sort(natural3).map((one) => `"@${one}"`).join(", ") : "none"})`;
13577
+ for (const key of Object.keys(model).sort(natural3)) {
13578
+ if (!MODEL_KEYS.includes(key)) say(`/${escapePointer3(key)}`, `states ${key}, which a model does not take; it takes ${either3(MODEL_KEYS)}`);
13579
+ }
13580
+ const { plan, results, lines, scenarios } = model;
13581
+ if (plan !== void 0) {
13582
+ if (!isPlainObject8(plan)) say("/plan", `states plan ${JSON.stringify(plan)}; a plan is {"module": "forecast" | "budget", "cycle": "4+8", "year": 2026}`);
13583
+ else {
13584
+ for (const key of Object.keys(plan).sort(natural3)) if (!MODEL_PLAN_KEYS.includes(key)) say(`/plan/${escapePointer3(key)}`, `plan states ${key}, which a plan does not take; it takes ${either3(MODEL_PLAN_KEYS)}`);
13585
+ if (!MODEL_MODULES.includes(plan.module)) say("/plan/module", `plan's module is ${JSON.stringify(plan.module ?? null)}; it is ${either3(MODEL_MODULES)}`);
13586
+ if (typeof plan.cycle !== "string" || plan.cycle.trim() === "" || plan.cycle.length > 64) say("/plan/cycle", `plan's cycle is ${JSON.stringify(plan.cycle ?? null)}; it is the cycle as Datarails names it ("4+8"), or "favourite"`);
13587
+ if (plan.year !== void 0 && !(Number.isInteger(plan.year) && plan.year >= 2e3 && plan.year <= 2100)) say("/plan/year", `plan's year is ${JSON.stringify(plan.year)}; it is a year, 2026`);
13588
+ }
13589
+ }
13590
+ if (results !== void 0) {
13591
+ if (!Array.isArray(results)) say("/results", `states results ${JSON.stringify(results)}; results is a list of declared metrics, each "@<key>"`);
13592
+ else results.forEach((ref, index) => known(ref) === null && say(`/results/${index}`, `result ${index} is ${refSentence(ref)}`));
13593
+ }
13594
+ if (lines !== void 0) {
13595
+ if (!isPlainObject8(lines)) say("/lines", `states lines ${JSON.stringify(lines)}; lines is an object keyed by a declared metric, "@<key>": {"fy": "sum"}`);
13596
+ else {
13597
+ for (const ref of Object.keys(lines).sort(natural3)) {
13598
+ const at = `/lines/${escapePointer3(ref)}`;
13599
+ if (known(ref) === null) say(at, `states a line for ${refSentence(ref)}`);
13600
+ const line2 = lines[ref];
13601
+ if (!isPlainObject8(line2)) {
13602
+ say(at, `line "${ref}" is ${JSON.stringify(line2 ?? null)}; a line is {"fy": "sum" | "last" | "average", "plain_english": "..."}`);
13603
+ continue;
13604
+ }
13605
+ for (const key of Object.keys(line2).sort(natural3)) if (!MODEL_LINE_KEYS.includes(key)) say(`${at}/${escapePointer3(key)}`, `line "${ref}" states ${key}, which a line does not take; it takes ${either3(MODEL_LINE_KEYS)}`);
13606
+ if (line2.fy !== void 0 && !MODEL_FY_RULES.includes(line2.fy)) say(`${at}/fy`, `line "${ref}" makes its year total by ${JSON.stringify(line2.fy)}; fy is ${either3(MODEL_FY_RULES)}`);
13607
+ if (line2.plain_english !== void 0 && (typeof line2.plain_english !== "string" || line2.plain_english.length > 500)) say(`${at}/plain_english`, `line "${ref}" states plain_english ${JSON.stringify(line2.plain_english)}; it is a sentence, at most 500 characters`);
13608
+ }
13609
+ }
13610
+ }
13611
+ if (scenarios !== void 0) {
13612
+ if (!isPlainObject8(scenarios)) say("/scenarios", `states scenarios ${JSON.stringify(scenarios)}; it is {"kind": "planning_scenario" | "app_plan", "names": "user" | [...], "versions": ["@<key>"]}`);
13613
+ else {
13614
+ for (const key of Object.keys(scenarios).sort(natural3)) if (!MODEL_SCENARIO_KEYS.includes(key)) say(`/scenarios/${escapePointer3(key)}`, `scenarios states ${key}, which it does not take; it takes ${either3(MODEL_SCENARIO_KEYS)}`);
13615
+ if (!MODEL_SCENARIO_KINDS.includes(scenarios.kind)) say("/scenarios/kind", `scenarios' kind is ${JSON.stringify(scenarios.kind ?? null)}; it is ${either3(MODEL_SCENARIO_KINDS)}`);
13616
+ const names = scenarios.names;
13617
+ if (names !== void 0 && names !== "user" && !(Array.isArray(names) && names.length > 0 && names.every((one) => typeof one === "string" && one.trim() !== "" && one.length <= 64) && new Set(names).size === names.length)) {
13618
+ say("/scenarios/names", `scenarios' names are ${JSON.stringify(names)}; names is "user" (the viewer names each) or a list of distinct names, each at most 64 characters`);
13619
+ }
13620
+ if (scenarios.versions !== void 0) {
13621
+ if (!Array.isArray(scenarios.versions)) say("/scenarios/versions", `scenarios' versions are ${JSON.stringify(scenarios.versions)}; versions is a list of declared calc metrics, each "@<key>"`);
13622
+ else {
13623
+ scenarios.versions.forEach((ref, index) => {
13624
+ const key = known(ref);
13625
+ if (key === null) say(`/scenarios/versions/${index}`, `version ${index} is ${refSentence(ref)}`);
13626
+ else if (declared[key]?.kind !== "calc") say(`/scenarios/versions/${index}`, `version ${index} is "${ref}", a ${declared[key]?.kind ?? "bound"} metric; a save binds a version as a Forecast calculation, which only a calc metric holds`);
13627
+ });
13628
+ }
13629
+ }
13630
+ }
13631
+ }
13632
+ return problems;
13633
+ }
13634
+ var FY_AGG = { sum: "sum", last: "last", average: "avg" };
13635
+ var BALANCE_ACCOUNT_TYPES = /* @__PURE__ */ new Set(["asset", "assets", "liability", "liabilities", "equity"]);
13636
+ function modelTotalProblems(model, sources) {
13637
+ const problems = [];
13638
+ const lines = isPlainObject8(model) && isPlainObject8(model.lines) ? model.lines : {};
13639
+ for (const [name, row] of Object.entries(isPlainObject8(sources) ? sources : {})) {
13640
+ if (!isPlainObject8(row) || row.shape !== "kpi" || row.transform !== void 0 && row.transform !== null && row.transform !== false && row.transform !== "") continue;
13641
+ const metric = isPlainObject8(row.from) && isPlainObject8(row.from.financeos) ? row.from.financeos.metric : null;
13642
+ const line2 = typeof metric === "string" && Object.hasOwn(lines, metric) && isPlainObject8(lines[metric]) ? lines[metric] : null;
13643
+ const want = line2 !== null && typeof line2.fy === "string" && Object.hasOwn(FY_AGG, line2.fy) ? FY_AGG[line2.fy] : null;
13644
+ if (want === null) continue;
13645
+ const stated2 = typeof row.agg === "string" && row.agg !== "";
13646
+ const balance = typeof row.account_type === "string" && BALANCE_ACCOUNT_TYPES.has(row.account_type.trim().toLowerCase());
13647
+ const drawn2 = stated2 ? row.agg : balance ? "last" : "sum";
13648
+ if (drawn2 === want) continue;
13649
+ problems.push({
13650
+ code: "source_fy_agg",
13651
+ pointer: `/data/sources/${escapePointer3(name)}/agg`,
13652
+ message: `source "${name}" totals ${metric}, whose model line makes its year total by fy ${JSON.stringify(line2.fy)}, and the card ${stated2 ? `states agg ${JSON.stringify(row.agg)}` : `states no agg, so it takes ${JSON.stringify(drawn2)}`}; state "agg": ${JSON.stringify(want)} on the source, or change the line's fy`
13653
+ });
13654
+ }
13655
+ return problems;
13656
+ }
13657
+ function driverParamProblems(contract) {
13658
+ const problems = [];
13659
+ const declared = isPlainObject8(contract?.data?.metrics) ? contract.data.metrics : {};
13660
+ const finite = (value) => typeof value === "number" && Number.isFinite(value);
13661
+ (Array.isArray(contract?.pages) ? contract.pages : []).forEach((page, pageIndex) => {
13662
+ (Array.isArray(page?.params) ? page.params : []).forEach((param, index) => {
13663
+ const match = isPlainObject8(param) && typeof param.default === "string" && NUMERIC_PARAM_KINDS.has(param.kind) ? METRIC_REF_RE.exec(param.default) : null;
13664
+ if (match === null) return;
13665
+ const pointer2 = `/pages/${pageIndex}/params/${index}/default`;
13666
+ const said2 = `page ${JSON.stringify(page.path ?? pageIndex)}'s param "${param.name}"`;
13667
+ const decl = Object.hasOwn(declared, match[1]) ? declared[match[1]] : void 0;
13668
+ if (decl === void 0 || decl?.kind !== "driver") {
13669
+ problems.push({
13670
+ code: "param_kind_value",
13671
+ pointer: pointer2,
13672
+ message: `${said2} (${param.kind}) defaults to ${JSON.stringify(param.default)}; a ${param.kind} opens on a finite number, or on a driver data.metrics declares, "@<key>"${decl !== void 0 ? ` \u2014 "${param.default}" is a ${decl?.kind ?? "bound"} metric, not a driver` : ""}`
13673
+ });
13674
+ return;
13675
+ }
13676
+ const below = finite(decl.min) && (!finite(param.min) || param.min < decl.min);
13677
+ const above = finite(decl.max) && (!finite(param.max) || param.max > decl.max);
13678
+ if (below || above) {
13679
+ problems.push({
13680
+ code: "driver_bounds",
13681
+ pointer: `/pages/${pageIndex}/params/${index}`,
13682
+ message: `${said2} moves driver "${param.default}" over [${finite(param.min) ? param.min : "\u2026"}, ${finite(param.max) ? param.max : "\u2026"}], and the driver takes [${finite(decl.min) ? decl.min : "\u2026"}, ${finite(decl.max) ? decl.max : "\u2026"}]; hold the ${param.kind}'s min and max within the driver's`,
13683
+ advisory: true
13684
+ });
13685
+ }
13686
+ });
13687
+ });
13688
+ return problems;
13689
+ }
13137
13690
  var SOURCE_ORDERS = ["source", "declared"];
13138
13691
  function orderProblems(name, row, at) {
13139
13692
  const problems = [];
@@ -13564,7 +14117,8 @@ function paramValueProblems(param, said2, at) {
13564
14117
  const value = param.default;
13565
14118
  const values = Array.isArray(param.values) ? param.values : null;
13566
14119
  if (NUMERIC_PARAM_KINDS.has(kind)) {
13567
- if (!finite(value)) refuse2("default", `defaults to ${JSON.stringify(value)}; a ${kind} opens on a finite number`);
14120
+ if (typeof value === "string" && METRIC_REF_RE.test(value)) return problems;
14121
+ if (!finite(value)) refuse2("default", `defaults to ${JSON.stringify(value)}; a ${kind} opens on a finite number, or on a driver data.metrics declares, "@<key>"`);
13568
14122
  else if (finite(min) && value < min || finite(max) && value > max) {
13569
14123
  refuse2("default", `defaults to ${value}, outside its own range [${finite(min) ? min : "\u2026"}, ${finite(max) ? max : "\u2026"}] \u2014 the page would open on no value at all`);
13570
14124
  }
@@ -13714,7 +14268,14 @@ function compileApp(contract, { kit = null, runtime = RUNTIME, extra = {} } = {}
13714
14268
  problems.push(...sourceFindings.filter((one) => !one.advisory));
13715
14269
  problems.push(...compareProblems(stated2, model));
13716
14270
  problems.push(...exprProblems(stated2));
13717
- const metricFindings = metricProblems(contract?.data?.metrics, stated2);
14271
+ problems.push(...shapedProblems(stated2));
14272
+ const metricFindings = [
14273
+ ...metricProblems(contract?.data?.metrics, stated2),
14274
+ // The forecast plan's P1: the planning model, and the params that open on a driver.
14275
+ ...planModelProblems(contract?.data?.model, contract?.data?.metrics),
14276
+ ...modelTotalProblems(contract?.data?.model, stated2),
14277
+ ...driverParamProblems(contract)
14278
+ ];
13718
14279
  problems.push(...metricFindings.filter((one) => !one.advisory));
13719
14280
  const owned = ownedReaders(contract.pages, extra);
13720
14281
  problems.push(...paramProblems(withOwnedReaders(contract, owned.readers), stated2));
@@ -17834,7 +18395,7 @@ var LITERAL_OK = /* @__PURE__ */ new Set([
17834
18395
  function validateContract(contract, catalog) {
17835
18396
  const problems = [];
17836
18397
  const warnings = [];
17837
- const doc = isObject4(contract) ? contract : {};
18398
+ const doc = isObject5(contract) ? contract : {};
17838
18399
  const app = obj(doc["app"]);
17839
18400
  const kind = kindOf2(doc);
17840
18401
  const renderer = kind === "dashboard" ? rendererOf2(doc) : "widgets";
@@ -17897,7 +18458,7 @@ function checkAppSources(doc, problems) {
17897
18458
  for (const [name, raw] of Object.entries(sources)) {
17898
18459
  const row = obj(raw);
17899
18460
  const from = row["from"];
17900
- const spelling = Array.isArray(from) ? "depends" : isObject4(from) ? ["financeos", "table", "call"].find((key) => key in from) ?? null : null;
18461
+ const spelling = Array.isArray(from) ? "depends" : isObject5(from) ? ["financeos", "table", "call"].find((key) => key in from) ?? null : null;
17901
18462
  if (spelling === null) {
17902
18463
  problems.push({
17903
18464
  code: "app-model",
@@ -17981,11 +18542,11 @@ function skipChartColumns(doc, skipped) {
17981
18542
  }
17982
18543
  }
17983
18544
  function kindOf2(contract) {
17984
- const doc = isObject4(contract) ? contract : {};
18545
+ const doc = isObject5(contract) ? contract : {};
17985
18546
  return obj(doc["app"])["kind"] === "dashboard" ? "dashboard" : "app";
17986
18547
  }
17987
18548
  function rendererOf2(contract) {
17988
- const doc = isObject4(contract) ? contract : {};
18549
+ const doc = isObject5(contract) ? contract : {};
17989
18550
  return obj(doc["app"])["renderer"] === RUNTIME_RENDERER2 ? "runtime" : "widgets";
17990
18551
  }
17991
18552
  function isRuntimeDashboard(contract) {
@@ -18095,7 +18656,7 @@ function valueAt(root, at) {
18095
18656
  for (const token of at.split("/").slice(1)) {
18096
18657
  const key = token.replace(/~1/g, "/").replace(/~0/g, "~");
18097
18658
  if (Array.isArray(node)) node = node[Number(key)];
18098
- else if (isObject4(node) && Object.prototype.hasOwnProperty.call(node, key)) node = node[key];
18659
+ else if (isObject5(node) && Object.prototype.hasOwnProperty.call(node, key)) node = node[key];
18099
18660
  else return void 0;
18100
18661
  }
18101
18662
  return node;
@@ -18112,7 +18673,7 @@ function authoredColumns(schema) {
18112
18673
  function authoringSchema(schema) {
18113
18674
  const relax = (node, keep) => {
18114
18675
  if (Array.isArray(node)) return node.map((item) => relax(item, keep));
18115
- if (!isObject4(node)) return node;
18676
+ if (!isObject5(node)) return node;
18116
18677
  const out2 = {};
18117
18678
  for (const [key, value] of Object.entries(node)) {
18118
18679
  if (key === "required" && Array.isArray(value)) {
@@ -18129,12 +18690,12 @@ function authoringSchema(schema) {
18129
18690
  out[key] = value.filter((name) => AUTHORED_REQUIRED[""]?.includes(String(name)));
18130
18691
  continue;
18131
18692
  }
18132
- if (key === "$defs" && isObject4(value)) {
18693
+ if (key === "$defs" && isObject5(value)) {
18133
18694
  const defs = {};
18134
18695
  for (const [name, def] of Object.entries(value)) {
18135
18696
  const keep = AUTHORED_REQUIRED[name] ?? [];
18136
18697
  const relaxed = relax(def, null);
18137
- if (isObject4(def) && Array.isArray(def["required"])) {
18698
+ if (isObject5(def) && Array.isArray(def["required"])) {
18138
18699
  relaxed["required"] = def["required"].filter((key2) => keep.includes(String(key2)));
18139
18700
  }
18140
18701
  defs[name] = relaxed;
@@ -18174,7 +18735,7 @@ function stripAuthoringKeys(doc) {
18174
18735
  }
18175
18736
  function checkPreset(app, problems) {
18176
18737
  const theme = app["theme"];
18177
- if (!isObject4(theme) || !("preset" in theme)) return;
18738
+ if (!isObject5(theme) || !("preset" in theme)) return;
18178
18739
  const preset = theme["preset"];
18179
18740
  if (typeof preset === "string" && PRESETS2.includes(preset)) return;
18180
18741
  problems.push({
@@ -18366,7 +18927,7 @@ function checkSources(doc, catalog, problems, skipped) {
18366
18927
  for (const key of ["measure", "period_field", "value_field", "label_field", "dimension"]) {
18367
18928
  const held = source[key];
18368
18929
  if (held === void 0 || held === null) continue;
18369
- if (isObject4(held)) {
18930
+ if (isObject5(held)) {
18370
18931
  if (typeof held["field"] === "string") {
18371
18932
  report(held["field"], ["data", "widgets", id, "source", key, "field"]);
18372
18933
  }
@@ -18376,8 +18937,8 @@ function checkSources(doc, catalog, problems, skipped) {
18376
18937
  }
18377
18938
  {
18378
18939
  const held = source["period_field"];
18379
- const field = isObject4(held) ? held["field"] : held;
18380
- const epoch = isObject4(held) && held["format"] === "epoch";
18940
+ const field = isObject5(held) ? held["field"] : held;
18941
+ const epoch = isObject5(held) && held["format"] === "epoch";
18381
18942
  if (typeof field === "string" && dated.has(field.toLowerCase()) && source["period_is_date"] !== true && !epoch) {
18382
18943
  problems.push({
18383
18944
  code: "period-needs-date",
@@ -18389,7 +18950,7 @@ function checkSources(doc, catalog, problems, skipped) {
18389
18950
  }
18390
18951
  for (const key of ["select", "dimensions", "measures"]) {
18391
18952
  for (const [index, name] of list2(source[key]).entries()) {
18392
- if (isObject4(name)) {
18953
+ if (isObject5(name)) {
18393
18954
  if (typeof name["field"] === "string") {
18394
18955
  report(name["field"], ["data", "widgets", id, "source", key, index, "field"]);
18395
18956
  }
@@ -18437,7 +18998,7 @@ var EPOCH_EXAMPLE = '{"type": "advanced", "val": [{"condition": "gte", "value":
18437
18998
  var PERIOD_SCOPE = "Scoping a dashboard to a period is normally the page\u2019s period window plus the widget\u2019s `honors`, not a `where` at all.";
18438
18999
  var CALENDAR_DATE = /^\d{4}-\d{2}-\d{2}/;
18439
19000
  function calendarDateIn(filter) {
18440
- if (!isObject4(filter)) return void 0;
19001
+ if (!isObject5(filter)) return void 0;
18441
19002
  if (!Array.isArray(filter["val"])) return void 0;
18442
19003
  for (const raw of filter["val"]) {
18443
19004
  const condition = obj(raw);
@@ -18667,7 +19228,7 @@ function checkPages(doc, kind, problems) {
18667
19228
  function checkPeriodOverride(doc, problems) {
18668
19229
  const widgets = obj(obj(doc["data"])["widgets"]);
18669
19230
  const reads = (row) => !(row["kind"] === "narrative" && row["mode"] === "agent") && ["source", "data", "compute", "depends"].some((key) => row[key] !== void 0 && row[key] !== null);
18670
- const overrides = (row) => isObject4(row["period"]) && Array.isArray(row["honors"]) && !row["honors"].includes("period");
19231
+ const overrides = (row) => isObject5(row["period"]) && Array.isArray(row["honors"]) && !row["honors"].includes("period");
18671
19232
  const byPage = /* @__PURE__ */ new Map();
18672
19233
  for (const raw of Object.values(obj(doc["elements"]))) {
18673
19234
  const element = obj(raw);
@@ -18708,7 +19269,7 @@ function checkKinds(doc, problems, renderer = "widgets") {
18708
19269
  const id = cardKeyOf(element, renderer);
18709
19270
  if (typeof id !== "string") continue;
18710
19271
  const row = widgets[id];
18711
- if (!isObject4(row)) continue;
19272
+ if (!isObject5(row)) continue;
18712
19273
  const payload = row["kind"];
18713
19274
  if (typeof payload !== "string" || !PAYLOAD_KINDS.includes(payload)) continue;
18714
19275
  if (KIND_READS3[cardKind]?.includes(payload) === true) continue;
@@ -18723,7 +19284,7 @@ function checkKinds(doc, problems, renderer = "widgets") {
18723
19284
  function checkDrillTargets(doc, problems) {
18724
19285
  const widgets = obj(obj(doc["data"])["widgets"]);
18725
19286
  for (const [id, raw] of Object.entries(widgets)) {
18726
- if (id.startsWith("_") || !isObject4(raw)) continue;
19287
+ if (id.startsWith("_") || !isObject5(raw)) continue;
18727
19288
  const row = raw;
18728
19289
  if (row["data"] !== void 0 && row["data"] !== null) continue;
18729
19290
  const drill = list2(row["drill"]).filter((name) => typeof name === "string");
@@ -18743,7 +19304,7 @@ function checkDrillTargets(doc, problems) {
18743
19304
  continue;
18744
19305
  }
18745
19306
  if (row["kind"] !== "table") continue;
18746
- const declared = list2(row["columns"]).map((column) => isObject4(column) ? column["key"] : void 0).filter((key) => typeof key === "string" && key !== "");
19307
+ const declared = list2(row["columns"]).map((column) => isObject5(column) ? column["key"] : void 0).filter((key) => typeof key === "string" && key !== "");
18747
19308
  const keys2 = declared.length > 0 ? declared : list2(obj(row["source"])["dimensions"]).filter((key) => typeof key === "string");
18748
19309
  if (keys2.length === 0 || keys2.some((key) => offered.has(key.toLowerCase()))) continue;
18749
19310
  problems.push({
@@ -18757,7 +19318,7 @@ function checkDrillTargets(doc, problems) {
18757
19318
  function menuless(row) {
18758
19319
  if (row["compute"] || row["transform"] !== void 0 && row["transform"] !== null) return true;
18759
19320
  const source = row["source"];
18760
- if (!isObject4(source) || "app_table" in source || "call" in source) return true;
19321
+ if (!isObject5(source) || "app_table" in source || "call" in source) return true;
18761
19322
  if ("metric_id" in source) return Boolean(source["drill_rows"]) && typeof row["value_field"] !== "string";
18762
19323
  if (!addressesTable(source)) return true;
18763
19324
  const measures = list2(source["measures"]).length > 0 ? list2(source["measures"]) : source["measure"] ? [source["measure"]] : [];
@@ -18772,10 +19333,10 @@ function checkAggOrAccountType(doc, warnings) {
18772
19333
  const widgets = obj(obj(doc["data"])["widgets"]);
18773
19334
  const declared = (value) => typeof value === "string" && value.trim() !== "";
18774
19335
  for (const [id, raw] of Object.entries(widgets)) {
18775
- if (id.startsWith("_") || !isObject4(raw)) continue;
19336
+ if (id.startsWith("_") || !isObject5(raw)) continue;
18776
19337
  const row = raw;
18777
19338
  if (row["kind"] !== "kpi" && row["kind"] !== "series") continue;
18778
- if (!isObject4(row["source"])) continue;
19339
+ if (!isObject5(row["source"])) continue;
18779
19340
  if (["data", "compute", "transform", "shape"].some((key) => row[key] !== void 0 && row[key] !== null)) continue;
18780
19341
  if (declared(row["agg"]) || declared(row["account_type"])) continue;
18781
19342
  warnings.push({
@@ -18788,7 +19349,7 @@ function checkAggOrAccountType(doc, warnings) {
18788
19349
  }
18789
19350
  function checkPairing(doc, problems, renderer = "widgets") {
18790
19351
  const data = doc["data"];
18791
- if (!isObject4(data) || !isObject4(data["widgets"])) return;
19352
+ if (!isObject5(data) || !isObject5(data["widgets"])) return;
18792
19353
  const widgets = obj(data["widgets"]);
18793
19354
  const drawn2 = /* @__PURE__ */ new Set();
18794
19355
  for (const [uid, raw] of Object.entries(obj(doc["elements"]))) {
@@ -18819,7 +19380,7 @@ function checkPairing(doc, problems, renderer = "widgets") {
18819
19380
  }
18820
19381
  function checkAppCards(doc, problems) {
18821
19382
  const data = doc["data"];
18822
- const rows2 = isObject4(data) ? obj(data["widgets"]) : {};
19383
+ const rows2 = isObject5(data) ? obj(data["widgets"]) : {};
18823
19384
  for (const id of Object.keys(rows2)) {
18824
19385
  problems.push({
18825
19386
  code: "orphan-spec",
@@ -18932,7 +19493,7 @@ function checkKitRules(doc, kind, problems, renderer = "widgets") {
18932
19493
  fix: "Name the file under ui/components that draws it, as components/<name>.js; app-space eject element:<uid> writes one."
18933
19494
  });
18934
19495
  }
18935
- if ("args" in props && !isObject4(props["args"])) {
19496
+ if ("args" in props && !isObject5(props["args"])) {
18936
19497
  problems.push({
18937
19498
  code: "vocabulary",
18938
19499
  pointer: pointer("elements", uid, "props", "args"),
@@ -18974,7 +19535,7 @@ function checkKitRules(doc, kind, problems, renderer = "widgets") {
18974
19535
  });
18975
19536
  }
18976
19537
  const agentNarrative = row["kind"] === "narrative" && row["mode"] === "agent";
18977
- if (!isObject4(row["source"]) && row["data"] === void 0 && row["compute"] === void 0 && !agentNarrative && typeof row["kind"] === "string") {
19538
+ if (!isObject5(row["source"]) && row["data"] === void 0 && row["compute"] === void 0 && !agentNarrative && typeof row["kind"] === "string") {
18978
19539
  problems.push({
18979
19540
  code: "missing-prop",
18980
19541
  pointer: pointer("data", "widgets", id, "source"),
@@ -18983,7 +19544,7 @@ function checkKitRules(doc, kind, problems, renderer = "widgets") {
18983
19544
  });
18984
19545
  }
18985
19546
  walk3(row, ["data", "widgets", id], (value, path3, key) => {
18986
- if (isObject4(value) && typeof value["$callable"] === "string") {
19547
+ if (isObject5(value) && typeof value["$callable"] === "string") {
18987
19548
  if (known.size > 0 && !known.has(value["$callable"])) {
18988
19549
  problems.push({
18989
19550
  code: "unknown_callable",
@@ -18994,7 +19555,7 @@ function checkKitRules(doc, kind, problems, renderer = "widgets") {
18994
19555
  }
18995
19556
  return false;
18996
19557
  }
18997
- if (isObject4(value) && "$unresolved" in value) {
19558
+ if (isObject5(value) && "$unresolved" in value) {
18998
19559
  problems.push({
18999
19560
  code: "unresolved_value",
19000
19561
  pointer: pointer(...path3),
@@ -19323,7 +19884,7 @@ var LITERAL_DEFAULT_FIX = `Drop "default": a column takes only "gen" (uuid) or "
19323
19884
  function checkColumnDefaults(tables, problems) {
19324
19885
  for (const [table, rawTable] of Object.entries(tables)) {
19325
19886
  for (const [column, raw] of Object.entries(obj(obj(rawTable)["columns"]))) {
19326
- if (!isObject4(raw)) continue;
19887
+ if (!isObject5(raw)) continue;
19327
19888
  const value = raw["default"];
19328
19889
  if (value === void 0 || value === null) continue;
19329
19890
  const type = typeof raw["type"] === "string" ? raw["type"] : "text";
@@ -19406,7 +19967,7 @@ function walk3(node, path3, visit) {
19406
19967
  });
19407
19968
  return;
19408
19969
  }
19409
- if (isObject4(node)) {
19970
+ if (isObject5(node)) {
19410
19971
  for (const [name, value] of Object.entries(node)) walk3(value, [...path3, name], visit);
19411
19972
  }
19412
19973
  }
@@ -19430,11 +19991,11 @@ function dedupeSkipped(skipped) {
19430
19991
  return true;
19431
19992
  });
19432
19993
  }
19433
- function isObject4(value) {
19994
+ function isObject5(value) {
19434
19995
  return typeof value === "object" && value !== null && !Array.isArray(value);
19435
19996
  }
19436
19997
  function obj(value) {
19437
- return isObject4(value) ? value : {};
19998
+ return isObject5(value) ? value : {};
19438
19999
  }
19439
20000
  function list2(value) {
19440
20001
  return Array.isArray(value) ? value : [];
@@ -19720,7 +20281,7 @@ function assemble(input) {
19720
20281
  if (problems.length > 0) return fail();
19721
20282
  const rebuilt = new Set(groups.map((group) => String(group.page["path"])));
19722
20283
  for (const { draft, key, name } of replaced) {
19723
- const readers = readersOf(contract, key, name).filter(
20284
+ const readers = readersOf2(contract, key, name).filter(
19724
20285
  (id) => Object.values(elements).some((element) => isObj(element) && keyOf(element) === id && !rebuilt.has(String(element["page"])))
19725
20286
  );
19726
20287
  did.push(
@@ -20279,7 +20840,7 @@ function rowAt(row, datasetAs) {
20279
20840
  function describe3(key, name) {
20280
20841
  return key === "reads" ? `read "${name}"` : key === "datasets" ? `dataset "${name}"` : `page "${name}"`;
20281
20842
  }
20282
- function readersOf(contract, key, name) {
20843
+ function readersOf2(contract, key, name) {
20283
20844
  const data = contract["data"];
20284
20845
  const widgets = isObj(data["widgets"]) ? data["widgets"] : {};
20285
20846
  const datasets = isObj(data["datasets"]) ? data["datasets"] : {};
@@ -21860,6 +22421,10 @@ function metricsTransport(client) {
21860
22421
  claims: () => client.claims === void 0 ? null : client.claims()
21861
22422
  };
21862
22423
  }
22424
+ function modelPlanOf(contract) {
22425
+ const plan = obj2(obj2(obj2(obj2(contract)["data"])["model"])["plan"]);
22426
+ return Object.keys(plan).length === 0 ? null : plan;
22427
+ }
21863
22428
  function declaredMetrics(contract) {
21864
22429
  const data = obj2(obj2(contract)["data"]);
21865
22430
  const metrics = obj2(data["metrics"]);
@@ -21925,7 +22490,13 @@ function catalogRow(raw) {
21925
22490
  description: typeof raw["description"] === "string" ? raw["description"] : null,
21926
22491
  category: typeof raw["category"] === "string" ? raw["category"] : isObj3(raw["category"]) && typeof raw["category"]["name"] === "string" ? raw["category"]["name"] : null,
21927
22492
  status: typeof status["status"] === "string" ? status["status"].toUpperCase() : null,
21928
- created_at: typeof raw["created_at"] === "string" ? raw["created_at"] : null
22493
+ created_at: typeof raw["created_at"] === "string" ? raw["created_at"] : null,
22494
+ calculations: (Array.isArray(raw["calculations"]) ? raw["calculations"] : []).filter(isObj3).flatMap((one) => {
22495
+ const formula = one["presented_formula"];
22496
+ if (typeof formula !== "string" || formula === "") return [];
22497
+ const text4 = (value) => typeof value === "string" ? value : "";
22498
+ return [{ scenario: text4(one["scenario"]), scenario_cycle: text4(one["scenario_cycle"]), planning_scenario: text4(one["planning_scenario"]), formula }];
22499
+ })
21929
22500
  };
21930
22501
  }
21931
22502
  function authTableRow(raw) {
@@ -21995,12 +22566,13 @@ function rollupOf(def) {
21995
22566
  }
21996
22567
  var OPERAND_RE = /'([^']*)'|\[([^[\]]*)\]/g;
21997
22568
  var MARK = "";
21998
- function calcSkeleton(formula, idOf4) {
22569
+ function calcSkeleton(formula, idOf4, self = null) {
21999
22570
  let missing = false;
22000
22571
  const ids = /* @__PURE__ */ new Set();
22001
22572
  const marked2 = formula.replace(OPERAND_RE, (_m, quoted3, bracketed) => {
22002
22573
  const name = quoted3 ?? bracketed ?? "";
22003
22574
  if (SYSTEM_VARIABLES.includes(name)) return `${MARK}${name.toLowerCase()}${MARK}`;
22575
+ if (self !== null && name === self) return `${MARK}self${MARK}`;
22004
22576
  const id = idOf4(name);
22005
22577
  if (id === null) {
22006
22578
  missing = true;
@@ -22013,9 +22585,30 @@ function calcSkeleton(formula, idOf4) {
22013
22585
  const skeleton = marked2.split(MARK).map((part, index) => index % 2 === 1 ? part : part.toLowerCase().replace(/\s+/g, "")).join("");
22014
22586
  return { skeleton, ids: [...ids].sort((a, b) => a - b) };
22015
22587
  }
22016
- function calcReuseKey(formula, idOf4) {
22588
+ function calcReuseKey(formula, idOf4, calculations = [], self = null) {
22017
22589
  const shape = calcSkeleton(formula, idOf4);
22018
- return shape === null ? null : `calc:${shape.skeleton}|${shape.ids.join(",")}`;
22590
+ if (shape === null) return null;
22591
+ const parts = [];
22592
+ const ids = new Set(shape.ids);
22593
+ for (const one of calculations) {
22594
+ const inner = calcSkeleton(one.formula, idOf4, self);
22595
+ if (inner === null) return null;
22596
+ for (const id of inner.ids) ids.add(id);
22597
+ parts.push(`${one.scenario}|${one.scenario_cycle}|${one.planning_scenario}=${inner.skeleton}`);
22598
+ }
22599
+ const base = `calc:${shape.skeleton}|${shape.ids.join(",")}`;
22600
+ return parts.length === 0 ? base : `${base}|calculations:${JSON.stringify(parts.sort())}|${[...ids].sort((a, b) => a - b).join(",")}`;
22601
+ }
22602
+ function driverReuseKey(def) {
22603
+ return `driver:${JSON.stringify([def.unit, def.additive, def.min, def.max])}`;
22604
+ }
22605
+ function driverDefinitionOf(decl) {
22606
+ return {
22607
+ unit: typeof decl.unit === "string" ? decl.unit : "",
22608
+ additive: decl.additive !== false,
22609
+ min: typeof decl.min === "number" ? decl.min : null,
22610
+ max: typeof decl.max === "number" ? decl.max : null
22611
+ };
22019
22612
  }
22020
22613
  function rowReuseKey(row, byName3) {
22021
22614
  if (row.kind === "BASE") {
@@ -22030,7 +22623,7 @@ function rowReuseKey(row, byName3) {
22030
22623
  filters: row.filters
22031
22624
  });
22032
22625
  }
22033
- if (row.kind === "CALC" && row.formula !== null) return calcReuseKey(row.formula, (name) => byName3.get(name)?.id ?? null);
22626
+ if (row.kind === "CALC" && row.formula !== null) return calcReuseKey(row.formula, (name) => byName3.get(name)?.id ?? null, row.calculations, row.name);
22034
22627
  return null;
22035
22628
  }
22036
22629
  var METRIC_CREATED_FOOTER = "Created by App Space for the app";
@@ -22090,9 +22683,32 @@ function dependencyOrder(decls) {
22090
22683
  }
22091
22684
  function operandsOf(decls, key) {
22092
22685
  const decl = decls[key];
22093
- if (decl === void 0 || decl.kind !== "calc" || typeof decl.formula !== "string") return [];
22686
+ if (decl === void 0) return [];
22687
+ if (decl.kind === "driver") return baselineRefsOf(decl);
22688
+ if (decl.kind !== "calc" || typeof decl.formula !== "string") return [];
22094
22689
  const found = metricFormulaProblems(decl.formula, Object.keys(decls));
22095
- return found.operands;
22690
+ const out = new Set(found.operands);
22691
+ for (const formula of Object.values(decl.calculations ?? {})) {
22692
+ const inner = metricFormulaProblems(formula, Object.keys(decls), { pinned: true, self: key });
22693
+ for (const one of inner.operands) if (one !== key) out.add(one);
22694
+ }
22695
+ return [...out].sort();
22696
+ }
22697
+ function baselineRefsOf(decl) {
22698
+ const from = decl.baseline_from;
22699
+ if (from === void 0) return [];
22700
+ const refs = from.rule === "l12m_ratio" ? from.ratio ?? [] : [from.metric ?? ""];
22701
+ return refs.filter((one) => /^@[a-z][a-z0-9_]*$/.test(one)).map((one) => one.slice(1));
22702
+ }
22703
+ function baselineSpecOf(decl) {
22704
+ if (decl.baseline_from !== void 0 && typeof decl.baseline_from.rule === "string") return canonicalJson(decl.baseline_from);
22705
+ if (typeof decl.baseline === "number") return canonicalJson({ baseline: decl.baseline });
22706
+ return null;
22707
+ }
22708
+ function canonicalJson(value) {
22709
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
22710
+ if (isObj3(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
22711
+ return JSON.stringify(value);
22096
22712
  }
22097
22713
  function credentialOf(claims) {
22098
22714
  const scopes = claims === null ? void 0 : claims["scopes"];
@@ -22132,6 +22748,52 @@ function describeBase(decl, tableName) {
22132
22748
  const filters = (decl.filters ?? []).map((one) => `${one.field} ${one.exclude === true ? "not in" : "in"} [${one.values.map(String).join(", ")}]`).join("; ");
22133
22749
  return `BASE on "${tableName}" (${decl.value ?? "?"} by ${decl.date ?? "?"}, ${(decl.aggregate ?? "?").toUpperCase()}${decl.time_aggregation === void 0 ? "" : `, ${decl.time_aggregation.toUpperCase()} over time`})${filters === "" ? "" : ` where ${filters}`}`;
22134
22750
  }
22751
+ function calculationsWire(decl, key, names) {
22752
+ const withSelf = { ...names, [key]: names[key] ?? decl.name };
22753
+ return Object.keys(decl.calculations ?? {}).sort().map((scenario) => ({
22754
+ scenario,
22755
+ scenario_cycle: "",
22756
+ planning_scenario: "",
22757
+ formula: wireFormula((decl.calculations ?? {})[scenario], withSelf, { pinned: true })
22758
+ }));
22759
+ }
22760
+ function describeCalc(wire, calculations) {
22761
+ const more = calculations.map((one) => `; ${one.scenario}: ${one.formula}`).join("");
22762
+ return `CALC ${wire}${more}`;
22763
+ }
22764
+ function describeDriver(def) {
22765
+ const bound = (value) => value === null ? "none" : String(value);
22766
+ return `DRIVER (unit ${def.unit === "" ? "none" : `"${def.unit}"`}, ${def.additive ? "additive" : "not additive"}, min ${bound(def.min)}, max ${bound(def.max)})`;
22767
+ }
22768
+ function baselineNote(decl) {
22769
+ if (typeof decl.baseline === "number") return `starting value ${String(decl.baseline)} (typed)`;
22770
+ const from = decl.baseline_from;
22771
+ if (from === void 0) return "no starting value";
22772
+ const refs = baselineRefsOf(decl).map((one) => `@${one}`).join(" / ");
22773
+ return `starting value read by ${from.rule} from ${refs} after it is bound`;
22774
+ }
22775
+ var DRIVER_GATES = "whether this company has the Planning product and scenario_bound_calculations on, and whether you are an admin or contributor (a driver needs all three)";
22776
+ var DEFAULT_DRIVER_CONTEXT = { scenario: "Actuals", scenario_cycle: "", planning_scenario: "" };
22777
+ async function readDriverRow(t, id) {
22778
+ const query = `scenario=Actuals&scenario_cycle=&planning_scenario=`;
22779
+ let answer;
22780
+ try {
22781
+ answer = await t.call("GET", `${t.host}/api/insights/metrics/${String(id)}/driver?${query}`);
22782
+ } catch (err) {
22783
+ return firstLine(err);
22784
+ }
22785
+ if (answer.status === 404 && isObj3(answer.body) && Object.keys(answer.body).length === 0) return null;
22786
+ if (answer.status !== 200 || !isObj3(answer.body)) return `HTTP ${String(answer.status)}${sentenceOf(answer.body) === "" ? "" : `: ${sentenceOf(answer.body)}`}`;
22787
+ const row = decodeEntities2(answer.body);
22788
+ const num = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
22789
+ return {
22790
+ unit: typeof row["unit"] === "string" ? row["unit"] : "",
22791
+ additive: row["is_additive"] !== false,
22792
+ min: num(row["min_value"]),
22793
+ max: num(row["max_value"]),
22794
+ baseline: num(row["baseline_value"])
22795
+ };
22796
+ }
22135
22797
  function describeRow(row, tables) {
22136
22798
  if (row.kind === "CALC") return `CALC ${row.formula ?? "(no formula)"}`;
22137
22799
  if (row.kind !== "BASE") return row.kind === "" ? "a metric" : `a ${row.kind} metric`;
@@ -22155,7 +22817,19 @@ async function readUsage(t, appId, metricId) {
22155
22817
  if (answer.status !== 200) return `App Space could not say whether it may change it (HTTP ${String(answer.status)})`;
22156
22818
  const one = obj2(obj2(obj2(answer.body)["metrics"])[String(metricId)]);
22157
22819
  const app = obj2(one["this_app"]);
22820
+ const baselines = {};
22821
+ for (const [key, raw] of Object.entries(obj2(app["baselines"]))) {
22822
+ if (!isObj3(raw)) continue;
22823
+ const num = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
22824
+ baselines[key] = {
22825
+ value: num(raw["value"]),
22826
+ spec: typeof raw["spec"] === "string" ? raw["spec"] : null,
22827
+ window: typeof raw["window"] === "string" ? raw["window"] : null,
22828
+ months: num(raw["months"])
22829
+ };
22830
+ }
22158
22831
  return {
22832
+ baselines,
22159
22833
  created_by_app_space: one["created_by_app_space"] === true,
22160
22834
  created_by_you: one["created_by_you"] === true,
22161
22835
  keys: Array.isArray(app["keys"]) ? app["keys"].map(String) : [],
@@ -22183,6 +22857,7 @@ async function planMetrics(contract, t, opts) {
22183
22857
  const byName3 = new Map(catalog.map((row) => [row.name, row]));
22184
22858
  const byId = new Map(catalog.map((row) => [row.id, row]));
22185
22859
  const rowKeys2 = new Map(catalog.map((row) => [row.id, rowReuseKey(row, byName3)]));
22860
+ const driverRows = /* @__PURE__ */ new Map();
22186
22861
  const usageRead = /* @__PURE__ */ new Map();
22187
22862
  const usageOf = (appId, id) => {
22188
22863
  let held = usageRead.get(id);
@@ -22203,7 +22878,7 @@ async function planMetrics(contract, t, opts) {
22203
22878
  not_checked: [],
22204
22879
  notes: [],
22205
22880
  problems: [],
22206
- internal: { decls, catalog, tables: null, base: {}, tableOf: {}, appName: opts.appName }
22881
+ internal: { decls, catalog, tables: null, base: {}, tableOf: {}, appName: opts.appName, plan: modelPlanOf(contract), baselines: {} }
22207
22882
  };
22208
22883
  if (t.overridden) {
22209
22884
  plan.notes.push(`metrics are read and created on ${t.host} (the Datarails host of ${t.serverKey}), not on --app-space-host ${t.appSpace}`);
@@ -22236,7 +22911,7 @@ async function planMetrics(contract, t, opts) {
22236
22911
  const resolved = /* @__PURE__ */ new Map();
22237
22912
  for (const key of dependencyOrder(decls)) {
22238
22913
  const decl = decls[key];
22239
- const kind = decl.kind === "base" || decl.kind === "calc" ? decl.kind : null;
22914
+ const kind = decl.kind === "base" || decl.kind === "calc" || decl.kind === "driver" ? decl.kind : null;
22240
22915
  const entry = { key, name: decl.name, kind, action: "refuse", metric_id: null, metric_name: null, origin: null, reuse_key: null, definition: "", note: "" };
22241
22916
  const refuse2 = (code, message, note) => {
22242
22917
  entry.action = "refuse";
@@ -22267,20 +22942,32 @@ async function planMetrics(contract, t, opts) {
22267
22942
  if (dep.metric_id !== null) ids[operand] = dep.metric_id;
22268
22943
  }
22269
22944
  }
22945
+ let calculations = [];
22270
22946
  if (defProblem === null) {
22271
22947
  try {
22272
22948
  wire = wireFormula(decl.formula, names);
22949
+ calculations = calculationsWire(decl, key, names);
22273
22950
  } catch (err) {
22274
22951
  defProblem = { code: "metric_preview", message: `metric "${key}"'s formula ${firstLine(err)}` };
22275
22952
  }
22276
22953
  }
22277
- if (wire !== null) {
22278
- entry.definition = `CALC ${wire}`;
22954
+ if (wire !== null && defProblem === null) {
22955
+ entry.definition = describeCalc(wire, calculations);
22279
22956
  if (pendingOperands.length === 0) {
22280
22957
  const nameToId = new Map(Object.entries(names).map(([operand, name]) => [name, ids[operand] ?? null]));
22281
- entry.reuse_key = calcReuseKey(wire, (name) => nameToId.get(name) ?? null);
22958
+ entry.reuse_key = calcReuseKey(wire, (name) => nameToId.get(name) ?? null, calculations, decl.name);
22282
22959
  }
22283
22960
  }
22961
+ } else if (kind === "driver") {
22962
+ const def = driverDefinitionOf(decl);
22963
+ entry.definition = describeDriver(def);
22964
+ entry.reuse_key = driverReuseKey(def);
22965
+ const holder = byName3.get(decl.name);
22966
+ if (holder !== void 0 && holder.kind === "DRIVER" && !driverRows.has(holder.id)) {
22967
+ const held = await readDriverRow(t, holder.id);
22968
+ rowKeys2.set(holder.id, typeof held === "string" || held === null ? null : driverReuseKey(held));
22969
+ driverRows.set(holder.id, held);
22970
+ }
22284
22971
  } else if (kind === "base") {
22285
22972
  const table = tables === null ? void 0 : findAuthTable(tables, decl.table);
22286
22973
  entry.definition = describeBase(decl, tableLabel(decl.table, table));
@@ -22327,6 +23014,14 @@ async function planMetrics(contract, t, opts) {
22327
23014
  }
22328
23015
  }
22329
23016
  const named13 = byName3.get(decl.name);
23017
+ const describeHeld = (row) => {
23018
+ if (row.kind !== "DRIVER") return describeRow(row, tables);
23019
+ const held = driverRows.get(row.id);
23020
+ if (held === void 0) return describeRow(row, tables);
23021
+ if (held === null) return "DRIVER with no default row (Actuals, no cycle)";
23022
+ if (typeof held === "string") return `DRIVER whose default row could not be read (${held})`;
23023
+ return describeDriver(held);
23024
+ };
22330
23025
  if (entry.reuse_key !== null) {
22331
23026
  const same5 = catalog.filter((row) => rowKeys2.get(row.id) === entry.reuse_key).sort((a, b) => Number(b.name === decl.name) - Number(a.name === decl.name) || (a.created_at ?? "").localeCompare(b.created_at ?? "") || a.id - b.id);
22332
23027
  const hit = same5[0];
@@ -22351,7 +23046,7 @@ async function planMetrics(contract, t, opts) {
22351
23046
  entry.metric_id = named13.id;
22352
23047
  entry.metric_name = named13.name;
22353
23048
  entry.origin = "named";
22354
- const theirs = describeRow(named13, tables);
23049
+ const theirs = describeHeld(named13);
22355
23050
  entry.note = kind === null ? "by name" : entry.reuse_key === null ? `by name (the contract's definition could not be compared here: ${defProblem?.message ?? "an operand is created on push"})` : `by name; its definition differs: ${theirs} against the contract's ${entry.definition}`;
22356
23051
  continue;
22357
23052
  }
@@ -22360,7 +23055,7 @@ async function planMetrics(contract, t, opts) {
22360
23055
  continue;
22361
23056
  }
22362
23057
  if (named13 !== void 0 && kind !== null) {
22363
- const theirs = describeRow(named13, tables);
23058
+ const theirs = describeHeld(named13);
22364
23059
  const sameKind = named13.kind === kind.toUpperCase();
22365
23060
  const previous = rowKeys2.get(named13.id) ?? null;
22366
23061
  let why = null;
@@ -22419,6 +23114,12 @@ async function planMetrics(contract, t, opts) {
22419
23114
  entry.note = `${entry.definition}; extracts after creation`;
22420
23115
  continue;
22421
23116
  }
23117
+ if (kind === "driver") {
23118
+ entry.action = "create";
23119
+ entry.note = `${entry.definition}; ${baselineNote(decl)}`;
23120
+ if (!plan.not_checked.some((one) => one.startsWith(DRIVER_GATES))) plan.not_checked.push(`${DRIVER_GATES}: Datarails answers when the driver is created`);
23121
+ continue;
23122
+ }
22422
23123
  entry.action = "create";
22423
23124
  if (pendingOperands.length > 0) {
22424
23125
  entry.after = pendingOperands;
@@ -22435,6 +23136,18 @@ async function planMetrics(contract, t, opts) {
22435
23136
  entry.preview = "ok";
22436
23137
  entry.note = `${entry.definition} preview ok`;
22437
23138
  }
23139
+ if (opts.appId !== null && opts.appId !== "") {
23140
+ for (const entry of resolved.values()) {
23141
+ if (entry.kind !== "driver" || entry.metric_id === null || entry.action === "refuse" || entry.action === "create") continue;
23142
+ const usage = await usageOf(opts.appId, entry.metric_id);
23143
+ if (typeof usage !== "string") plan.internal.baselines[entry.key] = usage.baselines[entry.key];
23144
+ }
23145
+ }
23146
+ for (const [key, decl] of Object.entries(decls)) {
23147
+ if (decl.kind === "calc" && Object.keys(decl.calculations ?? {}).length > 0) {
23148
+ plan.not_checked.push(`the ${Object.keys(decl.calculations ?? {}).join(", ")} calculation of "${decl.name}" (${key}): Datarails checks it when it is written, under scenario_bound_calculations and the Planning product`);
23149
+ }
23150
+ }
22438
23151
  const order2 = Object.keys(decls);
22439
23152
  plan.entries = [...resolved.values()].sort((a, b) => order2.indexOf(a.key) - order2.indexOf(b.key));
22440
23153
  for (const entry of plan.entries) {
@@ -22483,6 +23196,7 @@ async function applyPlan(plan, t, opts) {
22483
23196
  return out;
22484
23197
  };
22485
23198
  const waitFor = [];
23199
+ const inRow = /* @__PURE__ */ new Map();
22486
23200
  for (const key of dependencyOrder(decls)) {
22487
23201
  const entry = byKey2.get(key);
22488
23202
  const decl = decls[key];
@@ -22490,6 +23204,7 @@ async function applyPlan(plan, t, opts) {
22490
23204
  if (entry.action === "reuse" || entry.action === "bind") continue;
22491
23205
  if (entry.action !== "create" && entry.action !== "edit") continue;
22492
23206
  let wire = null;
23207
+ let calculations = [];
22493
23208
  if (entry.kind === "calc" && typeof decl.formula === "string") {
22494
23209
  const names = {};
22495
23210
  const ids = /* @__PURE__ */ new Map();
@@ -22499,17 +23214,54 @@ async function applyPlan(plan, t, opts) {
22499
23214
  ids.set(names[operand], dep?.metric_id ?? null);
22500
23215
  }
22501
23216
  wire = wireFormula(decl.formula, names);
22502
- entry.definition = `CALC ${wire}`;
23217
+ const self = entry.metric_name ?? decl.name;
23218
+ calculations = calculationsWire(decl, key, { ...names, [key]: self });
23219
+ entry.definition = describeCalc(wire, calculations);
22503
23220
  if (entry.action === "edit") entry.new_definition = entry.definition;
22504
- entry.reuse_key = calcReuseKey(wire, (name) => ids.get(name) ?? null);
23221
+ entry.reuse_key = calcReuseKey(wire, (name) => ids.get(name) ?? null, calculations, self);
22505
23222
  if (entry.preview !== "ok") {
22506
23223
  const preview = await previewFormula(t, wire);
22507
23224
  if (preview !== null) return fail(key, `metric "${key}": Datarails could not evaluate ${wire}: ${preview}`);
22508
23225
  entry.preview = "ok";
22509
23226
  }
22510
23227
  }
23228
+ let baseline = null;
23229
+ if (entry.kind === "driver") {
23230
+ const refs = baselineRefsOf(decl);
23231
+ const pending = waitFor.filter((one) => refs.includes(one.key));
23232
+ if (pending.length > 0) {
23233
+ await waitForExtraction(t, pending, opts, out.notes);
23234
+ for (const one of pending) waitFor.splice(waitFor.indexOf(one), 1);
23235
+ }
23236
+ const ready = await prepareBaseline(plan, t, opts, entry, decl, entry.action === "create" ? "created" : entry.origin);
23237
+ if (ready.state === "problem") {
23238
+ out.ok = false;
23239
+ out.problems.push(ready.problem);
23240
+ return out;
23241
+ }
23242
+ inRow.set(key, ready);
23243
+ if (ready.state === "stamp") baseline = ready.stamp.value;
23244
+ if (ready.state === "stamp" && baseline === null && !driverDefinitionOf(decl).additive) {
23245
+ return fail(
23246
+ key,
23247
+ `metric "${key}": a driver that does not add up over months (additive: false) needs a starting value, and Datarails refuses one without; ${unreadNote(`"${entry.metric_name ?? decl.name}"`, ready.reason)}. Type it ("baseline"), or ship again once the metrics it is read from hold the months`
23248
+ );
23249
+ }
23250
+ }
23251
+ if (entry.action === "edit" && entry.kind === "driver") {
23252
+ const written2 = await putDriverRow(t, entry.metric_id, driverRowBody(decl, baseline));
23253
+ if (written2 !== null) return fail(key, `metric "${key}": Datarails refused to change the driver "${entry.metric_name ?? entry.name}" (id ${String(entry.metric_id)}) in place: ${driverRefusal(written2)}`);
23254
+ out.created.push({ key, id: entry.metric_id, name: entry.metric_name ?? entry.name, action: "edit" });
23255
+ continue;
23256
+ }
22511
23257
  if (entry.action === "edit") {
22512
- const body2 = entry.kind === "calc" ? { configuration: { presented_formula: wire, ...formatOf(decl, plan, entry) } } : baseBody(plan.internal.base[key]);
23258
+ const body2 = entry.kind === "calc" ? {
23259
+ configuration: { presented_formula: wire, ...formatOf(decl, plan, entry) },
23260
+ // The PATCH replaces every stored calculation: sent where the
23261
+ // contract states one or the metric holds one, so a dropped
23262
+ // calculation goes and a metric with none is changed as before.
23263
+ ...calculations.length > 0 || (plan.internal.catalog.find((row) => row.id === entry.metric_id)?.calculations.length ?? 0) > 0 ? { calculations: calculationsBody(calculations) } : {}
23264
+ } : baseBody(plan.internal.base[key]);
22513
23265
  const answer2 = await t.call("PATCH", `${t.host}/api/insights/metrics/${String(entry.metric_id)}`, body2).catch((err) => ({ status: 0, body: firstLine(err) }));
22514
23266
  if (answer2.status < 200 || answer2.status >= 300) {
22515
23267
  return fail(key, `metric "${key}": Datarails refused to change "${entry.metric_name ?? entry.name}" (id ${String(entry.metric_id)}) in place: ${refusalSentence(answer2, entry, plan)}`);
@@ -22522,7 +23274,13 @@ async function applyPlan(plan, t, opts) {
22522
23274
  category = await appSpaceCategory(t, out.notes);
22523
23275
  }
22524
23276
  const description = [decl.description ?? "", createdFooter(plan.internal.appName)].filter((one) => one !== "").join("\n\n");
22525
- const body = entry.kind === "calc" ? { name: decl.name, kind: "CALC", configuration: { presented_formula: wire, ...decl.format === void 0 ? {} : { format: decl.format } } } : { name: decl.name, kind: "BASE", ...baseBody(plan.internal.base[key]), ...decl.format === void 0 ? {} : { configuration: { presented_formula: "", format: decl.format } } };
23277
+ const formatted = decl.format === void 0 ? {} : { configuration: { presented_formula: "", format: decl.format } };
23278
+ const body = entry.kind === "calc" ? {
23279
+ name: decl.name,
23280
+ kind: "CALC",
23281
+ configuration: { presented_formula: wire, ...decl.format === void 0 ? {} : { format: decl.format } },
23282
+ ...calculations.length === 0 ? {} : { calculations: calculationsBody(calculations) }
23283
+ } : entry.kind === "driver" ? { name: decl.name, kind: "DRIVER", ...formatted } : { name: decl.name, kind: "BASE", ...baseBody(plan.internal.base[key]), ...formatted };
22526
23284
  body["description"] = description;
22527
23285
  body["is_approved_by_user"] = true;
22528
23286
  if (category !== null) body["category"] = category;
@@ -22536,10 +23294,22 @@ async function applyPlan(plan, t, opts) {
22536
23294
  }
22537
23295
  const byName3 = new Map(again.map((row) => [row.name, row]));
22538
23296
  const holder = byName3.get(decl.name);
23297
+ if (holder === void 0 && entry.kind === "driver") {
23298
+ return fail(
23299
+ key,
23300
+ `metric "${key}": a metric named "${decl.name}" exists in this company and is not one you can see \u2014 a driver is hidden from every list where scenario_bound_calculations is off, and a metric over tables not shared with you is hidden from you; give the contract's driver another name, or ask an admin`
23301
+ );
23302
+ }
22539
23303
  if (holder === void 0) {
22540
23304
  return fail(key, `metric "${key}": a metric named "${decl.name}" exists in this company, but its source tables are not shared with you`);
22541
23305
  }
22542
- if (entry.reuse_key !== null && rowReuseKey(holder, byName3) === entry.reuse_key) {
23306
+ let held = rowReuseKey(holder, byName3);
23307
+ if (entry.kind === "driver" && holder.kind === "DRIVER") {
23308
+ const row = await readDriverRow(t, holder.id);
23309
+ held = row === null || typeof row === "string" ? null : driverReuseKey(row);
23310
+ }
23311
+ if (entry.reuse_key !== null && held === entry.reuse_key) {
23312
+ inRow.delete(key);
22543
23313
  entry.action = "reuse";
22544
23314
  entry.origin = "reused";
22545
23315
  entry.metric_id = holder.id;
@@ -22563,8 +23333,18 @@ async function applyPlan(plan, t, opts) {
22563
23333
  entry.origin = "created";
22564
23334
  out.created.push({ key, id, name: entry.metric_name, action: "create" });
22565
23335
  if (entry.kind === "base") waitFor.push(entry);
23336
+ if (entry.kind === "driver") {
23337
+ const written2 = await putDriverRow(t, id, driverRowBody(decl, baseline));
23338
+ if (written2 !== null) return fail(key, `metric "${key}": Datarails created the driver "${entry.metric_name}" (id ${String(id)}) and refused its definition: ${driverRefusal(written2)}`);
23339
+ }
22566
23340
  }
22567
23341
  if (waitFor.length > 0) await waitForExtraction(t, waitFor, opts, out.notes);
23342
+ const baselineProblems = await writeBaselines(plan, t, opts, out, inRow);
23343
+ if (baselineProblems.length > 0) {
23344
+ out.ok = false;
23345
+ out.problems.push(...baselineProblems);
23346
+ return out;
23347
+ }
22568
23348
  const written = plan.entries.filter((entry) => out.created.some((one) => one.key === entry.key));
22569
23349
  if (written.length > 0) {
22570
23350
  const drifted = await readBack(t, plan, written);
@@ -22580,7 +23360,8 @@ async function applyPlan(plan, t, opts) {
22580
23360
  metric_id: entry.metric_id,
22581
23361
  origin: entry.origin,
22582
23362
  ...entry.reuse_key === null ? {} : { reuse_key: entry.reuse_key },
22583
- ...entry.action === "edit" && typeof entry.previous_reuse_key === "string" ? { previous_reuse_key: entry.previous_reuse_key } : {}
23363
+ ...entry.action === "edit" && typeof entry.previous_reuse_key === "string" ? { previous_reuse_key: entry.previous_reuse_key } : {},
23364
+ ...entry.baseline === void 0 ? {} : { baseline: entry.baseline }
22584
23365
  };
22585
23366
  }
22586
23367
  return out;
@@ -22607,7 +23388,11 @@ async function readBack(t, plan, written) {
22607
23388
  problems.push(problem4("metric_changed", entry.key, `metric "${entry.key}": ${label} is not among this company's metrics you can read, just after this ship wrote it; nothing was pushed`));
22608
23389
  continue;
22609
23390
  }
22610
- const held = rowReuseKey(row, byName3);
23391
+ let held = rowReuseKey(row, byName3);
23392
+ if (entry.kind === "driver") {
23393
+ const driver = await readDriverRow(t, row.id);
23394
+ held = driver === null || typeof driver === "string" ? null : driverReuseKey(driver);
23395
+ }
22611
23396
  if (held === null || entry.reuse_key === null) {
22612
23397
  problems.push(
22613
23398
  problem4(
@@ -22633,6 +23418,227 @@ async function readBack(t, plan, written) {
22633
23418
  }
22634
23419
  return problems;
22635
23420
  }
23421
+ function calculationsBody(calculations) {
23422
+ return calculations.map((one) => ({
23423
+ scenario: one.scenario,
23424
+ scenario_cycle: one.scenario_cycle,
23425
+ planning_scenario: one.planning_scenario,
23426
+ presented_formula: one.formula
23427
+ }));
23428
+ }
23429
+ function driverRowBody(decl, baseline) {
23430
+ const def = driverDefinitionOf(decl);
23431
+ return {
23432
+ ...DEFAULT_DRIVER_CONTEXT,
23433
+ unit: def.unit,
23434
+ is_additive: def.additive,
23435
+ min_value: def.min,
23436
+ max_value: def.max,
23437
+ ...baseline === null ? {} : { baseline_value: baseline }
23438
+ };
23439
+ }
23440
+ async function putDriverRow(t, id, body) {
23441
+ const answer = await t.call("PUT", `${t.host}/api/insights/metrics/${String(id)}/driver`, body).catch((err) => ({ status: 0, body: firstLine(err) }));
23442
+ return answer.status >= 200 && answer.status < 300 ? null : answer;
23443
+ }
23444
+ function driverRefusal(answer) {
23445
+ const said2 = sentenceOf(decodeEntities2(answer.body));
23446
+ if (answer.status === 405) return `this company does not have the Planning product (budget or forecast cycle management), which every driver needs${said2 === "" ? "" : ` (${said2})`}`;
23447
+ if (/turned off/i.test(said2)) return `scenario-bound calculations are turned off for this company (the scenario_bound_calculations flag), and drivers exist only behind it (${said2})`;
23448
+ if (answer.status === 403) return `only an admin or a contributor (a Data Manager) may write a driver, or this credential lacks metrics:write (403${said2 === "" ? "" : `: ${said2}`})`;
23449
+ if (answer.status === 0) return `the request did not complete (${String(answer.body)})`;
23450
+ return said2 === "" ? `HTTP ${String(answer.status)}` : `${said2} (HTTP ${String(answer.status)})`;
23451
+ }
23452
+ function shiftMonth([year, month], by) {
23453
+ const index = year * 12 + (month - 1) + by;
23454
+ return [Math.floor(index / 12), index % 12 + 1];
23455
+ }
23456
+ function monthText([year, month]) {
23457
+ return `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}`;
23458
+ }
23459
+ function firstOpenMonth(plan, now) {
23460
+ const cycle = typeof plan?.cycle === "string" ? /^(\d{1,2})\+(\d{1,2})$/.exec(plan.cycle.trim()) : null;
23461
+ if (cycle !== null && typeof plan?.year === "number" && Number.isInteger(plan.year)) {
23462
+ const closed = Number(cycle[1]);
23463
+ if (closed >= 0 && closed <= 12) return shiftMonth([plan.year, 1], closed);
23464
+ }
23465
+ return [now.getUTCFullYear(), now.getUTCMonth() + 1];
23466
+ }
23467
+ function closedMonths(plan, now, count) {
23468
+ const first = firstOpenMonth(plan, now);
23469
+ return Array.from({ length: count }, (_, index) => shiftMonth(first, index - count));
23470
+ }
23471
+ function monthlyAmounts(body, metricId) {
23472
+ const data = obj2(obj2(body)["data"]);
23473
+ const listed = Array.isArray(data["metrics"]) ? data["metrics"] : Array.isArray(obj2(body)["metrics"]) ? obj2(body)["metrics"] : null;
23474
+ if (listed === null) return "the answer lists no metrics";
23475
+ const item = listed.filter(isObj3).find((one) => idIn(one["metric_id"]) === metricId);
23476
+ if (item === void 0) return `the answer has no figures for metric ${String(metricId)}`;
23477
+ if (isObj3(item["error"]) && typeof item["error"]["message"] === "string") return item["error"]["message"];
23478
+ const out = /* @__PURE__ */ new Map();
23479
+ for (const row of (Array.isArray(item["data"]) ? item["data"] : []).filter(isObj3)) {
23480
+ const date = row["date"];
23481
+ const amount = row["amount"] ?? row["value"];
23482
+ if (typeof date !== "string" || !/^\d{4}-\d{2}/.test(date)) continue;
23483
+ if (typeof amount !== "number" || !Number.isFinite(amount)) continue;
23484
+ const month = date.slice(0, 7);
23485
+ out.set(month, (out.get(month) ?? 0) + amount);
23486
+ }
23487
+ return out;
23488
+ }
23489
+ function baselineValue(rule, window, series, prior = []) {
23490
+ const at = (one, month) => one?.get(monthText(month));
23491
+ if (rule === "l12m_mean") {
23492
+ const found = window.map((month) => at(series[0], month)).filter((one) => one !== void 0);
23493
+ return { value: found.length === 0 ? null : found.reduce((a, b) => a + b, 0) / found.length, months: found.length };
23494
+ }
23495
+ if (rule === "l12m_ratio") {
23496
+ let top = 0;
23497
+ let bottom = 0;
23498
+ let months = 0;
23499
+ for (const month of window) {
23500
+ const a = at(series[0], month);
23501
+ const b = at(series[1], month);
23502
+ if (a === void 0 || b === void 0) continue;
23503
+ top += a;
23504
+ bottom += b;
23505
+ months += 1;
23506
+ }
23507
+ return { value: months === 0 || bottom === 0 ? null : top / bottom, months };
23508
+ }
23509
+ if (rule === "l12m_growth") {
23510
+ let now = 0;
23511
+ let before = 0;
23512
+ let months = 0;
23513
+ window.forEach((month, index) => {
23514
+ const a = at(series[0], month);
23515
+ const b = prior[index] === void 0 ? void 0 : at(series[0], prior[index]);
23516
+ if (a === void 0 || b === void 0) return;
23517
+ now += a;
23518
+ before += b;
23519
+ months += 1;
23520
+ });
23521
+ return { value: months === 0 || before === 0 ? null : now / before - 1, months };
23522
+ }
23523
+ return { value: null, months: 0 };
23524
+ }
23525
+ function lastDay([year, month]) {
23526
+ const day = new Date(Date.UTC(year, month, 0)).getUTCDate();
23527
+ return `${monthText([year, month])}-${String(day).padStart(2, "0")}`;
23528
+ }
23529
+ async function readMonthly(t, ids, from, to) {
23530
+ let answer;
23531
+ try {
23532
+ answer = await t.call("POST", `${t.host}/finance-os/api/metrics/v1/data`, {
23533
+ metric_ids: ids,
23534
+ aggregation_period: "month",
23535
+ aggregation_type: "DEFAULT",
23536
+ scenario: ["Actuals"],
23537
+ date_start: `${monthText(from)}-01`,
23538
+ date_end: lastDay(to)
23539
+ });
23540
+ } catch (err) {
23541
+ return `the Actuals could not be read (${firstLine(err)})`;
23542
+ }
23543
+ if (answer.status < 200 || answer.status >= 300) return `the Actuals could not be read (HTTP ${String(answer.status)}${sentenceOf(answer.body) === "" ? "" : `: ${sentenceOf(answer.body)}`})`;
23544
+ const out = [];
23545
+ for (const id of ids) {
23546
+ const one = monthlyAmounts(answer.body, id);
23547
+ if (typeof one === "string") return `the Actuals could not be read (${one})`;
23548
+ out.push(one);
23549
+ }
23550
+ return out;
23551
+ }
23552
+ async function prepareBaseline(plan, t, opts, entry, decl, origin) {
23553
+ const key = entry.key;
23554
+ const spec = baselineSpecOf(decl);
23555
+ if (spec === null) return { state: "none" };
23556
+ if (origin !== "created") return { state: "not_ours" };
23557
+ const before = plan.internal.baselines[key];
23558
+ if (before !== void 0 && before.spec === spec && before.value !== null) {
23559
+ return { state: "kept", stamp: { value: before.value, window: before.window, months: before.months } };
23560
+ }
23561
+ if (!plan.credential.can_write) return { state: "problem", problem: problem4("metric_scope", key, scopeSentence(key, decl.name, plan.credential, "changing")) };
23562
+ if (typeof decl.baseline === "number") return { state: "stamp", stamp: { value: decl.baseline, window: null, months: null }, source: "typed", reason: null };
23563
+ const byKey2 = new Map(plan.entries.map((one) => [one.key, one]));
23564
+ const now = new Date((opts.now ?? (() => Date.now()))());
23565
+ const rule = decl.baseline_from?.rule ?? "";
23566
+ const refs = baselineRefsOf(decl);
23567
+ const ids = refs.map((one) => byKey2.get(one)?.metric_id ?? null);
23568
+ const window = closedMonths(plan.internal.plan, now, 12);
23569
+ const prior = rule === "l12m_growth" ? window.map((month) => shiftMonth(month, -12)) : [];
23570
+ const span = `${monthText(window[0])}..${monthText(window[window.length - 1])}`;
23571
+ const source = `${rule} of ${refs.map((one) => `"${byKey2.get(one)?.metric_name ?? one}"`).join(" / ")}, ${span}`;
23572
+ if (ids.some((one) => one === null)) {
23573
+ return { state: "stamp", stamp: { value: null, window: span, months: 0 }, source, reason: "a metric it is read from is not bound" };
23574
+ }
23575
+ const read = await readMonthly(t, ids, prior[0] ?? window[0], window[window.length - 1]);
23576
+ if (typeof read === "string") return { state: "stamp", stamp: { value: null, window: span, months: 0 }, source, reason: `${read}; its pages open with no default until the next ship reads it` };
23577
+ const { value, months } = baselineValue(rule, window, read, prior);
23578
+ return {
23579
+ state: "stamp",
23580
+ stamp: { value, window: span, months },
23581
+ source,
23582
+ reason: value === null ? `${String(months)} of the 12 months ${span} hold a figure to compute it from (a metric still being prepared reads empty)` : null
23583
+ };
23584
+ }
23585
+ function unreadNote(label, reason) {
23586
+ return `${label}'s starting value was not read: ${reason ?? "nothing was found"}`;
23587
+ }
23588
+ async function writeBaselines(plan, t, opts, out, inRow) {
23589
+ const { decls } = plan.internal;
23590
+ const byKey2 = new Map(plan.entries.map((entry) => [entry.key, entry]));
23591
+ const problems = [];
23592
+ for (const key of dependencyOrder(decls)) {
23593
+ const entry = byKey2.get(key);
23594
+ const decl = decls[key];
23595
+ if (entry === void 0 || decl === void 0 || entry.kind !== "driver" || entry.metric_id === null) continue;
23596
+ const label = `"${entry.metric_name ?? entry.name}"`;
23597
+ const written = inRow.get(key);
23598
+ const ready = written ?? await prepareBaseline(plan, t, opts, entry, decl, entry.origin);
23599
+ if (ready.state === "none") continue;
23600
+ if (ready.state === "not_ours") {
23601
+ out.notes.push(`${label}'s starting value is the company's own: App Space did not create this driver, so it writes nothing into it`);
23602
+ continue;
23603
+ }
23604
+ if (ready.state === "problem") {
23605
+ problems.push(ready.problem);
23606
+ continue;
23607
+ }
23608
+ entry.baseline = ready.stamp;
23609
+ if (ready.state === "kept") continue;
23610
+ const stamp = ready.stamp;
23611
+ if (stamp.value === null) {
23612
+ out.notes.push(unreadNote(label, ready.reason));
23613
+ continue;
23614
+ }
23615
+ if (written === void 0) {
23616
+ const refused = await putDriverRow(t, entry.metric_id, { ...DEFAULT_DRIVER_CONTEXT, baseline_value: stamp.value });
23617
+ if (refused !== null) {
23618
+ problems.push(problem4("metric_create", key, `metric "${key}": Datarails refused ${label}'s starting value ${String(stamp.value)}: ${driverRefusal(refused)}`));
23619
+ continue;
23620
+ }
23621
+ }
23622
+ const back = await readDriverRow(t, entry.metric_id);
23623
+ if (back === null || typeof back === "string" || back.baseline === null || Math.abs(back.baseline - stamp.value) > 1e-9 * Math.max(1, Math.abs(stamp.value))) {
23624
+ problems.push(
23625
+ problem4(
23626
+ "metric_changed",
23627
+ key,
23628
+ `metric "${key}": ${label}'s starting value was written as ${String(stamp.value)} and reads back as ${typeof back === "object" && back !== null ? String(back.baseline) : `nothing (${String(back)})`}; nothing was pushed`
23629
+ )
23630
+ );
23631
+ continue;
23632
+ }
23633
+ const def = driverDefinitionOf(decl);
23634
+ if (def.min !== null && stamp.value < def.min || def.max !== null && stamp.value > def.max) {
23635
+ out.notes.push(`${label} starts at ${String(stamp.value)}, outside its declared bounds [${String(def.min ?? "\u2026")}, ${String(def.max ?? "\u2026")}]`);
23636
+ }
23637
+ const was = plan.internal.baselines[key]?.value ?? null;
23638
+ (out.baselined ??= []).push({ key, id: entry.metric_id, name: entry.metric_name ?? entry.name, value: stamp.value, was, window: stamp.window, months: stamp.months, source: ready.source });
23639
+ }
23640
+ return problems;
23641
+ }
22636
23642
  function formatOf(decl, plan, entry) {
22637
23643
  if (decl.format !== void 0) return { format: decl.format };
22638
23644
  const row = plan.internal.catalog.find((one) => one.id === entry.metric_id);
@@ -22786,6 +23792,12 @@ function renderApplied(plan, applied) {
22786
23792
  `;
22787
23793
  }
22788
23794
  }
23795
+ for (const one of applied.baselined ?? []) {
23796
+ const was = one.was === null ? "" : `; was ${String(one.was)}`;
23797
+ const months = one.months === null ? "" : ` (${String(one.months)} months found)`;
23798
+ out += `metric "${one.key}": "${one.name}" (id ${String(one.id)}) starts at ${String(one.value)}, ${one.source}${months}${was}; written into Datarails and read back
23799
+ `;
23800
+ }
22789
23801
  for (const note of applied.notes) out += `note: ${note}
22790
23802
  `;
22791
23803
  return out;
@@ -22815,7 +23827,7 @@ function planReport(plan, applied) {
22815
23827
  })),
22816
23828
  not_checked: plan.not_checked,
22817
23829
  notes: [...plan.notes, ...applied?.notes ?? []],
22818
- ...applied === void 0 ? {} : { created: applied.created, bindings: applied.bindings, ok: applied.ok }
23830
+ ...applied === void 0 ? {} : { created: applied.created, baselined: applied.baselined ?? [], bindings: applied.bindings, ok: applied.ok }
22819
23831
  };
22820
23832
  }
22821
23833
  async function checkMetricSources(t, appId, contract) {
@@ -25103,121 +26115,6 @@ function checkManifest(app) {
25103
26115
  return violations;
25104
26116
  }
25105
26117
 
25106
- // ../flows/insights-builder/kit/contract/figures.mjs
25107
- var APP_COMPUTED = "app_computed";
25108
- var APP_ROWS = "app_rows";
25109
- var APP_RECORDS = "app_records";
25110
- var KINDS = [APP_COMPUTED, APP_ROWS, APP_RECORDS];
25111
- var FIGURE_PARTS = /* @__PURE__ */ new Set(["widget", "stat", "chart", "callout", "variance_table", "scenario_columns", "progress"]);
25112
- var ALTERNATIVE = "Get the figure from Datarails instead: a metric (declared in data.metrics), a tier-3 formula (expr over from Datarails reads), or a direct FinanceOS read";
25113
- var isObject5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
25114
- var rowsOf = (table) => isObject5(table) ? Object.entries(table).filter(([, row]) => isObject5(row)) : [];
25115
- var byName = ([a], [b]) => a < b ? -1 : a > b ? 1 : 0;
25116
- var present = (value) => value !== void 0 && value !== null;
25117
- function hookName(value) {
25118
- const name = isObject5(value) ? value.$callable : void 0;
25119
- return typeof name === "string" && name !== "" ? name.split(".").at(-1) : null;
25120
- }
25121
- function transformName(value) {
25122
- if (typeof value === "string" && value !== "") return value;
25123
- return hookName(value) ?? "a transform";
25124
- }
25125
- function dashboardWhy(row) {
25126
- if (present(row.compute)) {
25127
- const name = hookName(row.compute);
25128
- return name ? `computed by its compute hook ${name}` : "computed by its compute hook";
25129
- }
25130
- if (present(row.transform)) return `drawn through ${transformName(row.transform)}`;
25131
- return null;
25132
- }
25133
- function origins(rows2, name, seen = /* @__PURE__ */ new Set()) {
25134
- if (seen.has(name)) return /* @__PURE__ */ new Set();
25135
- seen.add(name);
25136
- const origin = rows2[name]?.from;
25137
- if (Array.isArray(origin)) {
25138
- const out = /* @__PURE__ */ new Set();
25139
- for (const one of origin) if (typeof one === "string") for (const kind of origins(rows2, one, seen)) out.add(kind);
25140
- return out;
25141
- }
25142
- if (isObject5(origin)) {
25143
- if ("table" in origin) return /* @__PURE__ */ new Set(["app_table"]);
25144
- if ("financeos" in origin || "call" in origin) return /* @__PURE__ */ new Set(["datarails"]);
25145
- }
25146
- return /* @__PURE__ */ new Set();
25147
- }
25148
- function appTables(rows2, name, seen = /* @__PURE__ */ new Set()) {
25149
- if (seen.has(name)) return [];
25150
- seen.add(name);
25151
- const origin = rows2[name]?.from;
25152
- if (isObject5(origin) && typeof origin.table === "string") return [origin.table];
25153
- const out = [];
25154
- if (Array.isArray(origin)) {
25155
- for (const one of origin) {
25156
- if (typeof one !== "string") continue;
25157
- for (const table of appTables(rows2, one, seen)) if (!out.includes(table)) out.push(table);
25158
- }
25159
- }
25160
- return out;
25161
- }
25162
- function sourceFinding(card, row, rows2, readers) {
25163
- const figure2 = typeof row.shape === "string" && row.shape !== "rows" || readers.some((part) => FIGURE_PARTS.has(part));
25164
- const from = origins(rows2, card);
25165
- const transform = row.transform;
25166
- if (present(transform) && transform !== false && transform !== "") {
25167
- const through = transformName(transform);
25168
- if (from.has("datarails")) {
25169
- return figure2 ? { card, kind: APP_COMPUTED, why: `drawn through ${through}` } : { card, kind: APP_ROWS, why: `rows shaped by ${through}` };
25170
- }
25171
- if (from.size === 1 && from.has("app_table")) {
25172
- return { card, kind: APP_RECORDS, why: `${through} over ${appTables(rows2, card).join(", ")}, the app's own records` };
25173
- }
25174
- return null;
25175
- }
25176
- const origin = row.from;
25177
- if (isObject5(origin) && typeof origin.table === "string" && figure2) {
25178
- return { card, kind: APP_RECORDS, why: `a figure over ${origin.table}, the app's own records` };
25179
- }
25180
- return null;
25181
- }
25182
- function classify2({ widgets, sources, summaries, readers } = {}) {
25183
- const found = [];
25184
- for (const [card, row] of rowsOf(widgets).sort(byName)) {
25185
- if (card.startsWith("_")) continue;
25186
- const why = dashboardWhy(row);
25187
- if (why !== null) found.push({ card, kind: APP_COMPUTED, why });
25188
- }
25189
- const rows2 = Object.fromEntries(rowsOf(sources));
25190
- for (const [card, row] of Object.entries(rows2).sort(byName)) {
25191
- const finding = sourceFinding(card, row, rows2, isObject5(readers) && readers[card] || []);
25192
- if (finding !== null) found.push(finding);
25193
- }
25194
- for (const [card, row] of rowsOf(summaries).sort(byName)) {
25195
- if (row.role !== "summary") continue;
25196
- const named13 = typeof row.table === "string" ? ` of ${row.table}` : "";
25197
- found.push({ card, kind: APP_RECORDS, why: `counts and sums${named13}, the app's own records` });
25198
- }
25199
- const order2 = (kind) => KINDS.indexOf(kind);
25200
- return found.sort((a, b) => order2(a.kind) - order2(b.kind) || (a.card < b.card ? -1 : a.card > b.card ? 1 : 0));
25201
- }
25202
- function readersOf2(elements) {
25203
- const out = {};
25204
- if (!isObject5(elements)) return out;
25205
- for (const element of Object.values(elements)) {
25206
- if (!isObject5(element) || typeof element.type !== "string") continue;
25207
- const props = isObject5(element.props) ? element.props : {};
25208
- const inner = isObject5(props.props) ? props.props : {};
25209
- const source = "source" in props ? props.source : inner.source;
25210
- if (typeof source === "string") (out[source] ??= []).push(element.type);
25211
- }
25212
- return out;
25213
- }
25214
- function figuresOf(contract) {
25215
- if (!isObject5(contract)) return [];
25216
- const data = isObject5(contract.data) ? contract.data : {};
25217
- const app = isObject5(data.app) ? data.app : {};
25218
- return classify2({ widgets: data.widgets, sources: data.sources, summaries: app.handlers, readers: readersOf2(contract.elements) });
25219
- }
25220
-
25221
26118
  // ../flows/insights-builder/kit/checks/rules/figures.mjs
25222
26119
  function checkFigures(contract, { handlerWhere = "handlers" } = {}) {
25223
26120
  const warnings = figuresOf(contract).filter((one) => one.kind === APP_COMPUTED).map((one) => ({
@@ -27104,7 +28001,8 @@ function metricsOf2(pages) {
27104
28001
  const embedded = embeddedContractOf2(page);
27105
28002
  if (embedded === null) continue;
27106
28003
  const metrics = embedded.data?.metrics;
27107
- return isPlainObject12(metrics) ? { metrics } : {};
28004
+ const model = embedded.data?.model;
28005
+ return { ...isPlainObject12(metrics) ? { metrics } : {}, ...isPlainObject12(model) ? { model } : {} };
27108
28006
  }
27109
28007
  return {};
27110
28008
  }
@@ -27695,7 +28593,8 @@ function dataSection2(app, manifest, spec, elements, describe7, problems) {
27695
28593
  // Only when there are any: a contract written before sources existed
27696
28594
  // reads back byte for byte as it always did.
27697
28595
  ...Object.keys(sources).length > 0 ? { sources } : {},
27698
- // The same for declared metrics, which only an app's pages carry.
28596
+ // The same for declared metrics and the planning model, which only an
28597
+ // app's pages carry.
27699
28598
  ...isApp ? metricsOf2(app.pages) : {}
27700
28599
  };
27701
28600
  if (describe7) {
@@ -29248,9 +30147,14 @@ function whereOf(binding) {
29248
30147
 
29249
30148
  // ../flows/appspace-builder/kit/contract/figures.mjs
29250
30149
  var APP_COMPUTED2 = "app_computed";
30150
+ var APP_SHAPED2 = "app_shaped_figure";
30151
+ var FY_INFERRED2 = "fy_inferred";
29251
30152
  var APP_ROWS2 = "app_rows";
29252
30153
  var APP_RECORDS2 = "app_records";
29253
- var KINDS2 = [APP_COMPUTED2, APP_ROWS2, APP_RECORDS2];
30154
+ var KINDS2 = [APP_COMPUTED2, APP_SHAPED2, FY_INFERRED2, APP_ROWS2, APP_RECORDS2];
30155
+ var SHAPED_STEP_RE2 = /^(fy|split|solve|custom:[a-z][a-z0-9_]*)$/;
30156
+ var SHAPED_LABEL_MAX2 = 300;
30157
+ var FY_WORDS2 = { sum: "the sum of its months", last: "its last month", average: "the average of its months" };
29254
30158
  var FIGURE_PARTS2 = /* @__PURE__ */ new Set(["widget", "stat", "chart", "callout", "variance_table", "scenario_columns", "progress"]);
29255
30159
  var ALTERNATIVE2 = "Get the figure from Datarails instead: a metric (declared in data.metrics), a tier-3 formula (expr over from Datarails reads), or a direct FinanceOS read";
29256
30160
  var isObject7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
@@ -29302,14 +30206,47 @@ function appTables2(rows2, name, seen = /* @__PURE__ */ new Set()) {
29302
30206
  }
29303
30207
  return out;
29304
30208
  }
29305
- function sourceFinding2(card, row, rows2, readers) {
30209
+ function shapedOf2(row) {
30210
+ const shaped = isObject7(row) ? row.shaped : void 0;
30211
+ if (!isObject7(shaped)) return null;
30212
+ const { step, label } = shaped;
30213
+ if (typeof step !== "string" || !SHAPED_STEP_RE2.test(step)) return null;
30214
+ if (typeof label !== "string" || label.trim() === "" || label.length > SHAPED_LABEL_MAX2) return null;
30215
+ return { step, label };
30216
+ }
30217
+ function declaredKeyOf2(row) {
30218
+ const origin = row.from;
30219
+ const read = isObject7(origin) && isObject7(origin.financeos) ? origin.financeos : null;
30220
+ const metric = read === null ? null : read.metric;
30221
+ return typeof metric === "string" && /^@[a-z][a-z0-9_]*$/.test(metric) ? metric.slice(1) : null;
30222
+ }
30223
+ function yearTotalFinding2(card, row, model) {
30224
+ if (!isObject7(model) || row.shape !== "kpi" || present2(row.transform)) return null;
30225
+ const key = declaredKeyOf2(row);
30226
+ if (key === null) return null;
30227
+ const ref = `@${key}`;
30228
+ const lines = isObject7(model.lines) ? model.lines : {};
30229
+ const line2 = Object.hasOwn(lines, ref) && isObject7(lines[ref]) ? lines[ref] : null;
30230
+ const fy = line2 === null ? void 0 : line2.fy;
30231
+ if (typeof fy === "string" && Object.hasOwn(FY_WORDS2, fy)) {
30232
+ return { card, kind: APP_SHAPED2, step: "fy", why: `year total of ${ref}: ${FY_WORDS2[fy]} (declared)` };
30233
+ }
30234
+ const results = Array.isArray(model.results) ? model.results : [];
30235
+ if (line2 !== null || results.includes(ref)) {
30236
+ return { card, kind: FY_INFERRED2, why: `a year total of ${ref}, a line of the model with no fy declared: Datarails' own roll-up of the metric, which the model never chose` };
30237
+ }
30238
+ return null;
30239
+ }
30240
+ function sourceFinding2(card, row, rows2, readers, model) {
29306
30241
  const figure2 = typeof row.shape === "string" && row.shape !== "rows" || readers.some((part) => FIGURE_PARTS2.has(part));
29307
30242
  const from = origins2(rows2, card);
29308
30243
  const transform = row.transform;
29309
30244
  if (present2(transform) && transform !== false && transform !== "") {
29310
30245
  const through = transformName2(transform);
29311
30246
  if (from.has("datarails")) {
29312
- return figure2 ? { card, kind: APP_COMPUTED2, why: `drawn through ${through}` } : { card, kind: APP_ROWS2, why: `rows shaped by ${through}` };
30247
+ if (!figure2) return { card, kind: APP_ROWS2, why: `rows shaped by ${through}` };
30248
+ const shaped = shapedOf2(row);
30249
+ return shaped === null ? { card, kind: APP_COMPUTED2, why: `drawn through ${through}` } : { card, kind: APP_SHAPED2, step: shaped.step, why: `${shaped.label} (step ${shaped.step}, through ${through})` };
29313
30250
  }
29314
30251
  if (from.size === 1 && from.has("app_table")) {
29315
30252
  return { card, kind: APP_RECORDS2, why: `${through} over ${appTables2(rows2, card).join(", ")}, the app's own records` };
@@ -29320,9 +30257,9 @@ function sourceFinding2(card, row, rows2, readers) {
29320
30257
  if (isObject7(origin) && typeof origin.table === "string" && figure2) {
29321
30258
  return { card, kind: APP_RECORDS2, why: `a figure over ${origin.table}, the app's own records` };
29322
30259
  }
29323
- return null;
30260
+ return yearTotalFinding2(card, row, model);
29324
30261
  }
29325
- function classify4({ widgets, sources, summaries, readers } = {}) {
30262
+ function classify4({ widgets, sources, summaries, readers, model } = {}) {
29326
30263
  const found = [];
29327
30264
  for (const [card, row] of rowsOf2(widgets).sort(byName2)) {
29328
30265
  if (card.startsWith("_")) continue;
@@ -29331,7 +30268,7 @@ function classify4({ widgets, sources, summaries, readers } = {}) {
29331
30268
  }
29332
30269
  const rows2 = Object.fromEntries(rowsOf2(sources));
29333
30270
  for (const [card, row] of Object.entries(rows2).sort(byName2)) {
29334
- const finding = sourceFinding2(card, row, rows2, isObject7(readers) && readers[card] || []);
30271
+ const finding = sourceFinding2(card, row, rows2, isObject7(readers) && readers[card] || [], model);
29335
30272
  if (finding !== null) found.push(finding);
29336
30273
  }
29337
30274
  for (const [card, row] of rowsOf2(summaries).sort(byName2)) {
@@ -29358,7 +30295,7 @@ function figuresOf2(contract) {
29358
30295
  if (!isObject7(contract)) return [];
29359
30296
  const data = isObject7(contract.data) ? contract.data : {};
29360
30297
  const app = isObject7(data.app) ? data.app : {};
29361
- return classify4({ widgets: data.widgets, sources: data.sources, summaries: app.handlers, readers: readersOf3(contract.elements) });
30298
+ return classify4({ widgets: data.widgets, sources: data.sources, summaries: app.handlers, readers: readersOf3(contract.elements), model: data.model });
29362
30299
  }
29363
30300
 
29364
30301
  // ../flows/appspace-builder/kit/checks/rules/figures.mjs
@@ -29372,6 +30309,18 @@ function checkFigures2(contract) {
29372
30309
  where: where2,
29373
30310
  message: `source "${one.card}" draws a figure the app computes in its own code (${one.why}), not one from Datarails. ${ALTERNATIVE2}.`
29374
30311
  });
30312
+ } else if (one.kind === APP_SHAPED2) {
30313
+ violations.push({
30314
+ rule: "A4.3",
30315
+ where: where2,
30316
+ message: `source "${one.card}" draws a figure through a named step (${one.why}): its card says so, and the step's result is the app's or the platform's, not a Datarails evaluation.`
30317
+ });
30318
+ } else if (one.kind === FY_INFERRED2) {
30319
+ violations.push({
30320
+ rule: "A4.4",
30321
+ where: where2,
30322
+ message: `source "${one.card}" draws ${one.why}. Declare the line's rule in data.model.lines["@<key>"].fy: sum, last or average.`
30323
+ });
29375
30324
  } else if (one.kind === APP_ROWS2) {
29376
30325
  violations.push({
29377
30326
  rule: "A4.2",
@@ -31205,7 +32154,7 @@ function kitFromDisk2() {
31205
32154
  }
31206
32155
  return kitOnDisk2;
31207
32156
  }
31208
- var ADVISORY = /* @__PURE__ */ new Set(["A4.1", "A4.2", "L6", "L7", "L8", "L9", "A1.5", "A1.6", "A2.5", "A2.6", "A3.15", "A3.17", "A3.19", "A3.20", "A3.21", "A3.22", "A3.23", "A3.24", "A3.25", "A3.26", "A3.27", "A3.28", "A3.29"]);
32157
+ var ADVISORY = /* @__PURE__ */ new Set(["A4.1", "A4.2", "A4.3", "A4.4", "L6", "L7", "L8", "L9", "A1.5", "A1.6", "A2.5", "A2.6", "A3.15", "A3.17", "A3.19", "A3.20", "A3.21", "A3.22", "A3.23", "A3.24", "A3.25", "A3.26", "A3.27", "A3.28", "A3.29"]);
31209
32158
  function verify2({ app: appRef }, { extractContract: extractContract2 = extract2, kit } = {}) {
31210
32159
  const KIT = kit ?? kitFromDisk2();
31211
32160
  const app = loadApp2(resolve12(appRef.dir));
@@ -31367,11 +32316,16 @@ var REFUSALS = /* @__PURE__ */ new Set([
31367
32316
  // a declared Datarails metric (data.metrics, design 06), and a source that
31368
32317
  // reads one by key
31369
32318
  "metric_decl",
31370
- "metric_kind_later",
32319
+ "metric_driver",
31371
32320
  "metric_formula",
31372
32321
  "metric_base",
31373
32322
  "metric_format",
31374
32323
  "source_metric",
32324
+ // the planning model beside them, and a transform labelled with its step
32325
+ // (trusted forecast models P1)
32326
+ "model_decl",
32327
+ "source_shaped",
32328
+ "source_fy_agg",
31375
32329
  // dr-components parts (DC-4)
31376
32330
  "part_props",
31377
32331
  "part_source_shape",
@@ -31459,12 +32413,15 @@ var EXPR_REFUSALS = {
31459
32413
  source_expr: "a source's formula (its expr) has a from that is no list, or sits beside a transform; answers a shape other than kpi, series or breakdown; states compare (its compare is its formula over its operands' compares); cannot be evaluated (it is not text, a syntax error, a function other than abs, min, max, round and if, a wrong number of arguments, round decimals other than a whole number from 0 to 6, an if whose first argument is no comparison, a comparison anywhere but if's condition, a name not in from); can be, on some path, a number it states rather than an operand's (numbers alone such as 870000, a typed if() branch such as if(actual > 0, 870000, actual), or a typed min() or max() bound such as max(actual, 0): each branch of if() and each argument of min() and max() must come from an operand, and / already gives no figure for a zero divisor, so no fallback number is needed); names an operand it never reads; reads an operand that is not a FinanceOS read or metric or a formula over them (a transform, a composed source, a call, one of the app's own tables); reads an operand of a shape it cannot take (a kpi formula takes kpis; a series or breakdown formula its own shape and kpis), or, as a series or breakdown formula, has no operand of its own shape; reads a breakdown operand that does not state top: null; or reads itself \u2014 the message names which"
31460
32414
  };
31461
32415
  var METRIC_REFUSALS = {
31462
- metric_decl: `a data.metrics key that is not a lowercase letter then lowercase letters, digits or _; a declaration that is no object, or states a key a declaration does not take; a name that is empty, over 128 characters, holds ' [ or ], starts with @, or is DAYS_IN_PERIOD or PERIODS_IN_YEAR; a kind other than base or calc; a calc with no formula; a base with no table, value, date or aggregate, or a table that is not exactly one of alias, name and id; one kind's keys on the other; a reuse other than definition or name, a create that is not true or false, a description that is not text; or a declaration with no definition that does not say "reuse": "name" and "create": false \u2014 the message names which`,
31463
- metric_kind_later: 'a declaration of kind driver, which is reserved until driver declarations ship \u2014 declare a base or calc metric, or bind the driver by name ("reuse": "name", "create": false)',
31464
- metric_formula: "a calc formula Datarails would refuse (dr-cli's checks: empty or over 5000 characters, unbalanced brackets or grouping, a time modifier that is lowercase, chained, on no operand, malformed, a future SHIFT or one past 1200, an invalid unit or anchor, a modifier on a system variable, an unbracketed word, no metric read); arithmetic out of order (two operators in a row, a missing operand or operator, empty parentheses, a number such as 1.2.3); an operand that is not a declared [@key] \u2014 a metric named itself, quoted or bracketed ('Revenue', [Revenue]), so the contract names no company's metric; a scenario pin (|); a window function it cannot read; or a declaration that reads itself, however far round",
32416
+ metric_decl: `a data.metrics key that is not a lowercase letter then lowercase letters, digits or _; a declaration that is no object, or states a key a declaration does not take; a name that is empty, over 128 characters, holds ' [ or ], starts with @, or is DAYS_IN_PERIOD or PERIODS_IN_YEAR; a kind other than base, calc or driver; a calc with no formula, or calculations that are not formulas keyed by a scenario other than Actuals; a base with no table, value, date or aggregate, or a table that is not exactly one of alias, name and id; one kind's keys on the other; a reuse other than definition or name, a create that is not true or false, a description that is not text; or a declaration with no definition that does not say "reuse": "name" and "create": false \u2014 the message names which`,
32417
+ metric_driver: "a driver whose unit is not text of at most 32 characters, whose additive is not true or false, whose min or max is not a number (or min is above max), that states both baseline and baseline_from, or whose baseline_from is not {metric, rule: l12m_mean | l12m_growth} or {ratio: [a, b], rule: l12m_ratio} over declared metrics that are not drivers",
32418
+ metric_formula: "a calc formula Datarails would refuse (dr-cli's checks: empty or over 5000 characters, unbalanced brackets or grouping, a time modifier that is lowercase, chained, on no operand, malformed, a future SHIFT or one past 1200, an invalid unit or anchor, a modifier on a system variable, an unbracketed word, no metric read); arithmetic out of order (two operators in a row, a missing operand or operator, empty parentheses, a number such as 1.2.3); an operand that is not a declared [@key] \u2014 a metric named itself, quoted or bracketed ('Revenue', [Revenue]), so the contract names no company's metric; a scenario pin (|), except | Actuals inside a calculation; a window function it cannot read; or a declaration that reads itself, however far round",
31465
32419
  metric_base: "a base aggregate other than sum, count, cumulative_sum or cumulative_count, a time_aggregation other than sum, eop or avg, a cumulative aggregate rolled up with sum, or a filter that is not {field, values, exclude}",
31466
32420
  metric_format: 'a format the metric editor never writes (optional "$" quoted, \u20AC \xA3 \u20AA or a % suffix, #,### or ####, .# to .####, [kilo]k or [mega]M) \u2014 the message names the stored spelling where one was plainly meant',
31467
- source_metric: `a source's from.financeos.metric that is not "@<key>" of a key data.metrics declares, or that stands beside metric_id`
32421
+ source_metric: `a source's from.financeos.metric that is not "@<key>" of a key data.metrics declares, or that stands beside metric_id`,
32422
+ model_decl: 'a data.model that states a key it does not take, a plan whose module is not forecast or budget or whose cycle is empty, a line, result or version that is not "@<key>" of a declared metric, a version that is not a calc, an fy other than sum, last or average, or scenarios whose kind is not planning_scenario or app_plan',
32423
+ source_shaped: "a source's shaped that is not {step: fy | split | solve | custom:<name>, label}, or that labels a source with no transform",
32424
+ source_fy_agg: "a kpi source over a model line that totals its months by another rule than the line's fy (sum, last, average \u2192 agg sum, last, avg), stated or by the card's default"
31468
32425
  };
31469
32426
  var TRANSFORM_REFUSALS = {
31470
32427
  transform_row: 'a row names a transform and is not a dataset series row ("kind": "series", "data": "<dataset>", and no source, compute, depends, drill, window or by), or its dataset reads with the period pushed down (a period other than "all")',
@@ -32807,7 +33764,7 @@ function registerCompileCommand(parent) {
32807
33764
  ...Object.entries(EXPR_REFUSALS).map(([code, what]) => ` ${code.padEnd(22)}${what}`),
32808
33765
  'A declared Datarails metric (data.metrics, read by a source as from.financeos.metric "@<key>") is refused with:',
32809
33766
  ...Object.entries(METRIC_REFUSALS).map(([code, what]) => ` ${code.padEnd(22)}${what}`),
32810
- " (warnings, never refusals: metric_window, a window function Datarails gates by company; metric_unused, a declaration no source reads; expr_could_be_metric, an expr a calc metric could say)",
33767
+ " (warnings, never refusals: metric_window, a window function Datarails gates by company; metric_scenario_bound, a per-scenario calculation, gated the same way; metric_self_read, a calculation reading its own metric unpinned; metric_unused, a declaration no source reads; driver_no_baseline, driver_baseline_typed and driver_bounds, a driver's starting value missing, typed, or outside its bounds; expr_could_be_metric, an expr a calc metric could say)",
32811
33768
  ...metricHelpLines(),
32812
33769
  "",
32813
33770
  "A transform (a dashboard dataset series row's transforms/<name>.py, or an app source's) is refused with:",