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,876 @@
1
+ # Farseer Client — working patterns
2
+
3
+ The patterns that cover most app code. For anything beyond this, read the full guide in [`farseer-client-api-guide.md`](farseer-client-api-guide.md) or the TypeScript definitions in `node_modules/farseer-client/`.
4
+
5
+ ## Skeleton
6
+
7
+ ```typescript
8
+ import * as farseer from "farseer-client";
9
+
10
+ async function main(): Promise<void> {
11
+ const client = new farseer.FarseerClient();
12
+ // ... your logic
13
+ }
14
+
15
+ main().catch(async (error) => {
16
+ if (typeof error.text === "function") {
17
+ console.error(await error.text());
18
+ } else {
19
+ console.error(error);
20
+ }
21
+ process.exit(1);
22
+ });
23
+ ```
24
+
25
+ The `error.text()` branch is important — Farseer API errors carry their useful message in a lazy `text()` method, not in `.message`.
26
+
27
+ ## Export the model
28
+
29
+ ```typescript
30
+ // For large models (any model with meaningful cell data), exclude CELL.
31
+ // Otherwise the export fails with "Invalid string length".
32
+ const model = await client.model.exportModel({
33
+ types: ["DTAB", "DMEM", "VAR"] as any,
34
+ });
35
+ ```
36
+
37
+ Export type codes:
38
+
39
+ | Code | What it includes |
40
+ |---|---|
41
+ | `DTAB` | Dimension tables (names, columns, descriptions) |
42
+ | `DMEM` | Dimension members (the rows inside dimension tables) |
43
+ | `VAR` | Variables (structure, properties, formulas) |
44
+ | `CELL` | Actual cell values — exclude for large models |
45
+
46
+ What you get back — the shape you'll use most:
47
+
48
+ ```typescript
49
+ model.tables // DimensionTable[]; each has rows: DimensionMember[]
50
+ model.variables // Variable[]; each has tables: string[] (its grain)
51
+ ```
52
+
53
+ ### Bulk-read the cells of a variable slice (incl. computed) — `exportFormula` CSV
54
+
55
+ A model export carries no cell values (`CELL` is ignored), so cells come from
56
+ `export.exportFormula`. Scope the formula to the slice you need with `sum(...)`
57
+ filters, and pass `format: "csv"`:
58
+
59
+ ```typescript
60
+ const blob = await client.export.exportFormula({
61
+ formula: `sum("Revenue OUT", "Years">"Y2025", "Versions">"Actual")`, // the slice you need
62
+ format: "csv", // NOT json; do NOT pass tableGids
63
+ });
64
+ const csv = await blob.text(); // it's a Blob → .text(), never .toString()
65
+ // header: value,<Dim1>,<Dim2>,…,Years,Months,description,valueType
66
+ // 1 row per cell; valueType ∈ { Calculated, "Cell entry" }. (Real run: 59k rows / 4.4 MB, one call.)
67
+ ```
68
+
69
+ **A whole-variable read (a bare var name, no filter) on a live tenant needs the
70
+ user's go, or an offline or dev copy:** the engine evaluates every cell of the
71
+ variable in one request, which can stall the tenant for everyone. The Labs
72
+ agent gate refuses that form for agents.
73
+
74
+ One scoped `exportFormula` CSV replaces thousands of per-coordinate `evaluator.evaluate`
75
+ calls. The dim columns are dim **table names** and map straight onto an import
76
+ job's grain. Do **not** reach for `c.data.loadFarseerVariable` (wraps
77
+ `evaluatorExport`, `Not Implemented` on some backends).
78
+
79
+ ### Bounded read discipline — `farseer_export_variable_data` truncates, clobbers, and never caches
80
+
81
+ Three properties of the MCP tool `farseer_export_variable_data` (it wraps the same
82
+ `exportFormula` CSV call as above) that bite specifically at scale:
83
+
84
+ - **Silent truncation at `limit`.** When the true row count exceeds the requested `limit`, the
85
+ call returns exactly `limit` rows with no truncation flag — a result that looks like the
86
+ complete set. Always compare the returned row count against an independent expectation (a
87
+ control total, or a `sum()` over the same scope) before treating it as complete; don't infer
88
+ completeness from the row count alone.
89
+ - **A shared, deterministic temp path gets clobbered under parallel use.** Every export can
90
+ land at the *same* temp location, so a second export — your own later call, or a parallel
91
+ agent/script on the same machine — silently overwrites the first before you've consumed it.
92
+ Use a unique path per export (timestamp or run-id in the filename) rather than relying on
93
+ the default.
94
+ - **There is no read cache.** Every read re-hits the tenant — a repeated read of the same
95
+ variable/scope costs the same as the first. Cache locally within a script's lifetime if you
96
+ read the same slice more than once.
97
+
98
+ None of this is specific to one model — treat it as a standing discipline for
99
+ any bulk export: verify the count, use unique output paths, and don't re-read what you already
100
+ have in hand.
101
+
102
+ ## Find things in the model
103
+
104
+ ```typescript
105
+ const dim = model.tables?.find((t) => t.name === "Product Type");
106
+ // Member rows can be POSITIONAL arrays (name at index 0) — read defensively.
107
+ const members = dim?.rows?.map((r) => (Array.isArray(r) ? r[0] : r.name)) ?? [];
108
+
109
+ const variable = model.variables?.find((v) => v.name === "Revenue");
110
+ const grain = variable?.tables ?? [];
111
+ ```
112
+
113
+ Names are **case-sensitive** and must match exactly — including spaces, suffixes (` IN`, ` OUT`), and special characters.
114
+
115
+ **⚠ Dimension-member rows are POSITIONAL arrays, not objects.**
116
+ `model.exportModel({ types: ["DTAB", "DMEM"] })` returns each dimension-member
117
+ row as a positional array with the member name at **index 0** — e.g.
118
+ `["Y2023", null, 123, true, null]` — **not** an object with a `.name` field.
119
+ Reading `r.name` yields `undefined` for every member, so a membership check
120
+ built on it classifies **all** members as missing — observed live: a bogus
121
+ "year does not exist" filtered out 100% of a 7,485-cell migration write-plan.
122
+ Always read the name defensively:
123
+
124
+ ```typescript
125
+ const name = Array.isArray(r) ? r[0] : r.name;
126
+ ```
127
+
128
+ ## Validate before mutating
129
+
130
+ Every app that creates or writes to variables should first confirm the targets exist. If they don't, fail loudly rather than silently create wrong shape.
131
+
132
+ ```typescript
133
+ // Before importing: check the variable exists with the expected dimensions
134
+ const variable = model.variables?.find((v) => v.name === "Revenue");
135
+ if (!variable) {
136
+ throw new Error("Variable 'Revenue' not found — create it first.");
137
+ }
138
+ const expected = ["Date", "Product Type"];
139
+ const missing = expected.filter((d) => !(variable.tables ?? []).includes(d));
140
+ if (missing.length > 0) {
141
+ throw new Error(`Variable missing dimensions: ${missing.join(", ")}`);
142
+ }
143
+
144
+ // Before dimension-discriminated import: check members exist.
145
+ // DMEM rows are positional arrays (name at index 0) — never read r.name bare.
146
+ const dim = model.tables?.find((t) => t.name === "Product Type");
147
+ const existing = new Set(
148
+ dim?.rows?.map((r) => (Array.isArray(r) ? r[0] : r.name)),
149
+ );
150
+ const required = ["Product A", "Product B"];
151
+ const missingMembers = required.filter((m) => !existing.has(m));
152
+ if (missingMembers.length > 0) {
153
+ throw new Error(`Missing members: ${missingMembers.join(", ")}`);
154
+ }
155
+ ```
156
+
157
+ ## Create or update model objects
158
+
159
+ ```typescript
160
+ await client.model.load({
161
+ model: {
162
+ tables: [
163
+ {
164
+ name: "Product Type",
165
+ description: "Types of products",
166
+ rows: [{ name: "A" }, { name: "B" }, { name: "Unknown" }],
167
+ },
168
+ ],
169
+ variables: [],
170
+ dependencies: { tables: [], members: [], variables: [] },
171
+ },
172
+ options: {
173
+ clear: false, // false preserves existing
174
+ dryRun: false, // true for validation only
175
+ deleteEnabled: {
176
+ tables: false,
177
+ rows: false,
178
+ columns: false,
179
+ variables: false,
180
+ cells: false,
181
+ },
182
+ },
183
+ });
184
+ ```
185
+
186
+ Rules of thumb:
187
+
188
+ - Always `clear: false` unless you genuinely mean to wipe everything.
189
+ - Keep `deleteEnabled` fields `false` by default — opt in per call when you're sure.
190
+ - Always include `"Unknown"` in dimension member lists, so source data with null/missing values can land somewhere valid.
191
+
192
+ ## Adding members to an existing dimension (preserve first)
193
+
194
+ ```typescript
195
+ const model = await client.model.exportModel({ types: ["DTAB", "DMEM", "VAR"] as any });
196
+ const dim = model.tables?.find((t) => t.name === "Product Type");
197
+ const existing = dim?.rows ?? [];
198
+
199
+ const newNames = ["New A", "New B"];
200
+ const rows = [...existing, ...newNames.map((name) => ({ name }))];
201
+
202
+ await client.model.load({
203
+ model: {
204
+ tables: [{ name: "Product Type", rows }],
205
+ variables: [],
206
+ dependencies: { tables: [], members: [], variables: [] },
207
+ },
208
+ options: { clear: false, dryRun: false, deleteEnabled: { tables: false, rows: false, columns: false, variables: false, cells: false } },
209
+ });
210
+ ```
211
+
212
+ ## Organise variables into folders — create + move
213
+
214
+ Farseer separates two folder trees:
215
+
216
+ - **Variables tree** (root id=5, name `"Variables"`, allows `[VARIABLE, FOLDER]`)
217
+ - **Dimensions tree** (root id=4, name `"Dimensions"`, allows `[DIMENSION_TABLE, FOLDER]`)
218
+
219
+ Plus separate trees for Sheets (id=1), Dashboards (id=3), Files (id=13), Apps (id=15). System dimensions live under id=6 (`Dimensions/System dimensions`) and are platform-managed.
220
+
221
+ Variables and dim tables CANNOT share folders — they live in different trees by design. A "BS" folder for variables is a different folder entity from a "BS" folder for dimensions; create one in each tree if you want symmetric organisation.
222
+
223
+ ### Discover the root folder IDs
224
+
225
+ The root folder IDs are stable on a tenant but not documented. Probe them with:
226
+
227
+ ```typescript
228
+ for (let id = 1; id <= 20; id++) {
229
+ try {
230
+ const f = await client.entities.getSingle(id, "FOLD");
231
+ console.log(`id=${id} name="${f.meta?.name}" allows=${JSON.stringify(f.folder?.allowedTypes)}`);
232
+ } catch {}
233
+ }
234
+ ```
235
+
236
+ On a fresh tenant they appear as `Sheets=1, Dashboards=3, Dimensions=4, Variables=5, System dimensions=6, Files=13, Imports=14, Apps=15`.
237
+
238
+ ### Create a folder
239
+
240
+ ```typescript
241
+ const result = await client.folders.create({
242
+ parentId: 5, // Variables root
243
+ name: "BS",
244
+ allowedTypes: ["VARIABLE", "FOLDER"], // must match the parent's allowed set
245
+ });
246
+ const newFolderId = result.id ?? result.folderId;
247
+ ```
248
+
249
+ `allowedTypes` is required and must respect the parent's constraints. A folder under Variables must allow `VARIABLE` (and typically `FOLDER` for nesting). A folder under Dimensions must allow `DIMENSION_TABLE` (and `FOLDER`). Mixing — e.g. trying to allow `DIMENSION_TABLE` under the Variables tree — fails with `"Invalid allowed types"`.
250
+
251
+ **Folder names appear globally unique.** A folder called `"Import"` already existing under Variables will block another `"Import"` from being created elsewhere with `400 BadRequest "Name already taken"`. If a folder of the desired name already exists, search and reuse it instead of creating a duplicate:
252
+
253
+ ```typescript
254
+ const found = await client.entities.search({ name: "Import", types: ["FOLD"] });
255
+ const existing = found.find((f) => f.folder?.path?.[0] === 5); // Variables root
256
+ const folderId = existing?.id ?? (await client.folders.create({ parentId: 5, name: "Import", allowedTypes: ["VARIABLE", "FOLDER"] })).id;
257
+ ```
258
+
259
+ ### Move an existing variable / dim table into a folder
260
+
261
+ The "ITEM ID" passed to `moveItemsBatch` is **NOT** the entity ID — it's a separate folder-system ID. Get it from the entity's `folder.id` field via `entities.getSingle`:
262
+
263
+ ```typescript
264
+ // 1) Look up the entity by name
265
+ const found = await client.entities.search({ name: "BS_Closing_state_OUT", types: ["VAR"] });
266
+ const entity = found.find((e) => e.meta?.name === "BS_Closing_state_OUT");
267
+
268
+ // 2) Get the full entity to read its folder.id
269
+ const full = await client.entities.getSingle(entity.id, "VAR");
270
+ const folderItemId = full.folder?.id; // ≠ entity.id
271
+
272
+ // 3) Move via folders.moveItemsBatch
273
+ await client.folders.moveItemsBatch([{
274
+ id: folderItemId,
275
+ parentId: targetFolderId,
276
+ order: 0,
277
+ }]);
278
+ ```
279
+
280
+ ### Batch move many items at once
281
+
282
+ `moveItemsBatch` takes an array, so a project-wide reorganisation runs in one round-trip:
283
+
284
+ ```typescript
285
+ const moves = [
286
+ { id: 19, parentId: 35, order: 0 }, // FC_ONE_ALWAYS → Setup/Forecast
287
+ { id: 20, parentId: 35, order: 1 }, // FC_ONE_PASS_BY_INPUT → Setup/Forecast
288
+ { id: 22, parentId: 21, order: 0 }, // IMPORT_BS_Konto_level → Import
289
+ // …
290
+ ];
291
+ await client.folders.moveItemsBatch(moves);
292
+ ```
293
+
294
+ Verified on `<sandbox-B>-bs` (2026-05-01): batch-moved 12 variables and 3 dim tables across two trees in one reorg pass; cell data and formulas preserved end-to-end.
295
+
296
+ ### When to physically reorganise vs leave it
297
+
298
+ - **Reorganise** when: the folder hierarchy will be visible to the planner in the UI; people work in the model day-to-day; the audit trail matters.
299
+ - **Don't bother** when: the model is small (under ~10 variables), the planner doesn't browse the tree, or all consumption goes through dashboards/sheets that hide folder paths.
300
+
301
+ ## Rename a variable / dimension table in place
302
+
303
+ When refactoring a model — e.g. unifying naming style on an existing tenant — you usually want to **rename** entities rather than create new ones with the new name and orphan the old. A drop-and-recreate loses cell data, breaks any references that pointed at the old name from outside the model (sheets, dashboards, remote-job scripts), and clutters the tenant with stale objects.
304
+
305
+ **Wrong approaches that look right:**
306
+
307
+ - `client.folders.renameItem({ id, name })` — fails with `400 BadRequest "Requested item is not a folder"` for variables and dim tables. The endpoint is for renaming folders themselves only, despite "item" in the name.
308
+ - `client.model.load(...)` with the new name and `clear: false` — creates a new variable / dim alongside the old one. Old entity remains, old cell data stays attached to it; new entity is empty. Net effect: orphans + duplicated work.
309
+
310
+ **Right approach — `entities.mutate` with `EntityUpdate.meta.name`:**
311
+
312
+ ```typescript
313
+ // 1) Find the numeric ID of the entity to rename.
314
+ const results = await client.entities.search({ name: oldName, types: ["VAR"] });
315
+ const entity = results.find((r) => r.meta?.name === oldName && r.type === "VAR");
316
+ if (!entity) throw new Error(`Entity not found: ${oldName}`);
317
+
318
+ // 2) Mutate it — keep id and type, set new name in meta.
319
+ await client.entities.mutate({
320
+ updated: [{
321
+ id: entity.id,
322
+ type: "VAR",
323
+ meta: {
324
+ name: newName,
325
+ description: entity.meta?.description ?? null, // preserve description
326
+ },
327
+ }],
328
+ });
329
+ ```
330
+
331
+ `EntityType` accepts `"VAR"` (variable), `"DTAB"` (dimension table), `"DMEM"` (dimension member), `"FOLD"` (folder), `"SHEET"`, `"FUNC"`, `"SFUNC"`, `"ROW"`. Use the matching type for what you're renaming.
332
+
333
+ The platform preserves the entity ID, all cell data, and updates internal references in formulas and dependencies. No orphan, no data loss.
334
+
335
+ ### Why include `description` in the mutate
336
+
337
+ The `MetaComponent` shape has `name` and `description` as required fields when emitted. If you set `meta: { name: newName }` and omit the description, the platform may overwrite it with null. Always read the existing description first and pass it through (or pass the new description if you intend to change it). Same for any other meta-level fields (notes, etc.) the entity carries.
338
+
339
+ ### Batch renames
340
+
341
+ `entities.mutate` accepts an array of `updated[]` entries — you can rename multiple entities in one round-trip:
342
+
343
+ ```typescript
344
+ await client.entities.mutate({
345
+ updated: [
346
+ { id: 138, type: "VAR", meta: { name: "FC_ONE_ALWAYS", description: null } },
347
+ { id: 139, type: "VAR", meta: { name: "FC_ONE_PASS_BY_INPUT", description: null } },
348
+ // ...
349
+ ],
350
+ });
351
+ ```
352
+
353
+ Verified on `<sandbox-B>-bs` (2026-05-01): renamed 12 variables in one batch, all IDs preserved, all cell data intact.
354
+
355
+ ### When NOT to use rename
356
+
357
+ - **The old name is preferable and there's tenant drift** — e.g. someone renamed a variable in the UI but your code or files still use the original name. Rename the tenant entity back (or accept the UI rename and update your code).
358
+ - **Cross-tenant migration** — `entities.mutate` is per-tenant. Migrating from one tenant to another goes through `model.load` against the target.
359
+ - **Bulk style migration where you also want a clean break** — sometimes the right move is to delete the old entity entirely (with `deleted: [{ id, type }]` in `entities.mutate`) rather than rename, especially if the new name represents a semantic shift, not just a stylistic one.
360
+
361
+ ## Insert vs. Import — pick the right write path
362
+
363
+ > **Read [`cell-writes.md`](../farseer-author-import-job/cell-writes.md) first.** It is the canonical
364
+ > reference for programmatic cell writes — including the third path
365
+ > (`POST /sheets/setData`) for multi-dim leaf writes, the SDK methods
366
+ > that silently fail (most of `cells.*`), the top-down splice mechanic
367
+ > with the OR-vs-AND filter footgun on `model.updateCells`, and the
368
+ > cross-version-copy pattern. The summary below is preserved for quick
369
+ > reference but `cell-writes.md` supersedes it where they diverge.
370
+
371
+ There are two distinct ways to write cell values to Farseer. They have different
372
+ shapes, different costs, and different right-fit use cases. **Pick deliberately;
373
+ they are not interchangeable.**
374
+
375
+ ### `model.updateCells` — INSERT (atomic, lightweight)
376
+
377
+ Direct write of one or more specific cells. No job, no commit/undo, no audit
378
+ trail per write. Each entry targets exactly one cell intersection via a
379
+ `sum(...)` formula and supplies the value:
380
+
381
+ ```typescript
382
+ await client.model.updateCells({
383
+ filters: [],
384
+ cellUpdates: [
385
+ {
386
+ formula: `sum("Revenue", "Product">"P1", "Versions">"Plan", "Years">"Y2025", "Months">"M3")`,
387
+ value: 1234,
388
+ },
389
+ {
390
+ formula: `sum("Revenue", "Product">"P2", "Versions">"Plan", "Years">"Y2025", "Months">"M3")`,
391
+ value: 5678,
392
+ },
393
+ ],
394
+ });
395
+ ```
396
+
397
+ The formula is a **selector** — a `sum(variable, dim>member, dim>member, …)`
398
+ expression that pins exactly one cell. Same syntax used for reading; here it
399
+ denotes the target. The `value` is what you write there. `value: null` clears
400
+ the cell. Dimension names with spaces / special chars stay quoted
401
+ (`"Half years">"H1"`).
402
+
403
+ **When to use insert:**
404
+
405
+ - **Automated tests** that seed a few specific cells and verify computed
406
+ outputs. No noisy import job appears in the tenant audit trail; the tenant
407
+ stays clean across many test cycles.
408
+ - **One-off corrections** — a planner says "this one cell on this product is
409
+ wrong, set it to X" and the value is in your hand.
410
+ - **Programmatic adjustments** by an app: an FX rate update touches exactly
411
+ these N cells; nothing else; no need for an import-job ceremony.
412
+ - **Scaffold testing** during pattern development — verify rollup, override,
413
+ cumsum, FC-gate semantics by injecting deliberate inputs into a few cells
414
+ and reading the OUT.
415
+ - **Cleanup** — `value: null` in `cellUpdates` deletes a cell.
416
+
417
+ **Constraints:**
418
+
419
+ - The cell must be writable. **`400 BadRequest "Unable to write locked
420
+ cell"` comes from `@readonly true` OR from a tenant-wide global lock rule**
421
+ (`client.settings.getGlobalLocks()`) — the second shows `Readonly: false`
422
+ on the variable. Use the pattern's intended IN channel (override), flip
423
+ `@readonly` around the write, or write only the unlocked slice; never
424
+ lift a global lock without the user's consent. Details:
425
+ [`cell-writes.md`](../farseer-author-import-job/cell-writes.md) "INSERT" constraints.
426
+ - The formula must select **exactly one cell**. A `sum()` over a range
427
+ resolves to one rolled-up cell (not what you want for an insert), and the
428
+ platform may accept it but the result lands at the rolled-up coordinate
429
+ which probably isn't where you intended.
430
+ - No transactional guarantee across many `cellUpdates` entries — they're
431
+ applied in order; partial-failure semantics not documented.
432
+
433
+ ### `client.createImportJob({...}).addRow(...).commit()` — IMPORT (batched, audited)
434
+
435
+ A first-class platform job: title, description, labels, audit trail, undo.
436
+ Higher overhead per write, but built for bulk and for traceability.
437
+ **It also writes into globally locked cells** (measured 2026-10-08 — no
438
+ refusal), so an import script must check `settings.getGlobalLocks()` itself
439
+ before writing into a region such as a closed `Actual` period.
440
+
441
+ See ["Import data — basic"](#import-data--basic) below for the canonical
442
+ shape. **When to use import:**
443
+
444
+ - **Initial bulk loads** of historical data (months / years of monthly
445
+ actuals from the GL).
446
+ - **Recurring scheduled loads** that the user wants visible in the audit
447
+ trail, with the option to undo.
448
+ - **Large datasets** (10k+ rows) — the import-job pipeline is the path the
449
+ platform optimizes for high-throughput; `model.updateCells` was not
450
+ designed for that scale.
451
+ - **Multi-variable, multi-dim wide-format data** — import jobs with
452
+ `DIMENSION_TABLE` + per-`VARIABLE` columns map naturally onto
453
+ spreadsheet/CSV shapes.
454
+ - **Anything you want labelled** so QA / the customer can find and review it
455
+ later (e.g. `labels: ["actuals-load", "2025-Q4"]`).
456
+
457
+ ### Quick decision table
458
+
459
+ | Use case | Path |
460
+ |---|---|
461
+ | Test seeding a handful of cells | **Insert** |
462
+ | Verify a calc OUT in CI / scaffold dev | **Insert** |
463
+ | Single planner correction triggered by a UI action | **Insert** |
464
+ | Monthly GL → BS load (1000s of rows) | **Import** |
465
+ | Initial historical data load at project go-live | **Import** |
466
+ | Recurring nightly ETL feed | **Import** |
467
+ | Cleanup of a few stray cells | **Insert** (`value: null`) |
468
+ | Mass clear of all cells under a filter | Either; `model.updateCells` with one entry per cell, or import a CSV of nulls |
469
+
470
+ ### Don't mix metaphors
471
+
472
+ A common mistake: trying to use `model.updateCells` for a 5000-row monthly
473
+ load (no progress signal, easy to lose midway, no audit) — or trying to use
474
+ `createImportJob` for a 3-cell test seed (every test run leaves a job in the
475
+ tenant). Pick the path that fits the lifecycle of the data, not the shape of
476
+ the API call you remembered first.
477
+
478
+ ## Import data — basic
479
+
480
+ ```typescript
481
+ const importJob = await client.createImportJob({
482
+ title: `My import — ${new Date().toISOString()}`,
483
+ description: "Importing from source X",
484
+ columns: [
485
+ { type: "DIMENSION_TABLE", dimensionTableName: "Date" },
486
+ { type: "DIMENSION_TABLE", dimensionTableName: "Product Type" },
487
+ { type: "VARIABLE", variableName: "Revenue" },
488
+ { type: "VARIABLE", variableName: "Cost" },
489
+ ],
490
+ labels: ["automated", "source-x"],
491
+ });
492
+
493
+ for (const row of sourceData) {
494
+ await importJob.addRow([row.date, row.product, row.revenue, row.cost]);
495
+ }
496
+
497
+ await importJob.commit();
498
+ ```
499
+
500
+ **The order of values in `addRow([...])` must match the order of the `columns` array.** Column order mismatch is the most common cause of silently-wrong imports.
501
+
502
+ > **Column shape — `{ type: "DIMENSION_TABLE", dimensionTableName }`, not
503
+ > the older `DIMENSION_TABLE_COLUMN`/`dimensionTable` shape.** An earlier
504
+ > revision of this recipe used
505
+ > `{ type: "DIMENSION_TABLE_COLUMN", dimensionTable, columnName }` — on the
506
+ > current SDK that shape passes through `buildImportJobMetadata` building
507
+ > `columnMetas: [null, …]`, and `createImportJob` fails with a bare
508
+ > `{"code":"BadRequest"}` naming no field. **A bare 400 on `createImportJob` ⇒ inspect the
509
+ > built metadata's `columnMetas` for `null` entries first** — it is a column
510
+ > shape problem, not a data problem.
511
+
512
+ > **Silent zero-drop.** The simple `columns` overload used above hardcodes `importZeros:
513
+ > false` and `overwriteCells: false` under the hood — rows whose value is genuinely `0` are
514
+ > silently dropped from the commit, and re-importing into a cell that already has data won't
515
+ > overwrite it. If either behavior matters for the import you're writing (zero is a legitimate
516
+ > value; you need to overwrite existing cells), don't reach for this overload — see
517
+ > [`cell-writes.md`](../farseer-author-import-job/cell-writes.md) for the `metadata`-based escape hatch that flips
518
+ > both flags.
519
+
520
+ ## Import data — dimension discrimination
521
+
522
+ When one variable is populated from multiple source columns that each represent a different dimension slice:
523
+
524
+ ```typescript
525
+ const importJob = await client.createImportJob({
526
+ title: "Revenue by product — wide format",
527
+ columns: [
528
+ { type: "DIMENSION_TABLE", dimensionTableName: "Date" },
529
+ { type: "VARIABLE", variableName: "Revenue", dimensionsNames: [{ tableName: "Product Type", memberName: "Product A" }] },
530
+ { type: "VARIABLE", variableName: "Revenue", dimensionsNames: [{ tableName: "Product Type", memberName: "Product B" }] },
531
+ { type: "VARIABLE", variableName: "Revenue", dimensionsNames: [{ tableName: "Product Type", memberName: "Product C" }] },
532
+ ],
533
+ });
534
+
535
+ for (const row of sourceData) {
536
+ await importJob.addRow([row.date, row.revenue_a, row.revenue_b, row.revenue_c]);
537
+ }
538
+
539
+ await importJob.commit();
540
+ ```
541
+
542
+ The `dimensionsNames: [{ tableName, memberName }]` on a `VARIABLE` column pins that column's values to a specific dimension member (a `tables` key is ignored). Without it, the variable's full grain is expected elsewhere in the columns.
543
+
544
+ ## Log progress on large imports
545
+
546
+ ```typescript
547
+ let count = 0;
548
+ for (const row of sourceData) {
549
+ await importJob.addRow([...]);
550
+ count++;
551
+ if (count % 10_000 === 0) {
552
+ console.log(` ${count}/${sourceData.length} rows (${Math.round(count / sourceData.length * 100)}%)`);
553
+ }
554
+ }
555
+ console.log(`Adding ${count} rows done. Committing...`);
556
+ await importJob.commit();
557
+ console.log("✓ Import committed");
558
+ ```
559
+
560
+ ## Test incrementally
561
+
562
+ Never unleash a script on the full dataset the first time it runs:
563
+
564
+ ```typescript
565
+ const testRows = sourceData.slice(0, 10); // First: smoke test
566
+ // const testRows = sourceData.slice(0, 100); // Then: sanity
567
+ // const testRows = sourceData.slice(0, 1000); // Then: scale
568
+ // const testRows = sourceData; // Finally
569
+ ```
570
+
571
+ ## Dry-run flag
572
+
573
+ ```typescript
574
+ const DRY_RUN = process.env.DRY_RUN !== "false"; // writes only on an explicit "false"; unset, "TRUE", "yes" preview
575
+
576
+ if (DRY_RUN) {
577
+ console.log("DRY RUN — would create import job with:");
578
+ console.log(" columns:", columns);
579
+ console.log(" sample row:", sampleRow);
580
+ console.log(" total rows:", sourceData.length);
581
+ return;
582
+ }
583
+
584
+ const importJob = await client.createImportJob({ title, columns });
585
+ // ...
586
+ ```
587
+
588
+ > This `process.env.DRY_RUN` pattern is for **ad hoc local scripts only**,
589
+ > where you export `DRY_RUN` in your own shell before running them. It does
590
+ > **not** read an app argument: `farseer run-script` passes no arguments at
591
+ > all, local `farseer run` passes them only as positional argv, and a
592
+ > **deployed app** receives them as one JSON blob in
593
+ > `process.env.FARSEER_ARGS` (measured 2026-10-15). An app reading
594
+ > `process.env.DRY_RUN` gets `undefined` and silently takes its default. See
595
+ > [`deploying-a-farseer-app.md` §1a](../farseer-author-import-job/deploying-a-farseer-app.md#1a-the-arg-reading-contract--farseer_args-not-per-arg-env-vars)
596
+ > before wiring a dry-run flag (or any argument) into something that will run
597
+ > as an app.
598
+
599
+ ## Remote jobs (scripts running on Farseer)
600
+
601
+ Some scripts run on Farseer's servers, not your machine. Upload the script via `createOrUpdateFarseerFile`; the script itself is just a normal `farseer-client` script — it creates a `FarseerClient()` and calls the same API.
602
+
603
+ **Local edits to a remote-job script file are not enough.** You must also run the upload script to redeploy. Typical layout:
604
+
605
+ ```
606
+ src/
607
+ remoteJobReconciliation.ts # the job (runs on Farseer)
608
+ uploadReconciliation.ts # the deploy script (runs locally)
609
+ ```
610
+
611
+ ```typescript
612
+ // uploadReconciliation.ts
613
+ import * as farseer from "farseer-client";
614
+ import * as fs from "fs";
615
+ import * as path from "path";
616
+
617
+ async function upload(): Promise<void> {
618
+ const client = new farseer.FarseerClient();
619
+ const source = fs.readFileSync(path.join(__dirname, "remoteJobReconciliation.ts"), "utf-8");
620
+ await client.createOrUpdateFarseerFile(
621
+ { name: "reconciliation-job.ts", folderId: YOUR_FOLDER_ID },
622
+ source,
623
+ );
624
+ console.log("✓ Deployed");
625
+ }
626
+
627
+ upload().catch(console.error);
628
+ ```
629
+
630
+ ## Uploading files from a plain Node script — the SDK helper doesn't work there
631
+
632
+ Inside a plain Node execution context (as opposed to a script running
633
+ inside a Farseer app/remote-job environment), the SDK's file-upload helper
634
+ fails because its `Blob`/`WebFile` type check doesn't hold under Node's
635
+ multipart form-data implementation. The workaround that works locally is
636
+ raw HTTP multipart via `form-data` + `node-fetch`, authenticated with
637
+ `X-TENANT-ID` / `X-API-KEY` headers (not `Authorization: Bearer`):
638
+
639
+ ```ts
640
+ import FormData from "form-data";
641
+ import fetch from "node-fetch";
642
+
643
+ const form = new FormData();
644
+ form.append("file", Buffer.from(scriptContent, "utf-8"), { filename: "script.ts", contentType: "text/plain" });
645
+ form.append("category", "GENERAL");
646
+ form.append("folderId", String(folderId));
647
+ await fetch(`${apiUrl}/farseerFiles`, {
648
+ method: "POST",
649
+ headers: { ...form.getHeaders(), "X-TENANT-ID": tenantId, "X-API-KEY": apiKey },
650
+ body: form,
651
+ });
652
+ ```
653
+
654
+ Both `form-data` and `node-fetch@3` are ESM-only — use a top-level `import`,
655
+ not `require()` (throws `ReferenceError` under ts-node ESM). This
656
+ raw-multipart path is specifically for **local** Node execution — inside a
657
+ Farseer remote-job runner (the "Remote jobs" section above), the SDK helper
658
+ works fine.
659
+
660
+ **After upload, the id needed to create an app from the file is the
661
+ `reference` field (a UUID), not `id`** (the numeric folder-item id) — the
662
+ same `id`-vs-`reference` split documented elsewhere for sheets/folder items
663
+ applies to uploaded files too.
664
+
665
+ ## Registering an uploaded script as a remote-job app — `remoteJobs.create`
666
+
667
+ ```ts
668
+ await client.remoteJobs.create({
669
+ folderId: appsRootId,
670
+ name: "My Remote Job",
671
+ description: "…",
672
+ expectedArguments: [{ name: "Version", dataType: "string", options: ["Actual", "Plan"], defaultValue: "Actual" }],
673
+ mainScriptFileId: scriptFileId, // the .reference UUID from the upload, not .id
674
+ scriptFileIds: [scriptFileId],
675
+ });
676
+ ```
677
+
678
+ Check for an existing app by name first (`remoteJobs.list()`) and update
679
+ instead of create if found, to keep the operation idempotent.
680
+
681
+ **Typed arguments need SDK ≥ 1.8.19.** Send `dataType` (`"string"` /
682
+ `"boolean"`), plus `options` for a dropdown and `fixed: true` for a locked
683
+ value — not the legacy `type`. On 1.14.0 all three reach the server and read back unchanged (measured on a
684
+ sandbox tenant). On SDK ≤ 1.8.12 (what older CLIs scaffolded; `farseer pull` now writes 1.18.1) the
685
+ serializer sends only the legacy `type`: `"variable"` → a free-text string
686
+ argument, `"constant"` → a **locked** (`fixed: true`) argument; `dataType`,
687
+ `options` and `fixed` are dropped. There, prefer the manifest +
688
+ `farseer push` for arguments, or fix them with a pull → edit → push right
689
+ after creating —
690
+ [`deploying-a-farseer-app.md`](../farseer-author-import-job/deploying-a-farseer-app.md)
691
+ "App arguments end to end". Give the entrypoint a name unique on the
692
+ tenant (same doc, Gotchas).
693
+
694
+ ## Data transformation helpers
695
+
696
+ The SDK expects strings for text fields and numbers for numeric fields. Nulls typically need to be mapped to a known sentinel.
697
+
698
+ ```typescript
699
+ const toString = (value: unknown, fallback = "Unknown"): string =>
700
+ value === null || value === undefined || value === "" ? fallback : String(value);
701
+
702
+ const toNumber = (value: unknown): number | null => {
703
+ if (value === null || value === undefined) return null;
704
+ const n = Number(value);
705
+ return Number.isNaN(n) ? null : n;
706
+ };
707
+
708
+ const toDate = (value: Date | string | null): string => {
709
+ if (!value) return "Unknown";
710
+ if (typeof value === "string") return value;
711
+ return value.toISOString().split("T")[0]; // YYYY-MM-DD
712
+ };
713
+
714
+ const toBoolString = (value: boolean | null): string =>
715
+ value === null || value === undefined ? "Unknown" : value ? "true" : "false";
716
+ ```
717
+
718
+ ## Deleting sheets — sheets are folder items, not generic entities
719
+
720
+ To wipe sheets for a clean re-deploy (a re-create fails with
721
+ `Name already taken` if same-named sheets exist), you must delete them
722
+ first. The traps:
723
+
724
+ - `entities.mutate({ deleted: [{ id, type: EntityType.Sheet }] })`
725
+ deletes a sheet only when `id` is the **sheet id** (the folder item's
726
+ `reference`); it then also removes the folder item and the sheet's lines.
727
+ With any other id it returns a success-shaped response (echoes the
728
+ requested count) and deletes nothing, so read back. Separately,
729
+ `entities.getAll([EntityType.Sheet])` returns `0` even when sheets
730
+ exist.
731
+ - `SheetsApi` has **no** delete / remove method (create / update /
732
+ duplicate / setData / getData / search / get / getByIds — no delete).
733
+
734
+ Sheets are **folder items** in the Sheets tree. The Folders API deletes
735
+ them by folder-item id:
736
+
737
+ ```ts
738
+ // 1. Walk the folder tree. listItemsBatch returns ONE result-object per
739
+ // request, each wrapping .items — read result[0].items, NOT the
740
+ // result array itself (the #1 mistake here).
741
+ const FT = farseer.FolderItemType; // Sheet='SHEET', Folder='FOLDER'
742
+ const sheets: any[] = [];
743
+ async function walk(folderId: number | null) {
744
+ const res = await c.folders.listItemsBatch([{ id: folderId }]); // {id:null} = top level
745
+ for (const it of (res[0]?.items ?? [])) {
746
+ if (it.type === FT.Sheet) sheets.push(it); // it.id = FOLDER-ITEM id
747
+ else if (it.type === FT.Folder) await walk(it.id);
748
+ }
749
+ }
750
+ await walk(null);
751
+
752
+ // 2. Delete by FOLDER-ITEM id (NOT entity id, NOT the sheet's `reference`).
753
+ await c.folders.deleteItemsBatch(sheets.map((s) => ({ id: s.id })));
754
+ ```
755
+
756
+ Notes:
757
+
758
+ - `listItemsBatch([{ id: null }])` → top level; recurse into `FOLDER`
759
+ items. The same call with the result iterated directly (forgetting
760
+ `result[0].items`) silently yields nothing.
761
+ - `folders.deleteItemsBatch` takes the **folder-item id** (mirrors the
762
+ `moveItemsBatch` caveat: folder-system id, not entity id). The walk's
763
+ `it.id` IS that id.
764
+ - `folders.resolveItems(ReverseReference[])` is the alternative when you
765
+ only have a sheet's `reference` string (`{reference, type}` →
766
+ `FolderItemRepresentation` with `.id`).
767
+
768
+ **⚠ Danger** — deleting sheets is destructive. Dev / prototype sandbox
769
+ only; gate on prod with explicit confirmation.
770
+
771
+ ## Duplicating a sheet folder — `folders.duplicate` + the SheetRow remap gap
772
+
773
+ When you need a copy of a per-entity sheet (or a whole folder of sheets) as a starting point for
774
+ a new entity — e.g. cloning a reference entity's Trial Balance / P&L / BS sheets for a newly
775
+ onboarded company — `folders.duplicate` is the real Farseer function for it, and is more
776
+ reliable than manually re-creating each sheet (which inherits every `sheets.create` silent-drop
777
+ caveat documented elsewhere in this doc):
778
+
779
+ ```typescript
780
+ const dup = await client.folders.duplicate({
781
+ name: `<New entity> sheets`,
782
+ parentId,
783
+ sourceId: referenceFolderId,
784
+ });
785
+ const items = await client.folders.listItemsBatch([{ id: dup.id }]);
786
+ // NB: the sheet id of each item is `it.reference ?? it.id` — folder-item id ≠ backing sheet id
787
+ // (same id-vs-reference split noted elsewhere in this doc for sheets/folder items/files).
788
+ ```
789
+
790
+ **The gap `folders.duplicate` leaves: `SheetRow` entities live outside the sheet body.** A
791
+ sheet's persistent rows (`SheetRow`: `tableTagId`, `accountTagId`, `dimensionTagIds`, `name`)
792
+ are a **separate resource** (`GET /sheetRows/sheet/{sheetId}`) — `sheets.get` / `sheets.update`
793
+ don't see or touch them. `folders.duplicate` copies the rows along with the sheet, but every
794
+ copied row still points at whatever entity/variable it was bound to **on the source**. So
795
+ remapping a duplicated sheet to the new entity is a **two-level operation**:
796
+
797
+ 1. **The sheet body** (`rows.filters`, `columns.custom`) — updated via `sheets.update` (a deep
798
+ ID-remap of the sheet JSON).
799
+ 2. **The rows themselves** (`tableTagId` / `accountTagId` / `dimensionTagIds`) — updated via the
800
+ separate `sheetRows` API (`getBySheetId`, `update`, `create`, `_delete`, `move`), not through
801
+ the sheet-body call at all.
802
+
803
+ Doing step 1 alone and assuming the duplicated sheet is fully remapped is the common trap — the
804
+ sheet body looks right, but every row still shows data bound to the source entity.
805
+
806
+ ## `importZeros` can hang on commit, and transient commit errors are safe to retry
807
+
808
+ Two distinct `createImportJob` behaviors worth separating:
809
+
810
+ 1. `importZeros: true` can cause a server-side hang or an HTTP 500 on commit
811
+ for zero-valued cells on some instances — don't assume a hung commit
812
+ means the payload is malformed; try without `importZeros` first.
813
+ 2. Committing a large batch of cells occasionally throws transient network
814
+ errors (`ECONNRESET`, `ETIMEDOUT`, "socket hang up", `EPIPE`). These are
815
+ safe to retry — 3 attempts with exponential backoff (2s → 4s → 8s) — **as
816
+ long as the job carries `labels` and uses `undoPrevious()` so the retry
817
+ is idempotent** (it depends on the `undoPrevious()` + rewrite-everything rule — the
818
+ "why this retry is safe" reasoning is the idempotency-via-labels
819
+ guarantee, not the retry loop itself).
820
+
821
+ ```typescript
822
+ async function commitWithRetry(job: ImportJobHandle, attempts = 3): Promise<void> {
823
+ for (let i = 0; i < attempts; i++) {
824
+ try {
825
+ await job.commit();
826
+ return;
827
+ } catch (err) {
828
+ const transient = /ECONNRESET|ETIMEDOUT|socket hang up|EPIPE/.test(String(err));
829
+ if (!transient || i === attempts - 1) throw err;
830
+ await new Promise((r) => setTimeout(r, 2000 * 2 ** i)); // 2s → 4s → 8s
831
+ }
832
+ }
833
+ }
834
+ ```
835
+
836
+ ## Import jobs — id resolution + reversible re-import
837
+
838
+ Two facts the `createImportJob` shape hides:
839
+
840
+ - **`c.createImportJob(...)` returns a wrapper of CLOSURES, not the job** — it
841
+ exposes `addRow / addRows / flushRows / detectDimensions / importDimensions /
842
+ commit / undoPrevious / delete`, but **no `.id`**. To act on the job you just
843
+ created, resolve the id from `c.importJobs.list(labels)`, re-filtered
844
+ client-side by label **and** status (the server returns every job whose labels include these, newest first).
845
+ - **`undoPrevious()` / `deleteById(id, {undoData:true})` is DESTRUCTIVE** and
846
+ cannot be rolled back (it deletes the prior cells). The **reversible** primitive
847
+ is `importJobs.revert(id)` ↔ `importJobs.commit(id)`: status flips
848
+ `COMMITED ↔ REVERTED`, and re-committing a reverted job **re-applies its cells**.
849
+
850
+ ```ts
851
+ const job = await c.createImportJob({ title, labels, columns });
852
+ await job.addRow(...); await job.flushRows();
853
+ await job.detectDimensions(); await job.importDimensions();
854
+
855
+ // Reversible monthly re-import (NOT undoPrevious): every prior job with exactly these labels.
856
+ const same = (l: string[] = []) => l.length === labels.length && labels.every((x) => l.includes(x));
857
+ const priorIds = (await c.importJobs.list(labels))
858
+ .filter((j) => same(j.labels) && String(j.status) === "COMMITED").map((j) => j.id);
859
+ const reverted: typeof priorIds = [];
860
+ try {
861
+ for (const id of priorIds) { await c.importJobs.revert(id); reverted.push(id); } // pull prior cells out (COMMITED → REVERTED)
862
+ await job.commit(); // land the new month
863
+ } catch (e) {
864
+ for (const id of reverted) await c.importJobs.commit(id); // re-commit what was reverted → month never empty
865
+ await job.delete(); throw e;
866
+ }
867
+ ```
868
+
869
+ Reversibility verified on one backend (sentinel-slice probe); re-confirm on a new
870
+ tenant before treating as universal.
871
+
872
+ ## Where to look when you're unsure
873
+
874
+ 1. **TypeScript definitions** — `node_modules/farseer-client/dist/generated/apis/`, `node_modules/farseer-client/dist/FarseerClient.d.ts`. Authoritative.
875
+ 2. **The full guide** — [`farseer-client-api-guide.md`](farseer-client-api-guide.md).
876
+ 3. **Ask the user** — when a working example exists somewhere on the tenant, read it before guessing.