farseer-cli 1.19.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 (155) hide show
  1. package/README.md +31 -8
  2. package/dist/commands/app.js +42 -3
  3. package/dist/commands/app.js.map +1 -1
  4. package/dist/commands/cells.js +120 -85
  5. package/dist/commands/cells.js.map +1 -1
  6. package/dist/commands/dashboards.js +246 -12
  7. package/dist/commands/dashboards.js.map +1 -1
  8. package/dist/commands/dimensions.js +52 -27
  9. package/dist/commands/dimensions.js.map +1 -1
  10. package/dist/commands/docs.js +82 -0
  11. package/dist/commands/docs.js.map +6 -0
  12. package/dist/commands/files.js +49 -0
  13. package/dist/commands/files.js.map +2 -2
  14. package/dist/commands/folders.js +76 -0
  15. package/dist/commands/folders.js.map +6 -0
  16. package/dist/commands/formula.js +38 -30
  17. package/dist/commands/formula.js.map +1 -1
  18. package/dist/commands/install.js +32 -30
  19. package/dist/commands/install.js.map +2 -2
  20. package/dist/commands/model.js +30 -5
  21. package/dist/commands/model.js.map +2 -2
  22. package/dist/commands/push.js +5 -3
  23. package/dist/commands/push.js.map +1 -1
  24. package/dist/commands/sheets.js +289 -52
  25. package/dist/commands/sheets.js.map +1 -1
  26. package/dist/commands/skills.js +157 -0
  27. package/dist/commands/skills.js.map +6 -0
  28. package/dist/commands/variables.js +246 -82
  29. package/dist/commands/variables.js.map +1 -1
  30. package/dist/index.js +93 -13
  31. package/dist/index.js.map +1 -1
  32. package/dist/mcp/resources/documentation.js +19 -12
  33. package/dist/mcp/resources/documentation.js.map +1 -1
  34. package/dist/mcp/tools/appTools.js +1 -7
  35. package/dist/mcp/tools/appTools.js.map +1 -1
  36. package/dist/mcp/tools/cellTools.js +6 -19
  37. package/dist/mcp/tools/cellTools.js.map +1 -1
  38. package/dist/mcp/tools/dashboardTools.js +30 -412
  39. package/dist/mcp/tools/dashboardTools.js.map +2 -2
  40. package/dist/mcp/tools/dataTools.js +15 -146
  41. package/dist/mcp/tools/dataTools.js.map +1 -1
  42. package/dist/mcp/tools/folderTools.js +12 -78
  43. package/dist/mcp/tools/folderTools.js.map +1 -1
  44. package/dist/mcp/tools/modelTools.js +23 -372
  45. package/dist/mcp/tools/modelTools.js.map +1 -1
  46. package/dist/mcp/tools/pipelineContract.js +5 -1
  47. package/dist/mcp/tools/pipelineContract.js.map +1 -1
  48. package/dist/mcp/tools/runTools.js +8 -69
  49. package/dist/mcp/tools/runTools.js.map +1 -1
  50. package/dist/mcp/tools/sheetTools.js +14 -264
  51. package/dist/mcp/tools/sheetTools.js.map +1 -1
  52. package/dist/mcp/tools/syncTools.js +5 -1
  53. package/dist/mcp/tools/syncTools.js.map +1 -1
  54. package/dist/mcp/utils/operationResponse.js +41 -0
  55. package/dist/mcp/utils/operationResponse.js.map +6 -0
  56. package/dist/operations/cells.js +444 -0
  57. package/dist/operations/cells.js.map +6 -0
  58. package/dist/operations/dashboards.js +357 -0
  59. package/dist/operations/dashboards.js.map +6 -0
  60. package/dist/operations/data.js +206 -0
  61. package/dist/operations/data.js.map +6 -0
  62. package/dist/operations/errors.js +64 -0
  63. package/dist/operations/errors.js.map +6 -0
  64. package/dist/operations/exportModel.js +59 -0
  65. package/dist/operations/exportModel.js.map +6 -0
  66. package/dist/operations/folderPath.js +128 -0
  67. package/dist/operations/folderPath.js.map +6 -0
  68. package/dist/operations/folders.js +80 -0
  69. package/dist/operations/folders.js.map +6 -0
  70. package/dist/operations/install.js +109 -0
  71. package/dist/operations/install.js.map +6 -0
  72. package/dist/operations/model.js +271 -0
  73. package/dist/operations/model.js.map +6 -0
  74. package/dist/operations/sheets.js +428 -0
  75. package/dist/operations/sheets.js.map +6 -0
  76. package/dist/pipeline/failStep.js +43 -0
  77. package/dist/pipeline/failStep.js.map +6 -0
  78. package/dist/pipeline/generated-reference.json +10 -10
  79. package/dist/pipeline/queryWorker.js +3 -1
  80. package/dist/pipeline/queryWorker.js.map +1 -1
  81. package/dist/pipeline/requests.js +3 -32
  82. package/dist/pipeline/requests.js.map +1 -1
  83. package/dist/pipeline/service.js +46 -2
  84. package/dist/pipeline/service.js.map +1 -1
  85. package/dist/services/appSyncService.js +59 -9
  86. package/dist/services/appSyncService.js.map +1 -1
  87. package/dist/services/apps.js +10 -0
  88. package/dist/services/apps.js.map +1 -1
  89. package/dist/services/farseerService.js +28 -6
  90. package/dist/services/farseerService.js.map +1 -1
  91. package/dist/skills/bundled.js +106 -0
  92. package/dist/skills/bundled.js.map +6 -0
  93. package/dist/skills/install.js +257 -0
  94. package/dist/skills/install.js.map +6 -0
  95. package/dist/skills/pipeline.js +10 -18
  96. package/dist/skills/pipeline.js.map +1 -1
  97. package/dist/utils/agentSandbox.js +1 -1
  98. package/dist/utils/entityResolver.js +72 -25
  99. package/dist/utils/entityResolver.js.map +1 -1
  100. package/dist/utils/errorFormatter.js +13 -0
  101. package/dist/utils/errorFormatter.js.map +1 -1
  102. package/dist/utils/formulaFilters.js +11 -2
  103. package/dist/utils/formulaFilters.js.map +1 -1
  104. package/dist/utils/operationCli.js +102 -0
  105. package/dist/utils/operationCli.js.map +6 -0
  106. package/docs/cli-guide.md +181 -1
  107. package/docs/pipeline-reference.md +13 -7
  108. package/docs/troubleshooting.md +18 -0
  109. package/package.json +1 -1
  110. package/skills/farseer-app-dev/SKILL.md +131 -0
  111. package/skills/farseer-app-dev/assignments.md +185 -0
  112. package/skills/farseer-app-dev/farseer-client-api-guide.md +907 -0
  113. package/skills/farseer-app-dev/farseer-client-release-notes.md +212 -0
  114. package/skills/farseer-app-dev/working-patterns.md +876 -0
  115. package/skills/farseer-authenticate-to-tenant/SKILL.md +60 -0
  116. package/skills/farseer-authenticate-to-tenant/app-authentication.md +91 -0
  117. package/skills/farseer-author-import-job/SKILL.md +114 -0
  118. package/skills/farseer-author-import-job/cell-writes.md +530 -0
  119. package/skills/farseer-author-import-job/deploying-a-farseer-app.md +383 -0
  120. package/skills/farseer-author-import-job/import-job-pattern.md +232 -0
  121. package/skills/farseer-build-model/SKILL.md +122 -0
  122. package/skills/farseer-build-model/formula-grain-alignment.md +612 -0
  123. package/skills/farseer-build-model/naming-conventions.md +435 -0
  124. package/skills/farseer-build-model/sparse-formulas-pattern.md +330 -0
  125. package/skills/farseer-build-pipeline/SKILL.md +190 -0
  126. package/skills/farseer-build-pipeline/erp-sales/README.md +108 -0
  127. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/bronze/erp_sales_invoice_lines.yaml +23 -0
  128. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/bronze/erp_sales_invoice_lines_raw.yaml +23 -0
  129. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/bronze/erp_sales_item_product_map.yaml +17 -0
  130. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/bronze/erp_sales_item_product_map_raw.yaml +11 -0
  131. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/gold/erp_sales_cells.yaml +40 -0
  132. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/silver/erp_sales_lines.yaml +35 -0
  133. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/silver/erp_sales_recon.yaml +43 -0
  134. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/silver/erp_sales_unmapped_items.yaml +28 -0
  135. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/main.py +49 -0
  136. package/skills/farseer-build-pipeline/erp-sales/erp-sales-load/Models/in/erp_sales_cells.yaml +17 -0
  137. package/skills/farseer-build-pipeline/erp-sales/erp-sales-load/Models/in/erp_sales_cells_raw.yaml +14 -0
  138. package/skills/farseer-build-pipeline/erp-sales/erp-sales-load/Models/load/erp_sales_to_model.yaml +47 -0
  139. package/skills/farseer-build-pipeline/erp-sales/erp-sales-load/main.py +44 -0
  140. package/skills/farseer-build-pipeline/erp-sales/item_to_product.csv +5 -0
  141. package/skills/farseer-build-pipeline/pipeline-app-failure-report-pattern.md +103 -0
  142. package/skills/farseer-build-pipeline/pipeline-source-encoding.md +68 -0
  143. package/skills/farseer-dashboards/SKILL.md +1 -1
  144. package/skills/farseer-help-center/SKILL.md +66 -0
  145. package/skills/farseer-modify-model/SKILL.md +158 -0
  146. package/skills/farseer-modify-model/model-validation-pattern.md +251 -0
  147. package/skills/farseer-optimize-model/SKILL.md +314 -0
  148. package/skills/farseer-optimize-model/stats-dump.ts +139 -0
  149. package/skills/farseer-pnl/SKILL.md +220 -0
  150. package/skills/farseer-review-model/SKILL.md +172 -0
  151. package/skills/farseer-run-apps/SKILL.md +102 -0
  152. package/skills/pipeline-authoring/SKILL.md +4 -4
  153. package/skills/pipeline-authoring/practices.md +15 -3
  154. package/dist/services/agentApprovalFetch.js +0 -90
  155. package/dist/services/agentApprovalFetch.js.map +0 -6
@@ -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.
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Stats collector for the farseer-optimize-model skill, steps (a) and (b).
3
+ *
4
+ * A `farseer run-script` that reads `c.evaluator.stats()` (per-variable
5
+ * calculation duration + cell counts from the engine's LAST full
6
+ * calculation), writes it to a JSON file, and prints two rankings: by
7
+ * duration, and by µs/cell against the model's own median.
8
+ *
9
+ * Run-scripts don't receive CLI arguments (`farseer run-script <tenant>
10
+ * <file>` passes nothing through), so configuration is via env vars.
11
+ * CJS-style: no top-level await, `main().catch(...)` at the bottom.
12
+ *
13
+ * Env:
14
+ * FULL=1 force a fresh recalc before reading stats, via
15
+ * `evaluator.invalidateCache()`. **Blocks until the whole model
16
+ * recalculates — minutes on a real model.** Without FULL=1 you
17
+ * get the last calc's numbers (fast, possibly stale). Never set
18
+ * FULL=1 against a production tenant during business hours — it
19
+ * locks the model for every concurrent user for the duration.
20
+ * OUT output path for the JSON (default: ./stats-dump-<UTC time>.json, so
21
+ * no run overwrites an earlier one; relative to `farseer-apps/<tenant>/`,
22
+ * where run-script runs the script).
23
+ * TOP rows in each ranking (default 15).
24
+ * MIN_CELLS
25
+ * fewest cells for a formula variable to count toward the µs/cell
26
+ * ranking and its median (default 1000; small variables give
27
+ * noisy µs/cell numbers). Inputs, which the engine reports with
28
+ * no calculated cells or a zero duration, never count.
29
+ *
30
+ * Usage:
31
+ * farseer pull <org> <tenant> # once: creates farseer-apps/<tenant>/
32
+ * cp stats-dump.ts farseer-apps/<tenant>/files/Scripts/ # run-script finds it there
33
+ * farseer install <tenant> # once, cold start
34
+ * farseer run-script <tenant> stats-dump.ts # last-calc numbers
35
+ * FULL=1 farseer run-script <tenant> stats-dump.ts # fresh full calc
36
+ * FULL=1 OUT=stats-2026-09-17.json farseer run-script <tenant> stats-dump.ts
37
+ */
38
+ import { writeFileSync } from "node:fs";
39
+ import { FarseerClient } from "farseer-client";
40
+
41
+ const FULL = process.env.FULL === "1";
42
+ const OUT = process.env.OUT ?? `./stats-dump-${new Date().toISOString().replace(/[:.]/g, "-")}.json`;
43
+ const TOP = envNumber("TOP", 15);
44
+ const MIN_CELLS = envNumber("MIN_CELLS", 1000);
45
+
46
+ function log(...a: unknown[]) {
47
+ console.log(...a);
48
+ }
49
+
50
+ function envNumber(name: string, fallback: number) {
51
+ const n = Number(process.env[name] ?? fallback);
52
+ return Number.isFinite(n) ? n : fallback;
53
+ }
54
+
55
+ const fmt = (n: number | null | undefined) => (n == null ? "—" : Math.round(n).toLocaleString("en-US"));
56
+
57
+ function median(xs: number[]) {
58
+ const s = [...xs].sort((a, b) => a - b);
59
+ return s.length ? s[Math.floor(s.length / 2)] : 0;
60
+ }
61
+
62
+ /**
63
+ * Step (b): the top variables by duration, and by µs/cell against the median of the formula variables with MIN_CELLS
64
+ * cells or more. An input has no calculated cells, and on the C++ engine a zero duration: counting inputs would pull
65
+ * the median towards 0 on a data-heavy model.
66
+ */
67
+ function printRankings(vars: any[]) {
68
+ const rows = vars.map((s: any) => {
69
+ const cells = (s.calculated ?? 0) + (s.nonCalculated ?? 0);
70
+ const duration: number = s.duration ?? 0;
71
+ const calculated: number = s.calculated ?? 0;
72
+ return { name: s.name as string, duration, calculated, cells, usPerCell: cells > 0 ? (duration * 1000) / cells : null };
73
+ });
74
+
75
+ const total = rows.reduce((a, r) => a + r.duration, 0);
76
+ const byDuration = [...rows].sort((a, b) => b.duration - a.duration).slice(0, TOP);
77
+ const eligible = rows.filter((r) => r.calculated > 0 && r.duration > 0 && r.cells >= MIN_CELLS);
78
+ const byUs = [...eligible].sort((a, b) => b.usPerCell! - a.usPerCell!).slice(0, TOP);
79
+ const medUs = median(eligible.map((r) => r.usPerCell!));
80
+ log(` Σduration ${fmt(total)} ms · median µs/cell (formula variables, ≥${MIN_CELLS} cells) ${medUs.toFixed(2)}`);
81
+
82
+ const table = (list: typeof rows, title: string) => {
83
+ log(`\n## ${title}\n\n| # | variable | duration ms | % of Σ | cells | µs/cell | ×median |\n|---|---|---:|---:|---:|---:|---:|`);
84
+ list.forEach((r, i) => {
85
+ const pct = total > 0 ? ((100 * r.duration) / total).toFixed(1) : "0.0";
86
+ const us = r.usPerCell == null ? "—" : r.usPerCell.toFixed(2);
87
+ const ratio = r.usPerCell == null || medUs === 0 ? "—" : (r.usPerCell / medUs).toFixed(1);
88
+ log(`| ${i + 1} | ${r.name} | ${fmt(r.duration)} | ${pct} | ${fmt(r.cells)} | ${us} | ${ratio} |`);
89
+ });
90
+ };
91
+ table(byDuration, `Top ${TOP} by duration`);
92
+ table(byUs, `Top ${TOP} by µs/cell (formula variables, cells ≥ ${MIN_CELLS}) — the inefficiency index`);
93
+ }
94
+
95
+ async function main() {
96
+ log(`stats-dump.ts · FULL=${FULL ? "1 (invalidateCache first — this blocks)" : "0 (last calc)"} · OUT=${OUT}`);
97
+ const c = new FarseerClient();
98
+
99
+ if (FULL) {
100
+ log(" invalidateCache() — waiting for the full recalc to finish…");
101
+ const started = Date.now();
102
+ try {
103
+ await c.evaluator.invalidateCache();
104
+ } catch (e: any) {
105
+ // The SDK throws the Response on an HTTP error; a timeout or a dropped connection has no status.
106
+ if (typeof e?.status !== "number" || e.status >= 500) {
107
+ console.error(" invalidateCache() timed out or failed in transit. The recalculation continues on the server:");
108
+ console.error(" wait, then rerun WITHOUT FULL=1 to read its stats. Never rerun with FULL=1 after a timeout.");
109
+ }
110
+ throw e;
111
+ }
112
+ log(` recalc done in ${((Date.now() - started) / 1000).toFixed(1)}s (wall clock, incl. request overhead)`);
113
+ }
114
+
115
+ const stats: any = await c.evaluator.stats();
116
+ const vars = stats.variables ?? [];
117
+ const totalCells = vars.reduce((a: number, v: any) => a + (v.calculated ?? 0) + (v.nonCalculated ?? 0), 0);
118
+ log(` calculationTime ${stats.calculationTime ?? "?"} ms · ${vars.length} variables · ${totalCells.toLocaleString()} cells`);
119
+
120
+ writeFileSync(OUT, JSON.stringify(stats, null, 2));
121
+ log(` wrote ${OUT}`);
122
+ if (vars.length === 0) {
123
+ console.error(" The stats hold no variables: nothing has calculated since the model loaded. Nothing to rank.");
124
+ process.exit(1);
125
+ }
126
+ printRankings(vars);
127
+ }
128
+
129
+ main().catch(async (e: any) => {
130
+ if (typeof e?.text === "function") {
131
+ try {
132
+ console.error("error body:", await e.text());
133
+ } catch {
134
+ /* ignore */
135
+ }
136
+ }
137
+ console.error(e);
138
+ process.exit(1);
139
+ });