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
@@ -29,6 +29,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
29
29
  var layoutReceipt_exports = {};
30
30
  __export(layoutReceipt_exports, {
31
31
  createLayoutDestinationDirectories: () => createLayoutDestinationDirectories,
32
+ draftInFlight: () => draftInFlight,
32
33
  exitAfterWrites: () => exitAfterWrites,
33
34
  layoutReceiptDrafts: () => layoutReceiptDrafts,
34
35
  materializeLayoutPlan: () => materializeLayoutPlan,
@@ -36,6 +37,7 @@ __export(layoutReceipt_exports, {
36
37
  quarantinedApplyAdvice: () => quarantinedApplyAdvice,
37
38
  refuseUnwrittenReceipts: () => refuseUnwrittenReceipts,
38
39
  removeLayoutState: () => removeLayoutState,
40
+ supersededDrafts: () => supersededDrafts,
39
41
  vacateLayoutAliases: () => vacateLayoutAliases
40
42
  });
41
43
  module.exports = __toCommonJS(layoutReceipt_exports);
@@ -73,94 +75,6 @@ function persistedEvidence(state) {
73
75
  detachedDocumentProofs: (0, import_layoutCore.clone)(evidence.detachedDocumentProofs)
74
76
  };
75
77
  }
76
- function managedJsonArtifacts(scan) {
77
- return scan.artifacts.filter(
78
- (artifact) => artifact.present && !["raw", "attachment"].includes(artifact.role) && artifact.json !== void 0
79
- );
80
- }
81
- function expectedBytePaths(scan, evidence) {
82
- const expected = new Set(
83
- scan.artifacts.filter((artifact) => artifact.role === "raw" || artifact.role === "attachment").map((artifact) => artifact.path)
84
- );
85
- for (const route of evidence.binaryRoutes) if (route.bytes) expected.add(route.bytes);
86
- return expected;
87
- }
88
- function snapshotSeedDiagnostics(state, snapshot) {
89
- const diagnostics = [];
90
- const expectedJson = new Map(managedJsonArtifacts(snapshot.scan).map((artifact) => [artifact.path, artifact]));
91
- const actualJsonPaths = Object.keys(snapshot.jsonText);
92
- for (const [file, artifact] of expectedJson) {
93
- const text = snapshot.jsonText[file];
94
- if (typeof text !== "string") {
95
- diagnostics.push((0, import_layoutCore.diagnostic)("missing-layout-json-text", file, "Managed JSON text is missing"));
96
- continue;
97
- }
98
- try {
99
- if (!same(JSON.parse(text), artifact.json))
100
- diagnostics.push(
101
- (0, import_layoutCore.diagnostic)("layout-json-text-mismatch", file, "Managed JSON text does not match scan")
102
- );
103
- } catch {
104
- diagnostics.push((0, import_layoutCore.diagnostic)("invalid-layout-json-text", file, "Managed JSON text is invalid"));
105
- }
106
- }
107
- for (const file of actualJsonPaths)
108
- if (!expectedJson.has(file))
109
- diagnostics.push(
110
- (0, import_layoutCore.diagnostic)("extra-layout-json-text", file, "JSON text does not identify a managed JSON artifact")
111
- );
112
- const persistentTracked = new Map(state.layout?.tracked.map((item) => [item.route, item]));
113
- if (persistentTracked.size !== snapshot.scan.tracked.length)
114
- diagnostics.push(
115
- (0, import_layoutCore.diagnostic)("layout-tracking-mismatch", ".", "Tracked mapping does not match the supplied scan")
116
- );
117
- for (const tracked of snapshot.scan.tracked) {
118
- const original = persistentTracked.get(tracked.route);
119
- if (!original || original.path !== tracked.path)
120
- diagnostics.push(
121
- (0, import_layoutCore.diagnostic)("layout-tracking-mismatch", tracked.path, "Tracked mapping does not match the scan")
122
- );
123
- }
124
- return diagnostics;
125
- }
126
- function snapshotPathDiagnostics(state, snapshot, evidence) {
127
- const diagnostics = [];
128
- const expectedBytes = expectedBytePaths(snapshot.scan, evidence);
129
- const byteFacts = new Map(snapshot.byteFacts.map((fact) => [fact.path, fact]));
130
- const pathFacts = /* @__PURE__ */ new Map();
131
- for (const fact of snapshot.pathFacts) {
132
- if (pathFacts.has(fact.path)) throw new Error(`Path fact ${JSON.stringify(fact.path)} is duplicated`);
133
- pathFacts.set(fact.path, fact);
134
- }
135
- const requireState = (file, state2, message) => {
136
- if (pathFacts.get(file)?.state !== state2)
137
- diagnostics.push((0, import_layoutCore.diagnostic)("layout-path-fact-mismatch", file, message));
138
- };
139
- for (const artifact of snapshot.scan.artifacts)
140
- requireState(artifact.path, artifact.present ? "file" : "absent", "Artifact path fact does not match scan");
141
- for (const directory of snapshot.scan.opaqueDirectories)
142
- if ((0, import_layoutPaths.isPortableWorkspacePointer)(directory))
143
- requireState(directory, "directory", "Opaque directory fact is missing");
144
- const persistentTracked = new Map(state.layout?.tracked.map((item) => [item.route, item]));
145
- for (const tracked of snapshot.scan.tracked) {
146
- const original = persistentTracked.get(tracked.route);
147
- if (!original || original.path !== tracked.path) continue;
148
- const fact = pathFacts.get(original.path);
149
- if (tracked.status === "present") {
150
- requireState(tracked.path, original.kind, "Tracked path fact does not match scan");
151
- } else if (fact?.state !== "absent" || tracked.status === "missing-subtree" && fact.missingAncestor !== tracked.missingAncestor)
152
- diagnostics.push(
153
- (0, import_layoutCore.diagnostic)("layout-path-fact-mismatch", tracked.path, "Tracked absence fact does not match scan")
154
- );
155
- }
156
- for (const file of expectedBytes) {
157
- const byte = byteFacts.get(file);
158
- const physical = pathFacts.get(file);
159
- if (byte && (byte.state === "present" && physical?.state !== "file" || byte.state === "absent" && physical?.state !== "absent"))
160
- diagnostics.push((0, import_layoutCore.diagnostic)("layout-byte-path-mismatch", file, "Byte and path facts disagree"));
161
- }
162
- return diagnostics;
163
- }
164
78
  function compositionIndex(composition) {
165
79
  const bySource = (items, key) => (0, import_layoutCore.groupBySource)(items, key);
166
80
  return {
@@ -255,16 +169,14 @@ function filterReplay(readback, replayed) {
255
169
  };
256
170
  }
257
171
  const ADOPTABLE = /* @__PURE__ */ new Set(["eligible-stable-set", "eligible-assigned-create", "generated-share-deferred"]);
258
- function receiptHash(readback, key) {
259
- const matches = readback.receiptResults.filter(
260
- (item) => item.documentKey === key && ADOPTABLE.has(item.classification)
261
- );
172
+ function receiptHash(results, key) {
173
+ const matches = (results.get(key) ?? []).filter((item) => ADOPTABLE.has(item.classification));
262
174
  return matches.length === 1 && matches[0].receiptHash === matches[0].headHash ? matches[0].receiptHash : void 0;
263
175
  }
264
- function trackedRole(scan, path2, fallback) {
176
+ function trackedRole(artifactsByPath, path2, fallback) {
265
177
  const roles = [
266
178
  ...new Set(
267
- scan.artifacts.filter((artifact) => artifact.path === path2).map((artifact) => {
179
+ (artifactsByPath.get(path2) ?? []).map((artifact) => {
268
180
  if (["folder-control", "raw-metadata", "raw", "attachment"].includes(artifact.role))
269
181
  return artifact.role;
270
182
  return "document";
@@ -275,9 +187,10 @@ function trackedRole(scan, path2, fallback) {
275
187
  }
276
188
  function evidenceClaims(evidence, scan) {
277
189
  const claims = [];
190
+ const artifactsByPath = (0, import_layoutCore.groupBySource)(scan.artifacts, (artifact) => artifact.path);
278
191
  for (const route of evidence.groupedRoutes) {
279
192
  const role = trackedRole(
280
- scan,
193
+ artifactsByPath,
281
194
  route.selector.file,
282
195
  route.selector.file.endsWith("/_folder.json") ? "folder-control" : "document"
283
196
  );
@@ -318,7 +231,7 @@ function evidenceClaims(evidence, scan) {
318
231
  logical: `navigation:${(0, import_layoutCore.sourceIdentityKey)(route.source)}:raw-share`,
319
232
  path: route.groupFile,
320
233
  kind: "file",
321
- role: trackedRole(scan, route.groupFile, "document")
234
+ role: trackedRole(artifactsByPath, route.groupFile, "document")
322
235
  });
323
236
  const unique = /* @__PURE__ */ new Map();
324
237
  for (const claim of claims) unique.set((0, import_documents.canonicalText)([claim.logical, claim.path, claim.kind, claim.role]), claim);
@@ -333,16 +246,9 @@ function trackedRoute(logical) {
333
246
  function trackedAfter(input) {
334
247
  const beforeClaims = evidenceClaims(input.before, input.beforeScan);
335
248
  const afterClaims = evidenceClaims(input.after, input.afterScan);
336
- const beforeByPhysical = /* @__PURE__ */ new Map();
249
+ const beforeByPhysical = (0, import_layoutCore.groupBySource)(beforeClaims, physicalClaimKey);
337
250
  const beforeByRoute = new Map(beforeClaims.map((claim) => [trackedRoute(claim.logical), claim]));
338
- const afterByLogical = /* @__PURE__ */ new Map();
339
- for (const claim of beforeClaims)
340
- beforeByPhysical.set(physicalClaimKey(claim), [
341
- ...beforeByPhysical.get(physicalClaimKey(claim)) ?? [],
342
- claim
343
- ]);
344
- for (const claim of afterClaims)
345
- afterByLogical.set(claim.logical, [...afterByLogical.get(claim.logical) ?? [], claim]);
251
+ const afterByLogical = (0, import_layoutCore.groupBySource)(afterClaims, (claim) => claim.logical);
346
252
  const output = [];
347
253
  const represented = /* @__PURE__ */ new Set();
348
254
  const diagnostics = [];
@@ -435,13 +341,16 @@ function layoutReceiptDrafts(state) {
435
341
  ])
436
342
  ];
437
343
  }
438
- function refuseUnwrittenReceipts(state) {
344
+ function refuseUnwrittenReceipts(state, except) {
439
345
  for (const [planId, draft] of layoutReceiptDrafts(state)) {
346
+ if (planId === except) continue;
440
347
  if (draft.applying && draft.quarantined) throw new Error(quarantinedApplyAdvice(planId));
441
348
  if (draft.applying && !draft.receipt)
442
- throw new Error(`Resume farseer code apply p${planId} before creating another plan`);
349
+ throw new Error(`Resume farseer code apply p${planId} before planning or applying another plan`);
443
350
  if (draft.applying)
444
- throw new Error(`Run farseer code pull to write the receipt of p${planId} before creating another plan`);
351
+ throw new Error(
352
+ `Run farseer code pull to write the receipt of p${planId} before planning or applying another plan`
353
+ );
445
354
  }
446
355
  }
447
356
  function fileIdentity(root, relative) {
@@ -489,10 +398,15 @@ function unlinkLayoutFile(root, relative) {
489
398
  fs.unlinkSync(absolute);
490
399
  return true;
491
400
  }
492
- function removalMatchesCapture(root, snapshot, removal) {
401
+ function capturedByteFacts(snapshot) {
402
+ const facts = /* @__PURE__ */ new Map();
403
+ for (const fact of snapshot.byteFacts) if (!facts.has(fact.path)) facts.set(fact.path, fact);
404
+ return facts;
405
+ }
406
+ function removalMatchesCapture(root, snapshot, byteFacts, removal) {
493
407
  if (removal.kind === "directory" || removal.kind === "rewrite") return true;
494
408
  if (removal.kind === "bytes") {
495
- const expected = snapshot.byteFacts.find((fact) => fact.path === removal.path);
409
+ const expected = byteFacts.get(removal.path);
496
410
  const actual = (0, import_layoutScan.hashLayoutPath)(root, removal.path);
497
411
  return expected?.state === "present" && actual.state === "present" && (0, import_binaryDisk.sameBytes)(actual.content, expected.content);
498
412
  }
@@ -519,7 +433,8 @@ function materializeLayoutRemovals(input) {
519
433
  return identity ? [identity] : [];
520
434
  })
521
435
  );
522
- const capturedStill = (removal) => removalMatchesCapture(input.root, input.snapshot, removal);
436
+ const byteFacts = capturedByteFacts(input.snapshot);
437
+ const capturedStill = (removal) => removalMatchesCapture(input.root, input.snapshot, byteFacts, removal);
523
438
  const groupKeys = (removal) => removal.documentKeys.length > 0 ? removal.documentKeys : [`path:${removal.kind}:${removal.path}`];
524
439
  const proven = new Map(input.removals.map((removal) => [removal, capturedStill(removal)]));
525
440
  const failed = new Set(input.keep ?? []);
@@ -621,13 +536,14 @@ function vacateLayoutAliases(root, snapshot, removals, written) {
621
536
  })
622
537
  );
623
538
  if (identities.size === 0) return [];
539
+ const byteFacts = capturedByteFacts(snapshot);
624
540
  const vacated = [];
625
541
  for (const removal of removals) {
626
542
  if (removal.kind !== "file" && removal.kind !== "bytes") continue;
627
543
  if (destinations.has(removal.path)) continue;
628
544
  const identity = fileIdentity(root, removal.path);
629
545
  if (identity === void 0 || !identities.has(identity)) continue;
630
- if (!removalMatchesCapture(root, snapshot, removal)) continue;
546
+ if (!removalMatchesCapture(root, snapshot, byteFacts, removal)) continue;
631
547
  unlinkLayoutFile(root, removal.path);
632
548
  vacated.push(removal.path);
633
549
  }
@@ -661,42 +577,94 @@ function removeEmptyDirectories(root, created) {
661
577
  function descriptorKey(content) {
662
578
  return `${content.sha256}/${content.size}`;
663
579
  }
664
- async function stageByteWrites(input, snapshot, prepared, into) {
665
- const local = snapshot.byteFacts.filter(
666
- (fact) => fact.state === "present"
667
- );
668
- const sources = /* @__PURE__ */ new Map();
669
- const sidecars = new Map(prepared.jsonWrites.map((item) => [item.path, item]));
670
- for (const write of prepared.byteWrites) {
671
- const key = descriptorKey(write.descriptor);
672
- const destination = (0, import_layoutScan.resolveLayoutPath)(input.root, write.path);
673
- const supplied = sources.get(key);
674
- const reusable = local.find((fact) => (0, import_binaryDisk.sameBytes)(fact.content, write.descriptor));
675
- let file;
676
- if (supplied) file = (0, import_workspace.stageVerifiedFile)(supplied, destination, write.descriptor, write.path);
677
- else if (reusable)
678
- file = (0, import_workspace.stageVerifiedFile)(
679
- (0, import_layoutScan.resolveLayoutPath)(input.root, reusable.path),
680
- destination,
681
- write.descriptor,
682
- write.path
683
- );
684
- else {
685
- if (!input.api) throw new Error(`No byte source for ${write.path}`);
580
+ const DOWNLOAD_CONCURRENCY = 16;
581
+ function runEach(functions) {
582
+ for (const run of functions)
583
+ try {
584
+ run();
585
+ } catch {
586
+ }
587
+ }
588
+ async function downloadMissingBlobs(api, wanted, into) {
589
+ const finished = /* @__PURE__ */ new Map();
590
+ const streaming = /* @__PURE__ */ new Set();
591
+ let failure;
592
+ into.inFlight = () => {
593
+ runEach(streaming);
594
+ runEach([...finished.values()].map((file) => () => file.cleanup()));
595
+ };
596
+ let next = 0;
597
+ const worker = async () => {
598
+ while (!failure && next < wanted.length) {
599
+ const item = wanted[next++];
600
+ let abandon;
686
601
  try {
687
- file = await (0, import_workspace.stageDownloadedFile)(input.api, destination, write.descriptor, (abandon) => {
688
- into.inFlight = abandon;
602
+ const file = await (0, import_workspace.stageDownloadedFile)(api, item.destination, item.descriptor, (stop) => {
603
+ abandon = stop;
604
+ streaming.add(stop);
605
+ if (failure) stop();
689
606
  });
607
+ finished.set(item.key, file);
608
+ } catch (error) {
609
+ failure ??= { error };
610
+ runEach(streaming);
690
611
  } finally {
691
- into.inFlight = void 0;
612
+ if (abandon) streaming.delete(abandon);
692
613
  }
693
614
  }
694
- into.staged.push({ path: write.path, file });
695
- if (!sources.has(key)) sources.set(key, file.temporary);
696
- const sidecar = sidecars.get((0, import_layoutPaths.rawSidecarPath)(write.path));
697
- if (!sidecar) continue;
698
- into.sidecars.set(write.path, (0, import_workspace.stageText)((0, import_layoutScan.resolveLayoutPath)(input.root, sidecar.path), sidecar.text));
699
- into.paired.add(sidecar.path);
615
+ };
616
+ await Promise.all(Array.from({ length: Math.min(DOWNLOAD_CONCURRENCY, wanted.length) }, worker));
617
+ if (!failure) return finished;
618
+ runEach([...finished.values()].map((file) => () => file.cleanup()));
619
+ throw failure.error;
620
+ }
621
+ async function stageByteWrites(input, snapshot, prepared, into) {
622
+ const local = /* @__PURE__ */ new Map();
623
+ for (const fact of snapshot.byteFacts)
624
+ if (fact.state === "present" && fact.content && !local.has(descriptorKey(fact.content)))
625
+ local.set(descriptorKey(fact.content), fact);
626
+ const wanted = /* @__PURE__ */ new Map();
627
+ for (const write of prepared.byteWrites) {
628
+ const key = descriptorKey(write.descriptor);
629
+ if (local.has(key) || wanted.has(key)) continue;
630
+ if (!input.api) throw new Error(`No byte source for ${write.path}`);
631
+ wanted.set(key, { key, destination: (0, import_layoutScan.resolveLayoutPath)(input.root, write.path), descriptor: write.descriptor });
632
+ }
633
+ let downloaded = /* @__PURE__ */ new Map();
634
+ try {
635
+ if (input.api && wanted.size > 0)
636
+ downloaded = await downloadMissingBlobs(input.api, [...wanted.values()], into);
637
+ const sources = /* @__PURE__ */ new Map();
638
+ const sidecars = new Map(prepared.jsonWrites.map((item) => [item.path, item]));
639
+ for (const write of prepared.byteWrites) {
640
+ const key = descriptorKey(write.descriptor);
641
+ const destination = (0, import_layoutScan.resolveLayoutPath)(input.root, write.path);
642
+ const supplied = sources.get(key);
643
+ const reusable = local.get(key);
644
+ const fetched = downloaded.get(key);
645
+ let file;
646
+ if (supplied) file = (0, import_workspace.stageVerifiedFile)(supplied, destination, write.descriptor, write.path);
647
+ else if (reusable)
648
+ file = (0, import_workspace.stageVerifiedFile)(
649
+ (0, import_layoutScan.resolveLayoutPath)(input.root, reusable.path),
650
+ destination,
651
+ write.descriptor,
652
+ write.path
653
+ );
654
+ else if (fetched?.destination === destination) {
655
+ downloaded.delete(key);
656
+ file = fetched;
657
+ } else throw new Error(`No byte source for ${write.path}`);
658
+ into.staged.push({ path: write.path, file });
659
+ if (!sources.has(key)) sources.set(key, file.temporary);
660
+ const sidecar = sidecars.get((0, import_layoutPaths.rawSidecarPath)(write.path));
661
+ if (!sidecar) continue;
662
+ into.sidecars.set(write.path, (0, import_workspace.stageText)((0, import_layoutScan.resolveLayoutPath)(input.root, sidecar.path), sidecar.text));
663
+ into.paired.add(sidecar.path);
664
+ }
665
+ } finally {
666
+ into.inFlight = void 0;
667
+ runEach([...downloaded.values()].map((file) => () => file.cleanup()));
700
668
  }
701
669
  }
702
670
  function validateDestinations(snapshot, prepared) {
@@ -759,36 +727,31 @@ function planSubmissionProofs(state, source) {
759
727
  )
760
728
  };
761
729
  }
762
- function requiredPathsFor(snapshot, state, rendering) {
730
+ function touchedPaths(rendering) {
763
731
  const paths = /* @__PURE__ */ new Set();
764
732
  const add = (candidate) => {
765
733
  paths.add(candidate);
766
734
  for (const ancestor of (0, import_layoutCore.pathAncestors)(candidate)) paths.add(ancestor);
767
735
  };
768
- for (const artifact of snapshot.scan.artifacts) add(artifact.path);
769
- for (const directory of snapshot.scan.opaqueDirectories) if ((0, import_layoutPaths.isPortableWorkspacePointer)(directory)) add(directory);
770
- for (const tracked of snapshot.scan.tracked) {
771
- add(tracked.path);
772
- if (tracked.missingAncestor) add(tracked.missingAncestor);
773
- }
774
- for (const tracked of state.layout.tracked) add(tracked.path);
775
- for (const file of Object.keys(snapshot.jsonText)) add(file);
776
- for (const fact of snapshot.byteFacts) add(fact.path);
777
736
  for (const rendered of rendering.json) add(rendered.path);
778
737
  for (const rendered of rendering.bytes) add(rendered.destination);
779
738
  for (const removal of rendering.removals) add(removal.path);
739
+ for (const rename of rendering.directoryRenames) {
740
+ add(rename.from);
741
+ add(rename.to);
742
+ }
780
743
  return [...paths].sort(import_layoutCore.compareText);
781
744
  }
782
745
  const PLAIN_ROUTE_KINDS = /* @__PURE__ */ new Set(["variable", "sheet", "dashboard", "remote_job"]);
783
746
  function plainHeadRoute(document) {
784
747
  const value = document;
785
- const folder = value.folder;
786
748
  if (!PLAIN_ROUTE_KINDS.has(document.kind) || typeof value.name !== "string") return void 0;
787
- if (!Array.isArray(folder) || folder.some((segment) => typeof segment !== "string")) return void 0;
749
+ const folder = value.folder === null ? void 0 : (0, import_layoutPaths.itemFolderPath)(value.folder);
750
+ if (!folder) return void 0;
788
751
  const segments = [...folder, value.name];
789
- if (segments.some((segment) => (0, import_layoutPaths.layoutNameNeedsOverride)(segment))) return void 0;
752
+ if (segments.some((segment) => typeof segment === "string" && (0, import_layoutPaths.layoutNameNeedsOverride)(segment))) return void 0;
790
753
  try {
791
- return `tree/${segments.map(import_layoutPaths.encodeLayoutSegment).join("/")}.json`;
754
+ return `${(0, import_layoutPaths.folderPathDirectory)(segments)}.json`;
792
755
  } catch {
793
756
  return void 0;
794
757
  }
@@ -893,7 +856,11 @@ function destinationsMatchCapture(root, snapshot) {
893
856
  function orderedWrites(units, holders, unchanged) {
894
857
  const writers = /* @__PURE__ */ new Map();
895
858
  units.forEach((unit, index) => {
896
- for (const key of unit.keys) writers.set(key, [...writers.get(key) ?? [], index]);
859
+ for (const key of unit.keys) {
860
+ const indexes = writers.get(key);
861
+ if (indexes) indexes.push(index);
862
+ else writers.set(key, [index]);
863
+ }
897
864
  });
898
865
  const folded = units.map((unit) => unit.paths.map(import_layoutPaths.layoutCollisionKey));
899
866
  const waits = units.map((unit, index) => {
@@ -1034,8 +1001,6 @@ function prepareLayoutPlan(input, captured) {
1034
1001
  if (Array.isArray(parsed)) return { status: "blocked", diagnostics: parsed };
1035
1002
  const state = parsed;
1036
1003
  const evidence = { ...persistedEvidence(state), ...planSubmissionProofs(state, input.source) };
1037
- const diagnostics = snapshotSeedDiagnostics(state, captured.snapshot);
1038
- if (diagnostics.length > 0) return { status: "blocked", diagnostics };
1039
1004
  const byteEvidence = { facts: captured.snapshot.byteFacts, diagnostics: [] };
1040
1005
  const composed = (0, import_layoutCompose.composeLayoutSubmission)({ scan: captured.snapshot.scan, byteEvidence, evidence });
1041
1006
  let staleOrigins = [];
@@ -1131,8 +1096,12 @@ function prepareLayoutPlan(input, captured) {
1131
1096
  const authoritativeDocuments = new Map(sets.map((item) => [item.documentKey, item.document]));
1132
1097
  const adoptedKeys = sets.map((item) => item.documentKey).sort(import_layoutCore.compareText);
1133
1098
  const baselineSet = {};
1099
+ const receiptResults = (0, import_layoutCore.groupBySource)(
1100
+ readback.receiptResults.filter((item) => item.documentKey !== void 0),
1101
+ (item) => item.documentKey
1102
+ );
1134
1103
  for (const key of adoptedKeys) {
1135
- const hash = input.source.kind === "receipt" ? receiptHash(readback, key) : input.head.manifest[key];
1104
+ const hash = input.source.kind === "receipt" ? receiptHash(receiptResults, key) : input.head.manifest[key];
1136
1105
  if (!hash)
1137
1106
  return {
1138
1107
  status: "blocked",
@@ -1173,7 +1142,7 @@ function prepareLayoutPlan(input, captured) {
1173
1142
  appliedBaseline,
1174
1143
  jsonWrites,
1175
1144
  byteWrites,
1176
- requiredPaths: requiredPathsFor(captured.snapshot, state, rendering),
1145
+ touchedPaths: touchedPaths(rendering),
1177
1146
  notices: [...readback.notices, ...rendering.notices, ...localPathNotices(captured.snapshot.scan)],
1178
1147
  dropQuarantinedReceipts: input.source.kind === "checkout" && input.source.force === true,
1179
1148
  compositionWarnings: [
@@ -1230,22 +1199,57 @@ function harvestRoutes(recomposed, sources, rewritten) {
1230
1199
  function groupHeader(source, file, rewritten) {
1231
1200
  return source.type === "group" && rewritten.has(file);
1232
1201
  }
1233
- function observedCleanly(recomposed, source) {
1234
- const key = (0, import_layoutCore.sourceIdentityKey)(source);
1235
- const observations = [
1236
- ...recomposed.grouped.observations,
1237
- ...recomposed.binary.rawObservations,
1238
- ...recomposed.binary.attachmentObservations
1239
- ].filter((observation) => (0, import_layoutCore.sourceIdentityKey)(observation.source) === key);
1240
- return observations.every(
1202
+ function observationsBySource(recomposed) {
1203
+ return (0, import_layoutCore.groupBySource)(
1204
+ [
1205
+ ...recomposed.grouped.observations,
1206
+ ...recomposed.binary.rawObservations,
1207
+ ...recomposed.binary.attachmentObservations
1208
+ ],
1209
+ (observation) => (0, import_layoutCore.sourceIdentityKey)(observation.source)
1210
+ );
1211
+ }
1212
+ function observedCleanly(observations, source) {
1213
+ return (observations.get((0, import_layoutCore.sourceIdentityKey)(source)) ?? []).every(
1241
1214
  (observation) => !!observation.currentHash && ["clean", "new"].includes(observation.state)
1242
1215
  );
1243
1216
  }
1244
1217
  function sameDocument(left, right) {
1245
1218
  return (0, import_documents.canonicalText)((0, import_layoutReadback.withoutContainerSuppliedFields)(left)) === (0, import_documents.canonicalText)((0, import_layoutReadback.withoutContainerSuppliedFields)(right));
1246
1219
  }
1247
- function adoptLayoutPlan(root, captured, prepared, removal, deletes) {
1248
- const original = (0, import_documents.parseState)(captured.snapshot.stateText);
1220
+ function adoptionFiles(prepared) {
1221
+ const files = /* @__PURE__ */ new Set();
1222
+ for (const rendered of prepared.rendering.json) files.add(rendered.path);
1223
+ for (const rendered of prepared.rendering.bytes) {
1224
+ files.add(rendered.destination);
1225
+ if (rendered.kind === "raw") files.add((0, import_layoutPaths.rawSidecarPath)(rendered.destination));
1226
+ }
1227
+ for (const removal of prepared.rendering.removals) if (removal.kind !== "directory") files.add(removal.path);
1228
+ for (const patch of prepared.readback.identityPatches) files.add(patch.container);
1229
+ const keys = /* @__PURE__ */ new Set([...prepared.adoptedKeys, ...Object.keys(prepared.appliedBaseline)]);
1230
+ for (const item of prepared.current.sources) {
1231
+ const key = stableSourceKeyOf(item.mapping.source);
1232
+ if (key === void 0 || !keys.has(key)) continue;
1233
+ if (item.codec === "grouped") files.add(item.mapping.selector.file);
1234
+ else files.add(item.mapping.selector.sidecar).add(item.mapping.bytes);
1235
+ }
1236
+ for (const file of [...files]) if ((0, import_layoutPaths.isRawSidecarPath)(file)) files.add((0, import_layoutPaths.rawBytesPath)(file));
1237
+ return files;
1238
+ }
1239
+ function rescannedEvidence(evidence, scanned) {
1240
+ return {
1241
+ ...evidence,
1242
+ groupedRoutes: evidence.groupedRoutes.filter(
1243
+ (route) => scanned.has(route.selector.file) || route.selector.slot === "share-group-owner"
1244
+ ),
1245
+ binaryRoutes: evidence.binaryRoutes.filter(
1246
+ (route) => scanned.has(route.selector.slot === "file-entry" ? route.selector.sidecar : route.selector.ownerFile)
1247
+ ),
1248
+ rawNavigationRoutes: evidence.rawNavigationRoutes.filter((route) => scanned.has(route.selector.sidecar))
1249
+ };
1250
+ }
1251
+ function adoptLayoutPlan(root, snapshot, prepared, removal, deletes) {
1252
+ const original = (0, import_documents.parseState)(snapshot.stateText);
1249
1253
  const base = removeLayoutState(original, deletes, removal.removed);
1250
1254
  const previous = base.layout.evidence;
1251
1255
  const sourceOf = (key) => (0, import_layoutCore.stableSource)(key);
@@ -1263,13 +1267,15 @@ function adoptLayoutPlan(root, captured, prepared, removal, deletes) {
1263
1267
  );
1264
1268
  const derived = [...untouched(previous.derivedSourceProofs)];
1265
1269
  for (const proof of prepared.readback.derivedSourceProofs) derived.push((0, import_layoutCore.clone)(proof));
1270
+ const derivedSources = new Set(derived.map((proof) => (0, import_layoutCore.sourceIdentityKey)(proof.source)));
1266
1271
  for (const key of prepared.adoptedKeys) {
1267
1272
  if (!key.startsWith("user_permissions/")) continue;
1268
1273
  const source = sourceOf(key);
1269
1274
  const document = prepared.authoritativeDocuments.get(key);
1270
1275
  const selectorHash = document && (0, import_layoutProjection.derivedSourceSelectorHash)(document);
1271
1276
  if (!source || !selectorHash) continue;
1272
- if (derived.some((proof) => (0, import_layoutCore.sourceIdentityKey)(proof.source) === (0, import_layoutCore.sourceIdentityKey)(source))) continue;
1277
+ if (derivedSources.has((0, import_layoutCore.sourceIdentityKey)(source))) continue;
1278
+ derivedSources.add((0, import_layoutCore.sourceIdentityKey)(source));
1273
1279
  derived.push({
1274
1280
  source: { type: "resource", resource: { kind: "user_permissions", id: source.resource.id } },
1275
1281
  selectorHash
@@ -1299,11 +1305,15 @@ function adoptLayoutPlan(root, captured, prepared, removal, deletes) {
1299
1305
  detachedFileProofs,
1300
1306
  detachedDocumentProofs
1301
1307
  };
1302
- const scan = (0, import_layoutScan.scanLayout)({ root, tracked: base.layout.tracked });
1308
+ const files = adoptionFiles(prepared);
1309
+ const whole = [...files].some((file) => file.startsWith("detached/"));
1310
+ const scan = (0, import_layoutScan.scanLayout)({ root, tracked: base.layout.tracked, ...whole ? {} : { only: files } });
1311
+ const scanned = new Set(scan.artifacts.map((artifact) => artifact.path));
1312
+ const rescanned = whole ? candidate : rescannedEvidence(candidate, scanned);
1303
1313
  const recomposed = (0, import_layoutCompose.composeLayoutSubmission)({
1304
1314
  scan,
1305
- byteEvidence: (0, import_layoutScan.loadLayoutByteEvidence)({ root, scan, evidence: candidate }),
1306
- evidence: candidate
1315
+ byteEvidence: (0, import_layoutScan.loadLayoutByteEvidence)({ root, scan, evidence: rescanned }),
1316
+ evidence: rescanned
1307
1317
  });
1308
1318
  const keep = (state, unverified2, diagnostics = [], notices = []) => ({ state, unverified: unverified2, diagnostics, notices });
1309
1319
  if (recomposed.status === "blocked")
@@ -1315,12 +1325,13 @@ function adoptLayoutPlan(root, captured, prepared, removal, deletes) {
1315
1325
  const bySource = (0, import_layoutCore.groupBySource)(recomposed.sources, (item) => (0, import_layoutCore.sourceIdentityKey)(item.mapping.source));
1316
1326
  const verified = [];
1317
1327
  const unverified = [];
1328
+ const observations = observationsBySource(recomposed);
1318
1329
  for (const key of prepared.adoptedKeys) {
1319
1330
  const source = sourceOf(key);
1320
1331
  const mappings = source ? bySource.get((0, import_layoutCore.sourceIdentityKey)(source)) ?? [] : [];
1321
1332
  const composed = mappings.length === 1 ? recomposed.documents[mappings[0].mapping.documentIndex] : void 0;
1322
1333
  const expected = prepared.authoritativeDocuments.get(key);
1323
- if (source && composed && expected && sameDocument(composed, expected) && observedCleanly(recomposed, source))
1334
+ if (source && composed && expected && sameDocument(composed, expected) && observedCleanly(observations, source))
1324
1335
  verified.push(key);
1325
1336
  else unverified.push(key);
1326
1337
  }
@@ -1332,12 +1343,12 @@ function adoptLayoutPlan(root, captured, prepared, removal, deletes) {
1332
1343
  );
1333
1344
  const appliedNotices = [];
1334
1345
  const applied = {};
1335
- const appliedPath = (key) => {
1336
- for (const patch of prepared.readback.identityPatches) if (patch.documentKey === key) return patch.container;
1337
- for (const artifact of prepared.rendering.json)
1338
- if (artifact.authorizingDocumentKeys.includes(key)) return artifact.path;
1339
- return void 0;
1340
- };
1346
+ const appliedPaths = /* @__PURE__ */ new Map();
1347
+ for (const artifact of [...prepared.rendering.json].reverse())
1348
+ for (const key of artifact.authorizingDocumentKeys) appliedPaths.set(key, artifact.path);
1349
+ for (const patch of [...prepared.readback.identityPatches].reverse())
1350
+ appliedPaths.set(patch.documentKey, patch.container);
1351
+ const appliedPath = (key) => appliedPaths.get(key);
1341
1352
  for (const [key, hash] of Object.entries(prepared.appliedBaseline)) {
1342
1353
  const source = sourceOf(key);
1343
1354
  const mappings = source ? bySource.get((0, import_layoutCore.sourceIdentityKey)(source)) ?? [] : [];
@@ -1363,9 +1374,16 @@ function adoptLayoutPlan(root, captured, prepared, removal, deletes) {
1363
1374
  const tracking = trackedAfter({
1364
1375
  tracked: base.layout.tracked,
1365
1376
  before: original.layout.evidence,
1366
- beforeScan: captured.snapshot.scan,
1377
+ beforeScan: snapshot.scan,
1367
1378
  after: evidence,
1368
- afterScan: scan
1379
+ // A path outside the rescan still holds what the capture read there.
1380
+ afterScan: whole ? scan : {
1381
+ ...scan,
1382
+ artifacts: [
1383
+ ...snapshot.scan.artifacts.filter((item) => !files.has(item.path) && !scanned.has(item.path)),
1384
+ ...scan.artifacts
1385
+ ]
1386
+ }
1369
1387
  });
1370
1388
  const baseline = { ...base.baseline, ...applied };
1371
1389
  for (const key of verified) baseline[key] = prepared.baselineSet[key];
@@ -1387,23 +1405,32 @@ function adoptLayoutPlan(root, captured, prepared, removal, deletes) {
1387
1405
  appliedNotices
1388
1406
  );
1389
1407
  }
1408
+ function draftInFlight(draft) {
1409
+ return draft.applying === true || draft.unanswered === true || draft.receipt !== void 0;
1410
+ }
1411
+ const planSequence = (planId) => /^[0-9]+$/.test(planId) ? BigInt(planId) : void 0;
1412
+ function supersededDrafts(receipts, appliedPlanId) {
1413
+ const applied = planSequence(appliedPlanId);
1414
+ if (applied === void 0) return [];
1415
+ return Object.entries(receipts).filter(([planId, draft]) => {
1416
+ const sequence = planSequence(planId);
1417
+ return sequence !== void 0 && sequence < applied && !draftInFlight(draft);
1418
+ }).map(([planId]) => planId).sort((left, right) => Number(left) - Number(right));
1419
+ }
1420
+ function settleReceipt(state, source) {
1421
+ if (source.kind !== "receipt" || !state.layout) return { state, dropped: [] };
1422
+ const receipts = { ...state.layout.receipts };
1423
+ const failed = receipts[source.planId]?.receipt?.status === import_farseer_client.ReceiptStatusEnum.Failed;
1424
+ delete receipts[source.planId];
1425
+ const dropped = failed ? [] : supersededDrafts(receipts, source.planId);
1426
+ for (const planId of dropped) delete receipts[planId];
1427
+ return { state: { ...state, layout: { ...state.layout, receipts } }, dropped };
1428
+ }
1390
1429
  async function materializeLayoutPlan(input) {
1391
- const seed = (0, import_layoutScan.captureLayoutWorkspaceSeed)(input.root);
1392
- const first = prepareLayoutPlan(input, seed);
1393
- if (first.status === "blocked") return first;
1394
- const captured = (0, import_layoutScan.captureLayoutWorkspace)(input.root, first.prepared.requiredPaths);
1395
- const second = prepareLayoutPlan(input, captured);
1396
- if (second.status === "blocked") return second;
1397
- const prepared = second.prepared;
1398
- if (prepared.action !== first.prepared.action || !(0, import_layoutScan.sameValue)(prepared.requiredPaths, first.prepared.requiredPaths))
1399
- return (0, import_layoutCore.blocked)([
1400
- (0, import_layoutCore.diagnostic)("layout-path-requirements-changed", ".", "Layout paths changed while preparing the plan")
1401
- ]);
1402
- const pathDiagnostics = snapshotPathDiagnostics(prepared.state, captured.snapshot, {
1403
- ...persistedEvidence(prepared.state),
1404
- ...planSubmissionProofs(prepared.state, input.source)
1405
- });
1406
- if (pathDiagnostics.length > 0) return (0, import_layoutCore.blocked)(pathDiagnostics);
1430
+ const captured = (0, import_layoutScan.captureLayoutWorkspaceSeed)(input.root);
1431
+ const planned = prepareLayoutPlan(input, captured);
1432
+ if (planned.status === "blocked") return planned;
1433
+ const prepared = planned.prepared;
1407
1434
  const performedDeletes = (removals) => {
1408
1435
  const retained = new Set(removals.retained);
1409
1436
  if (retained.size === 0) return prepared.readback.deletes;
@@ -1416,27 +1443,42 @@ async function materializeLayoutPlan(input) {
1416
1443
  })
1417
1444
  };
1418
1445
  };
1419
- const outcome = (removals, unverified, verificationDiagnostics = [], extraNotices = [], unwritten = /* @__PURE__ */ new Set()) => ({
1420
- status: "complete",
1421
- action: prepared.action,
1422
- // A set the writer left unwritten is reported as `unmaterialized`, never as written.
1423
- materializations: prepared.readback.materializations.filter(
1424
- (item) => item.mode !== "set" || !unwritten.has(item.documentKey)
1425
- ),
1426
- deletes: performedDeletes(removals),
1427
- adoptedDocumentKeys: prepared.adoptedKeys.filter((key) => !unverified.includes(key)),
1428
- unverifiedDocumentKeys: [...unverified],
1429
- verificationDiagnostics,
1430
- compositionWarnings: prepared.compositionWarnings,
1431
- jsonWrites: prepared.jsonWrites,
1432
- byteWrites: prepared.byteWrites,
1433
- removals,
1434
- notices: [...prepared.notices, ...extraNotices]
1435
- });
1446
+ const outcome = (removals, unverified, verificationDiagnostics = [], extraNotices = [], unwritten = /* @__PURE__ */ new Set()) => {
1447
+ const unverifiedKeys = new Set(unverified);
1448
+ return {
1449
+ status: "complete",
1450
+ action: prepared.action,
1451
+ // A set the writer left unwritten is reported as `unmaterialized`, never as written.
1452
+ materializations: prepared.readback.materializations.filter(
1453
+ (item) => item.mode !== "set" || !unwritten.has(item.documentKey)
1454
+ ),
1455
+ deletes: performedDeletes(removals),
1456
+ adoptedDocumentKeys: prepared.adoptedKeys.filter((key) => !unverifiedKeys.has(key)),
1457
+ unverifiedDocumentKeys: [...unverified],
1458
+ verificationDiagnostics,
1459
+ compositionWarnings: prepared.compositionWarnings,
1460
+ jsonWrites: prepared.jsonWrites,
1461
+ byteWrites: prepared.byteWrites,
1462
+ removals,
1463
+ notices: [...prepared.notices, ...extraNotices]
1464
+ };
1465
+ };
1436
1466
  if (prepared.action === "noop") {
1437
- (0, import_workspace.saveLearnedByteHashes)(input.root, captured.snapshot.stateText);
1467
+ if (input.source.kind !== "receipt") (0, import_workspace.saveLearnedByteHashes)(input.root, captured.snapshot.stateText);
1468
+ else {
1469
+ if ((0, import_layoutScan.stateText)(input.root) !== captured.snapshot.stateText)
1470
+ throw new Error("Layout state changed before the final save");
1471
+ const settled = settleReceipt(prepared.state, input.source);
1472
+ (0, import_workspace.saveState)(input.root, settled.state);
1473
+ return {
1474
+ ...outcome({ removed: [], rewritten: [], kept: [], retained: [] }, []),
1475
+ droppedDrafts: settled.dropped
1476
+ };
1477
+ }
1438
1478
  return outcome({ removed: [], rewritten: [], kept: [], retained: [] }, []);
1439
1479
  }
1480
+ const touched = (0, import_layoutScan.touchedPathFacts)(input.root, captured.observation, prepared.touchedPaths);
1481
+ const snapshot = { ...captured.snapshot, pathFacts: touched.pathFacts };
1440
1482
  const written = [
1441
1483
  ...prepared.jsonWrites.map((write) => write.path),
1442
1484
  ...prepared.byteWrites.map((write) => write.path)
@@ -1449,6 +1491,7 @@ async function materializeLayoutPlan(input) {
1449
1491
  let unpaired;
1450
1492
  let order;
1451
1493
  let result;
1494
+ let droppedDrafts = [];
1452
1495
  const abandon = () => {
1453
1496
  bytes.inFlight?.();
1454
1497
  for (const item of [...bytes.staged.map((entry) => entry.file), ...bytes.sidecars.values(), ...held.values()])
@@ -1458,17 +1501,15 @@ async function materializeLayoutPlan(input) {
1458
1501
  deferInterrupts();
1459
1502
  activeWrites.add(abandon);
1460
1503
  try {
1461
- const current = (0, import_layoutScan.captureLayoutWorkspace)(input.root, prepared.requiredPaths);
1462
- if (!(0, import_layoutScan.sameValue)(current.snapshot, captured.snapshot)) throw new Error("Layout changed before materialization");
1463
- validateDestinations(current.snapshot, prepared);
1504
+ const changed = (0, import_layoutScan.changedObservedPath)(input.root, touched.observation);
1505
+ if (changed !== void 0) throw new Error(`Layout changed before materialization: ${changed}`);
1506
+ validateDestinations(snapshot, prepared);
1464
1507
  createdDirectories = createLayoutDestinationDirectories(input.root, written);
1465
- await stageByteWrites(input, captured.snapshot, prepared, bytes);
1508
+ await stageByteWrites(input, snapshot, prepared, bytes);
1466
1509
  activeWrites.delete(abandon);
1467
1510
  for (const rename of prepared.rendering.directoryRenames) renameDirectorySpelling(input.root, rename);
1468
1511
  const vacate = (destination) => {
1469
- for (const origin of vacateLayoutAliases(input.root, captured.snapshot, prepared.rendering.removals, [
1470
- destination
1471
- ]))
1512
+ for (const origin of vacateLayoutAliases(input.root, snapshot, prepared.rendering.removals, [destination]))
1472
1513
  vacated.push({ origin, destination });
1473
1514
  };
1474
1515
  const byteWriteAt = new Map(prepared.byteWrites.map((write) => [write.path, write]));
@@ -1506,14 +1547,10 @@ async function materializeLayoutPlan(input) {
1506
1547
  })
1507
1548
  )
1508
1549
  ];
1509
- order = orderedWrites(
1510
- units,
1511
- currentHolders(prepared.current),
1512
- destinationsMatchCapture(input.root, captured.snapshot)
1513
- );
1550
+ order = orderedWrites(units, currentHolders(prepared.current), destinationsMatchCapture(input.root, snapshot));
1514
1551
  order.run();
1515
1552
  const unrestored = order.revertUnfinished(
1516
- (unit) => restoreCapturedPaths(input.root, captured.snapshot, unit.paths, bytes.staged)
1553
+ (unit) => restoreCapturedPaths(input.root, snapshot, unit.paths, bytes.staged)
1517
1554
  );
1518
1555
  if (unrestored.length > 0)
1519
1556
  throw new Error(
@@ -1521,27 +1558,28 @@ async function materializeLayoutPlan(input) {
1521
1558
  );
1522
1559
  const removals = materializeLayoutRemovals({
1523
1560
  root: input.root,
1524
- snapshot: captured.snapshot,
1561
+ snapshot,
1525
1562
  removals: prepared.rendering.removals,
1526
1563
  written,
1527
1564
  keep: [...order.skipped]
1528
1565
  });
1529
- const changed = order.notices();
1530
- const adopted = adoptLayoutPlan(input.root, captured, prepared, removals, performedDeletes(removals));
1531
- if ((0, import_layoutScan.stateText)(input.root) !== captured.snapshot.stateText)
1532
- throw new Error("Layout state changed before the final save");
1533
- (0, import_workspace.saveState)(input.root, adopted.state);
1566
+ const kept = order.notices();
1567
+ const adopted = adoptLayoutPlan(input.root, snapshot, prepared, removals, performedDeletes(removals));
1568
+ if ((0, import_layoutScan.stateText)(input.root) !== snapshot.stateText) throw new Error("Layout state changed before the final save");
1569
+ const settled = settleReceipt(adopted.state, input.source);
1570
+ (0, import_workspace.saveState)(input.root, settled.state);
1571
+ droppedDrafts = settled.dropped;
1534
1572
  result = outcome(
1535
1573
  removals,
1536
1574
  adopted.unverified,
1537
1575
  adopted.diagnostics,
1538
- [...adopted.notices, ...changed],
1576
+ [...adopted.notices, ...kept],
1539
1577
  order.skipped
1540
1578
  );
1541
1579
  } catch (error) {
1542
1580
  activeWrites.delete(abandon);
1543
1581
  const lost = [
1544
- ...restoreVacatedOrigins(input.root, captured.snapshot, vacated, [
1582
+ ...restoreVacatedOrigins(input.root, snapshot, vacated, [
1545
1583
  ...bytes.staged,
1546
1584
  ...[...bytes.sidecars].map(([path2, file]) => ({
1547
1585
  path: (0, import_layoutPaths.rawSidecarPath)(path2),
@@ -1550,10 +1588,10 @@ async function materializeLayoutPlan(input) {
1550
1588
  }))
1551
1589
  ]),
1552
1590
  ...order?.revertUnfinished(
1553
- (unit) => restoreCapturedPaths(input.root, captured.snapshot, unit.paths, bytes.staged)
1591
+ (unit) => restoreCapturedPaths(input.root, snapshot, unit.paths, bytes.staged)
1554
1592
  ) ?? []
1555
1593
  ];
1556
- const stray = withdrawUnpairedBytes(input.root, captured.snapshot, vacated, unpaired);
1594
+ const stray = withdrawUnpairedBytes(input.root, snapshot, vacated, unpaired);
1557
1595
  if (lost.length === 0 && stray.length === 0) throw error;
1558
1596
  const message = [
1559
1597
  error instanceof Error ? error.message : String(error),
@@ -1575,11 +1613,12 @@ async function materializeLayoutPlan(input) {
1575
1613
  for (const [path2, item] of held) clean(() => item.cleanup(), `temporary file for ${path2}`);
1576
1614
  removeEmptyDirectories(input.root, createdDirectories);
1577
1615
  }
1578
- return { ...result, cleanupWarnings };
1616
+ return { ...result, cleanupWarnings, droppedDrafts };
1579
1617
  }
1580
1618
  // Annotate the CommonJS export names for ESM import in node:
1581
1619
  0 && (module.exports = {
1582
1620
  createLayoutDestinationDirectories,
1621
+ draftInFlight,
1583
1622
  exitAfterWrites,
1584
1623
  layoutReceiptDrafts,
1585
1624
  materializeLayoutPlan,
@@ -1587,6 +1626,7 @@ async function materializeLayoutPlan(input) {
1587
1626
  quarantinedApplyAdvice,
1588
1627
  refuseUnwrittenReceipts,
1589
1628
  removeLayoutState,
1629
+ supersededDrafts,
1590
1630
  vacateLayoutAliases
1591
1631
  });
1592
1632
  //# sourceMappingURL=layoutReceipt.js.map