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
@@ -297,12 +297,20 @@ function submittedResources(submission, snapshotIndex) {
297
297
  }
298
298
  return { resources, diagnostics };
299
299
  }
300
- function hasSavedTransientProof(composition, source) {
300
+ function savedProofIndex(composition) {
301
+ const { groupedSubmissions: grouped, binarySubmissions: binary } = composition;
302
+ return {
303
+ ...grouped ? { grouped: (0, import_layoutCore.groupBySource)(grouped, (proof) => (0, import_layoutCore.sourceIdentityKey)(proof.source)) } : {},
304
+ ...binary ? { binary: (0, import_layoutCore.groupBySource)(binary, (proof) => (0, import_layoutCore.sourceIdentityKey)(proof.source)) } : {}
305
+ };
306
+ }
307
+ function hasSavedTransientProof(saved, source) {
301
308
  if (source.mapping.source.type !== "transient") return true;
302
- const proofs = source.codec === "grouped" ? composition.groupedSubmissions : composition.binarySubmissions;
303
- if (!proofs) return false;
309
+ const index = source.codec === "grouped" ? saved.grouped : saved.binary;
310
+ if (!index) return false;
311
+ const proofs = index.get((0, import_layoutCore.sourceIdentityKey)(source.mapping.source)) ?? [];
304
312
  const matches = proofs.filter(
305
- (proof) => (0, import_layoutCore.sourceIdentityKey)(proof.source) === (0, import_layoutCore.sourceIdentityKey)(source.mapping.source) && (0, import_layoutCore.samePath)(proof.sourcePath, source.mapping.sourcePath) && (source.codec === "grouped" ? (0, import_layoutCore.sameSelector)(
313
+ (proof) => (0, import_layoutCore.samePath)(proof.sourcePath, source.mapping.sourcePath) && (source.codec === "grouped" ? (0, import_layoutCore.sameSelector)(
306
314
  proof.selector,
307
315
  source.mapping.selector
308
316
  ) : sameBinarySelector(
@@ -312,9 +320,9 @@ function hasSavedTransientProof(composition, source) {
312
320
  );
313
321
  return matches.length === 1;
314
322
  }
315
- function createSourceMatches(composition, submitted, operation) {
323
+ function createSourceMatches(saved, submitted, operation) {
316
324
  const source = submitted.source;
317
- if (source.type === "transient") return hasSavedTransientProof(composition, submitted.submissionSource);
325
+ if (source.type === "transient") return hasSavedTransientProof(saved, submitted.submissionSource);
318
326
  if (source.type !== "resource" || !("key" in source.resource)) return false;
319
327
  return source.resource.kind === submitted.document.kind && operation.kind === submitted.document.kind;
320
328
  }
@@ -404,14 +412,14 @@ function hasFolderDescendants(scan, mapping, current, currentFolder, detachedDoc
404
412
  ...scan.opaqueDirectories
405
413
  ];
406
414
  if (directory && paths.some((path) => path !== mapping.selector.file && pathInside(path, directory))) return true;
407
- const semanticPath = currentFolder?.kind === "folder" && Array.isArray(currentFolder.path) && currentFolder.path.every((part) => typeof part === "string") ? currentFolder.path : void 0;
415
+ const semanticPath = currentFolder?.kind === "folder" ? (0, import_layoutPaths.folderPathSegments)(currentFolder.path) : void 0;
408
416
  if (semanticPath) {
417
+ const segmentKey = (part) => typeof part === "string" ? part : (0, import_documents.canonicalText)(part);
409
418
  const descendant = current.documents.some((document) => {
410
419
  if (document === currentFolder) return false;
411
- const path = document.kind === "folder" && Array.isArray(document.path) ? document.path : Array.isArray(document.folder) ? document.folder : void 0;
412
- if (!path || path.some((part) => typeof part !== "string") || path.length < semanticPath.length)
413
- return false;
414
- if (!semanticPath.every((part, index) => path[index] === part)) return false;
420
+ const path = document.kind === "folder" ? (0, import_layoutPaths.folderPathSegments)(document.path) : (0, import_layoutPaths.itemFolderPath)(document.folder);
421
+ if (!path || path.length < semanticPath.length) return false;
422
+ if (!semanticPath.every((part, index) => segmentKey(path[index]) === segmentKey(part))) return false;
415
423
  return document.kind !== "folder" || path.length > semanticPath.length;
416
424
  });
417
425
  if (descendant) return true;
@@ -434,7 +442,7 @@ function hasDetachedDescendants(mapping, directory, semanticPath, detachedDocume
434
442
  let semanticDirectory;
435
443
  if (semanticPath)
436
444
  try {
437
- semanticDirectory = `tree/${semanticPath.map(import_layoutPaths.encodeLayoutSegment).join("/")}`;
445
+ semanticDirectory = (0, import_layoutPaths.folderPathDirectory)(semanticPath);
438
446
  } catch {
439
447
  semanticDirectory = void 0;
440
448
  }
@@ -650,6 +658,7 @@ function decideReceiptEligibility(input) {
650
658
  ...resource.document ? { document: (0, import_layoutCore.clone)(resource.document) } : {}
651
659
  });
652
660
  };
661
+ let savedProofs;
653
662
  for (const operation of input.submission.operations) {
654
663
  const outcomeKey = operationOutcomeKey(operation);
655
664
  if (!outcomeKey) {
@@ -747,7 +756,7 @@ function decideReceiptEligibility(input) {
747
756
  );
748
757
  continue;
749
758
  }
750
- if (create && !createSourceMatches(input.submission.composition, submitted, operation)) {
759
+ if (create && !createSourceMatches(savedProofs ??= savedProofIndex(input.submission.composition), submitted, operation)) {
751
760
  result.classification = "assigned-create-deferred";
752
761
  continue;
753
762
  }
@@ -1003,28 +1012,99 @@ function planMaterialization(input) {
1003
1012
  const setDecisions = eligibility.decisions.flatMap((decision) => decision.mode === "set" ? [decision] : []);
1004
1013
  const setByKey = new Map(setDecisions.map((decision) => [decision.documentKey, decision]));
1005
1014
  const demoted = /* @__PURE__ */ new Map();
1015
+ const current = currentMaterializationIndex(input.current);
1016
+ const headProof = { matched: /* @__PURE__ */ new Map() };
1006
1017
  for (; ; ) {
1007
- const result = planMaterializationAttempt(input, { setDecisions, setByKey, deletes, demoted });
1018
+ const result = planMaterializationAttempt(input, {
1019
+ setDecisions,
1020
+ setByKey,
1021
+ deletes,
1022
+ demoted,
1023
+ current,
1024
+ headProof
1025
+ });
1008
1026
  if (result.status !== "retry") return result;
1009
1027
  }
1010
1028
  }
1029
+ function currentMaterializationIndex(current) {
1030
+ const sourcesByFile = /* @__PURE__ */ new Map();
1031
+ current.sources.forEach((source, position) => {
1032
+ if (source.codec !== "grouped") return;
1033
+ const list = sourcesByFile.get(source.mapping.selector.file);
1034
+ if (list) list.push({ position, source });
1035
+ else sourcesByFile.set(source.mapping.selector.file, [{ position, source }]);
1036
+ });
1037
+ return {
1038
+ snapshot: indexSnapshot(resourceEvidence(current)),
1039
+ groupedBySource: (0, import_layoutCore.groupBySource)(current.grouped.sources, (candidate) => (0, import_layoutCore.sourceIdentityKey)(candidate.source)),
1040
+ groupedByFileSlot: (0, import_layoutCore.groupBySource)(
1041
+ current.grouped.sources,
1042
+ (candidate) => JSON.stringify([candidate.selector.file, candidate.selector.slot])
1043
+ ),
1044
+ observationsAt: (0, import_layoutCore.groupBySource)(
1045
+ current.grouped.observations,
1046
+ (observation) => (0, import_layoutCore.sourceSelectorKey)(observation.source, observation.selector)
1047
+ ),
1048
+ sourcesByFile
1049
+ };
1050
+ }
1051
+ function mergeByPosition(left, right) {
1052
+ const merged = [];
1053
+ let i = 0;
1054
+ let j = 0;
1055
+ while (i < left.length || j < right.length) {
1056
+ if (j >= right.length || i < left.length && left[i].position < right[j].position) merged.push(left[i++]);
1057
+ else if (i >= left.length || right[j].position < left[i].position) merged.push(right[j++]);
1058
+ else {
1059
+ merged.push(left[i++]);
1060
+ j++;
1061
+ }
1062
+ }
1063
+ return merged;
1064
+ }
1065
+ const fileTouch = (file) => `file\0${file}`;
1066
+ const sourceTouch = (source) => `source\0${(0, import_layoutCore.sourceIdentityKey)(source)}`;
1067
+ const keyTouch = (key) => `key\0${key}`;
1068
+ const groupedTouches = (source) => [
1069
+ sourceTouch(source.mapping.source),
1070
+ fileTouch(source.mapping.selector.file),
1071
+ fileTouch(source.destination.file)
1072
+ ];
1073
+ function settleFailures(failures, setByKey, demoted) {
1074
+ if (failures.length === 0) return void 0;
1075
+ const placed = (failure) => failure.keys.filter((key) => setByKey.has(key) && !demoted.has(key));
1076
+ if (placed(failures[0]).length === 0) return (0, import_layoutCore.blocked)([failures[0].item]);
1077
+ const read = /* @__PURE__ */ new Set();
1078
+ for (const [position, failure] of failures.entries()) {
1079
+ const touches = [...failure.keys.map(keyTouch), ...failure.touches];
1080
+ const coupled = position > 0 && touches.some((touch) => read.has(touch));
1081
+ for (const touch of touches) read.add(touch);
1082
+ if (coupled) continue;
1083
+ const pending = placed(failure);
1084
+ if (pending.length === 0) break;
1085
+ for (const key of pending) demoted.set(key, { reason: "unmaterialized", diagnostic: failure.item });
1086
+ }
1087
+ failures.length = 0;
1088
+ return { status: "retry" };
1089
+ }
1011
1090
  function planMaterializationAttempt(input, attempt) {
1012
1091
  const { eligibility } = input;
1013
1092
  const { setByKey, deletes, demoted } = attempt;
1014
1093
  const head = eligibility.headDocuments;
1015
- const currentIndex = indexSnapshot(resourceEvidence(input.current));
1094
+ const currentIndex = attempt.current.snapshot;
1016
1095
  const receiptResults = eligibility.receiptResults;
1017
1096
  const assignments = eligibility.assignments;
1018
1097
  const diagnostics = [];
1019
1098
  const perResource = [];
1020
1099
  const retry = { status: "retry" };
1021
- const fail = (key, item) => failMany(key === void 0 ? [] : [key], item);
1022
- const failMany = (keys, item) => {
1023
- const pending = keys.filter((key) => setByKey.has(key) && !demoted.has(key));
1024
- if (pending.length === 0) return (0, import_layoutCore.blocked)([item]);
1025
- for (const key of pending) demoted.set(key, { reason: "unmaterialized", diagnostic: item });
1026
- return retry;
1100
+ const failures = [];
1101
+ const fail = (key, touches, item) => {
1102
+ failures.push({ keys: key === void 0 ? [] : [key], touches, item });
1027
1103
  };
1104
+ const failMany = (keys, touches, item) => {
1105
+ failures.push({ keys, touches, item });
1106
+ };
1107
+ const settle = () => settleFailures(failures, setByKey, demoted);
1028
1108
  const materializations = eligibility.decisions.flatMap(
1029
1109
  (decision) => decision.mode === "preserve" || decision.mode === "keep-absent" || decision.mode === "suppressed" ? [(0, import_layoutCore.clone)(decision)] : []
1030
1110
  );
@@ -1101,7 +1181,7 @@ function planMaterializationAttempt(input, attempt) {
1101
1181
  detachedFileProofs: input.current.context.evidence.detachedFileProofs,
1102
1182
  canonicalBaseline: input.current.context.evidence.canonicalBaseline,
1103
1183
  groupedRoutes: input.current.context.evidence.groupedRoutes,
1104
- ...input.head ? { head: input.head, headDocuments: head } : {},
1184
+ ...input.head ? { head: input.head, headDocuments: head, headProof: attempt.headProof } : {},
1105
1185
  documents,
1106
1186
  documentKeys,
1107
1187
  intents,
@@ -1122,15 +1202,11 @@ function planMaterializationAttempt(input, attempt) {
1122
1202
  const siblingKey = tableSiblingKey(source.documentKey);
1123
1203
  if (!siblingKey || placedKeys.has(siblingKey)) continue;
1124
1204
  const siblingSource = decidedSourceByKey.get(siblingKey) ?? eligibility.submittedSources?.[siblingKey] ?? (0, import_layoutCore.stableSource)(siblingKey);
1125
- let siblingMappings = siblingSource ? input.current.grouped.sources.filter(
1126
- (candidate) => (0, import_layoutCore.sourceIdentityKey)(candidate.source) === (0, import_layoutCore.sourceIdentityKey)(siblingSource)
1127
- ) : [];
1205
+ let siblingMappings = siblingSource ? attempt.current.groupedBySource.get((0, import_layoutCore.sourceIdentityKey)(siblingSource)) ?? [] : [];
1128
1206
  const currentSource = setByKey.get(source.documentKey)?.current;
1129
1207
  if (siblingMappings.length !== 1 && currentSource?.codec === "grouped") {
1130
1208
  const slot = currentSource.mapping.selector.slot === "table-definition" ? "member-set" : "table-definition";
1131
- siblingMappings = input.current.grouped.sources.filter(
1132
- (candidate) => candidate.selector.file === currentSource.mapping.selector.file && candidate.selector.slot === slot
1133
- );
1209
+ siblingMappings = attempt.current.groupedByFileSlot.get(JSON.stringify([currentSource.mapping.selector.file, slot])) ?? [];
1134
1210
  }
1135
1211
  if (siblingMappings.length !== 1) {
1136
1212
  perResource.push({
@@ -1160,13 +1236,25 @@ function planMaterializationAttempt(input, attempt) {
1160
1236
  currentArtifacts: input.current.context.groupedArtifacts,
1161
1237
  current: input.current.grouped,
1162
1238
  vacating,
1239
+ rawKeyAssignments: placement.rawSources.map((source) => ({
1240
+ source: source.mapping.source,
1241
+ documentKey: source.documentKey
1242
+ })),
1163
1243
  ...eligibility.submissionProofs ? { submissionProofs: eligibility.submissionProofs.grouped } : {}
1164
1244
  });
1165
1245
  if (grouped.diagnostics.length > 0) return (0, import_layoutCore.blocked)(grouped.diagnostics);
1246
+ const patchesAt = (0, import_layoutCore.groupBySource)(grouped.patches, (patch) => (0, import_layoutCore.sourceSelectorKey)(patch.source, patch.selector));
1247
+ const patchesFor = (source) => patchesAt.get((0, import_layoutCore.sourceSelectorKey)(source.mapping.source, source.mapping.selector)) ?? [];
1248
+ const placedBySource = (0, import_layoutCore.groupBySource)(
1249
+ placement.groupedSources,
1250
+ (source) => (0, import_layoutCore.sourceIdentityKey)(source.mapping.source)
1251
+ );
1252
+ const placedByFile = (0, import_layoutCore.groupBySource)(placement.groupedSources, (source) => source.mapping.selector.file);
1166
1253
  const groupedCompanions = [];
1167
1254
  const companionTargets = /* @__PURE__ */ new Set();
1168
1255
  for (const patch of grouped.patches.filter((candidate) => candidate.selector.slot === "share-group-owner")) {
1169
1256
  const target = (0, import_documents.canonicalText)(patch.selector);
1257
+ if (companionTargets.has(target) && failures.length > 0) break;
1170
1258
  if (companionTargets.has(target))
1171
1259
  return (0, import_layoutCore.blocked)([
1172
1260
  (0, import_layoutCore.diagnostic)(
@@ -1176,34 +1264,36 @@ function planMaterializationAttempt(input, attempt) {
1176
1264
  )
1177
1265
  ]);
1178
1266
  companionTargets.add(target);
1179
- const headerProofs = input.current.grouped.observations.filter(
1180
- (observation) => observation.selector.slot === "share-group-owner" && (0, import_layoutCore.sameSelector)(observation.selector, patch.selector) && (0, import_layoutCore.sourceIdentityKey)(observation.source) === (0, import_layoutCore.sourceIdentityKey)(patch.source) && observation.currentHash !== void 0 && observation.currentHash === patch.expectedCurrentHash
1267
+ const headerProofs = (attempt.current.observationsAt.get((0, import_layoutCore.sourceSelectorKey)(patch.source, patch.selector)) ?? []).filter(
1268
+ (observation) => observation.selector.slot === "share-group-owner" && observation.currentHash !== void 0 && observation.currentHash === patch.expectedCurrentHash
1181
1269
  );
1182
- const authorizers = placement.groupedSources.filter((source) => {
1183
- if (source.mapping.selector.slot !== "share-entry" || source.mapping.selector.file !== patch.selector.file)
1184
- return false;
1270
+ const authorizers = (placedByFile.get(patch.selector.file) ?? []).filter((source) => {
1271
+ if (source.mapping.selector.slot !== "share-entry") return false;
1185
1272
  const document = placement.groupedDocuments[source.mapping.documentIndex];
1186
- const entryPatch = grouped.patches.filter(
1187
- (candidate) => (0, import_layoutCore.sameSelector)(candidate.selector, source.mapping.selector) && (0, import_layoutCore.sourceIdentityKey)(candidate.source) === (0, import_layoutCore.sourceIdentityKey)(source.mapping.source)
1188
- );
1273
+ const entryPatch = patchesFor(source);
1189
1274
  return document.kind === "share" && entryPatch.length === 1 && (0, import_layoutCore.same)(document.owner, patch.value);
1190
1275
  });
1191
1276
  const insertedGroup = authorizers.length > 0 && authorizers.every((source) => setByKey.get(source.documentKey)?.placement === "insert-authoritative");
1192
- if (headerProofs.length !== 1 && !insertedGroup || authorizers.length === 0)
1193
- return failMany(
1194
- placement.groupedSources.filter((source) => source.mapping.selector.file === patch.selector.file).map((source) => source.documentKey),
1277
+ if (headerProofs.length !== 1 && !insertedGroup || authorizers.length === 0) {
1278
+ failMany(
1279
+ (placedByFile.get(patch.selector.file) ?? []).map((source) => source.documentKey),
1280
+ [fileTouch(patch.selector.file)],
1195
1281
  (0, import_layoutCore.diagnostic)(
1196
1282
  "unbound-share-group-companion",
1197
1283
  patch.selector.file,
1198
1284
  "Share group header candidate lacks exact accepted-entry proof"
1199
1285
  )
1200
1286
  );
1287
+ continue;
1288
+ }
1201
1289
  groupedCompanions.push({
1202
1290
  kind: "share-group-owner",
1203
1291
  authorizingDocumentKeys: authorizers.map((source) => source.documentKey),
1204
1292
  patch: (0, import_layoutCore.clone)(patch)
1205
1293
  });
1206
1294
  }
1295
+ const afterCompanions = settle();
1296
+ if (afterCompanions) return afterCompanions;
1207
1297
  const ownerDocuments = placement.groupedSources.flatMap((placedSource) => {
1208
1298
  const document = placement.groupedDocuments[placedSource.mapping.documentIndex];
1209
1299
  return (0, import_layoutCore.attachmentField)(document) ? [
@@ -1264,59 +1354,86 @@ function planMaterializationAttempt(input, attempt) {
1264
1354
  if (documentKey) decidedDocumentKeys.add(documentKey);
1265
1355
  decidedSources.add(sourceKey);
1266
1356
  };
1357
+ const undecidedByFile = new Map(attempt.current.sourcesByFile);
1358
+ const undecided = (entry) => {
1359
+ const documentKey = stableSourceKey(entry.source.mapping.source);
1360
+ const sourceKey = (0, import_layoutCore.sourceIdentityKey)(entry.source.mapping.source);
1361
+ return !(documentKey && (physicallySet.has(documentKey) || decidedDocumentKeys.has(documentKey)) || physicallySetSources.has(sourceKey) || decidedSources.has(sourceKey));
1362
+ };
1267
1363
  for (const placedSource of placement.groupedSources) {
1268
- const files = /* @__PURE__ */ new Set([placedSource.mapping.selector.file, placedSource.destination.file]);
1269
- for (const source of input.current.sources)
1270
- if (source.codec === "grouped" && files.has(source.mapping.selector.file))
1271
- preserveSharedSource(source, placedSource.documentKey);
1364
+ const files = [.../* @__PURE__ */ new Set([placedSource.mapping.selector.file, placedSource.destination.file])];
1365
+ const lists = files.map((file) => undecidedByFile.get(file) ?? []);
1366
+ const entries = lists.length === 1 ? lists[0] : mergeByPosition(lists[0], lists[1]);
1367
+ for (const entry of entries) preserveSharedSource(entry.source, placedSource.documentKey);
1368
+ for (const file of files) {
1369
+ const list = undecidedByFile.get(file);
1370
+ if (list) undecidedByFile.set(file, list.filter(undecided));
1371
+ }
1272
1372
  }
1273
1373
  const afterSiblingSources = checkpoint();
1274
1374
  if (afterSiblingSources) return afterSiblingSources;
1275
1375
  const attachmentDestinations = /* @__PURE__ */ new Map();
1276
1376
  for (const patch of binary.ownerPatches) {
1277
- const placedOwner = placement.groupedSources.filter(
1278
- (source) => (0, import_layoutCore.sourceIdentityKey)(source.mapping.source) === (0, import_layoutCore.sourceIdentityKey)(patch.source) && source.mapping.selector.file === patch.ownerFile && (0, import_layoutCore.attachmentField)(placement.groupedDocuments[source.mapping.documentIndex]) === patch.field
1377
+ const placedOwner = (placedBySource.get((0, import_layoutCore.sourceIdentityKey)(patch.source)) ?? []).filter(
1378
+ (source) => source.mapping.selector.file === patch.ownerFile && (0, import_layoutCore.attachmentField)(placement.groupedDocuments[source.mapping.documentIndex]) === patch.field
1279
1379
  );
1280
1380
  const placedAttachment = placement.attachments.filter(
1281
- (attachment) => (0, import_layoutCore.sourceIdentityKey)(attachment.source) === (0, import_layoutCore.sourceIdentityKey)(patch.source) && attachment.field === patch.field && (patch.origin === "authoritative-insertion" ? attachment.current === void 0 && attachment.destination.ownerFile === patch.ownerFile : attachment.current?.ownerFile === patch.ownerFile)
1381
+ (attachment) => attachment.field === patch.field && (patch.origin === "authoritative-insertion" ? (0, import_layoutCore.sourceIdentityKey)(attachment.source) === (0, import_layoutCore.sourceIdentityKey)(patch.source) && attachment.current === void 0 && attachment.destination.ownerFile === patch.ownerFile : attachment.current !== void 0 && (0, import_layoutCore.sourceIdentityKey)(attachment.current.ownerSource) === (0, import_layoutCore.sourceIdentityKey)(patch.source) && attachment.current.ownerFile === patch.ownerFile)
1282
1382
  );
1283
1383
  const ownerSet = placedOwner.flatMap(
1284
- (source) => grouped.patches.filter(
1285
- (candidate) => candidate.action === "set" && (0, import_layoutCore.sourceIdentityKey)(candidate.source) === (0, import_layoutCore.sourceIdentityKey)(source.mapping.source) && (0, import_layoutCore.sameSelector)(candidate.selector, source.mapping.selector) && (0, import_layoutCore.same)(candidate.value, placement.groupedDocuments[source.mapping.documentIndex])
1384
+ (source) => patchesFor(source).filter(
1385
+ (candidate) => candidate.action === "set" && (0, import_layoutCore.same)(candidate.value, placement.groupedDocuments[source.mapping.documentIndex])
1286
1386
  )
1287
1387
  );
1288
1388
  const authoritativeValue = placedOwner.length === 1 ? placement.groupedDocuments[placedOwner[0].mapping.documentIndex][patch.field] : void 0;
1289
1389
  const descriptorMatches = patch.action === "set" ? (0, import_layoutCore.same)(patch.value, authoritativeValue) : authoritativeValue === null || authoritativeValue === void 0 && patch.field === "icon";
1290
1390
  const currentHashMatches = patch.origin === "authoritative-insertion" ? placedAttachment.length === 1 && placedAttachment[0].current === void 0 && placedOwner[0]?.mode === "insert-authoritative" && patch.groupedSelector.file === placedOwner[0]?.destination.file : placedAttachment.length === 1 && patch.expectedCurrentHash === placedAttachment[0].current?.currentHash;
1291
- if (placedOwner.length !== 1 || placedAttachment.length !== 1 || ownerSet.length !== 1 || !(0, import_layoutCore.same)(patch.ownerDocument, placement.groupedDocuments[placedOwner[0]?.mapping.documentIndex]) || !descriptorMatches || !currentHashMatches)
1292
- return fail(
1391
+ if (placedOwner.length !== 1 || placedAttachment.length !== 1 || ownerSet.length !== 1 || !(0, import_layoutCore.same)(patch.ownerDocument, placement.groupedDocuments[placedOwner[0]?.mapping.documentIndex]) || !descriptorMatches || !currentHashMatches) {
1392
+ fail(
1293
1393
  placedOwner[0]?.documentKey ?? stableSourceKey(patch.source),
1394
+ [
1395
+ fileTouch(patch.ownerFile),
1396
+ sourceTouch(patch.source),
1397
+ ...patch.bytes ? [fileTouch(patch.bytes)] : [],
1398
+ ...placedOwner.flatMap((source) => [
1399
+ keyTouch(source.documentKey),
1400
+ fileTouch(source.destination.file)
1401
+ ]),
1402
+ ...placedAttachment.flatMap(
1403
+ (attachment) => attachment.destination.bytes ? [fileTouch(attachment.destination.bytes)] : []
1404
+ )
1405
+ ],
1294
1406
  (0, import_layoutCore.diagnostic)(
1295
1407
  "unpaired-attachment-patch",
1296
1408
  patch.ownerFile,
1297
1409
  "Attachment candidate does not match one whole-owner set"
1298
1410
  )
1299
1411
  );
1412
+ continue;
1413
+ }
1300
1414
  attachmentDestinations.set(
1301
1415
  `${(0, import_layoutCore.sourceIdentityKey)(patch.source)}/${patch.field}`,
1302
1416
  (0, import_layoutCore.clone)(placedAttachment[0].destination)
1303
1417
  );
1304
1418
  }
1419
+ const afterAttachments = settle();
1420
+ if (afterAttachments) return afterAttachments;
1305
1421
  for (const source of placement.groupedSources) {
1306
1422
  const candidate = setByKey.get(source.documentKey);
1307
- const patches = grouped.patches.filter(
1308
- (patch) => (0, import_layoutCore.sourceIdentityKey)(patch.source) === (0, import_layoutCore.sourceIdentityKey)(source.mapping.source) && (0, import_layoutCore.sameSelector)(patch.selector, source.mapping.selector)
1309
- );
1423
+ const patches = patchesFor(source);
1310
1424
  const expectedValue = mappingValue(candidate.document, source.mapping);
1311
- if (patches.length !== 1 || patches[0].action !== "set" || expectedValue === void 0 || !(0, import_layoutCore.same)(patches[0].value, expectedValue))
1312
- return fail(
1425
+ if (patches.length !== 1 || patches[0].action !== "set" || expectedValue === void 0 || !(0, import_layoutCore.same)(patches[0].value, expectedValue)) {
1426
+ fail(
1313
1427
  source.documentKey,
1428
+ groupedTouches(source),
1314
1429
  (0, import_layoutCore.diagnostic)(
1315
1430
  "invalid-accepted-patch",
1316
1431
  source.documentKey,
1317
1432
  "Grouped set does not match accepted current and authoritative evidence"
1318
1433
  )
1319
1434
  );
1435
+ continue;
1436
+ }
1320
1437
  materializations.push({
1321
1438
  mode: "set",
1322
1439
  codec: "grouped",
@@ -1329,20 +1446,30 @@ function planMaterializationAttempt(input, attempt) {
1329
1446
  patches: (0, import_layoutCore.clone)(patches)
1330
1447
  });
1331
1448
  }
1449
+ const afterGroupedSets = settle();
1450
+ if (afterGroupedSets) return afterGroupedSets;
1451
+ const rawPatchesBySource = (0, import_layoutCore.groupBySource)(binary.rawPatches, (patch) => (0, import_layoutCore.sourceIdentityKey)(patch.source));
1332
1452
  for (const source of placement.rawSources) {
1333
1453
  const candidate = setByKey.get(source.documentKey);
1334
- const patches = binary.rawPatches.filter(
1335
- (patch) => (0, import_layoutCore.sourceIdentityKey)(patch.source) === (0, import_layoutCore.sourceIdentityKey)(source.mapping.source)
1336
- );
1337
- if (patches.length !== 1 || patches[0].action !== "set" || !sameBinarySelector(patches[0].selector, source.mapping.selector) || !(0, import_layoutCore.same)(patches[0].document, candidate.document) || patches[0].bytes !== source.mapping.bytes || !(0, import_layoutCore.same)(patches[0].content, candidate.document.content))
1338
- return fail(
1454
+ const patches = rawPatchesBySource.get((0, import_layoutCore.sourceIdentityKey)(source.mapping.source)) ?? [];
1455
+ if (patches.length !== 1 || patches[0].action !== "set" || !sameBinarySelector(patches[0].selector, source.mapping.selector) || !(0, import_layoutCore.same)(patches[0].document, candidate.document) || patches[0].bytes !== source.mapping.bytes || !(0, import_layoutCore.same)(patches[0].content, candidate.document.content)) {
1456
+ fail(
1339
1457
  source.documentKey,
1458
+ [
1459
+ sourceTouch(source.mapping.source),
1460
+ fileTouch(source.mapping.selector.sidecar),
1461
+ fileTouch(source.mapping.bytes),
1462
+ fileTouch(source.destination.sidecar),
1463
+ fileTouch(source.bytes)
1464
+ ],
1340
1465
  (0, import_layoutCore.diagnostic)(
1341
1466
  "invalid-accepted-patch",
1342
1467
  source.documentKey,
1343
1468
  "Raw set does not match accepted current and authoritative evidence"
1344
1469
  )
1345
1470
  );
1471
+ continue;
1472
+ }
1346
1473
  materializations.push({
1347
1474
  mode: "set",
1348
1475
  codec: "raw",
@@ -1356,13 +1483,13 @@ function planMaterializationAttempt(input, attempt) {
1356
1483
  patch: (0, import_layoutCore.clone)(patches[0])
1357
1484
  });
1358
1485
  }
1486
+ const afterRawSets = settle();
1487
+ if (afterRawSets) return afterRawSets;
1359
1488
  const attachments = binary.ownerPatches.map((patch) => {
1360
- const ownerDocumentKey = placement.groupedSources.find(
1361
- (source) => (0, import_layoutCore.sourceIdentityKey)(source.mapping.source) === (0, import_layoutCore.sourceIdentityKey)(patch.source)
1362
- )?.documentKey ?? stableSourceKey(patch.source);
1489
+ const ownerDocumentKey = placedBySource.get((0, import_layoutCore.sourceIdentityKey)(patch.source))?.[0]?.documentKey ?? stableSourceKey(patch.source);
1363
1490
  const destination = attachmentDestinations.get(`${(0, import_layoutCore.sourceIdentityKey)(patch.source)}/${patch.field}`);
1364
- const retainedNull = patch.action === "clear" && input.current.binary.ownerFields.some(
1365
- (field) => (0, import_layoutCore.sourceIdentityKey)(field.ownerSource) === (0, import_layoutCore.sourceIdentityKey)(patch.source) && field.field === patch.field && field.status === "value" && field.value === null
1491
+ const retainedNull = patch.action === "clear" && (currentIndex.ownerFields.get((0, import_layoutCore.sourceIdentityKey)(patch.source)) ?? []).some(
1492
+ (field) => field.field === patch.field && field.status === "value" && field.value === null
1366
1493
  );
1367
1494
  return retainedNull ? {
1368
1495
  mode: "known-null",
@@ -1372,12 +1499,17 @@ function planMaterializationAttempt(input, attempt) {
1372
1499
  field: patch.field
1373
1500
  } : { mode: patch.action, ownerDocumentKey, patch: (0, import_layoutCore.clone)(patch), destination };
1374
1501
  });
1502
+ const attachmentKey = (ownerDocumentKey, field) => `${ownerDocumentKey}\0${field}`;
1503
+ const attachedFields = new Set(
1504
+ attachments.map(
1505
+ (candidate) => attachmentKey(candidate.ownerDocumentKey, "patch" in candidate ? candidate.patch.field : candidate.field)
1506
+ )
1507
+ );
1375
1508
  for (const source of placement.groupedSources) {
1376
1509
  const document = placement.groupedDocuments[source.mapping.documentIndex];
1377
1510
  const nullField = knownNull(document);
1378
- if (nullField && !attachments.some(
1379
- (candidate) => candidate.ownerDocumentKey === source.documentKey && ("patch" in candidate ? candidate.patch.field : candidate.field) === nullField.field
1380
- ))
1511
+ if (nullField && !attachedFields.has(attachmentKey(source.documentKey, nullField.field))) {
1512
+ attachedFields.add(attachmentKey(source.documentKey, nullField.field));
1381
1513
  attachments.push({
1382
1514
  mode: "known-null",
1383
1515
  ownerDocumentKey: source.documentKey,
@@ -1385,14 +1517,12 @@ function planMaterializationAttempt(input, attempt) {
1385
1517
  ownerFile: source.destination.file,
1386
1518
  field: nullField.field
1387
1519
  });
1520
+ }
1388
1521
  }
1389
1522
  for (const source of placement.groupedSources) {
1390
1523
  const document = placement.groupedDocuments[source.mapping.documentIndex];
1391
1524
  const field = (0, import_layoutCore.attachmentField)(document);
1392
- if (!field || attachments.some(
1393
- (candidate) => candidate.ownerDocumentKey === source.documentKey && ("patch" in candidate ? candidate.patch.field : candidate.field) === field
1394
- ))
1395
- continue;
1525
+ if (!field || attachedFields.has(attachmentKey(source.documentKey, field))) continue;
1396
1526
  const projection = coherentPreservedAttachment(
1397
1527
  input.current,
1398
1528
  source.mapping.source,
@@ -1400,15 +1530,19 @@ function planMaterializationAttempt(input, attempt) {
1400
1530
  field,
1401
1531
  document[field]
1402
1532
  );
1403
- if (!projection)
1404
- return fail(
1533
+ if (!projection) {
1534
+ fail(
1405
1535
  source.documentKey,
1536
+ groupedTouches(source),
1406
1537
  (0, import_layoutCore.diagnostic)(
1407
1538
  "incoherent-accepted-attachment",
1408
1539
  source.destination.file,
1409
1540
  "Accepted owner attachment has no coherent current association"
1410
1541
  )
1411
1542
  );
1543
+ continue;
1544
+ }
1545
+ attachedFields.add(attachmentKey(source.documentKey, field));
1412
1546
  attachments.push({
1413
1547
  mode: "preserve",
1414
1548
  ownerDocumentKey: source.documentKey,
@@ -1418,6 +1552,8 @@ function planMaterializationAttempt(input, attempt) {
1418
1552
  ...projection.bytes ? { bytes: projection.bytes } : {}
1419
1553
  });
1420
1554
  }
1555
+ const afterOwnerFields = settle();
1556
+ if (afterOwnerFields) return afterOwnerFields;
1421
1557
  const setKeys = new Set(
1422
1558
  materializations.filter((decision) => decision.mode === "set").map((decision) => decision.documentKey)
1423
1559
  );
@@ -1504,18 +1640,48 @@ function holdFolders(current, decisions) {
1504
1640
  ...scan.localOnlyFiles,
1505
1641
  ...scan.opaqueDirectories
1506
1642
  ];
1643
+ const byDirectory = (items, pathsOf) => {
1644
+ const index = /* @__PURE__ */ new Map();
1645
+ for (const item of items) {
1646
+ const directories = new Set(pathsOf(item).flatMap((path) => (0, import_layoutCore.pathAncestors)(path)));
1647
+ for (const directory of directories) {
1648
+ const list = index.get(directory);
1649
+ if (list) list.push(item);
1650
+ else index.set(directory, [item]);
1651
+ }
1652
+ }
1653
+ return index;
1654
+ };
1655
+ const occupiedIn = byDirectory(occupied, (path) => [path]);
1656
+ const setsIn = byDirectory(
1657
+ decisions.filter((decision) => decision.mode === "set"),
1658
+ decisionPaths
1659
+ );
1660
+ const leavingCount = /* @__PURE__ */ new Map();
1661
+ const movingByKey = /* @__PURE__ */ new Map();
1662
+ const countLeaving = (decision, delta) => {
1663
+ for (const path of new Set(decisionPaths(decision)))
1664
+ leavingCount.set(path, (leavingCount.get(path) ?? 0) + delta);
1665
+ };
1666
+ for (const decision of decisions)
1667
+ if (decision.mode === "set" || decision.mode === "remove") {
1668
+ countLeaving(decision, 1);
1669
+ const moving = movingByKey.get(decision.documentKey);
1670
+ if (moving) moving.push(decision);
1671
+ else movingByKey.set(decision.documentKey, [decision]);
1672
+ }
1507
1673
  const heldKeys = /* @__PURE__ */ new Set();
1674
+ const hold = (key) => {
1675
+ if (heldKeys.has(key)) return;
1676
+ heldKeys.add(key);
1677
+ for (const decision of movingByKey.get(key) ?? []) countLeaving(decision, -1);
1678
+ };
1508
1679
  const heldDirectories = /* @__PURE__ */ new Set();
1509
1680
  for (let changed = true; changed; ) {
1510
1681
  changed = false;
1511
1682
  for (const candidate of candidates) {
1512
1683
  if (heldDirectories.has(candidate.directory)) continue;
1513
- const leaving = new Set(
1514
- decisions.flatMap(
1515
- (decision) => (decision.mode === "set" || decision.mode === "remove") && !heldKeys.has(decision.documentKey) ? decisionPaths(decision) : []
1516
- )
1517
- );
1518
- const blockers = occupied.filter((path) => inside(path, candidate.directory) && !leaving.has(path)).sort(import_layoutCore.compareText);
1684
+ const blockers = (occupiedIn.get(candidate.directory) ?? []).filter((path) => !leavingCount.get(path)).sort(import_layoutCore.compareText);
1519
1685
  const detached = hasDetachedDescendants(
1520
1686
  candidate.mapping,
1521
1687
  candidate.directory,
@@ -1525,10 +1691,8 @@ function holdFolders(current, decisions) {
1525
1691
  );
1526
1692
  if (blockers.length === 0 && !detached) continue;
1527
1693
  heldDirectories.add(candidate.directory);
1528
- heldKeys.add(candidate.decision.documentKey);
1529
- for (const decision of decisions)
1530
- if (decision.mode === "set" && decisionPaths(decision).some((path) => inside(path, candidate.directory)))
1531
- heldKeys.add(decision.documentKey);
1694
+ hold(candidate.decision.documentKey);
1695
+ for (const decision of setsIn.get(candidate.directory) ?? []) hold(decision.documentKey);
1532
1696
  changed = true;
1533
1697
  }
1534
1698
  }
@@ -1546,7 +1710,7 @@ function holdFolders(current, decisions) {
1546
1710
  const notices = [...heldDirectories].filter((directory) => ![...heldDirectories].some((other) => inside(directory, other))).map((directory) => ({
1547
1711
  status: "kept-in-place",
1548
1712
  path: directory,
1549
- paths: occupied.filter((path) => inside(path, directory) && !spared.has(path)).sort(import_layoutCore.compareText)
1713
+ paths: (occupiedIn.get(directory) ?? []).filter((path) => !spared.has(path)).sort(import_layoutCore.compareText)
1550
1714
  }));
1551
1715
  const output = decisions.map(
1552
1716
  (decision) => (decision.mode === "set" || heldRemoval(decision)) && heldKeys.has(decision.documentKey ?? "") ? {
@@ -1631,7 +1795,7 @@ function decideCheckoutEligibility(input) {
1631
1795
  continue;
1632
1796
  }
1633
1797
  if (!authoritative) {
1634
- if (resource.presence === "absent") decisions.push({ mode: "noop", documentKey });
1798
+ if (resource.presence === "absent") remove();
1635
1799
  else if (resource.contributors.every(contributorIsClean)) remove();
1636
1800
  else preserve("kept-local-edits");
1637
1801
  continue;
@@ -1671,7 +1835,7 @@ function decideCheckoutEligibility(input) {
1671
1835
  function sameRawSelector(left, right) {
1672
1836
  return left.sidecar === right.sidecar && (0, import_documents.canonicalText)(left.identity) === (0, import_documents.canonicalText)(right.identity);
1673
1837
  }
1674
- function renderingIndex(context) {
1838
+ function renderingIndex(context, proofs) {
1675
1839
  return {
1676
1840
  grouped: (0, import_layoutCore.groupBySource)(context.grouped.observations, (observation) => (0, import_layoutCore.sourceIdentityKey)(observation.source)),
1677
1841
  raw: (0, import_layoutCore.groupBySource)(context.binary.rawObservations, (observation) => (0, import_layoutCore.sourceIdentityKey)(observation.source)),
@@ -1684,7 +1848,8 @@ function renderingIndex(context) {
1684
1848
  context.authored.artifacts.filter((artifact) => artifact.present),
1685
1849
  (artifact) => artifact.path
1686
1850
  ),
1687
- ownerFields: (0, import_layoutCore.groupBySource)(context.binary.ownerFields, (field) => (0, import_layoutCore.sourceIdentityKey)(field.ownerSource))
1851
+ ownerFields: (0, import_layoutCore.groupBySource)(context.binary.ownerFields, (field) => (0, import_layoutCore.sourceIdentityKey)(field.ownerSource)),
1852
+ proofsByToken: (0, import_layoutCore.groupBySource)(proofs, (proof) => proof.source.token)
1688
1853
  };
1689
1854
  }
1690
1855
  function observationForGrouped(index, source, selector) {
@@ -1730,6 +1895,7 @@ function insertedRole(file) {
1730
1895
  if (file.endsWith("/_folder.json")) return "folder-control";
1731
1896
  if ((0, import_layoutPaths.isRawSidecarPath)(file)) return "raw-metadata";
1732
1897
  if (file === "definitions/settings.json") return "settings";
1898
+ if (file === "definitions/global_locks.json") return "global-locks";
1733
1899
  for (const [root, role] of INSERTED_ROLES) if (file.startsWith(root)) return role;
1734
1900
  return "document";
1735
1901
  }
@@ -1739,6 +1905,8 @@ function insertedArtifact(file, owner) {
1739
1905
  return { path: file, kind: "file", role, present: false, json };
1740
1906
  }
1741
1907
  function detachedBuckets(origin) {
1908
+ const anchor = (0, import_layoutPaths.sharedAnchorDirectory)(origin);
1909
+ if (anchor) return [import_layoutPaths.SHARED_ROOT, anchor.directory].map((path) => ({ kind: "directory", path }));
1742
1910
  if (!origin.startsWith("detached/")) return [];
1743
1911
  return (0, import_layoutCore.pathAncestors)(origin).map((path) => ({ kind: "directory", path }));
1744
1912
  }
@@ -1824,12 +1992,13 @@ function outputRole(artifact, value) {
1824
1992
  if (artifact.role === "share-group") return "share-group";
1825
1993
  return value.kind === "dimension_table" ? "combined-table" : "document";
1826
1994
  }
1827
- function shareEntryIndex(index, proofs, entries, selector, source) {
1995
+ function shareEntryIndex(index, entries, selector, source) {
1828
1996
  if (!("transient" in selector.identity)) return shareIdentityIndex(entries, selector);
1829
1997
  const observation = observationForGrouped(index, source, selector);
1830
1998
  if (!observation?.currentHash) return -1;
1831
- const proven = proofs.filter(
1832
- (proof) => proof.source.token === selector.identity.transient && (0, import_layoutCore.sameSelector)(proof.selector, selector) && (0, import_layoutCore.samePath)(proof.sourcePath, observation.sourcePath) && proof.fragmentHash === observation.currentHash
1999
+ const token = selector.identity.transient;
2000
+ const proven = (index.proofsByToken.get(token) ?? []).filter(
2001
+ (proof) => (0, import_layoutCore.sameSelector)(proof.selector, selector) && (0, import_layoutCore.samePath)(proof.sourcePath, observation.sourcePath) && proof.fragmentHash === observation.currentHash
1833
2002
  );
1834
2003
  if (proven.length !== 1) return -1;
1835
2004
  const sourcePath = observation.sourcePath;
@@ -1847,30 +2016,67 @@ function shareIdentityIndex(entries, selector) {
1847
2016
  });
1848
2017
  return matches.length === 1 ? matches[0] : -1;
1849
2018
  }
2019
+ function shareIdentityPositions(entries) {
2020
+ const byField = { id: /* @__PURE__ */ new Map(), key: /* @__PURE__ */ new Map() };
2021
+ const track = (position, add) => {
2022
+ const candidate = (0, import_layoutCore.object)(entries[position]);
2023
+ if (!candidate) return;
2024
+ for (const field of ["id", "key"]) {
2025
+ const value = candidate[field];
2026
+ if (value === void 0) continue;
2027
+ let positions = byField[field].get(value);
2028
+ if (add) byField[field].set(value, (positions ??= /* @__PURE__ */ new Set()).add(position));
2029
+ else positions?.delete(position);
2030
+ }
2031
+ };
2032
+ entries.forEach((_, position) => track(position, true));
2033
+ return {
2034
+ find(selector) {
2035
+ if ("transient" in selector.identity) return void 0;
2036
+ const field = "id" in selector.identity ? "id" : "key";
2037
+ const value = "id" in selector.identity ? selector.identity.id : selector.identity.key;
2038
+ if (value === void 0) return shareIdentityIndex(entries, selector);
2039
+ const matches = byField[field].get(value);
2040
+ return matches?.size === 1 ? matches.values().next().value : -1;
2041
+ },
2042
+ set(position, entry) {
2043
+ if (position < entries.length) track(position, false);
2044
+ entries[position] = entry;
2045
+ track(position, true);
2046
+ }
2047
+ };
2048
+ }
1850
2049
  function groupedPatchKey(selector) {
1851
2050
  return (0, import_documents.canonicalText)(selector);
1852
2051
  }
1853
2052
  function rawPatchKey(set) {
1854
2053
  return set.destination.sidecar;
1855
2054
  }
1856
- function ownerNavigationTarget(context, ownerKey2) {
2055
+ function ownerNavigationIndex(context) {
2056
+ const dirtyFiles = /* @__PURE__ */ new Set();
2057
+ for (const observation of context.grouped.observations)
2058
+ if (observation.state !== "clean") dirtyFiles.add(observation.selector.file);
2059
+ for (const observation of context.binary.rawObservations)
2060
+ if (observation.selector.slot === "file-entry" && observation.state !== "clean")
2061
+ dirtyFiles.add(observation.selector.sidecar);
2062
+ return {
2063
+ documentsBySource: (0, import_layoutCore.groupBySource)(
2064
+ context.grouped.sources.filter((mapping) => mapping.selector.slot === "document"),
2065
+ (mapping) => (0, import_layoutCore.sourceIdentityKey)(mapping.source)
2066
+ ),
2067
+ rawBySource: (0, import_layoutCore.groupBySource)(context.binary.rawSources, (mapping) => (0, import_layoutCore.sourceIdentityKey)(mapping.source)),
2068
+ dirtyFiles
2069
+ };
2070
+ }
2071
+ function ownerNavigationTarget(index, ownerKey2) {
1857
2072
  const source = (0, import_layoutCore.stableSource)(ownerKey2);
1858
2073
  if (!source) return void 0;
1859
2074
  const key = (0, import_layoutCore.sourceIdentityKey)(source);
1860
- const grouped = context.grouped.sources.filter(
1861
- (mapping) => (0, import_layoutCore.sourceIdentityKey)(mapping.source) === key && mapping.selector.slot === "document"
1862
- );
2075
+ const grouped = index.documentsBySource.get(key) ?? [];
1863
2076
  if (grouped.length === 1) return { file: grouped[0].selector.file };
1864
- const raw = context.binary.rawSources.filter((mapping) => (0, import_layoutCore.sourceIdentityKey)(mapping.source) === key);
2077
+ const raw = index.rawBySource.get(key) ?? [];
1865
2078
  return raw.length === 1 ? { file: raw[0].selector.sidecar } : void 0;
1866
2079
  }
1867
- function containerFragmentsAreClean(context, file) {
1868
- return context.grouped.observations.every(
1869
- (observation) => observation.selector.file !== file || observation.state === "clean"
1870
- ) && context.binary.rawObservations.every(
1871
- (observation) => observation.selector.slot !== "file-entry" || observation.selector.sidecar !== file || observation.state === "clean"
1872
- );
1873
- }
1874
2080
  const KEYED_CHILD_KINDS = /* @__PURE__ */ new Set(["sheet_line", "tile"]);
1875
2081
  function withoutId(value) {
1876
2082
  return (0, import_layoutCore.without)(value, ["id"]);
@@ -1991,9 +2197,11 @@ function renderIdentityPatches(readback, index, json, notices) {
1991
2197
  const removed = new Set(
1992
2198
  readback.deletes.json.map((removal) => removal.path).concat(readback.deletes.bytes.map((removal) => removal.path))
1993
2199
  );
2200
+ const firstByPath = /* @__PURE__ */ new Map();
2201
+ for (const artifact of json) if (!firstByPath.has(artifact.path)) firstByPath.set(artifact.path, artifact);
1994
2202
  for (const patch of readback.identityPatches) {
1995
2203
  if (removed.has(patch.container)) continue;
1996
- const target = json.find((candidate) => candidate.path === patch.container);
2204
+ const target = firstByPath.get(patch.container);
1997
2205
  const artifact = authoredArtifact(index, patch.container);
1998
2206
  const authored = artifact && (0, import_layoutCore.object)(artifact.json);
1999
2207
  if (!artifact || !authored) {
@@ -2011,7 +2219,6 @@ function renderIdentityPatches(readback, index, json, notices) {
2011
2219
  const shares = Array.isArray(container.shares) ? container.shares : [];
2012
2220
  const at = patch.shareIdentity ? shareEntryIndex(
2013
2221
  index,
2014
- readback.submissionProofs,
2015
2222
  shares,
2016
2223
  { file: patch.container, slot: "share-entry", identity: patch.shareIdentity },
2017
2224
  patch.source
@@ -2031,13 +2238,16 @@ function renderIdentityPatches(readback, index, json, notices) {
2031
2238
  for (const key of result.keys) notices.push({ status: "ambiguous-patch", path: patch.container, key });
2032
2239
  continue;
2033
2240
  }
2034
- if (!target)
2035
- json.push({
2241
+ if (!target) {
2242
+ const rendered = {
2036
2243
  path: patch.container,
2037
2244
  role: outputRole(artifact, container),
2038
2245
  value: container,
2039
2246
  authorizingDocumentKeys: []
2040
- });
2247
+ };
2248
+ json.push(rendered);
2249
+ firstByPath.set(patch.container, rendered);
2250
+ }
2041
2251
  }
2042
2252
  }
2043
2253
  function renderRemovals(readback, index, json, diagnostics, notices, retainedKeys) {
@@ -2119,7 +2329,7 @@ function planReceiptRendering(input) {
2119
2329
  function renderReceiptAttempt(input, excluded) {
2120
2330
  const { readback } = input;
2121
2331
  const context = readback.renderingContext;
2122
- const index = renderingIndex(context);
2332
+ const index = renderingIndex(context, readback.submissionProofs);
2123
2333
  const diagnostics = [];
2124
2334
  const perResource = [];
2125
2335
  const groupedSets = readback.materializations.filter(
@@ -2184,7 +2394,9 @@ function renderReceiptAttempt(input, excluded) {
2184
2394
  continue;
2185
2395
  }
2186
2396
  groupedOrigin.set(set.destination.file, originFile);
2187
- groupedByFile.set(set.destination.file, [...groupedByFile.get(set.destination.file) ?? [], { set, patch }]);
2397
+ const inFile = groupedByFile.get(set.destination.file);
2398
+ if (inFile) inFile.push({ set, patch });
2399
+ else groupedByFile.set(set.destination.file, [{ set, patch }]);
2188
2400
  }
2189
2401
  for (const set of rawSets) {
2190
2402
  const patch = set.patch;
@@ -2263,21 +2475,21 @@ function renderReceiptAttempt(input, excluded) {
2263
2475
  }
2264
2476
  }
2265
2477
  const companionsByFile = /* @__PURE__ */ new Map();
2478
+ const setsByDestination = (0, import_layoutCore.groupBySource)(groupedSets, (set) => set.destination.file);
2266
2479
  for (const companion of readback.groupedCompanions) {
2267
2480
  const patch = companion.patch;
2268
- const selectedShares = groupedSets.filter(
2269
- (set) => set.destination.file === patch.selector.file && set.destination.slot === "share-entry" && companion.authorizingDocumentKeys.includes(set.documentKey)
2270
- );
2271
- const allAuthorizersSelected = companion.authorizingDocumentKeys.length > 0 && companion.authorizingDocumentKeys.every(
2272
- (key) => groupedSets.some(
2273
- (set) => set.documentKey === key && set.destination.file === patch.selector.file && set.destination.slot === "share-entry"
2274
- )
2481
+ const authorizing = new Set(companion.authorizingDocumentKeys);
2482
+ const shareSets = (setsByDestination.get(patch.selector.file) ?? []).filter(
2483
+ (set) => set.destination.slot === "share-entry"
2275
2484
  );
2485
+ const selectedShares = shareSets.filter((set) => authorizing.has(set.documentKey));
2486
+ const shareSetKeys = new Set(shareSets.map((set) => set.documentKey));
2487
+ const allAuthorizersSelected = companion.authorizingDocumentKeys.length > 0 && companion.authorizingDocumentKeys.every((key) => shareSetKeys.has(key));
2276
2488
  const observation = observationForGrouped(index, patch.source, patch.selector);
2277
2489
  const insertedGroup = selectedShares.every((set) => set.placement === "insert-authoritative");
2278
2490
  if (patch.action !== "set" || patch.selector.slot !== "share-group-owner" || selectedShares.length === 0 || !allAuthorizersSelected || companionsByFile.has(patch.selector.file) || !insertedGroup && !observation?.currentHash) {
2279
2491
  unplaceable(
2280
- groupedSets.filter((set) => set.destination.file === patch.selector.file).map((set) => set.documentKey),
2492
+ (setsByDestination.get(patch.selector.file) ?? []).map((set) => set.documentKey),
2281
2493
  (0, import_layoutCore.diagnostic)("invalid-render-companion", patch.selector.file, "Share header is not fully authorized")
2282
2494
  );
2283
2495
  continue;
@@ -2346,6 +2558,7 @@ function renderReceiptAttempt(input, excluded) {
2346
2558
  continue;
2347
2559
  }
2348
2560
  const shares = (0, import_layoutCore.clone)(authored.shares);
2561
+ const positions = shareIdentityPositions(shares);
2349
2562
  let invalid = false;
2350
2563
  for (const { set, patch } of selected) {
2351
2564
  const entry = (0, import_layoutCore.object)(patch.value);
@@ -2353,13 +2566,12 @@ function renderReceiptAttempt(input, excluded) {
2353
2566
  invalid = true;
2354
2567
  break;
2355
2568
  }
2356
- const at = shareEntryIndex(index, readback.submissionProofs, shares, patch.selector, patch.source);
2569
+ const at = positions.find(patch.selector) ?? shareEntryIndex(index, shares, patch.selector, patch.source);
2357
2570
  if (at < 0 && set.placement !== "insert-authoritative") {
2358
2571
  invalid = true;
2359
2572
  break;
2360
2573
  }
2361
- if (at < 0) shares.push((0, import_layoutCore.clone)(entry));
2362
- else shares[at] = (0, import_layoutCore.clone)(entry);
2574
+ positions.set(at < 0 ? shares.length : at, (0, import_layoutCore.clone)(entry));
2363
2575
  }
2364
2576
  const companion = companionsByFile.get(file);
2365
2577
  if (invalid || companion && !(0, import_layoutCore.object)(companion.value)) {
@@ -2447,8 +2659,15 @@ function renderReceiptAttempt(input, excluded) {
2447
2659
  if (artifact.role !== "share-group")
2448
2660
  for (const key of artifact.authorizingDocumentKeys) renderedOwners.set(key, artifact);
2449
2661
  const pointsHere = (host, file) => !!host && (0, import_layoutCore.own)(host, "shares") && (0, import_documents.canonicalText)(host.shares) === (0, import_documents.canonicalText)({ file });
2662
+ const jsonByPath = (0, import_layoutCore.groupBySource)(json, (artifact) => artifact.path);
2663
+ const firstPatchByKey = /* @__PURE__ */ new Map();
2664
+ for (const patch of readback.identityPatches)
2665
+ if (!firstPatchByKey.has(patch.documentKey)) firstPatchByKey.set(patch.documentKey, patch);
2666
+ let navigation;
2450
2667
  const dropGroup = (artifact) => {
2451
2668
  json.splice(json.indexOf(artifact), 1);
2669
+ const samePath2 = jsonByPath.get(artifact.path);
2670
+ samePath2.splice(samePath2.indexOf(artifact), 1);
2452
2671
  unplaceable(
2453
2672
  artifact.authorizingDocumentKeys,
2454
2673
  (0, import_layoutCore.diagnostic)("unlinked-generated-share", artifact.path, "The owner cannot point to this new share group")
@@ -2465,27 +2684,31 @@ function renderReceiptAttempt(input, excluded) {
2465
2684
  else if (!pointsHere(host2, artifact.path)) dropGroup(artifact);
2466
2685
  continue;
2467
2686
  }
2468
- const patched = readback.identityPatches.find((patch) => patch.documentKey === ownerKey2);
2469
- const route = patched ? { file: patched.container } : ownerKey2 ? ownerNavigationTarget(context, ownerKey2) : void 0;
2687
+ const patched = ownerKey2 === void 0 ? void 0 : firstPatchByKey.get(ownerKey2);
2688
+ const route = patched ? { file: patched.container } : ownerKey2 ? ownerNavigationTarget(navigation ??= ownerNavigationIndex(context), ownerKey2) : void 0;
2470
2689
  if (!route) continue;
2471
2690
  const authored = authoredArtifact(index, route.file);
2472
2691
  const value = authored && (0, import_layoutCore.object)(authored.json);
2473
2692
  const host = value;
2474
2693
  if (pointsHere(host, artifact.path)) continue;
2475
- if (!containerFragmentsAreClean(context, route.file) || !authored || !value || !host || (0, import_layoutCore.own)(host, "shares")) {
2694
+ navigation ??= ownerNavigationIndex(context);
2695
+ if (navigation.dirtyFiles.has(route.file) || !authored || !value || !host || (0, import_layoutCore.own)(host, "shares")) {
2476
2696
  dropGroup(artifact);
2477
2697
  continue;
2478
2698
  }
2479
- const target = json.find((candidate) => candidate.path === route.file);
2699
+ const target = jsonByPath.get(route.file)?.[0];
2480
2700
  const container = target ? target.value : (0, import_layoutCore.clone)(value);
2481
2701
  container.shares = { file: artifact.path };
2482
- if (!target)
2483
- json.push({
2702
+ if (!target) {
2703
+ const rendered = {
2484
2704
  path: route.file,
2485
2705
  role: outputRole(authored, container),
2486
2706
  value: container,
2487
2707
  authorizingDocumentKeys: [...artifact.authorizingDocumentKeys]
2488
- });
2708
+ };
2709
+ json.push(rendered);
2710
+ jsonByPath.set(route.file, [rendered]);
2711
+ }
2489
2712
  }
2490
2713
  renderIdentityPatches(readback, index, json, notices);
2491
2714
  const retainedRemovalKeys = [];
@@ -2509,8 +2732,12 @@ function renderReceiptAttempt(input, excluded) {
2509
2732
  diagnostics.push(
2510
2733
  (0, import_layoutCore.diagnostic)("conflicting-removal-target", removal.path, "Removed path is also a rendered output")
2511
2734
  );
2512
- const outputs = [...jsonTargets, ...byteTargets];
2513
- const holdsOutput = (directory) => outputs.some((target) => target === directory || pathInside(target, directory));
2735
+ const outputDirectories = /* @__PURE__ */ new Set();
2736
+ for (const target of [...jsonTargets, ...byteTargets]) {
2737
+ outputDirectories.add(target);
2738
+ for (const ancestor of (0, import_layoutCore.pathAncestors)(target)) outputDirectories.add(ancestor);
2739
+ }
2740
+ const holdsOutput = (directory) => outputDirectories.has(directory);
2514
2741
  const vacated = new Set(removals.filter((removal) => removal.kind !== "rewrite").map((removal) => removal.path));
2515
2742
  for (const origin of origins) {
2516
2743
  if (jsonTargets.has(origin.path) || byteTargets.has(origin.path) || vacated.has(origin.path)) continue;