farseer-cli 1.18.0 → 1.20.0

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 (262) hide show
  1. package/README.md +33 -10
  2. package/dist/commands/app.js +42 -3
  3. package/dist/commands/app.js.map +1 -2
  4. package/dist/commands/apps.js.map +0 -1
  5. package/dist/commands/cells.js +120 -85
  6. package/dist/commands/cells.js.map +1 -2
  7. package/dist/commands/code.js.map +0 -1
  8. package/dist/commands/config.js.map +0 -1
  9. package/dist/commands/dashboards.js +246 -12
  10. package/dist/commands/dashboards.js.map +1 -2
  11. package/dist/commands/diff.js.map +0 -1
  12. package/dist/commands/dimensions.js +52 -27
  13. package/dist/commands/dimensions.js.map +1 -2
  14. package/dist/commands/docs.js +82 -0
  15. package/dist/commands/docs.js.map +6 -0
  16. package/dist/commands/files.js +49 -0
  17. package/dist/commands/files.js.map +2 -3
  18. package/dist/commands/folders.js +76 -0
  19. package/dist/commands/folders.js.map +6 -0
  20. package/dist/commands/formula.js +38 -30
  21. package/dist/commands/formula.js.map +1 -2
  22. package/dist/commands/install.js +32 -30
  23. package/dist/commands/install.js.map +2 -3
  24. package/dist/commands/list.js.map +0 -1
  25. package/dist/commands/login.js +3 -3
  26. package/dist/commands/login.js.map +1 -2
  27. package/dist/commands/logout.js.map +0 -1
  28. package/dist/commands/mcp-server.js.map +0 -1
  29. package/dist/commands/model.js +30 -5
  30. package/dist/commands/model.js.map +2 -3
  31. package/dist/commands/pipeline.js.map +0 -1
  32. package/dist/commands/pull.js +1 -1
  33. package/dist/commands/pull.js.map +1 -2
  34. package/dist/commands/push.js +6 -4
  35. package/dist/commands/push.js.map +1 -2
  36. package/dist/commands/refresh.js.map +0 -1
  37. package/dist/commands/run.js.map +0 -1
  38. package/dist/commands/sheets.js +289 -52
  39. package/dist/commands/sheets.js.map +1 -2
  40. package/dist/commands/skills.js +157 -0
  41. package/dist/commands/skills.js.map +6 -0
  42. package/dist/commands/status.js.map +0 -1
  43. package/dist/commands/tool.js.map +0 -1
  44. package/dist/commands/variables.js +246 -82
  45. package/dist/commands/variables.js.map +1 -2
  46. package/dist/commands/whoami.js.map +0 -1
  47. package/dist/index.js +117 -23
  48. package/dist/index.js.map +1 -2
  49. package/dist/mcp/index.js.map +0 -1
  50. package/dist/mcp/prompts/workflows.js.map +0 -1
  51. package/dist/mcp/resources/documentation.js +19 -12
  52. package/dist/mcp/resources/documentation.js.map +1 -2
  53. package/dist/mcp/server.js.map +0 -1
  54. package/dist/mcp/skills.js.map +0 -1
  55. package/dist/mcp/tools/appTools.js +1 -7
  56. package/dist/mcp/tools/appTools.js.map +1 -2
  57. package/dist/mcp/tools/authTools.js +1 -1
  58. package/dist/mcp/tools/authTools.js.map +1 -2
  59. package/dist/mcp/tools/cellTools.js +6 -19
  60. package/dist/mcp/tools/cellTools.js.map +1 -2
  61. package/dist/mcp/tools/dashboardTools.js +30 -412
  62. package/dist/mcp/tools/dashboardTools.js.map +2 -3
  63. package/dist/mcp/tools/dataTools.js +15 -146
  64. package/dist/mcp/tools/dataTools.js.map +1 -2
  65. package/dist/mcp/tools/folderTools.js +12 -78
  66. package/dist/mcp/tools/folderTools.js.map +1 -2
  67. package/dist/mcp/tools/modelTools.js +23 -372
  68. package/dist/mcp/tools/modelTools.js.map +1 -2
  69. package/dist/mcp/tools/pipelineContract.js +5 -1
  70. package/dist/mcp/tools/pipelineContract.js.map +1 -2
  71. package/dist/mcp/tools/pipelineTools.js.map +0 -1
  72. package/dist/mcp/tools/runTools.js +8 -69
  73. package/dist/mcp/tools/runTools.js.map +1 -2
  74. package/dist/mcp/tools/sheetTools.js +14 -264
  75. package/dist/mcp/tools/sheetTools.js.map +1 -2
  76. package/dist/mcp/tools/syncTools.js +7 -3
  77. package/dist/mcp/tools/syncTools.js.map +1 -2
  78. package/dist/mcp/utils/helpers.js.map +0 -1
  79. package/dist/mcp/utils/launchPin.js.map +0 -1
  80. package/dist/mcp/utils/operationResponse.js +41 -0
  81. package/dist/mcp/utils/operationResponse.js.map +6 -0
  82. package/dist/mcp/utils/registerTool.js.map +0 -1
  83. package/dist/mcp/utils/session.js.map +0 -1
  84. package/dist/mcp/utils/tenantPin.js.map +0 -1
  85. package/dist/operations/cells.js +444 -0
  86. package/dist/operations/cells.js.map +6 -0
  87. package/dist/operations/dashboards.js +357 -0
  88. package/dist/operations/dashboards.js.map +6 -0
  89. package/dist/operations/data.js +206 -0
  90. package/dist/operations/data.js.map +6 -0
  91. package/dist/operations/errors.js +64 -0
  92. package/dist/operations/errors.js.map +6 -0
  93. package/dist/operations/exportModel.js +59 -0
  94. package/dist/operations/exportModel.js.map +6 -0
  95. package/dist/operations/folderPath.js +128 -0
  96. package/dist/operations/folderPath.js.map +6 -0
  97. package/dist/operations/folders.js +80 -0
  98. package/dist/operations/folders.js.map +6 -0
  99. package/dist/operations/install.js +109 -0
  100. package/dist/operations/install.js.map +6 -0
  101. package/dist/operations/model.js +271 -0
  102. package/dist/operations/model.js.map +6 -0
  103. package/dist/operations/sheets.js +428 -0
  104. package/dist/operations/sheets.js.map +6 -0
  105. package/dist/pipeline/compatibility.js.map +0 -1
  106. package/dist/pipeline/connect.js.map +0 -1
  107. package/dist/pipeline/create.js.map +0 -1
  108. package/dist/pipeline/errors.js.map +0 -1
  109. package/dist/pipeline/failStep.js +43 -0
  110. package/dist/pipeline/failStep.js.map +6 -0
  111. package/dist/pipeline/generated-reference.json +25 -13
  112. package/dist/pipeline/guide.js.map +0 -1
  113. package/dist/pipeline/init.js.map +0 -1
  114. package/dist/pipeline/operations.js.map +0 -1
  115. package/dist/pipeline/query.js.map +0 -1
  116. package/dist/pipeline/queryDownloads.js.map +0 -1
  117. package/dist/pipeline/queryWorker.js +3 -1
  118. package/dist/pipeline/queryWorker.js.map +1 -2
  119. package/dist/pipeline/readiness.js.map +0 -1
  120. package/dist/pipeline/reference.js.map +0 -1
  121. package/dist/pipeline/requests.js +3 -32
  122. package/dist/pipeline/requests.js.map +1 -2
  123. package/dist/pipeline/runArguments.js.map +0 -1
  124. package/dist/pipeline/runtime.js.map +0 -1
  125. package/dist/pipeline/service.js +46 -2
  126. package/dist/pipeline/service.js.map +1 -2
  127. package/dist/services/appSyncService.js +59 -9
  128. package/dist/services/appSyncService.js.map +1 -2
  129. package/dist/services/apps.js +10 -0
  130. package/dist/services/apps.js.map +1 -2
  131. package/dist/services/authErrors.js.map +0 -1
  132. package/dist/services/codefirst/api.js +38 -5
  133. package/dist/services/codefirst/api.js.map +1 -2
  134. package/dist/services/codefirst/binaryDisk.js.map +0 -1
  135. package/dist/services/codefirst/byteHashes.js +5 -0
  136. package/dist/services/codefirst/byteHashes.js.map +1 -2
  137. package/dist/services/codefirst/documents.js +41 -15
  138. package/dist/services/codefirst/documents.js.map +1 -2
  139. package/dist/services/codefirst/layoutBinaryProjection.js +24 -13
  140. package/dist/services/codefirst/layoutBinaryProjection.js.map +1 -2
  141. package/dist/services/codefirst/layoutCompose.js +44 -38
  142. package/dist/services/codefirst/layoutCompose.js.map +1 -2
  143. package/dist/services/codefirst/layoutCore.js +14 -1
  144. package/dist/services/codefirst/layoutCore.js.map +1 -2
  145. package/dist/services/codefirst/layoutPaths.js +80 -4
  146. package/dist/services/codefirst/layoutPaths.js.map +1 -2
  147. package/dist/services/codefirst/layoutProjection.js +73 -39
  148. package/dist/services/codefirst/layoutProjection.js.map +1 -2
  149. package/dist/services/codefirst/layoutReadback.js +357 -130
  150. package/dist/services/codefirst/layoutReadback.js.map +2 -3
  151. package/dist/services/codefirst/layoutReadbackPlacement.js +94 -57
  152. package/dist/services/codefirst/layoutReadbackPlacement.js.map +2 -3
  153. package/dist/services/codefirst/layoutReceipt.js +283 -243
  154. package/dist/services/codefirst/layoutReceipt.js.map +2 -3
  155. package/dist/services/codefirst/layoutScan.js +208 -110
  156. package/dist/services/codefirst/layoutScan.js.map +1 -2
  157. package/dist/services/codefirst/output.js +76 -10
  158. package/dist/services/codefirst/output.js.map +1 -2
  159. package/dist/services/codefirst/types.js.map +0 -1
  160. package/dist/services/codefirst/workflow.js +65 -29
  161. package/dist/services/codefirst/workflow.js.map +2 -3
  162. package/dist/services/codefirst/workspace.js.map +0 -1
  163. package/dist/services/codefirst/workspaceLock.js.map +0 -1
  164. package/dist/services/codefirst/workspaceRoot.js +2 -1
  165. package/dist/services/codefirst/workspaceRoot.js.map +1 -2
  166. package/dist/services/configService.js.map +0 -1
  167. package/dist/services/credentials.js.map +0 -1
  168. package/dist/services/farseerService.js +31 -7
  169. package/dist/services/farseerService.js.map +1 -2
  170. package/dist/services/httpError.js.map +0 -1
  171. package/dist/services/modelExport.js.map +0 -1
  172. package/dist/services/organisation.js.map +0 -1
  173. package/dist/services/preflight.js.map +0 -1
  174. package/dist/services/realms.js.map +0 -1
  175. package/dist/services/syncService.js +3 -3
  176. package/dist/services/syncService.js.map +1 -2
  177. package/dist/skills/bundled.js +106 -0
  178. package/dist/skills/bundled.js.map +6 -0
  179. package/dist/skills/install.js +257 -0
  180. package/dist/skills/install.js.map +6 -0
  181. package/dist/skills/pipeline.js +10 -18
  182. package/dist/skills/pipeline.js.map +1 -2
  183. package/dist/utils/agentSandbox.js +1 -1
  184. package/dist/utils/agentSandbox.js.map +0 -1
  185. package/dist/utils/cliOptions.js.map +0 -1
  186. package/dist/utils/constants.js.map +0 -1
  187. package/dist/utils/entityResolver.js +72 -25
  188. package/dist/utils/entityResolver.js.map +1 -2
  189. package/dist/utils/errorFormatter.js +72 -11
  190. package/dist/utils/errorFormatter.js.map +1 -2
  191. package/dist/utils/fileLogger.js.map +0 -1
  192. package/dist/utils/fileValidation.js.map +0 -1
  193. package/dist/utils/folderMatch.js.map +0 -1
  194. package/dist/utils/formulaFilters.js +11 -2
  195. package/dist/utils/formulaFilters.js.map +1 -2
  196. package/dist/utils/helpers.js.map +0 -1
  197. package/dist/utils/logger.js.map +0 -1
  198. package/dist/utils/nameResolver.js.map +0 -1
  199. package/dist/utils/operationCli.js +102 -0
  200. package/dist/utils/operationCli.js.map +6 -0
  201. package/dist/utils/packageManager.js.map +0 -1
  202. package/dist/utils/syncReporting.js.map +0 -1
  203. package/dist/utils/syncScope.js.map +0 -1
  204. package/dist/utils/updateCheck.js.map +0 -1
  205. package/dist/utils/variableValues.js.map +0 -1
  206. package/dist/utils/workspace.js.map +0 -1
  207. package/docs/cli-guide.md +182 -2
  208. package/docs/import-workflows.md +14 -14
  209. package/docs/new-app-template.md +1 -1
  210. package/docs/pipeline-client-guide.md +1 -1
  211. package/docs/pipeline-reference.md +304 -9
  212. package/docs/troubleshooting.md +18 -0
  213. package/package.json +2 -2
  214. package/skills/farseer-analysis/SKILL.md +132 -0
  215. package/skills/farseer-app-dev/SKILL.md +131 -0
  216. package/skills/farseer-app-dev/assignments.md +185 -0
  217. package/skills/farseer-app-dev/farseer-client-api-guide.md +907 -0
  218. package/skills/farseer-app-dev/farseer-client-release-notes.md +212 -0
  219. package/skills/farseer-app-dev/working-patterns.md +876 -0
  220. package/skills/farseer-authenticate-to-tenant/SKILL.md +60 -0
  221. package/skills/farseer-authenticate-to-tenant/app-authentication.md +91 -0
  222. package/skills/farseer-author-import-job/SKILL.md +114 -0
  223. package/skills/farseer-author-import-job/cell-writes.md +530 -0
  224. package/skills/farseer-author-import-job/deploying-a-farseer-app.md +383 -0
  225. package/skills/farseer-author-import-job/import-job-pattern.md +232 -0
  226. package/skills/farseer-build-model/SKILL.md +122 -0
  227. package/skills/farseer-build-model/formula-grain-alignment.md +612 -0
  228. package/skills/farseer-build-model/naming-conventions.md +435 -0
  229. package/skills/farseer-build-model/sparse-formulas-pattern.md +330 -0
  230. package/skills/farseer-build-pipeline/SKILL.md +190 -0
  231. package/skills/farseer-build-pipeline/erp-sales/README.md +108 -0
  232. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/bronze/erp_sales_invoice_lines.yaml +23 -0
  233. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/bronze/erp_sales_invoice_lines_raw.yaml +23 -0
  234. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/bronze/erp_sales_item_product_map.yaml +17 -0
  235. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/bronze/erp_sales_item_product_map_raw.yaml +11 -0
  236. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/gold/erp_sales_cells.yaml +40 -0
  237. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/silver/erp_sales_lines.yaml +35 -0
  238. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/silver/erp_sales_recon.yaml +43 -0
  239. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/silver/erp_sales_unmapped_items.yaml +28 -0
  240. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/main.py +49 -0
  241. package/skills/farseer-build-pipeline/erp-sales/erp-sales-load/Models/in/erp_sales_cells.yaml +17 -0
  242. package/skills/farseer-build-pipeline/erp-sales/erp-sales-load/Models/in/erp_sales_cells_raw.yaml +14 -0
  243. package/skills/farseer-build-pipeline/erp-sales/erp-sales-load/Models/load/erp_sales_to_model.yaml +47 -0
  244. package/skills/farseer-build-pipeline/erp-sales/erp-sales-load/main.py +44 -0
  245. package/skills/farseer-build-pipeline/erp-sales/item_to_product.csv +5 -0
  246. package/skills/farseer-build-pipeline/pipeline-app-failure-report-pattern.md +103 -0
  247. package/skills/farseer-build-pipeline/pipeline-source-encoding.md +68 -0
  248. package/skills/farseer-dashboards/SKILL.md +40 -0
  249. package/skills/farseer-formulas/SKILL.md +165 -0
  250. package/skills/farseer-help-center/SKILL.md +66 -0
  251. package/skills/farseer-model/SKILL.md +119 -0
  252. package/skills/farseer-modify-model/SKILL.md +158 -0
  253. package/skills/farseer-modify-model/model-validation-pattern.md +251 -0
  254. package/skills/farseer-optimize-model/SKILL.md +314 -0
  255. package/skills/farseer-optimize-model/stats-dump.ts +139 -0
  256. package/skills/farseer-pnl/SKILL.md +220 -0
  257. package/skills/farseer-review-model/SKILL.md +172 -0
  258. package/skills/farseer-run-apps/SKILL.md +102 -0
  259. package/skills/pipeline-authoring/SKILL.md +7 -5
  260. package/skills/pipeline-authoring/practices.md +21 -8
  261. package/dist/services/agentApprovalFetch.js +0 -86
  262. package/dist/services/agentApprovalFetch.js.map +0 -7
@@ -0,0 +1,251 @@
1
+ # Model validation pattern — tests + backtests
2
+
3
+ How AI agents and human modelers validate a Farseer model: before declaring work done, after any modification, and when bringing a new model up against real client data.
4
+
5
+ This pattern applies whenever a Farseer model is built, modified, or refactored. Cells are named with the formula syntax (`"Table">"Member"`); the `farseer-model` skill has the write requests.
6
+
7
+ ---
8
+
9
+ ## 0. Definition of done — what "validated" actually means
10
+
11
+ A model change is **NOT done** until ALL of these are true for the regime that applies (see §1):
12
+
13
+ **Common to all regimes:**
14
+
15
+ - ✓ The validation regime that applies (functional / backtest / both) is identified in writing
16
+ - ✓ Outcome is recorded as one of: `pending` (scaffolded, not yet run) / `pass` (all instances passed) / `pass-with-expected-deltas` (passed with rationale per delta) / `partial-pass` (multi-instance test where some instances passed and at least one failed) / `fail` (no instances passed) / `baseline` (only for bootstrap)
17
+ - ✓ For `pass-with-expected-deltas`: written rationale per non-zero delta, recorded with the run
18
+ - ✓ For `partial-pass` (a test run on several tenants, where some passed and at least one failed): the status per tenant + rationale for the failing tenant(s)
19
+
20
+ **Regime-specific gates:** see §1 for which gate fires when.
21
+
22
+ **Functional regime — a reviewer can see the result:** give the domain
23
+ reviewer a thin, read-only sheet pinned to the test slice, with one column per
24
+ asserted OUT variable.
25
+
26
+ A functional test runner that passes 81/81 in a terminal a non-technical
27
+ reviewer never sees is not a complete deliverable. The confirmation sheet
28
+ makes the result inspectable on the tenant by the same domain experts
29
+ who own the test data.
30
+
31
+ ---
32
+
33
+ ## 1. Three regimes — which one applies, and when
34
+
35
+ The right validation depends on what kind of change is happening:
36
+
37
+ | Scenario | Regime | Trigger |
38
+ | --- | --- | --- |
39
+ | **A. New model from scratch, no client reference data** | Functional tests | First build; planner has no external truth to compare against yet |
40
+ | **B. Modification of an existing model** | Backtest (regression) | Any non-trivial variable/sheet/table change to a deployed model |
41
+ | **C. New model with client reference data available** | Backtest (validation) | Client provided exports/workbook; model must reproduce them |
42
+
43
+ These are **not mutually exclusive** — a major refactor to a model that has client reference data may need both functional tests (new logic correctness) and backtest (no regression on existing reference).
44
+
45
+ ### 1.A — New model from scratch (functional tests)
46
+
47
+ There is nothing external to compare against. Validation is *common-sense correctness*: do the formulas behave the way they should under known inputs?
48
+
49
+ - Edge cases mandatory: zero, negative, very large input (overflow / division-by-zero classes)
50
+ - Signature checks: revenue stays > 0 and COGS stays ≥ 0 **in storage** (everything is stored positive; a cost turns negative only where a formula presents it as a deduction), equity = assets - liabilities, etc. — each with its own pass/fail status
51
+
52
+ This is **not a unit-test framework** — these are scripted scenarios that an AI agent (or human) walks through deliberately: seed known inputs on a test slice, read the computed outputs back (§4.1), compare within a tolerance.
53
+
54
+ ### 1.B — Modification of an existing model (backtest)
55
+
56
+ If you are touching a model that has been deployed and run for clients, you must guarantee you didn't silently break anything.
57
+
58
+ **If a backtest baseline exists:**
59
+
60
+ - Read the model's outputs again for the latest reference dataset
61
+ - Compute delta against the reference outputs (variable-by-variable)
62
+ - Expected outcome: delta == 0 for every variable that was not intentionally changed
63
+ - For variables that were intentionally changed: document the reason with the run
64
+
65
+ **If NO backtest baseline exists — "bootstrap a baseline" sub-procedure:**
66
+
67
+ This is the common case for older client models that pre-date this pattern. Before making any modification:
68
+
69
+ 1. **Halt the planned change.** Do not modify a single variable or sheet config yet.
70
+ 2. Identify all relevant output variables for the model (typically: P&L final lines, BS final lines, cash flow final lines, key KPIs).
71
+ 3. Read the current production output of those variables with bounded reads, never a whole-variable export on a live tenant: `formula eval` totals per variable, version and period; `cells query --input` for the cells the change touches; `variable export --filter` on one version and month. Dump the whole time horizon only on a dev or test copy.
72
+ 4. Save the reads, with the list of captured variables and of those deliberately left out (intermediate derivatives that are pure functions of captured ones, derivable period aggregates) — e.g. `farseer formula eval '"<Var>"' <tenant> --filter Versions=<version> --filter Months=<month> --json` for a total, `farseer cells query <tenant> --input cells.json` for the touched cells, and `farseer variable export "<Var>" --filter Versions=<version> --filter Months=<month> --output baseline/<var>-<month>.csv` for a slice, with `FARSEER_TENANT` set
73
+ 5. **Commit the baseline as its own step** — separate commit from the modification work that follows. This makes "before" and "after" reviewable.
74
+ 6. Now proceed with the planned modification. After modification, read the same totals, cells and slices again and compare against the baseline.
75
+
76
+ The bootstrap baseline is the contract: "this is what the model produced before I touched it." Without it, claims of "I didn't break anything" are unverifiable.
77
+
78
+ ### 1.C — New model with client reference data (backtest)
79
+
80
+ The client has provided their existing workbook / export — the model must reproduce it cent-perfect (or document tolerances).
81
+
82
+ - One reconciliation row per (variable, period): model output, reference, delta, status
83
+ - Until every row is `pass` (or has a documented rationale as an expected delta), the model is **not deployed to production tenants**
84
+
85
+ ---
86
+
87
+ ## 4. AI agent contract
88
+
89
+ When an AI agent (Claude, Cursor, Copilot, …) is asked to build, modify, or refactor a Farseer model, it MUST:
90
+
91
+ 1. **Before any code change** — identify which regime applies (§1) and state it back to the user.
92
+ 2. **If regime B and no baseline exists** — execute the bootstrap sub-procedure (§1.B). Stop, capture the baseline and commit it as its own step BEFORE touching the modification.
93
+ 3. **Before saying "done"** — verify outcome is `pass` or `pass-with-expected-deltas`. If `fail` or `pending`, the work is NOT done; surface this to the user, don't paper over it.
94
+ 4. **Surface, don't bypass.** If validation reveals a deeper bug than the user's task scope, do not "fix" it silently. Document, surface, ask.
95
+
96
+ ### 4.1 Functional regime — seed, read back, compare
97
+
98
+ **Test-slice precondition — a usable test version is `active: true` AND outside
99
+ the planning rotation.** When the test slice is isolated on a dedicated
100
+ `Versions` member (rather than a dedicated test period on a live version), verify the member's ACTIVE flag before seeding:
101
+ `farseer model <tenant> --table Versions --json` → ACTIVE column. An
102
+ **inactive** version silently swallows every write — members and variables
103
+ resolve, `commit()` reports success, zero cells land — so the failure presents
104
+ as a passing seed step and a mysteriously all-null read-back. If the only candidate test
105
+ versions on a tenant are inactive, **escalate rather than write into a live
106
+ version** — or use the verify-without-writing fallback (§4.4).
107
+
108
+ **Seeding is a tenant write**: a dev or test tenant only, never production. This
109
+ guide has no write procedure — the `farseer-model` skill has the cell-write
110
+ request today, and `farseer code` (Experimental) is the future path. Where no
111
+ test slice can be written, use the read-only variant (§4.4).
112
+
113
+ **Reading back** — evaluate one formula per asserted cell, for example
114
+ `farseer formula eval 'sum("Margin OUT", "Product">"P-100", "Versions">"Plan", "Years">"Y2026", "Months">"M1")' <tenant> --json`
115
+ (the same evaluator as the API's `/evaluate`, which takes many cell queries in
116
+ one request). Variable names are **quoted** (they contain spaces / ` OUT`);
117
+ member filters use `"Table">"Member"`.
118
+
119
+ **Read back after the write has returned.** A cell write through
120
+ `/model/updateCells` returns after the engine has applied it and cleared the
121
+ read cache, so a read right after it normally sees the new values; after an
122
+ import or a job that is still running, wait for it to finish first. A read that
123
+ was already running when the write landed can still answer with the pre-write
124
+ values for a short while: if a read-back shows pre-write values, read again
125
+ after a minute before suspecting the formula. A variable with Calculate on
126
+ demand (`calculateOnDemand`), and every formula that reads it, is not
127
+ recalculated by the write. Don't call `POST /api/v3/evaluator/invalidateCache`
128
+ for a read-back: it recalculates the whole model and adds a command to the
129
+ tenant's command log.
130
+
131
+ ### 4.2 Backtest regime — compare against a reference
132
+
133
+ Same shape, but the comparison is against an external reference instead of
134
+ expected values: a Farseer export already confirmed accurate (a previous
135
+ baseline that signed off, or an audit pack the client accepted), or a client
136
+ workbook. Per (variable, period): model output, reference, delta, status. If
137
+ every status is `pass`, the outcome is `pass`. If some are `fail` and ALL of
138
+ them have a written rationale as expected deltas, the outcome can be
139
+ `pass-with-expected-deltas`. Otherwise `fail` — surface the offending rows to
140
+ the user, and do NOT mark the model deployable.
141
+
142
+ ### 4.2.1 Operating a real-data backtest (ground truth = a client workbook)
143
+
144
+ When the ground truth is a client workbook with personal data and the model
145
+ already carries a synthetic functional test rig, four operating rules:
146
+
147
+ 1. **Sibling tenant — do not wipe the functional rig.** Functional tests
148
+ (synthetic positions) and the backtest (real, personal data) must **not
149
+ share a tenant**: a wipe for real data destroys the synthetic rig and vice
150
+ versa, forcing a choice between regression and backtest. Use a separate
151
+ sibling tenant for the real data; the functional rig stays intact and the
152
+ personal data is physically isolated on one tenant. The model is the same;
153
+ only the tenant differs.
154
+
155
+ 2. **Non-circular expected — from the client's *computed* grid, not from the
156
+ drivers.** The expected figure MUST come from the template's **computed
157
+ columns** (its own "Total …" outputs), never from re-applying the model formula
158
+ to the same drivers — otherwise it is a tautology (model ≡ expected by
159
+ construction). Σ of those Total columns over the in-scope members = the sector
160
+ expected. A `dev2` that holds ONLY the scope → the model's grand Σ equals the
161
+ sector Σ (no filter needed in the eval).
162
+
163
+ 3. **Calibrate units against the expected aggregate = double confirmation.**
164
+ Before seeding, calibrate each parameter's unit by dividing the expected
165
+ aggregate by its carrier: e.g. `Σ_expected ÷ Σ FTE-months = per-FTE-month rate`
166
+ confirms BOTH the input unit AND that the model formula (`× FTE`) is correct,
167
+ simultaneously. If the calibration doesn't come out to a clean parameter, the
168
+ unit or the formula is wrong — catch it **before** the seed, not after a
169
+ mysterious delta.
170
+
171
+ 4. **A backtest catches bugs the functional test cannot.** A functional test on
172
+ synthetic tables has **complete FKs by construction**, so it masks missing
173
+ FKs. A real-data extract exposes them: an FK column from X to Y that the
174
+ model relies on, but that is absent or empty in the extracted members → the
175
+ FK resolves to NULL → every per-`Y` parameter returns null. **Rule: when
176
+ extracting real tables, cross-check EVERY FK the model relies on against the
177
+ FK values of the extracted members.**
178
+
179
+ **Outcome vocabulary in practice.** `pass-with-expected-deltas` is a legitimate v1
180
+ target: reconcile the bulk (gross + contributions + allowances) and document any
181
+ component that is a *sketch* in the model (e.g. a distribution not yet modelled)
182
+ as an expected-delta with amount + reason. Do not
183
+ force a `pass` through an approximation that hides the gap.
184
+
185
+ ### 4.3 What the AI does NOT do
186
+
187
+ - Does NOT push model changes to production tenants until validation passes.
188
+ - Does NOT silently fix a "validation revealed a bug" — surfaces it, asks the user, then either widens the change scope (with permission) or files it for follow-up.
189
+
190
+ ### 4.4 Sanctioned fallback — verify without writing
191
+
192
+ When no usable test slice exists (no active test version, no free test period,
193
+ or the tenant is live and any seed is a risk), the functional regime has a
194
+ **read-only variant**: instead of seeding synthetic inputs, find coordinates in
195
+ the **real data** that already exhibit each scenario shape, and assert the
196
+ formula's value there.
197
+
198
+ 1. **Export the input variables, scoped** to one version and a few months (`farseer variable export "<Var>" --filter Versions=<version> --filter Months=<month> --output <var>-<month>.csv`, one file per month, with `FARSEER_TENANT` set). Full grain only on a dev or test copy: an unfiltered export runs every cell through the engine of a live tenant.
199
+ 2. **Find coordinates already exhibiting each scenario shape** — e.g. a
200
+ no-revenue confirmation, a negative/storno entry, a large-magnitude value,
201
+ an aggregate rollup, an out-of-filter member.
202
+ 3. **Compute the expectation FROM THE EXPORT** — never hand-write it — and
203
+ assert the formula's output at those coordinates.
204
+ 4. **Bracket the run with a before/after aggregate measurement** of the
205
+ untouched active versions, proving the validation cycle changed nothing.
206
+
207
+ What it should achieve: every scenario closes to the cent or names its gap,
208
+ including a precision check at a large magnitude — arguably **stronger** than synthetic seeding (the shapes come
209
+ from the real data distribution), and it mutates nothing.
210
+
211
+ The two disciplines in bold above are what keep it honest: expectations
212
+ **computed from the export** (a hand-written expectation silently degenerates
213
+ into testing your own arithmetic), and the **no-mutation proof**.
214
+
215
+ **Honest limitation:** a shape absent from the data cannot be tested this way.
216
+ List every untestable scenario as **residual** with the test — never silently
217
+ drop it from the scenario set.
218
+
219
+ ### 4.5 Joining actual with plan — find where they meet before building report variables
220
+
221
+ Before writing any variable that puts actual next to plan / forecast (a
222
+ variance line, an "actual + forecast" splice, a report that shows both),
223
+ answer three questions **in this order**.
224
+
225
+ 1. **Get the client's control numbers first** — one total per version and
226
+ period you are about to show. They are the expected values of the backtest
227
+ (§4.2) and the only way to tell a modelling error from a data gap; without
228
+ them every "is this right?" turn ends in "no clear answer".
229
+ 2. **Read the plan side, then mirror the sibling.** At what grain is plan
230
+ entered (it may be an item the actual source never carries — a
231
+ Farseer-generated code, a planning bucket)? Which existing variable
232
+ already combines actual and plan for a **sibling measure**? Copy its
233
+ pattern (the version split, the meeting grain) rather than inventing one;
234
+ a second pattern for the same join is a reconciliation problem later.
235
+ 3. **Test the actual source for a multi-path FK with two pins.** Pin the
236
+ actual to two mutually exclusive members of the reporting dimension: if
237
+ the pinned sums add up to more than the unpinned total — in the incident
238
+ each pin returned the whole total — the same cells reach the target by two
239
+ paths; fix the link graph before building on it. If they add up to
240
+ **less**, holding only the cells where two grain dimensions share a target
241
+ member, the variable is read at a shared FK descendant and returns the
242
+ intersection (measured 2026-10-17) — read a one-sided roll-up there instead.
243
+
244
+ **A cross-version reference needs no special form.** `sum(V, Versions >
245
+ "Plan")` from inside another version works as the sole term, inside `if()`
246
+ and inside a sum (measured 2026-10-15 on a sandbox tenant). The one null
247
+ measured: a variable with rollup FORMULA read at a single version — a
248
+ FORMULA-rollup ratio of two cross-version references returned its value
249
+ unpinned and `null` under `Versions > "Plan"` and under the forecast
250
+ version. Don't put cross-version references in a FORMULA-rollup variable that
251
+ consumers read per version.
@@ -0,0 +1,314 @@
1
+ ---
2
+ name: farseer-optimize-model
3
+ description: >-
4
+ How to make a slow Farseer model calculate faster: measure each variable's calculation time and cells after a full calculation, rank them by time and by µs per cell against the model's median, match each flagged formula to a catalogue of known slow shapes (a version flag multiplied in, a broadcast and an FK lift in one product, `0 + X` lifts, self-grain `sum()` filters, `delay()` across years), and prove each faster rewrite on throwaway copies (values, cell counts, CHECK controls) before the real formula changes. Use when a model in use recalculates slowly, a save or a full recalculation takes too long, or the user asks why the model is slow or how to cut its calculation time. Not for business numbers or trends (farseer-analysis), designing a new model (farseer-build-model) or a change unrelated to speed (farseer-modify-model).
5
+ metadata:
6
+ version: "1"
7
+ domain: modeling
8
+ ---
9
+
10
+ # Optimize a Deployed Farseer Model
11
+
12
+ ## When this skill applies
13
+
14
+ A model that is already built and pushed — dev, test, or prod — where a
15
+ full calculation or a day-to-day recalc is slow enough to be a problem:
16
+ before handing the model over, when a planner complains about save/recalc time,
17
+ after a model has grown past its original design (more customers, more
18
+ SKUs, more versions), or whenever the user just asks to make it faster.
19
+
20
+ Do **not** use this skill for:
21
+ - Correctness / naming / discipline audit → the `farseer-review-model` skill (run that
22
+ first if you haven't recently — a model with grain-alignment or sparse
23
+ discipline defects should be reviewed, not just profiled; many
24
+ performance defects below ARE review findings, just triaged
25
+ here by cost instead of by rule)
26
+ - A model that doesn't exist yet → the `farseer-build-model` skill
27
+ - A specific bug fix / change unrelated to speed → the `farseer-modify-model` skill (this
28
+ skill's step (e) delegates the actual change there)
29
+
30
+ This skill is a **diagnose-then-fix loop bounded by measurement**, not a
31
+ list of things to try. Every fix below is proven with numbers on the
32
+ variable it targets before it's allowed to replace the real formula.
33
+
34
+ The mechanisms behind the catalogue are in the `farseer-build-model` skill's
35
+ reference files, linked below. If a link does not open because this skill was
36
+ installed on its own, `farseer skills show farseer-build-model --file <file>`
37
+ prints the file.
38
+
39
+ ## Inputs to gather first
40
+
41
+ 1. **Which instance, and why now** — dev/test/prod, and whether this is
42
+ routine handover hygiene or a reported complaint (a reported complaint
43
+ usually names the slow screen/sheet — start the triage from the
44
+ variable(s) behind it, not just the global top-N).
45
+ 2. **A local script run** — step (a) runs [`stats-dump.ts`](stats-dump.ts),
46
+ shipped next to this file, with `farseer run-script`, which runs it on
47
+ this machine with the tenant's credentials. Once per tenant, from one
48
+ working folder (the commands look for `farseer-apps/` in the current
49
+ one): `farseer pull <org> <tenant>` (it creates `farseer-apps/<tenant>/`),
50
+ `farseer install <tenant>`, then copy `stats-dump.ts` into
51
+ `farseer-apps/<tenant>/files/Scripts/` — `run-script` finds a script
52
+ there by its file name. If the CLI session is missing, use the
53
+ `farseer-authenticate-to-tenant` skill first.
54
+ 3. **A same-day read of the model** — `farseer model --json <tenant> >
55
+ model.json` for the tables and formula text step (c) classifies
56
+ (`farseer model --variable "<Variable>" <tenant>` for one variable).
57
+ A stale read risks triaging formulas that no longer exist.
58
+ 4. **Timing expectations** — a FULL calc via `invalidateCache` **blocks
59
+ until the whole model recalculates** — minutes on a real model. Budget
60
+ for it, and **never run it against a production tenant during business
61
+ hours** — planners lose write access to a locked/recalculating model
62
+ for the duration. Schedule off-hours or use dev/test.
63
+
64
+ ## Procedure
65
+
66
+ ### (a) Collect a FULL-calc stats snapshot
67
+
68
+ Run [`stats-dump.ts`](stats-dump.ts) with `FULL=1` (it invalidates the
69
+ cache first, then reads `c.evaluator.stats()`), and name the snapshot:
70
+
71
+ ```bash
72
+ FULL=1 OUT=before.json farseer run-script <tenant> stats-dump.ts
73
+ ```
74
+
75
+ It writes `before.json` into `farseer-apps/<tenant>/`, then prints the two
76
+ rankings of step (b). Without `OUT` the file is `stats-dump-<UTC time>.json`,
77
+ so no run overwrites an earlier one. If the `FULL=1` request times out or
78
+ loses its connection (the script says so), the recalculation continues on
79
+ the server: wait, then run it again **without** `FULL=1` (same `OUT`) to
80
+ read its stats. Never rerun with `FULL=1` after a timeout: that starts a
81
+ second full recalculation. Never push the copy in
82
+ `files/Scripts/` to the tenant; remove it when you're done.
83
+
84
+ Without `FULL=1` you get the last calc's numbers, which is fine for a
85
+ quick re-check but not for a first triage (a partial/incremental calc
86
+ under-counts variables nothing touched).
87
+
88
+ **Field semantics (each one has burned a debug round):**
89
+
90
+ - **Key variables by `gid`, never `id`** — `gid` is the stable entity GID;
91
+ `id` is an internal index and joins to nothing.
92
+ - `duration` is **milliseconds**; `calculated` = formula-evaluated cells,
93
+ `nonCalculated` = input/imported cells; total cells = the sum of both.
94
+
95
+ The entries sit under `variables`, with the model-level `calculationTime`
96
+ beside them.
97
+
98
+ **Tenant discipline:** confirm with the user which tenant before running
99
+ `FULL=1` — it is a blocking write-adjacent operation on a live tenant.
100
+ Dev/test any time; prod only off-hours with explicit confirmation, same
101
+ promotion discipline as the `farseer-modify-model` skill.
102
+
103
+ **Where `farseer run-script` is refused** (an agent sandbox cannot run a
104
+ local script): don't run the script any other way. Ask the user to run it
105
+ on their machine (the setup in Inputs 2, then the command above) and share
106
+ the JSON, or stop here.
107
+
108
+ ### (b) Read the two rankings
109
+
110
+ The stats script prints them after it writes the JSON: `TOP` rows each
111
+ (default 15), with the median taken over the formula variables of at least
112
+ `MIN_CELLS` cells (default 1000). Inputs don't count: they have no
113
+ calculated cells, and on some engines a zero duration, so they would pull
114
+ the median towards 0. Set either next to `FULL=1` to change it.
115
+
116
+ The two rankings are — **by duration** (where the wall-clock goes) and
117
+ **by µs/cell** (`duration * 1000 / (calculated + nonCalculated)`, the
118
+ **inefficiency index**: cost per cell against the model's own median
119
+ µs/cell for formula variables with ≥`MIN_CELLS` cells). A variable can be slow
120
+ because it has many cells (duration-ranked, often fine) or because each
121
+ cell is expensive (µs/cell-ranked, almost always a defect). Triage the
122
+ µs/cell list first — that's where the catalogue in step (c) applies.
123
+
124
+ ### (c) Classify each flagged variable against the catalogue
125
+
126
+ For every flagged variable, read its grain, formula, and the grain of
127
+ every variable it references (`farseer model --variable "<V>" <tenant>`
128
+ prints a variable's tables, fixed members and formula; mark where a
129
+ referenced variable's tables differ from the flagged one's). Match the shape
130
+ against this catalogue — it's the fixed set of causes seen in practice,
131
+ each with its measured cost and fix:
132
+
133
+ | # | Cause | Symptom (measured) | Fix | After (measured) |
134
+ |---|---|---|---|---|
135
+ | 1 | **Versions broadcast as a product** — a formula multiplies by a version-carrier flag: `X * carrier` | tens of times the model median µs/cell | `if(eq(carrier, 1), X)` — a condition, not a product | back near the model median |
136
+ | 2 | **Broadcast + FK hop in ONE product** — a Versions broadcast AND a cross-dimension (FK) lift happen inside the same multiply | hundreds of times the median — the single worst shape seen | Split into two stored steps: broadcast first (fix #1), lift the coarse operand across the FK hop on its **own sparse grain** (fix #3), then multiply two already-aligned-grain operands | back near the median |
137
+ | 3 | **`0 + X` lift creates phantom zeros** — a coarse operand lifted to a finer grain via `0 + X` materialises an explicit `0` wherever `X` is null on the finer grain, instead of staying null | inflated cell counts; breaks "reached by both paths"-style CHECK controls (a zero cell counts as data) | `if(hasValue(X), X)` when the result must stay sparse. Keep `0 + X` **only** where an explicit zero is actually wanted (e.g. a factor that must read `1 − 0`, not `1 − null`) | same duration order of magnitude as #2's second half; correctness fix as much as speed fix |
138
+ | 4 | **Operand order** | no measurable effect | not a lever — don't spend time reordering operands looking for a win | — |
139
+ | 5 | **Rollup to a coarser grain** — e.g. `"X by Customer" [Customer] = "X" [Customer, Item]` | close to the model median | acceptable; don't chase this shape, it isn't the antipattern | — |
140
+ | 6 | **Pre-existing cookbook cases** — self-grain `sum()` filter (a `sum(var, Dim>Member)` filtering a dimension that's in the variable's own grain — [`formula-grain-alignment.md`](../farseer-build-model/formula-grain-alignment.md)), and `delay()` reaching across a year boundary into periods with no data (`delay()` itself crosses years — re-measured 2026-10-03; a January that reads empty means December is empty, often an import that has not loaded) | model-specific | see the linked doc | — |
141
+
142
+ **How to check fix #1's semantics hold before applying it:** the
143
+ condition and the product are identical **only** when the carrier stores
144
+ `1` or `null` — never a stored `0`. If the carrier can hold `0` (a
145
+ planner-entered "explicitly off" state, not "not applicable"), the
146
+ product zeroes the result while the condition nulls it — different
147
+ values in a downstream `sum()`. Check the carrier's own formula/import
148
+ job before assuming this; when unsure, dump the carrier's distinct
149
+ values for the affected cells and confirm no `0`s exist.
150
+
151
+ To dump them, scoped to the versions and months the flagged formula reads:
152
+ `farseer variable export "<carrier>" --filter Versions=<version> --filter Months=<month> --output carrier-<version>-<month>.csv`
153
+ (the tenant comes from `FARSEER_TENANT`) writes one row per stored cell of
154
+ that slice; look for a `0`. Never export the whole carrier on a live tenant:
155
+ an unfiltered export runs every cell through the engine. Dev/test any time;
156
+ on production only with the user's explicit go and outside business hours,
157
+ the same as a FULL recalc.
158
+
159
+ **Dense cell production — check this BEFORE debugging a variable that
160
+ reads null everywhere or recalculates for minutes.** A formula that
161
+ produces a dense layout of cells (a broadcast or cross product over a
162
+ detail grain × `Versions` × periods) is one class of problem from tens of
163
+ millions of cells up: slow recalculation, then a variable that reads null
164
+ downstream with no further diagnostic. The platform does not warn loudly;
165
+ there is no safe threshold to aim under. (The grain's member-count product
166
+ alone is not it: a grain in the hundreds of millions holding one cell computed normally —
167
+ count the cells formulas produce.) This is a design-time constraint
168
+ ([`formula-grain-alignment.md` §7](../farseer-build-model/formula-grain-alignment.md#7--avoid-it-at-the-start-design-time-performance-rules)
169
+ covers it), not a performance-tuning one, but it produces symptoms that
170
+ look exactly like a performance defect (silently-null OUT) — rule it
171
+ out first if a flagged variable produces a dense layout of cells (e.g. a
172
+ few hundred customers × a few thousand items × many Versions members × 36
173
+ months adds up fast).
174
+
175
+ ### (d) Fix with SCRATCH variables first — never edit the real formula on the first pass
176
+
177
+ **Where:** start on a dev or test copy of the tenant. On production, the
178
+ scratch folder, each `XP` variable (a new formula variable calculates on
179
+ the live model), each FULL recalc and each `delete -y` need the user's
180
+ explicit go, step by step, and a FULL recalc never runs in business hours.
181
+
182
+ 1. Create the candidate fix as new variables in a **`99 Experiments`**
183
+ folder, named so they're unmistakably
184
+ throwaway (a recommended convention, not a platform rule: an `XP …` prefix). Nothing in the
185
+ model reads them.
186
+ 2. Create **only** the scratch variables, one command each — never a
187
+ whole-model change for an experiment:
188
+ ```bash
189
+ farseer variables create <tenant> --name "XP <Variable>" \
190
+ --folder-path "<root>/99 Experiments" --dimensions "<Table A>,<Table B>" \
191
+ --rollup <the original's> --data-type <the original's> --formula '<candidate>'
192
+ ```
193
+ Copy the original's tables, roll-up type and data type from
194
+ `farseer model --variable "<Variable>" <tenant>`, so only the formula
195
+ differs. The folder path starts at the tenant's top-level folder, read
196
+ from the `folderPath` of existing variables in `farseer model --json`
197
+ (often `Variables`). It must exist: `farseer folders create "99
198
+ Experiments" <tenant> --parent-path "<root>"` or the UI makes it;
199
+ without it, the `XP` prefix alone marks the copies. A candidate that
200
+ needs a fixed member in its tables can't be made with these flags: use
201
+ the UI. The copy doesn't carry calculate-on-demand or `zConstraint`: if
202
+ the original has either (`farseer model --variable` shows the first,
203
+ `--json` both), the copy calculates differently, so say so next to its
204
+ duration and cells, or make the copy in the UI with the same settings.
205
+ 3. Full recalc (`FULL=1 OUT=candidate.json farseer run-script <tenant>
206
+ stats-dump.ts`).
207
+ 4. Compare, all four, not just duration:
208
+ - **duration** — the candidate variable's own µs/cell and total ms
209
+ - **values** — diff the candidate against the current production
210
+ formula's output, per version, per segment (or whatever the
211
+ model's natural slicing dim is), and per month. Float noise
212
+ (~1e-7) is fine; anything else is not
213
+ - **cell counts** — the candidate must produce the **same** cell
214
+ count as the original unless the fix is deliberately correcting a
215
+ sparsity bug (catalogue #3) — a cell-count change you didn't intend
216
+ is a silent semantics change, not a speed win
217
+ - **the relevant CHECK controls** — every CHECK FINAL the candidate's
218
+ area feeds must still read green (empty / zero); a control that
219
+ goes red on a "faster but equivalent" fix means it wasn't equivalent
220
+ 5. Only a `pass` on all four moves to step (e). Anything else — fix the
221
+ candidate, or fall back to the catalogue and reclassify; a mismatch
222
+ isn't the model being weird, it's usually classification #2 applied
223
+ as #1 or vice versa.
224
+
225
+ Reading the four with the CLI (reads only):
226
+ - **duration, cell counts** — the candidate's and the original's entries
227
+ in `candidate.json`: `duration`, and `calculated + nonCalculated`.
228
+ - **values** — both in one request, per slice:
229
+ `farseer formula eval '"<Variable>"' <tenant> --formula '"XP <Variable>"' --filter Versions=<version> --filter Months=<month> --json`.
230
+ Many slices at once: `farseer cells query <tenant> --input slices.json`,
231
+ where the file is a JSON array with one query per variable and slice:
232
+ `[{"variable": "XP <Variable>", "dimensions": [{"dimensionTable": "Versions", "dimensionValue": "<version>"}]}, …]`;
233
+ a table a query leaves out is totalled by its rollup. Cell by cell, on a
234
+ dev or test copy, or for a single month on production:
235
+ `farseer variable export "<Variable>" --filter Versions=<version> --filter Months=<month> --output a.csv`,
236
+ the same for `"XP <Variable>"` into `b.csv` (the tenant comes from
237
+ `FARSEER_TENANT`), then compare the two files.
238
+ - **CHECK controls** — `farseer formula eval '"<CHECK variable>"' <tenant>`
239
+ for each control the area feeds; an `XP` copy of a control, pointed at
240
+ the candidate, reads the candidate's side.
241
+
242
+ ### (e) Replace the real formula, re-measure, clean up
243
+
244
+ 1. Once a scratch candidate passes step (d) in full, apply the same
245
+ change to the **real** variable via the `farseer-modify-model` skill (this skill
246
+ doesn't push production formulas itself — delegate the snapshot /
247
+ impact-analysis / promotion discipline there).
248
+ The write itself is `farseer variables update <tenant> --name
249
+ "<Variable>" --formula '<new formula>'`.
250
+ 2. Full recalc once more; confirm the model-level `calculationTime` drop
251
+ matches what the scratch candidate predicted (report both).
252
+ `FULL=1 OUT=after.json farseer run-script <tenant> stats-dump.ts`, then
253
+ compare `calculationTime` in `before.json` and `after.json`.
254
+ 3. **Delete the scratch variables** — they're disposable by design and
255
+ a full recalc with unused `XP …` variables still present pays their
256
+ cost every time.
257
+ `farseer variables delete "XP <Variable>" <tenant>` prints a preview:
258
+ check that it names the copy, then run it again with `-y`.
259
+ 4. Report the before/after to the user: the variable(s) touched, the catalogue cause
260
+ #, before/after duration and µs/cell, the model-level
261
+ `calculationTime` before/after, and the CHECK controls verified green.
262
+
263
+ ## Expected output
264
+
265
+ - The two rankings from the stats script, and for each flagged variable
266
+ its tables, formula and the tables of the variables it references
267
+ - For each variable actually fixed: scratch-variable comparison results
268
+ (values / cells / CHECK controls) and the catalogue cause #
269
+ - Real-formula change delegated to the `farseer-modify-model` skill with its own
270
+ snapshot + impact analysis
271
+
272
+ ## Definition of done
273
+
274
+ - Every variable flagged by the two rankings is either
275
+ fixed (with before/after numbers recorded) or explicitly left as-is
276
+ with a one-line reason (e.g. "duration-ranked only, µs/cell is at the
277
+ median — not a defect", or catalogue #5's "acceptable rollup cost").
278
+ - All scratch (`XP …` / `99 Experiments`) variables are deleted from the
279
+ tenant — a `pass` result that leaves scratch clutter behind is not
280
+ done.
281
+ - The model-level `calculationTime` before/after is recorded even when
282
+ a single variable's fix looks small — the sum across several small
283
+ fixes is often the real win.
284
+ - CHECK controls are green after the real-formula push, not just after
285
+ the scratch validation (re-verify — a push can differ from the
286
+ scratch experiment in ways the four-way comparison in step (d) didn't
287
+ cover, e.g. a downstream consumer that only exists on the real
288
+ variable's name).
289
+ - The copy of `stats-dump.ts` is gone from
290
+ `farseer-apps/<tenant>/files/Scripts/`, so no later `farseer push`
291
+ uploads it to the tenant.
292
+
293
+ ## Constraints
294
+
295
+ - **Do not** edit the real formula before a scratch-variable pass has
296
+ validated it on values, cell counts, AND CHECK controls — duration
297
+ alone is not sufficient proof of equivalence.
298
+ - **Do not** run `invalidateCache` (the FULL-calc precondition) against
299
+ a production tenant during business hours. It blocks the whole model
300
+ for minutes; confirm timing with the user first.
301
+ - **Do not** treat catalogue #5 (coarser rollup, close to the median µs/cell) as a defect
302
+ — chasing it wastes a validation cycle for no measurable gain.
303
+ - **Do not** apply catalogue #1's condition form without checking the
304
+ carrier never stores a literal `0` — the condition and the product
305
+ are only equivalent under the 1/null convention.
306
+ - **Do not** leave scratch variables in the model after the real fix
307
+ ships — they cost calc time every recalc while present.
308
+ - **Do not** skip the `farseer-modify-model` skill's snapshot/impact-analysis/promotion
309
+ discipline for the real-formula push — this skill only earns the
310
+ right to make that change, it doesn't replace the process for making
311
+ it safely.
312
+ - **Do not** change the real formula from this skill — the scratch
313
+ experiments go through `farseer variables create`, the real formula
314
+ goes through the `farseer-modify-model` skill.