farseer-cli 1.16.0 → 1.18.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 (61) hide show
  1. package/README.md +329 -1
  2. package/dist/commands/code.js +104 -0
  3. package/dist/commands/code.js.map +7 -0
  4. package/dist/commands/formula.js +16 -7
  5. package/dist/commands/formula.js.map +2 -2
  6. package/dist/commands/tool.js +120 -0
  7. package/dist/commands/tool.js.map +7 -0
  8. package/dist/index.js +21 -2
  9. package/dist/index.js.map +2 -2
  10. package/dist/mcp/tools/modelTools.js +65 -23
  11. package/dist/mcp/tools/modelTools.js.map +3 -3
  12. package/dist/mcp/tools/runTools.js +6 -2
  13. package/dist/mcp/tools/runTools.js.map +2 -2
  14. package/dist/mcp/utils/launchPin.js +1 -1
  15. package/dist/mcp/utils/launchPin.js.map +2 -2
  16. package/dist/pipeline/service.js +1 -1
  17. package/dist/pipeline/service.js.map +2 -2
  18. package/dist/services/codefirst/api.js +269 -0
  19. package/dist/services/codefirst/api.js.map +7 -0
  20. package/dist/services/codefirst/binaryDisk.js +67 -0
  21. package/dist/services/codefirst/binaryDisk.js.map +7 -0
  22. package/dist/services/codefirst/byteHashes.js +129 -0
  23. package/dist/services/codefirst/byteHashes.js.map +7 -0
  24. package/dist/services/codefirst/documents.js +563 -0
  25. package/dist/services/codefirst/documents.js.map +7 -0
  26. package/dist/services/codefirst/layoutBinaryProjection.js +974 -0
  27. package/dist/services/codefirst/layoutBinaryProjection.js.map +7 -0
  28. package/dist/services/codefirst/layoutCompose.js +593 -0
  29. package/dist/services/codefirst/layoutCompose.js.map +7 -0
  30. package/dist/services/codefirst/layoutCore.js +260 -0
  31. package/dist/services/codefirst/layoutCore.js.map +7 -0
  32. package/dist/services/codefirst/layoutPaths.js +492 -0
  33. package/dist/services/codefirst/layoutPaths.js.map +7 -0
  34. package/dist/services/codefirst/layoutProjection.js +995 -0
  35. package/dist/services/codefirst/layoutProjection.js.map +7 -0
  36. package/dist/services/codefirst/layoutReadback.js +2552 -0
  37. package/dist/services/codefirst/layoutReadback.js.map +7 -0
  38. package/dist/services/codefirst/layoutReadbackPlacement.js +1517 -0
  39. package/dist/services/codefirst/layoutReadbackPlacement.js.map +7 -0
  40. package/dist/services/codefirst/layoutReceipt.js +1592 -0
  41. package/dist/services/codefirst/layoutReceipt.js.map +7 -0
  42. package/dist/services/codefirst/layoutScan.js +882 -0
  43. package/dist/services/codefirst/layoutScan.js.map +7 -0
  44. package/dist/services/codefirst/output.js +179 -0
  45. package/dist/services/codefirst/output.js.map +7 -0
  46. package/dist/services/codefirst/types.js +17 -0
  47. package/dist/services/codefirst/types.js.map +7 -0
  48. package/dist/services/codefirst/workflow.js +581 -0
  49. package/dist/services/codefirst/workflow.js.map +7 -0
  50. package/dist/services/codefirst/workspace.js +310 -0
  51. package/dist/services/codefirst/workspace.js.map +7 -0
  52. package/dist/services/codefirst/workspaceLock.js +148 -0
  53. package/dist/services/codefirst/workspaceLock.js.map +7 -0
  54. package/dist/services/codefirst/workspaceRoot.js +147 -0
  55. package/dist/services/codefirst/workspaceRoot.js.map +7 -0
  56. package/dist/utils/formulaFilters.js +48 -0
  57. package/dist/utils/formulaFilters.js.map +7 -0
  58. package/dist/utils/logger.js +9 -3
  59. package/dist/utils/logger.js.map +2 -2
  60. package/docs/cli-guide.md +13 -0
  61. package/package.json +3 -2
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/services/codefirst/layoutReadback.ts"],
4
+ "sourcesContent": ["/**\n * Readback: it decides per canonical key what a receipt or a checkout permits, turns those decisions\n * into placed physical sets, and renders the complete containers those sets belong in.\n * Placement allocation lives in layoutReadbackPlacement; writing files lives in layoutReceipt.\n */\nimport { canonicalText, headDocuments } from './documents';\nimport {\n decomposeBinaryLayout,\n type BinaryFragmentObservation,\n type BinaryFragmentSelector,\n type BinarySubmissionProof,\n type LayoutByteFact,\n type OwnerAttachmentPatch,\n type OwnerFieldProjection,\n type RawFileSelector,\n type RawFileWireSourceMapping,\n type RawResourcePatch,\n} from './layoutBinaryProjection';\nimport {\n attachmentField,\n attachmentField as ownerField,\n blocked,\n canonicalFragmentHash,\n clone,\n compareText,\n diagnostic,\n FILENAME_NAME_ROLES,\n groupBySource,\n object,\n own,\n ownerKey,\n pathAncestors,\n RESOURCE_ID,\n same,\n samePath,\n sameSelector,\n sourceIdentityKey,\n stableSource,\n without,\n type JsonObject,\n type StableSource,\n} from './layoutCore';\nimport {\n decodeLayoutName,\n encodeLayoutSegment,\n folderDirectory,\n isRawSidecarPath,\n layoutCollisionKey,\n layoutNameNeedsOverride,\n} from './layoutPaths';\nimport {\n decomposeGroupedLayout,\n derivedSourceSelectorHash,\n type ArtifactPatch,\n type DerivedSourceProof,\n type FragmentObservation,\n type FragmentSelector,\n type GroupOwnerSelector,\n type OwnerNavigationRoute,\n type ProjectionDiagnostic,\n type SourceIdentity,\n type SubmissionCorrespondence,\n type WireSourceMapping,\n} from './layoutProjection';\nimport {\n planAuthoritativePlacement,\n type AllocatedAttachmentCorrespondence,\n type AuthoritativeCurrentSource,\n type AuthoritativeDamagePlacement,\n type AuthoritativePlacementIntent,\n} from './layoutReadbackPlacement';\nimport type { LayoutArtifact, LayoutArtifactRole, LayoutScanResult } from './layoutScan';\nimport type {\n ComposeLayoutSubmissionResult,\n LayoutSubmissionSource,\n RawShareNavigationObservation,\n} from './layoutCompose';\nimport { OperationOutcomeOutcomeEnum, PlanOperationActionEnum } from 'farseer-client';\nimport type { BlobContent, Document, Handle, Head, Json, Plan, PlanOperation, Receipt, ResourceKey } from './types';\ntype CompleteComposition = Extract<ComposeLayoutSubmissionResult, { status: 'complete' }>;\n\nexport interface CapturedLayoutComposition {\n composition: LayoutSubmissionSnapshot;\n}\n\nexport interface BindLayoutReceiptSubmissionInput {\n planId: string;\n plan: Pick<Plan, 'planId' | 'documentKeys' | 'operations' | 'handles'>;\n captured: CapturedLayoutComposition;\n}\n\n/** Immutable pre-POST facts. A workflow must persist this before it can activate receipt readback. */\nexport interface LayoutSubmissionSnapshot {\n documents: readonly Document[];\n sources: readonly LayoutSubmissionSource[];\n groupedObservations: readonly FragmentObservation[];\n groupedNavigation: readonly OwnerNavigationRoute[];\n rawObservations: readonly BinaryFragmentObservation[];\n ownerFields: readonly OwnerFieldProjection[];\n attachmentObservations: readonly BinaryFragmentObservation[];\n rawNavigation: readonly RawShareNavigationObservation[];\n groupedSubmissions?: readonly SubmissionCorrespondence[];\n binarySubmissions?: readonly BinarySubmissionProof[];\n}\n\nexport interface LayoutReceiptSubmission {\n planId: string;\n documentKeys: readonly string[];\n operations: readonly PlanOperation[];\n handles: Readonly<Record<string, Handle>>;\n composition: LayoutSubmissionSnapshot;\n}\n\nexport type LayoutReadbackContributor =\n | {\n kind: 'grouped-navigation';\n source: SourceIdentity;\n selector: { file: string; slot: 'owner-navigation' };\n sourcePath: readonly (string | number)[];\n groupFile: string;\n owner: GroupOwnerSelector;\n }\n | {\n kind: 'grouped';\n source: SourceIdentity;\n selector: FragmentSelector;\n sourcePath: readonly (string | number)[];\n state: FragmentObservation['state'];\n currentHash?: string;\n derivedSelectorHash?: string;\n value?: Json;\n }\n | {\n kind: 'share-group-owner';\n source: Extract<SourceIdentity, { type: 'group' }>;\n selector: FragmentSelector;\n sourcePath: readonly (string | number)[];\n state: FragmentObservation['state'];\n currentHash?: string;\n value: GroupOwnerSelector;\n }\n | {\n kind: 'raw';\n source: SourceIdentity;\n selector: RawFileSelector;\n sourcePath: readonly (string | number)[];\n state: BinaryFragmentObservation['state'];\n currentHash?: string;\n entryHash?: string;\n byteHash?: string;\n bytes?: string;\n detached?: boolean;\n nameOverride?: boolean;\n value?: Json;\n }\n | {\n kind: 'raw-navigation';\n source: StableSource;\n selector: RawShareNavigationObservation['selector'];\n sourcePath: readonly (string | number)[];\n state: RawShareNavigationObservation['state'];\n currentHash?: string;\n groupFile?: string;\n }\n | {\n kind: 'owner-field';\n source: SourceIdentity;\n ownerFile: string;\n field: 'icon' | 'template';\n status: OwnerFieldProjection['status'];\n value?: Json;\n bytes?: string;\n currentHash?: string;\n state?: BinaryFragmentObservation['state'];\n }\n | {\n kind: 'attachment';\n source: SourceIdentity;\n selector: Extract<BinaryFragmentSelector, { slot: 'owner-attachment' }>;\n sourcePath: readonly (string | number)[];\n state: BinaryFragmentObservation['state'];\n currentHash?: string;\n byteHash?: string;\n bytes?: string;\n };\n\nexport type ReceiptResultClassification =\n | 'eligible-stable-set'\n | 'eligible-assigned-create'\n | 'failed'\n | 'blocked'\n | 'missing-outcome'\n | 'no-receipt-baseline'\n | 'head-hash-mismatch'\n | 'missing-head-document'\n | 'assigned-create-deferred'\n | 'generated-share-deferred'\n | 'delete-deferred'\n | 'eligible-removal';\n\nexport interface ReceiptReadbackResult {\n outcomeKey: string;\n documentKey?: string;\n handle?: string;\n assignment?: ResourceKey;\n outcome?: Receipt['outcomes'][string]['outcome'];\n receiptHash?: string;\n headHash?: string;\n classification: ReceiptResultClassification;\n}\n\nexport interface ReceiptAssignmentResult {\n handle: string;\n assignment: ResourceKey;\n location: Handle;\n}\n\n/**\n * Why a resource keeps its current local content. The first seven reasons come from receipt\n * readback; the last four are the pull/checkout notices ported from the flat `model/` layout.\n */\nexport type PreserveReason =\n /** One resource the plan could not materialize; its content, baseline and routes stay as they are. */\n | 'unmaterialized'\n | 'unsuccessful-outcome'\n | 'missing-outcome'\n | 'deferred-receipt'\n | 'post-submission-change'\n | 'protected-descendant'\n | 'folder-held'\n | 'unsupported-evidence'\n | 'shared-container-relocation'\n | 'shared-container-sibling'\n | 'kept-local'\n | 'kept-local-edits'\n | 'conflict'\n | 'local-deletion-pending'\n | 'pull-needed';\n\nexport interface GroupedCompanionMaterialization {\n kind: 'share-group-owner';\n authorizingDocumentKeys: readonly string[];\n patch: ArtifactPatch;\n}\n\nexport type PhysicalMaterialization =\n | {\n mode: 'set';\n codec: 'grouped';\n documentKey: string;\n outcomeKey: string;\n /** How the destination was allocated. An insert has no current container to merge into. */\n placement: AuthoritativePlacementIntent['mode'];\n document: Document;\n destination: FragmentSelector;\n /** The selector the patch replaces. A promoted create changes identity inside its container. */\n origin?: FragmentSelector;\n patches: readonly ArtifactPatch[];\n }\n | {\n mode: 'set';\n codec: 'raw';\n documentKey: string;\n outcomeKey: string;\n placement: AuthoritativePlacementIntent['mode'];\n document: Document;\n destination: RawFileSelector;\n /** The selector the patch replaces. A promoted create changes identity inside its sidecar. */\n origin?: RawFileSelector;\n bytes: string;\n patch: RawResourcePatch;\n }\n | {\n mode: 'preserve';\n documentKey?: string;\n source: SourceIdentity;\n document?: Document;\n contributors: readonly LayoutReadbackContributor[];\n reason: PreserveReason;\n }\n | {\n mode: 'keep-absent';\n documentKey: string;\n contributors: readonly LayoutReadbackContributor[];\n }\n | {\n mode: 'suppressed';\n documentKey: string;\n container: string;\n reason: 'intentional-sibling-absence';\n };\n\nexport type AttachmentMaterialization =\n | {\n mode: 'set' | 'clear';\n ownerDocumentKey: string;\n patch: OwnerAttachmentPatch;\n destination: AllocatedAttachmentCorrespondence['destination'];\n }\n | {\n /** `known-null` releases the association; `preserve` keeps the coherent local one. */\n mode: 'known-null' | 'preserve';\n ownerDocumentKey: string;\n source: StableSource;\n ownerFile: string;\n field: 'icon' | 'template';\n bytes?: string;\n };\n\nexport interface LayoutReadbackRenderingContext {\n readonly authored: LayoutScanResult;\n readonly grouped: CompleteComposition['grouped'];\n readonly binary: CompleteComposition['binary'];\n readonly byteFacts: CompleteComposition['byteFacts'];\n}\n\nexport interface PlanReceiptReadbackInput {\n head: Head;\n receipt: Receipt;\n submission: LayoutReceiptSubmission;\n current: CompleteComposition;\n}\n\n/**\n * One decision per canonical key, taken from the boundary evidence alone. A `set` names the\n * authoritative document and how it reaches the workspace; every other kind keeps what is there.\n */\nexport type EligibilityDecision =\n | {\n mode: 'set';\n documentKey: string;\n placement: AuthoritativePlacementIntent['mode'];\n /** `pull --force` re-inserts a resource this workspace deleted locally but still tracks. */\n reinsert?: boolean;\n document: Document;\n /** The current source: numeric for a stable resource, transient or keyed for a promoted create. */\n source: SourceIdentity;\n contributors: readonly LayoutReadbackContributor[];\n outcomeKey?: string;\n current?: AuthoritativeCurrentSource;\n expectedCurrentHash?: string;\n currentDocument?: Document;\n }\n | {\n mode: 'remove';\n documentKey: string;\n source: SourceIdentity;\n contributors: readonly LayoutReadbackContributor[];\n current?: AuthoritativeCurrentSource;\n document?: Document;\n /** `pull --force` discards a local difference; every other removal keeps a dirty contributor. */\n force?: boolean;\n }\n | { mode: 'noop'; documentKey: string }\n | Extract<PhysicalMaterialization, { mode: 'preserve' | 'keep-absent' | 'suppressed' }>;\n\n/** One document whose assigned identity reaches the workspace as a patch, not as a rewrite. */\nexport interface PlannedIdentityPatch {\n /** The canonical key this document has once the assigned identity is on disk. */\n documentKey: string;\n source: SourceIdentity;\n container: string;\n slot: FragmentSelector['slot'] | 'file-entry';\n /** The group entry, when the document is a share. */\n shareIdentity?: Extract<FragmentSelector, { slot: 'share-entry' }>['identity'];\n submittedDocument: Document;\n assignments: readonly ReceiptAssignmentResult[];\n}\n\n/** A share entry that a removal takes out of a group it does not own alone. */\nexport interface PlannedContainerRemoval {\n documentKey: string;\n container: string;\n entry: FragmentSelector;\n}\n\n/** The navigation pointer an owner loses when the last share of its group goes away. */\nexport interface PlannedPointerRemoval {\n documentKey: string;\n /** The owner's own file: a document path, or the sidecar of a raw uploaded file. */\n owner: string;\n groupFile: string;\n}\n\n/** One path a removal takes out of the workspace, with the canonical keys that asked for it. */\nexport interface PlannedPathRemoval {\n path: string;\n documentKeys: readonly string[];\n}\n\n/** Everything one removal set takes out of the workspace. Planning never touches the filesystem. */\nexport interface PlannedLayoutDeletes {\n json: readonly PlannedPathRemoval[];\n bytes: readonly PlannedPathRemoval[];\n /** Managed directories whose marker goes away. Each one survives when local content remains. */\n directories: readonly PlannedPathRemoval[];\n groupEntries: readonly PlannedContainerRemoval[];\n pointers: readonly PlannedPointerRemoval[];\n /** The canonical keys whose baseline entry goes away. */\n keys: readonly string[];\n /** The sources whose routes, proofs and tracked claims go away. */\n sources: readonly SourceIdentity[];\n}\n\nexport type EligibilityResult =\n | {\n status: 'complete';\n decisions: readonly EligibilityDecision[];\n receiptResults: readonly ReceiptReadbackResult[];\n assignments: readonly ReceiptAssignmentResult[];\n /** The selected Head, validated once at the boundary where it enters. */\n headDocuments: ReadonlyMap<string, Document>;\n /** The current source of every resolved create key, promoted or not. */\n submittedSources?: Readonly<Record<string, SourceIdentity>>;\n /** Documents whose assigned identity is patched in place instead of rewritten. */\n identityPatches?: readonly PlannedIdentityPatch[];\n /** The exact codec correspondence this submission saved. Only a receipt has one. */\n submissionProofs?: {\n grouped: readonly SubmissionCorrespondence[];\n binary: readonly BinarySubmissionProof[];\n };\n /** Per-resource problems this decision skipped; the resource keeps every fact it had. */\n warnings?: readonly ProjectionDiagnostic[];\n /** What the decision itself has to tell the author, before anything is rendered. */\n notices?: readonly LayoutReadbackNotice[];\n }\n | { status: 'blocked'; diagnostics: readonly ProjectionDiagnostic[] };\n\nexport interface PlanMaterializationInput {\n eligibility: Extract<EligibilityResult, { status: 'complete' }>;\n /** The server Head the authoritative documents came from. */\n head?: Head;\n current: CompleteComposition;\n}\n\nexport type PlanReceiptReadbackResult =\n | {\n status: 'complete';\n receiptResults: readonly ReceiptReadbackResult[];\n assignments: readonly ReceiptAssignmentResult[];\n materializations: readonly PhysicalMaterialization[];\n deletes: PlannedLayoutDeletes;\n identityPatches: readonly PlannedIdentityPatch[];\n groupedPatches: readonly ArtifactPatch[];\n groupedCompanions: readonly GroupedCompanionMaterialization[];\n rawPatches: readonly RawResourcePatch[];\n attachments: readonly AttachmentMaterialization[];\n pendingDamage: readonly AuthoritativeDamagePlacement[];\n /**\n * The server-proven selector mapping of every ID-free grant this plan inserts. A checkout has\n * no local derived proof, so the Head pairing is the only thing that binds the new artifact.\n */\n derivedSourceProofs: readonly DerivedSourceProof[];\n /** Why each preserved resource could not be materialized; the command reports them. */\n unmaterializedDiagnostics: readonly ProjectionDiagnostic[];\n /** Notices the eligibility decision raised; rendering adds its own to them. */\n notices: readonly LayoutReadbackNotice[];\n renderingContext: LayoutReadbackRenderingContext;\n /** The grouped correspondence the receipt's submission saved; empty for a checkout. */\n submissionProofs: readonly SubmissionCorrespondence[];\n }\n | { status: 'blocked'; diagnostics: readonly ProjectionDiagnostic[] };\n\ninterface SubmittedResource {\n documentKey: string;\n document: Document;\n source: SourceIdentity;\n submissionSource: LayoutSubmissionSource;\n contributors: LayoutReadbackContributor[];\n}\n\ninterface CurrentResource {\n document?: Document;\n current?: AuthoritativeCurrentSource;\n contributors: LayoutReadbackContributor[];\n /** The primary contributor's hash, taken once while the resource is built. */\n currentHash?: string;\n presence: 'present' | 'absent' | 'unsupported';\n}\n\ninterface EligibleResource {\n result: ReceiptReadbackResult;\n submitted: SubmittedResource;\n current: CurrentResource & { current: AuthoritativeCurrentSource; currentHash: string; presence: 'present' };\n authoritative: Document;\n}\n\nfunction sameBinarySelector(left: BinaryFragmentSelector, right: BinaryFragmentSelector): boolean {\n return same(left, right);\n}\n\nfunction stableSourceKey(source: SourceIdentity): string | undefined {\n return source.type === 'resource' && 'id' in source.resource\n ? `${source.resource.kind}/${source.resource.id}`\n : undefined;\n}\n\nfunction resourceEvidence(composition: CompleteComposition): LayoutSubmissionSnapshot {\n return {\n documents: composition.documents,\n sources: composition.sources,\n groupedObservations: composition.grouped.observations,\n groupedNavigation: composition.grouped.navigation,\n rawObservations: composition.binary.rawObservations,\n ownerFields: composition.binary.ownerFields,\n attachmentObservations: composition.binary.attachmentObservations,\n rawNavigation: composition.rawNavigation,\n groupedSubmissions: composition.grouped.submissions,\n binarySubmissions: composition.binary.submissions,\n };\n}\n\nfunction mappingDocument(composition: LayoutSubmissionSnapshot, source: LayoutSubmissionSource): Document | undefined {\n return composition.documents[source.mapping.documentIndex];\n}\n\nfunction mappingValue(document: Document | undefined, mapping: WireSourceMapping): Json | undefined {\n if (!document) return undefined;\n if (mapping.selector.slot === 'member-set') return document.members;\n if (mapping.selector.slot === 'share-entry') {\n const entry: JsonObject = { ...document };\n delete entry.kind;\n delete entry.owner;\n return entry;\n }\n return document;\n}\n\n/** One index of a submission snapshot. Every resource lookup reads it instead of rescanning the lists. */\ninterface SnapshotIndex {\n snapshot: LayoutSubmissionSnapshot;\n sources: ReadonlyMap<string, LayoutSubmissionSource[]>;\n groupedObservations: ReadonlyMap<string, FragmentObservation[]>;\n rawObservations: ReadonlyMap<string, BinaryFragmentObservation[]>;\n attachmentObservations: ReadonlyMap<string, BinaryFragmentObservation[]>;\n ownerFields: ReadonlyMap<string, OwnerFieldProjection[]>;\n groupedNavigation: ReadonlyMap<string, OwnerNavigationRoute[]>;\n rawNavigation: ReadonlyMap<string, RawShareNavigationObservation[]>;\n groupOwners: ReadonlyMap<string, FragmentObservation[]>;\n}\n\nfunction indexSnapshot(snapshot: LayoutSubmissionSnapshot): SnapshotIndex {\n return {\n snapshot,\n sources: groupBySource(snapshot.sources, (source) => sourceIdentityKey(source.mapping.source)),\n groupedObservations: groupBySource(snapshot.groupedObservations, (item) => sourceIdentityKey(item.source)),\n rawObservations: groupBySource(snapshot.rawObservations, (item) => sourceIdentityKey(item.source)),\n attachmentObservations: groupBySource(snapshot.attachmentObservations, (item) =>\n sourceIdentityKey(item.source),\n ),\n ownerFields: groupBySource(snapshot.ownerFields, (item) => sourceIdentityKey(item.ownerSource)),\n groupedNavigation: groupBySource(snapshot.groupedNavigation, (item) => sourceIdentityKey(item.source)),\n rawNavigation: groupBySource(snapshot.rawNavigation, (item) => sourceIdentityKey(item.source)),\n groupOwners: groupBySource(\n snapshot.groupedObservations.filter(\n (item) => item.source.type === 'group' && item.selector.slot === 'share-group-owner',\n ),\n (item) =>\n `${item.selector.file}\\u0000${ownerKey((item.source as Extract<SourceIdentity, { type: 'group' }>).owner)}`,\n ),\n };\n}\n\nfunction groupedObservation(index: SnapshotIndex, mapping: WireSourceMapping): FragmentObservation | undefined {\n const matches = (index.groupedObservations.get(sourceIdentityKey(mapping.source)) ?? []).filter((candidate) =>\n sameSelector(candidate.selector, mapping.selector),\n );\n return matches.length === 1 ? matches[0] : undefined;\n}\n\nfunction rawObservation(\n index: SnapshotIndex,\n mapping: RawFileWireSourceMapping,\n): BinaryFragmentObservation | undefined {\n const matches = (index.rawObservations.get(sourceIdentityKey(mapping.source)) ?? []).filter((candidate) =>\n sameBinarySelector(candidate.selector, mapping.selector),\n );\n return matches.length === 1 ? matches[0] : undefined;\n}\n\nfunction contributorsForMapping(index: SnapshotIndex, source: LayoutSubmissionSource): LayoutReadbackContributor[] {\n const composition = index.snapshot;\n const document = mappingDocument(composition, source);\n const contributors: LayoutReadbackContributor[] = [];\n if (source.codec === 'grouped') {\n const observation = groupedObservation(index, source.mapping);\n if (observation)\n contributors.push({\n kind: 'grouped',\n source: clone(observation.source),\n selector: clone(observation.selector),\n sourcePath: clone(observation.sourcePath),\n state: observation.state,\n ...(observation.currentHash ? { currentHash: observation.currentHash } : {}),\n ...(observation.derivedSelectorHash ? { derivedSelectorHash: observation.derivedSelectorHash } : {}),\n ...(mappingValue(document, source.mapping) !== undefined\n ? { value: clone(mappingValue(document, source.mapping)!) }\n : {}),\n });\n if (source.mapping.selector.slot === 'share-entry' && source.mapping.groupOwner) {\n const owners = (index.groupOwners.get(\n `${source.mapping.selector.file}\\u0000${ownerKey(source.mapping.groupOwner)}`,\n ) ?? []) as (FragmentObservation & { source: Extract<SourceIdentity, { type: 'group' }> })[];\n if (owners.length === 1)\n contributors.push({\n kind: 'share-group-owner',\n source: clone(owners[0].source),\n selector: clone(owners[0].selector),\n sourcePath: clone(owners[0].sourcePath),\n state: owners[0].state,\n ...(owners[0].currentHash ? { currentHash: owners[0].currentHash } : {}),\n value: clone(source.mapping.groupOwner),\n });\n }\n } else {\n const observation = rawObservation(index, source.mapping);\n if (observation)\n contributors.push({\n kind: 'raw',\n source: clone(observation.source),\n selector: clone(source.mapping.selector),\n sourcePath: clone(observation.sourcePath),\n state: observation.state,\n ...(observation.currentHash ? { currentHash: observation.currentHash } : {}),\n ...(observation.entryHash ? { entryHash: observation.entryHash } : {}),\n ...(observation.byteHash ? { byteHash: observation.byteHash } : {}),\n ...(observation.bytes ? { bytes: observation.bytes } : {}),\n detached: source.mapping.detached,\n nameOverride: source.mapping.nameOverride,\n ...(document ? { value: clone(document) } : {}),\n });\n for (const navigation of index.rawNavigation.get(sourceIdentityKey(source.mapping.source)) ?? [])\n contributors.push({\n kind: 'raw-navigation',\n source: clone(navigation.source) as StableSource,\n selector: clone(navigation.selector),\n sourcePath: clone(navigation.sourcePath),\n state: navigation.state,\n ...(navigation.currentHash ? { currentHash: navigation.currentHash } : {}),\n ...(navigation.groupFile ? { groupFile: navigation.groupFile } : {}),\n });\n }\n\n for (const navigation of index.groupedNavigation.get(sourceIdentityKey(source.mapping.source)) ?? [])\n contributors.push({\n kind: 'grouped-navigation',\n source: clone(navigation.source),\n selector: clone(navigation.selector),\n sourcePath: clone(navigation.sourcePath),\n groupFile: navigation.groupFile,\n owner: clone(navigation.owner),\n });\n\n // A new owner carries the same attachment evidence as a stable one, under its committed identity.\n for (const field of index.ownerFields.get(sourceIdentityKey(source.mapping.source)) ?? [])\n contributors.push({\n kind: 'owner-field',\n source: clone(field.ownerSource),\n ownerFile: field.ownerFile,\n field: field.field,\n status: field.status,\n ...(field.value !== undefined ? { value: clone(field.value) as unknown as Json } : {}),\n ...(field.bytes ? { bytes: field.bytes } : {}),\n ...(field.currentHash ? { currentHash: field.currentHash } : {}),\n ...(field.state ? { state: field.state } : {}),\n });\n for (const observation of (index.attachmentObservations.get(sourceIdentityKey(source.mapping.source)) ?? []).filter(\n (candidate) => candidate.selector.slot === 'owner-attachment',\n ))\n contributors.push({\n kind: 'attachment',\n source: clone(observation.source),\n selector: clone(observation.selector) as Extract<BinaryFragmentSelector, { slot: 'owner-attachment' }>,\n sourcePath: clone(observation.sourcePath),\n state: observation.state,\n ...(observation.currentHash ? { currentHash: observation.currentHash } : {}),\n ...(observation.byteHash ? { byteHash: observation.byteHash } : {}),\n ...(observation.bytes ? { bytes: observation.bytes } : {}),\n });\n return contributors;\n}\n\nfunction currentResource(\n index: SnapshotIndex,\n rawSources: ReadonlyMap<string, RawFileWireSourceMapping[]>,\n identity: SourceIdentity,\n /** A combined table emits two sources under one transient token, so a create names its own slot. */\n discriminator?: LayoutSubmissionSource,\n): CurrentResource {\n const sourceKey = sourceIdentityKey(identity);\n const all = index.sources.get(sourceKey) ?? [];\n const matches = discriminator\n ? all.filter(\n (candidate) =>\n candidate.codec === discriminator.codec &&\n (candidate.codec === 'grouped' && discriminator.codec === 'grouped'\n ? sameSelector(candidate.mapping.selector, discriminator.mapping.selector)\n : candidate.codec === 'raw' &&\n discriminator.codec === 'raw' &&\n sameBinarySelector(candidate.mapping.selector, discriminator.mapping.selector)),\n )\n : all;\n if (matches.length > 1) throw new Error(`Composition emitted more than one source for ${sourceKey}`);\n if (matches.length === 1) {\n const source = matches[0];\n const contributors = contributorsForMapping(index, source);\n const primary =\n source.codec === 'grouped'\n ? contributors.find((candidate) => candidate.kind === 'grouped')\n : contributors.find((candidate) => candidate.kind === 'raw');\n if (!primary || primary.state === 'present-unclassified' || primary.currentHash === undefined)\n return { contributors, presence: 'unsupported' };\n if (primary.state === 'absent') return { contributors, presence: 'absent' };\n let current: AuthoritativeCurrentSource | undefined;\n if (source.codec === 'grouped') current = { codec: 'grouped', mapping: source.mapping };\n else {\n const raw = (rawSources.get(sourceKey) ?? []).filter((candidate) =>\n sameBinarySelector(candidate.selector, source.mapping.selector),\n );\n if (raw.length === 1) current = { codec: 'raw', mapping: raw[0] };\n }\n if (!current) return { contributors, presence: 'unsupported' };\n return {\n document: mappingDocument(index.snapshot, source),\n current,\n contributors,\n currentHash: primary.currentHash,\n presence: 'present',\n };\n }\n\n const absent: LayoutReadbackContributor[] = [];\n for (const observation of (index.groupedObservations.get(sourceKey) ?? []).filter(\n (candidate) => candidate.state === 'absent',\n ))\n absent.push({\n kind: 'grouped',\n source: clone(observation.source),\n selector: clone(observation.selector),\n sourcePath: clone(observation.sourcePath),\n state: observation.state,\n ...(observation.derivedSelectorHash ? { derivedSelectorHash: observation.derivedSelectorHash } : {}),\n });\n for (const observation of (index.rawObservations.get(sourceKey) ?? []).filter(\n (candidate) => candidate.state === 'absent',\n ))\n absent.push({\n kind: 'raw',\n source: clone(observation.source),\n selector: clone(observation.selector as RawFileSelector),\n sourcePath: clone(observation.sourcePath),\n state: observation.state,\n ...(observation.bytes ? { bytes: observation.bytes } : {}),\n });\n return { contributors: absent, presence: absent.length > 0 ? 'absent' : 'unsupported' };\n}\n\n/**\n * One canonical fingerprint of everything that contributes to a resource. Share-entry re-indexing moves\n * the source path inside its group, so that path is not part of the fingerprint.\n */\nfunction resourceFingerprint(contributors: readonly LayoutReadbackContributor[]): string {\n const parts = contributors\n .map((contributor) => {\n const value = clone(contributor) as JsonObject;\n if (contributor.kind === 'grouped' && contributor.selector.slot === 'share-entry') delete value.sourcePath;\n return canonicalFragmentHash(value);\n })\n .sort();\n return canonicalFragmentHash(parts);\n}\n\nfunction sourceMatchesKey(source: SourceIdentity, key: string): source is StableSource {\n const expected = stableSource(key);\n return !!expected && sourceIdentityKey(source) === sourceIdentityKey(expected);\n}\n\nfunction submittedResources(\n submission: LayoutReceiptSubmission,\n snapshotIndex: SnapshotIndex,\n): {\n resources: Map<string, SubmittedResource>;\n diagnostics: ProjectionDiagnostic[];\n} {\n const diagnostics: ProjectionDiagnostic[] = [];\n const resources = new Map<string, SubmittedResource>();\n const { composition } = submission;\n for (const source of composition.sources) {\n const index = source.mapping.documentIndex;\n const documentKey = submission.documentKeys[index];\n const document = mappingDocument(composition, source);\n if (!documentKey || !document) continue;\n // A plan handle key has no stable identity, so only a numeric key must match its source.\n if (stableSource(documentKey) && !sourceMatchesKey(source.mapping.source, documentKey)) continue;\n if (resources.has(documentKey)) {\n diagnostics.push(\n diagnostic('duplicate-submission-resource', documentKey, 'Submission has duplicate resource sources'),\n );\n continue;\n }\n const contributors = contributorsForMapping(snapshotIndex, source);\n if (contributors.length === 0)\n diagnostics.push(\n diagnostic('unsupported-submission-evidence', documentKey, 'Submission has no resource contributor'),\n );\n resources.set(documentKey, {\n documentKey,\n document: clone(document),\n source: clone(source.mapping.source),\n submissionSource: clone(source),\n contributors,\n });\n }\n return { resources, diagnostics };\n}\n\n/** A promoted transient source needs the exact correspondence the submission saved for its slot. */\nfunction hasSavedTransientProof(composition: LayoutSubmissionSnapshot, source: LayoutSubmissionSource): boolean {\n if (source.mapping.source.type !== 'transient') return true;\n const proofs = source.codec === 'grouped' ? composition.groupedSubmissions : composition.binarySubmissions;\n if (!proofs) return false;\n const matches = proofs.filter(\n (proof) =>\n sourceIdentityKey(proof.source) === sourceIdentityKey(source.mapping.source) &&\n samePath(proof.sourcePath, source.mapping.sourcePath) &&\n (source.codec === 'grouped'\n ? sameSelector(\n (proof as SubmissionCorrespondence).selector,\n source.mapping.selector as FragmentSelector,\n )\n : sameBinarySelector(\n (proof as BinarySubmissionProof).selector,\n source.mapping.selector as BinaryFragmentSelector,\n )),\n );\n return matches.length === 1;\n}\n\n/**\n * Whether a create's submitted source can be promoted at all. A transient source needs saved proof;\n * a committed local key only has to belong to the kind the operation created. A local `key` and a\n * `new:N` plan handle are different namespaces, so neither is ever compared to the other.\n */\nfunction createSourceMatches(\n composition: LayoutSubmissionSnapshot,\n submitted: SubmittedResource,\n operation: PlanOperation,\n): boolean {\n const source = submitted.source;\n if (source.type === 'transient') return hasSavedTransientProof(composition, submitted.submissionSource);\n if (source.type !== 'resource' || !('key' in source.resource)) return false;\n return source.resource.kind === submitted.document.kind && operation.kind === submitted.document.kind;\n}\n\n/** A create handle must address the top-level `id` of the document its operation created. */\nfunction topLevelCreateHandleValid(\n submission: LayoutReceiptSubmission,\n operation: PlanOperation,\n submitted: SubmittedResource,\n): boolean {\n if (!operation.handle) return false;\n const location = submission.handles[operation.handle];\n if (!location || !samePath(location.path, ['id'])) return false;\n if (operation.kind === 'dimension_members' && location.kind === 'dimension_table') {\n // A member set has no handle of its own; it resolves through its table's assignment.\n const ownerIndex = submission.documentKeys.indexOf(`dimension_table/${operation.handle}`);\n if (ownerIndex < 0 || ownerIndex !== location.documentIndex) return false;\n const owner = submission.composition.sources.filter(\n (source) => source.mapping.documentIndex === ownerIndex && source.codec === 'grouped',\n );\n const member = submitted.submissionSource;\n return (\n owner.length === 1 &&\n owner[0].codec === 'grouped' &&\n member.codec === 'grouped' &&\n owner[0].mapping.selector.slot === 'table-definition' &&\n member.mapping.selector.slot === 'member-set' &&\n owner[0].mapping.selector.file === member.mapping.selector.file\n );\n }\n return (\n location.kind === operation.kind && location.documentIndex === submitted.submissionSource.mapping.documentIndex\n );\n}\n\nfunction locationExists(document: Document, handle: Handle): boolean {\n if (!Number.isInteger(handle.documentIndex) || handle.documentIndex < 0) return false;\n let value: Json = document;\n for (const part of handle.path.slice(0, -1)) {\n if (typeof part === 'number') {\n if (!Array.isArray(value) || part < 0 || part >= value.length) return false;\n value = value[part];\n } else {\n if (!value || typeof value !== 'object' || Array.isArray(value) || !(part in value)) return false;\n value = value[part];\n }\n }\n return (\n handle.path.length > 0 &&\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n handle.path[handle.path.length - 1] === 'id'\n );\n}\n\nfunction validateAssignments(\n submission: LayoutReceiptSubmission,\n receipt: Receipt,\n): { assignments: ReceiptAssignmentResult[]; diagnostics: ProjectionDiagnostic[] } {\n const diagnostics: ProjectionDiagnostic[] = [];\n const assignments: ReceiptAssignmentResult[] = [];\n const locations = new Set<string>();\n for (const [handle, location] of Object.entries(submission.handles)) {\n const document = submission.composition.documents[location.documentIndex];\n const locationKey = canonicalText([location.documentIndex, location.path]);\n if (\n typeof location.kind !== 'string' ||\n !document ||\n !Array.isArray(location.path) ||\n !locationExists(document, location)\n )\n diagnostics.push(diagnostic('invalid-submission-handle', handle, 'Submission handle location is invalid'));\n else if (locations.has(locationKey))\n diagnostics.push(\n diagnostic('duplicate-submission-handle', handle, 'Submission handle location is duplicated'),\n );\n else locations.add(locationKey);\n }\n for (const [handle, assignment] of Object.entries(receipt.assignments)) {\n const location = submission.handles[handle];\n if (!location || location.kind !== assignment.kind || !RESOURCE_ID.test(assignment.id)) {\n diagnostics.push(\n diagnostic('invalid-receipt-assignment', handle, 'Receipt assignment does not match its handle'),\n );\n continue;\n }\n assignments.push({ handle, assignment: clone(assignment), location: clone(location) });\n }\n return { assignments, diagnostics };\n}\n\nfunction operationOutcomeKey(operation: PlanOperation): string | undefined {\n if (operation.key) return operation.key;\n return operation.handle ? `${operation.kind}/${operation.handle}` : undefined;\n}\n\nfunction operationMatchesHandle(operationKind: string, handleKind: string): boolean {\n return operationKind === handleKind || (operationKind === 'dimension_members' && handleKind === 'dimension_table');\n}\n\nfunction currentContainer(resource: CurrentResource): string {\n if (!resource.current) {\n const contributor = resource.contributors[0];\n if (!contributor) return '.';\n if (\n contributor.kind === 'grouped' ||\n contributor.kind === 'share-group-owner' ||\n contributor.kind === 'grouped-navigation'\n )\n return contributor.selector.file;\n if (contributor.kind === 'raw' || contributor.kind === 'raw-navigation') return contributor.selector.sidecar;\n return contributor.kind === 'owner-field' ? contributor.ownerFile : contributor.selector.ownerFile;\n }\n return resource.current.codec === 'grouped'\n ? resource.current.mapping.selector.file\n : resource.current.mapping.selector.sidecar;\n}\n\nfunction pathInside(path: string, directory: string): boolean {\n return path.startsWith(`${directory}/`);\n}\n\nfunction hasFolderDescendants(\n scan: LayoutScanResult,\n mapping: WireSourceMapping,\n current: CompleteComposition,\n currentFolder: Document | undefined,\n detachedDocumentProofs: CompleteComposition['context']['evidence']['detachedDocumentProofs'],\n detachedFileProofs: CompleteComposition['context']['evidence']['detachedFileProofs'],\n): boolean {\n const directory = mapping.selector.file.endsWith('/_folder.json')\n ? folderDirectory(mapping.selector.file)\n : undefined;\n const paths = [\n ...scan.artifacts.filter((artifact) => artifact.present).map((artifact) => artifact.path),\n ...scan.tracked.map((tracked) => tracked.path),\n ...scan.localOnlyFiles,\n ...scan.opaqueDirectories,\n ];\n if (directory && paths.some((path) => path !== mapping.selector.file && pathInside(path, directory))) return true;\n\n const semanticPath =\n currentFolder?.kind === 'folder' &&\n Array.isArray(currentFolder.path) &&\n currentFolder.path.every((part) => typeof part === 'string')\n ? (currentFolder.path as string[])\n : undefined;\n if (semanticPath) {\n const descendant = current.documents.some((document) => {\n if (document === currentFolder) return false;\n const path =\n document.kind === 'folder' && Array.isArray(document.path)\n ? document.path\n : Array.isArray(document.folder)\n ? document.folder\n : undefined;\n if (!path || path.some((part) => typeof part !== 'string') || path.length < semanticPath.length)\n return false;\n if (!semanticPath.every((part, index) => path[index] === part)) return false;\n return document.kind !== 'folder' || path.length > semanticPath.length;\n });\n if (descendant) return true;\n }\n\n return hasDetachedDescendants(mapping, directory, semanticPath, detachedDocumentProofs, detachedFileProofs);\n}\n\n/** Descendants a directory does not hold: detached fallbacks that inherit this folder's limit. */\nfunction hasDetachedDescendants(\n mapping: WireSourceMapping,\n directory: string | undefined,\n semanticPath: readonly string[] | undefined,\n detachedDocumentProofs: CompleteComposition['context']['evidence']['detachedDocumentProofs'],\n detachedFileProofs: CompleteComposition['context']['evidence']['detachedFileProofs'],\n): boolean {\n const dependentSources = new Set([sourceIdentityKey(mapping.source)]);\n const proofs = [...Object.values(detachedDocumentProofs), ...Object.values(detachedFileProofs)];\n let changed = true;\n while (changed) {\n changed = false;\n for (const proof of proofs)\n if (\n proof.reason === 'representation-fallback' &&\n proof.inheritedFrom &&\n dependentSources.has(proof.inheritedFrom.sourceKey) &&\n !dependentSources.has(proof.sourceKey)\n ) {\n dependentSources.add(proof.sourceKey);\n changed = true;\n }\n }\n if (dependentSources.size > 1) return true;\n\n let semanticDirectory: string | undefined;\n if (semanticPath)\n try {\n semanticDirectory = `tree/${semanticPath.map(encodeLayoutSegment).join('/')}`;\n } catch {\n semanticDirectory = undefined;\n }\n return proofs.some(\n (proof) =>\n proof.reason === 'representation-fallback' &&\n proof.sourceKey !== sourceIdentityKey(mapping.source) &&\n proof.request !== undefined &&\n [directory, semanticDirectory].some(\n (parent) =>\n parent !== undefined &&\n (proof.request!.directory === parent || pathInside(proof.request!.directory, parent)),\n ),\n );\n}\n\n/**\n * Whether a folder the receipt would re-place may leave the directory the author gave it. The\n * receipt rewrites only the resources it carried, so a marker that travels alone would strand every\n * descendant the plan never touched. A folder with descendants therefore keeps its current\n * directory and the author pulls; a folder without descendants moves freely.\n */\nfunction folderMoveAllowed(\n current: CompleteComposition,\n mapping: WireSourceMapping,\n currentFolder: Document | undefined,\n): boolean {\n const evidence = current.context.evidence;\n return !hasFolderDescendants(\n current.context.scan,\n mapping,\n current,\n currentFolder,\n evidence.detachedDocumentProofs,\n evidence.detachedFileProofs,\n );\n}\n\n/**\n * Whether the workspace already holds this resource exactly as the head has it, placement included.\n * The canonical hash says nothing about placement: a folder rename leaves every descendant's hash\n * alone and changes only the folder path each descendant's document carries, and that path is what\n * decides the directory the descendant belongs in.\n */\nfunction placedAsAuthoritative(current: Document | undefined, authoritative: Document): boolean {\n return (\n current !== undefined &&\n same(withoutContainerSuppliedFields(current), withoutContainerSuppliedFields(authoritative))\n );\n}\n\nfunction folderRouteChanged(current: Document | undefined, authoritative: Document): boolean {\n return authoritative.kind === 'folder' && (!current || !same(current.path, authoritative.path));\n}\n\nfunction tableSiblingKey(key: string): string | undefined {\n if (key.startsWith('dimension_table/')) return `dimension_members/${key.slice('dimension_table/'.length)}`;\n if (key.startsWith('dimension_members/')) return `dimension_table/${key.slice('dimension_members/'.length)}`;\n return undefined;\n}\n\nfunction knownNull(document: Document): { field: 'icon' | 'template' } | undefined {\n if (document.kind === 'remote_job' && (document.icon === null || document.icon === undefined))\n return { field: 'icon' };\n if (document.kind === 'export_configuration' && document.template === null) return { field: 'template' };\n return undefined;\n}\n\n/**\n * The current association an accepted owner may keep. It is coherent only when the local projection\n * already carries the authoritative value, so no owner is ever written half from each side.\n */\nfunction coherentPreservedAttachment(\n current: CompleteComposition,\n source: SourceIdentity,\n ownerFile: string,\n field: 'icon' | 'template',\n authoritative: Json | undefined,\n): OwnerFieldProjection | undefined {\n const matches = current.binary.ownerFields.filter(\n (candidate) =>\n sourceIdentityKey(candidate.ownerSource) === sourceIdentityKey(source) &&\n candidate.ownerFile === ownerFile &&\n candidate.field === field,\n );\n if (matches.length !== 1) return undefined;\n const projection = matches[0];\n if (projection.status === 'omitted') return authoritative === undefined ? projection : undefined;\n if (projection.status !== 'value') return undefined;\n if (projection.value === null) return authoritative === null ? projection : undefined;\n return same(projection.value as unknown as Json, authoritative) ? projection : undefined;\n}\n\n/**\n * One document without the fields its physical container supplies: a combined table file names the\n * member set's table, and a directory names its folder. Rendering never writes them and composition\n * derives them again, so these fields are representation and not part of a round-trip comparison.\n */\nexport function withoutContainerSuppliedFields(document: Document): Document {\n if (document.kind === 'dimension_members') return without(document as JsonObject, ['table']) as Document;\n if (document.kind === 'folder') return without(document as JsonObject, ['name']) as Document;\n return clone(document);\n}\n\nfunction renderingContext(current: CompleteComposition): LayoutReadbackRenderingContext {\n return clone({\n authored: current.context.scan,\n grouped: current.grouped,\n binary: current.binary,\n byteFacts: current.context.byteFacts,\n });\n}\n\n/** Freeze the receipt-relevant composition facts before the plan POST. */\nexport function captureLayoutSubmissionComposition(composition: CompleteComposition): CapturedLayoutComposition {\n return { composition: clone(resourceEvidence(composition)) };\n}\n\n/** Bind returned plan identities to the already frozen composition before the apply POST. */\nexport function bindLayoutReceiptSubmission(input: BindLayoutReceiptSubmissionInput): LayoutReceiptSubmission {\n if (!input.planId || (input.plan.planId !== undefined && input.plan.planId !== input.planId))\n throw new Error('Submission plan identity is invalid');\n if (input.plan.documentKeys.length !== input.captured.composition.documents.length)\n throw new Error('Submission document keys do not align');\n return clone({\n planId: input.planId,\n documentKeys: input.plan.documentKeys,\n operations: input.plan.operations,\n handles: input.plan.handles,\n composition: input.captured.composition,\n });\n}\n\n/** A container is cleanable only while every fragment it still holds is exactly the proven one. */\nfunction containerIsClean(current: CompleteComposition, file: string): boolean {\n return (\n current.grouped.observations.every(\n (observation) => observation.selector.file !== file || observation.state === 'clean',\n ) &&\n current.binary.rawObservations.every(\n (observation) =>\n observation.selector.slot !== 'file-entry' ||\n observation.selector.sidecar !== file ||\n observation.state === 'clean',\n )\n );\n}\n\nfunction pathRemovals(paths: ReadonlyMap<string, Set<string>>, descending = false): PlannedPathRemoval[] {\n return [...paths]\n .map(([path, keys]) => ({ path, documentKeys: [...keys].sort(compareText) }))\n .sort((left, right) => (descending ? compareText(right.path, left.path) : compareText(left.path, right.path)));\n}\n\n/**\n * Split a removal set into whole files, loose bytes, container entries, owner pointers and the state\n * facts that go with them. This plans; it never deletes. An absent contributor has nothing physical\n * left to take out, so the author's own deletion only advances state.\n */\nfunction planRemovals(\n removals: readonly Extract<EligibilityDecision, { mode: 'remove' }>[],\n current: CompleteComposition,\n): PlannedLayoutDeletes {\n const json = new Map<string, Set<string>>();\n const bytes = new Map<string, Set<string>>();\n const directories = new Map<string, Set<string>>();\n const groupEntries: PlannedContainerRemoval[] = [];\n const pointers: PlannedPointerRemoval[] = [];\n const keys = new Set<string>();\n const sources = new Map<string, SourceIdentity>();\n const removedKeys = new Set(removals.map((removal) => removal.documentKey));\n const claim = (paths: Map<string, Set<string>>, path: string, documentKey: string) =>\n paths.set(path, (paths.get(path) ?? new Set<string>()).add(documentKey));\n const memberFiles = new Map<string, Set<string>>();\n const presentSidecars = new Set(\n current.context.scan.artifacts\n .filter((artifact) => artifact.role === 'raw-metadata' && artifact.present)\n .map((artifact) => artifact.path),\n );\n /** Deleting the bytes is the author's own deletion request, so it never keeps the resource. */\n const removable = (contributor: LayoutReadbackContributor) =>\n contributorIsClean(contributor) || (contributor.kind === 'raw' && contributor.state === 'absent');\n\n for (const removal of removals) {\n keys.add(removal.documentKey);\n sources.set(sourceIdentityKey(removal.source), clone(removal.source));\n // A dirty contributor keeps every contributor of its resource; only its state advances.\n if (removal.force !== true && !removal.contributors.every(removable)) continue;\n for (const contributor of removal.contributors) {\n if (contributor.kind === 'grouped') {\n if (contributor.state === 'absent') continue;\n if (contributor.selector.slot === 'share-entry')\n groupEntries.push({\n documentKey: removal.documentKey,\n container: contributor.selector.file,\n entry: clone(contributor.selector),\n });\n else if (contributor.selector.slot === 'member-set')\n // A member set never disappears alone; it joins the file its definition takes away.\n claim(memberFiles, contributor.selector.file, removal.documentKey);\n else {\n claim(json, contributor.selector.file, removal.documentKey);\n if (contributor.selector.file.endsWith('/_folder.json'))\n claim(directories, folderDirectory(contributor.selector.file), removal.documentKey);\n }\n } else if (contributor.kind === 'raw') {\n if (contributor.bytes && contributor.state !== 'absent')\n claim(bytes, contributor.bytes, removal.documentKey);\n // A sidecar holds one raw file alone, so it leaves whether or not its bytes are still there.\n if (presentSidecars.has(contributor.selector.sidecar))\n claim(json, contributor.selector.sidecar, removal.documentKey);\n } else if (contributor.kind === 'attachment' && contributor.bytes && contributor.state !== 'absent')\n claim(bytes, contributor.bytes, removal.documentKey);\n }\n }\n\n for (const [file, documentKeys] of memberFiles)\n if (json.has(file)) for (const documentKey of documentKeys) claim(json, file, documentKey);\n\n for (const file of new Set(groupEntries.map((entry) => entry.container))) {\n const entries = current.grouped.observations.filter(\n (observation) => observation.selector.file === file && observation.selector.slot === 'share-entry',\n );\n const removed = groupEntries.filter((entry) => entry.container === file);\n if (entries.length > removed.length || !containerIsClean(current, file)) continue;\n for (const entry of removed) claim(json, file, entry.documentKey);\n // A pointer leaves only beside a clean owner: a local edit after planning always wins over cleanup.\n for (const navigation of current.grouped.navigation.filter((route) => route.groupFile === file))\n if (\n !removedKeys.has(stableSourceKey(navigation.source) ?? '') &&\n !json.has(navigation.selector.file) &&\n containerIsClean(current, navigation.selector.file)\n )\n pointers.push({\n documentKey: removed[0].documentKey,\n owner: navigation.selector.file,\n groupFile: file,\n });\n for (const navigation of current.rawNavigation.filter((route) => route.groupFile === file))\n if (\n !removedKeys.has(stableSourceKey(navigation.source) ?? '') &&\n !json.has(navigation.selector.sidecar) &&\n containerIsClean(current, navigation.selector.sidecar)\n )\n pointers.push({\n documentKey: removed[0].documentKey,\n owner: navigation.selector.sidecar,\n groupFile: file,\n });\n }\n\n return {\n json: pathRemovals(json),\n bytes: pathRemovals(bytes),\n directories: pathRemovals(directories, true),\n groupEntries: groupEntries.filter((entry) => !json.has(entry.container)),\n pointers,\n keys: [...keys].sort(compareText),\n sources: [...sources.values()],\n };\n}\n\n/** Pure stable-resource receipt readback. It does not assemble files, write state, or adopt baselines. */\nexport function planReceiptReadback(input: PlanReceiptReadbackInput): PlanReceiptReadbackResult {\n const eligibility = decideReceiptEligibility(input);\n if (eligibility.status === 'blocked') return blocked(eligibility.diagnostics);\n return planMaterialization({ eligibility, head: input.head, current: input.current });\n}\n\n/**\n * Decide per canonical key what the receipt permits. Placement, decomposition and rendering do not\n * run here; {@link planMaterialization} consumes these decisions instead of recomputing them.\n */\nexport function decideReceiptEligibility(input: PlanReceiptReadbackInput): EligibilityResult {\n let head: Map<string, Document>;\n try {\n head = headDocuments(input.head);\n } catch (error) {\n return blocked([diagnostic('invalid-selected-head', '.', (error as Error).message)]);\n }\n const submittedIndex = indexSnapshot(input.submission.composition);\n const currentIndex = indexSnapshot(resourceEvidence(input.current));\n const currentRawSources = groupBySource(input.current.binary.rawSources, (mapping) =>\n sourceIdentityKey(mapping.source),\n );\n const snapshot = submittedResources(input.submission, submittedIndex);\n const assignmentValidation = validateAssignments(input.submission, input.receipt);\n const diagnostics = [...snapshot.diagnostics, ...assignmentValidation.diagnostics];\n /** Per-resource problems this decision skips; the resource keeps its content and its facts. */\n const warnings: ProjectionDiagnostic[] = [];\n const receiptResults: ReceiptReadbackResult[] = [];\n const decisions: EligibilityDecision[] = [];\n const eligible: EligibleResource[] = [];\n const consumedOutcomes = new Set<string>();\n const resolvedKeys = new Set<string>();\n const submittedByResolvedKey = new Map<string, SubmittedResource>();\n const deletedKeys = new Set(input.receipt.baseline.deleted);\n const removedKeys = new Set<string>();\n /** Drop one represented resource: its physical contributors when clean, and always its state. */\n const removeResource = (documentKey: string): void => {\n if (removedKeys.has(documentKey)) return;\n const source = stableSource(documentKey);\n if (!source) {\n // The key names no resource identity, so nothing is removed and nothing is forgotten.\n warnings.push(\n diagnostic('unsupported-removal-key', documentKey, 'Deleted key has no stable resource identity'),\n );\n return;\n }\n removedKeys.add(documentKey);\n const resource = currentResource(currentIndex, currentRawSources, source);\n decisions.push({\n mode: 'remove',\n documentKey,\n source: clone(source),\n contributors: clone(resource.contributors),\n ...(resource.current ? { current: clone(resource.current) } : {}),\n ...(resource.document ? { document: clone(resource.document) } : {}),\n });\n };\n\n for (const operation of input.submission.operations) {\n const outcomeKey = operationOutcomeKey(operation);\n if (!outcomeKey) {\n diagnostics.push(\n diagnostic('invalid-submission-operation', operation.name, 'Operation has no receipt identity'),\n );\n continue;\n }\n if (consumedOutcomes.has(outcomeKey)) {\n diagnostics.push(\n diagnostic('duplicate-submission-operation', outcomeKey, 'Operation receipt identity is duplicated'),\n );\n continue;\n }\n consumedOutcomes.add(outcomeKey);\n if (\n operation.handle &&\n (!input.submission.handles[operation.handle] ||\n !operationMatchesHandle(operation.kind, input.submission.handles[operation.handle].kind))\n )\n diagnostics.push(\n diagnostic(\n 'invalid-submission-operation',\n outcomeKey,\n 'Create operation does not match its stored handle',\n ),\n );\n const outcome = input.receipt.outcomes[outcomeKey];\n const assignment = operation.handle ? input.receipt.assignments[operation.handle] : undefined;\n if (assignment && !operationMatchesHandle(operation.kind, assignment.kind))\n diagnostics.push(\n diagnostic(\n 'invalid-receipt-assignment',\n outcomeKey,\n 'Receipt assignment kind does not match the create operation',\n ),\n );\n if (\n operation.handle &&\n outcome &&\n (outcome.outcome === OperationOutcomeOutcomeEnum.Applied ||\n outcome.outcome === OperationOutcomeOutcomeEnum.Unchanged) &&\n !assignment\n )\n diagnostics.push(\n diagnostic('missing-receipt-assignment', outcomeKey, 'Successful create outcome has no assignment'),\n );\n const documentKey = operation.key ?? (assignment ? `${operation.kind}/${assignment.id}` : undefined);\n if (documentKey && resolvedKeys.has(documentKey)) {\n diagnostics.push(\n diagnostic('duplicate-resolved-receipt-key', documentKey, 'Receipt operations resolve to one resource'),\n );\n continue;\n }\n if (documentKey) resolvedKeys.add(documentKey);\n const receiptHash = documentKey ? input.receipt.baseline.set[documentKey] : undefined;\n const headHash = documentKey ? input.head.manifest[documentKey] : undefined;\n const base = {\n outcomeKey,\n ...(documentKey ? { documentKey } : {}),\n ...(operation.handle ? { handle: operation.handle } : {}),\n ...(assignment ? { assignment: clone(assignment) } : {}),\n ...(outcome ? { outcome: outcome.outcome } : {}),\n ...(receiptHash ? { receiptHash } : {}),\n ...(headHash ? { headHash } : {}),\n };\n\n let classification: ReceiptResultClassification;\n if (!outcome) classification = 'missing-outcome';\n else if (outcome.outcome === OperationOutcomeOutcomeEnum.Failed) classification = 'failed';\n // A skipped resource never ran, so like a blocked one its file keeps the author's change.\n else if (\n outcome.outcome === OperationOutcomeOutcomeEnum.Blocked ||\n outcome.outcome === OperationOutcomeOutcomeEnum.Skipped\n )\n classification = 'blocked';\n else if (operation.action === PlanOperationActionEnum.Delete)\n classification = documentKey && deletedKeys.has(documentKey) ? 'eligible-removal' : 'delete-deferred';\n else if (!receiptHash) classification = 'no-receipt-baseline';\n else if (!headHash) classification = 'missing-head-document';\n else if (receiptHash !== headHash) classification = 'head-hash-mismatch';\n else classification = operation.handle ? 'eligible-assigned-create' : 'eligible-stable-set';\n const result: ReceiptReadbackResult = { ...base, classification };\n receiptResults.push(result);\n\n if (operation.action === PlanOperationActionEnum.Delete) {\n if (documentKey && classification === 'eligible-removal') removeResource(documentKey);\n continue;\n }\n if (!documentKey) continue;\n const create = operation.handle !== undefined;\n // A create's submitted resource is stored under its plan handle key, not its assigned key.\n const submitted = snapshot.resources.get(create ? outcomeKey : documentKey);\n if (create && submitted) submittedByResolvedKey.set(documentKey, submitted);\n if (create && classification !== 'eligible-assigned-create') continue;\n if (!submitted) {\n if (create) result.classification = 'assigned-create-deferred';\n // A converged key the workspace never submitted is not this receipt's business.\n else if (operation.action === PlanOperationActionEnum.Noop) continue;\n else\n diagnostics.push(\n diagnostic(\n 'unsupported-submission-evidence',\n documentKey,\n 'Stable operation has no retained resource snapshot',\n ),\n );\n continue;\n }\n if (create && !topLevelCreateHandleValid(input.submission, operation, submitted)) {\n diagnostics.push(\n diagnostic('invalid-submission-operation', outcomeKey, 'Create operation handle is not top-level'),\n );\n continue;\n }\n if (create && !createSourceMatches(input.submission.composition, submitted, operation)) {\n result.classification = 'assigned-create-deferred';\n continue;\n }\n const current = currentResource(\n currentIndex,\n currentRawSources,\n submitted.source,\n create ? submitted.submissionSource : undefined,\n );\n const preserve = (reason: PreserveReason): void => {\n decisions.push({\n mode: 'preserve',\n documentKey,\n source: clone(submitted.source),\n ...(current.document ? { document: clone(current.document) } : {}),\n contributors: clone(current.contributors),\n reason,\n });\n };\n if (current.presence === 'unsupported') {\n // The container changed since submission, so only the assigned identity is patched.\n if (create) result.classification = 'assigned-create-deferred';\n else preserve('unsupported-evidence');\n continue;\n }\n if (current.presence === 'absent') {\n if (create) result.classification = 'assigned-create-deferred';\n else decisions.push({ mode: 'keep-absent', documentKey, contributors: clone(current.contributors) });\n continue;\n }\n if (classification !== 'eligible-stable-set' && classification !== 'eligible-assigned-create') {\n preserve(\n classification === 'failed' || classification === 'blocked'\n ? 'unsuccessful-outcome'\n : classification === 'missing-outcome'\n ? 'missing-outcome'\n : 'deferred-receipt',\n );\n continue;\n }\n if (resourceFingerprint(submitted.contributors) !== resourceFingerprint(current.contributors)) {\n if (create) result.classification = 'assigned-create-deferred';\n else preserve('post-submission-change');\n continue;\n }\n const authoritative = head.get(documentKey);\n const hash = current.currentHash;\n if (!authoritative || !current.current || !hash) {\n preserve('unsupported-evidence');\n continue;\n }\n if (\n authoritative.kind === 'folder' &&\n current.current.codec === 'grouped' &&\n folderRouteChanged(current.document, authoritative) &&\n !folderMoveAllowed(input.current, current.current.mapping, current.document)\n ) {\n preserve('protected-descendant');\n continue;\n }\n eligible.push({\n result,\n submitted,\n current: { ...current, current: current.current, currentHash: hash, presence: 'present' },\n authoritative,\n });\n }\n\n for (const [outcomeKey, outcome] of Object.entries(input.receipt.outcomes)) {\n if (consumedOutcomes.has(outcomeKey)) continue;\n if (!outcomeKey.startsWith('share/')) {\n warnings.push(\n diagnostic('unmatched-receipt-outcome', outcomeKey, 'Receipt outcome has no stored operation'),\n );\n continue;\n }\n const receiptHash = input.receipt.baseline.set[outcomeKey];\n const headHash = input.head.manifest[outcomeKey];\n receiptResults.push({\n outcomeKey,\n documentKey: outcomeKey,\n outcome: outcome.outcome,\n ...(receiptHash ? { receiptHash } : {}),\n ...(headHash ? { headHash } : {}),\n classification:\n outcome.outcome === OperationOutcomeOutcomeEnum.Failed\n ? 'failed'\n : outcome.outcome === OperationOutcomeOutcomeEnum.Blocked\n ? 'blocked'\n : 'generated-share-deferred',\n });\n }\n\n for (const documentKey of [...deletedKeys].sort(compareText)) removeResource(documentKey);\n\n const knownBaselineKeys = new Set([\n ...receiptResults.flatMap((result) => (result.documentKey ? [result.documentKey] : [])),\n ]);\n for (const key of Object.keys(input.receipt.baseline.set).sort(compareText)) {\n if (knownBaselineKeys.has(key)) continue;\n // Item-node creation generates inherited and creator shares the submission never authored.\n if (key.startsWith('share/')) {\n knownBaselineKeys.add(key);\n receiptResults.push({\n outcomeKey: key,\n documentKey: key,\n receiptHash: input.receipt.baseline.set[key],\n ...(input.head.manifest[key] ? { headHash: input.head.manifest[key] } : {}),\n classification: 'generated-share-deferred',\n });\n continue;\n }\n warnings.push(\n diagnostic('unmatched-receipt-baseline', key, 'Receipt baseline has no operation or generated share'),\n );\n }\n\n if (diagnostics.length > 0) return blocked(diagnostics);\n\n for (const result of receiptResults.filter((item) => item.classification === 'generated-share-deferred')) {\n const documentKey = result.documentKey!;\n const source = stableSource(documentKey);\n if (!source) {\n warnings.push(\n diagnostic('unsupported-generated-share', documentKey, 'Generated share key has no stable identity'),\n );\n continue;\n }\n const resource = currentResource(currentIndex, currentRawSources, source);\n const authoritative = head.get(documentKey);\n const preserveGenerated = (reason: PreserveReason): void => {\n decisions.push({\n mode: 'preserve',\n documentKey,\n source: clone(source),\n ...(resource.document ? { document: clone(resource.document) } : {}),\n contributors: clone(resource.contributors),\n reason,\n });\n };\n if (!authoritative || !result.receiptHash || result.receiptHash !== result.headHash) {\n preserveGenerated('pull-needed');\n continue;\n }\n if (resource.presence === 'present') {\n // A replayed receipt finds its own earlier insertion; it never rewrites a later local edit.\n if (resource.contributors.every(contributorIsClean) && same(resource.document, authoritative))\n decisions.push({ mode: 'noop', documentKey });\n else preserveGenerated('kept-local');\n continue;\n }\n // Pull must not recreate a locally deleted group, and a generated share follows the same rule.\n if (resource.presence === 'absent' || ownerGroupDeleted(input.current, authoritative)) {\n preserveGenerated('local-deletion-pending');\n continue;\n }\n decisions.push({\n mode: 'set',\n documentKey,\n placement: 'insert-authoritative',\n document: clone(authoritative),\n source: clone(source),\n contributors: clone(resource.contributors),\n });\n }\n\n if (diagnostics.length > 0) return blocked(diagnostics);\n\n const suppressed = new Set<string>();\n for (const candidate of eligible) {\n const siblingKey = tableSiblingKey(candidate.result.documentKey!);\n if (!siblingKey) continue;\n const decidedAbsent = decisions.find(\n (decision) => decision.mode === 'keep-absent' && decision.documentKey === siblingKey,\n );\n // A promoted create's sibling is still stored under its own plan handle key.\n const siblingSubmittedKey = tableSiblingKey(candidate.result.outcomeKey);\n const submittedSibling =\n submittedByResolvedKey.get(siblingKey) ??\n snapshot.resources.get(siblingKey) ??\n (siblingSubmittedKey ? snapshot.resources.get(siblingSubmittedKey) : undefined);\n const currentSibling = submittedSibling\n ? currentResource(\n currentIndex,\n currentRawSources,\n submittedSibling.source,\n submittedSibling.submissionSource,\n )\n : undefined;\n if (!decidedAbsent && currentSibling?.presence !== 'absent') {\n if (!submittedSibling || currentSibling?.presence === 'unsupported')\n diagnostics.push(\n diagnostic(\n 'unsupported-table-sibling',\n siblingKey,\n 'Table sibling evidence is missing or ambiguous',\n ),\n );\n continue;\n }\n if (!decidedAbsent && currentSibling?.presence === 'absent')\n decisions.push({\n mode: 'keep-absent',\n documentKey: siblingKey,\n contributors: clone(currentSibling.contributors),\n });\n suppressed.add(candidate.result.documentKey!);\n decisions.push({\n mode: 'suppressed',\n documentKey: candidate.result.documentKey!,\n container: currentContainer(candidate.current),\n reason: 'intentional-sibling-absence',\n });\n }\n\n if (diagnostics.length > 0) return blocked(diagnostics);\n\n for (const candidate of eligible) {\n const documentKey = candidate.result.documentKey!;\n if (suppressed.has(documentKey)) continue;\n decisions.push({\n mode: 'set',\n documentKey,\n placement: 'replace-proven',\n outcomeKey: candidate.result.outcomeKey,\n document: clone(candidate.authoritative),\n source: clone(candidate.submitted.source),\n current: clone(candidate.current.current),\n expectedCurrentHash: candidate.current.currentHash,\n ...(candidate.current.document ? { currentDocument: clone(candidate.current.document) } : {}),\n contributors: clone(candidate.current.contributors),\n });\n }\n\n // Every assigned id reaches the workspace: a rewritten document carries it, the rest is patched.\n const rewrittenIndexes = new Set(\n eligible\n .filter((candidate) => !suppressed.has(candidate.result.documentKey!))\n .map((candidate) => candidate.submitted.submissionSource.mapping.documentIndex),\n );\n const assignmentsByIndex = groupBySource(assignmentValidation.assignments, (item) =>\n String(item.location.documentIndex),\n );\n const identityPatches: PlannedIdentityPatch[] = [];\n for (const [index, list] of [...assignmentsByIndex].sort((left, right) => compareText(left[0], right[0]))) {\n const documentIndex = Number(index);\n if (rewrittenIndexes.has(documentIndex)) continue;\n const document = input.submission.composition.documents[documentIndex];\n const sources = input.submission.composition.sources.filter(\n (candidate) =>\n candidate.mapping.documentIndex === documentIndex &&\n (candidate.codec === 'raw' || candidate.mapping.selector.slot !== 'member-set'),\n );\n if (!document || sources.length !== 1) continue;\n const source = sources[0];\n const submittedKey = input.submission.documentKeys[documentIndex];\n const resolved = receiptResults.filter((item) => item.outcomeKey === submittedKey && item.documentKey);\n identityPatches.push({\n documentKey: resolved.length === 1 ? resolved[0].documentKey! : submittedKey,\n source: clone(source.mapping.source),\n ...(source.codec === 'grouped'\n ? {\n container: source.mapping.selector.file,\n slot: source.mapping.selector.slot,\n ...(source.mapping.selector.slot === 'share-entry'\n ? { shareIdentity: clone(source.mapping.selector.identity) }\n : {}),\n }\n : { container: source.mapping.selector.sidecar, slot: 'file-entry' as const }),\n submittedDocument: clone(document),\n assignments: clone(list),\n });\n }\n\n return {\n status: 'complete',\n decisions,\n receiptResults,\n assignments: assignmentValidation.assignments,\n headDocuments: head,\n submittedSources: Object.fromEntries(\n [...submittedByResolvedKey].map(([key, item]) => [key, clone(item.source)]),\n ),\n identityPatches,\n submissionProofs: {\n grouped: clone(input.submission.composition.groupedSubmissions ?? []),\n binary: clone(input.submission.composition.binarySubmissions ?? []),\n },\n warnings,\n };\n}\n\n/**\n * Turn decisions into physical sets: allocate destinations, decompose the authoritative documents\n * into container patches and pair attachments. Every decision arrives already taken.\n */\n/**\n * Plan what the writer physically does with every accepted resource. A problem that names one\n * resource takes that resource out of the placement and preserves it; the rest is planned again,\n * so a shared container never keeps a decision that its co-hosted sibling's failure invalidated.\n */\nexport function planMaterialization(input: PlanMaterializationInput): PlanReceiptReadbackResult {\n const { eligibility } = input;\n const removals = eligibility.decisions.flatMap((decision) => (decision.mode === 'remove' ? [decision] : []));\n const deletes = planRemovals(removals, input.current);\n const setDecisions = eligibility.decisions.flatMap((decision) => (decision.mode === 'set' ? [decision] : []));\n const setByKey = new Map(setDecisions.map((decision) => [decision.documentKey, decision]));\n const demoted = new Map<string, { reason: PreserveReason; diagnostic?: ProjectionDiagnostic }>();\n for (;;) {\n const result = planMaterializationAttempt(input, { setDecisions, setByKey, deletes, demoted });\n if (result.status !== 'retry') return result;\n }\n}\n\ninterface MaterializationAttempt {\n setDecisions: readonly Extract<EligibilityDecision, { mode: 'set' }>[];\n setByKey: ReadonlyMap<string, Extract<EligibilityDecision, { mode: 'set' }>>;\n deletes: PlannedLayoutDeletes;\n demoted: Map<string, { reason: PreserveReason; diagnostic?: ProjectionDiagnostic }>;\n}\n\nfunction planMaterializationAttempt(\n input: PlanMaterializationInput,\n attempt: MaterializationAttempt,\n): PlanReceiptReadbackResult | { status: 'retry' } {\n const { eligibility } = input;\n const { setByKey, deletes, demoted } = attempt;\n const head = eligibility.headDocuments;\n const currentIndex = indexSnapshot(resourceEvidence(input.current));\n const receiptResults = eligibility.receiptResults;\n const assignments = eligibility.assignments;\n const diagnostics: ProjectionDiagnostic[] = [];\n /** Resources this attempt must hand back to the workspace before the next one runs. */\n const perResource: { key: string; diagnostic?: ProjectionDiagnostic }[] = [];\n const retry = { status: 'retry' } as const;\n /** One resource's problem: preserve it and plan again; anything else still blocks the command. */\n const fail = (\n key: string | undefined,\n item: ProjectionDiagnostic,\n ): PlanReceiptReadbackResult | { status: 'retry' } => failMany(key === undefined ? [] : [key], item);\n /** A container problem takes every resource hosted in it out of the plan, never only one. */\n const failMany = (\n keys: readonly string[],\n item: ProjectionDiagnostic,\n ): PlanReceiptReadbackResult | { status: 'retry' } => {\n const pending = keys.filter((key) => setByKey.has(key) && !demoted.has(key));\n if (pending.length === 0) return blocked([item]);\n for (const key of pending) demoted.set(key, { reason: 'unmaterialized', diagnostic: item });\n return retry;\n };\n const materializations: PhysicalMaterialization[] = eligibility.decisions.flatMap((decision) =>\n decision.mode === 'preserve' || decision.mode === 'keep-absent' || decision.mode === 'suppressed'\n ? [clone(decision)]\n : [],\n );\n const preserveDemoted = (documentKey: string, reason: PreserveReason): void => {\n const candidate = setByKey.get(documentKey)!;\n materializations.push({\n mode: 'preserve',\n documentKey,\n source: clone(candidate.source),\n ...(candidate.currentDocument ? { document: clone(candidate.currentDocument) } : {}),\n contributors: clone(candidate.contributors),\n reason,\n });\n };\n for (const [documentKey, entry] of demoted) preserveDemoted(documentKey, entry.reason);\n\n const placed = attempt.setDecisions.filter((decision) => !demoted.has(decision.documentKey));\n const finish = (extra: Partial<Extract<PlanReceiptReadbackResult, { status: 'complete' }>> = {}) =>\n ({\n status: 'complete',\n receiptResults,\n assignments,\n materializations,\n deletes,\n identityPatches: clone(eligibility.identityPatches ?? []),\n groupedPatches: [],\n groupedCompanions: [],\n rawPatches: [],\n attachments: [],\n pendingDamage: [],\n derivedSourceProofs: [],\n unmaterializedDiagnostics: [\n ...(eligibility.warnings ?? []),\n ...[...demoted.values()].flatMap((entry) => (entry.diagnostic ? [entry.diagnostic] : [])),\n ],\n notices: clone(eligibility.notices ?? []) as LayoutReadbackNotice[],\n renderingContext: renderingContext(input.current),\n submissionProofs: clone(eligibility.submissionProofs?.grouped ?? []),\n ...extra,\n }) as Extract<PlanReceiptReadbackResult, { status: 'complete' }>;\n /** Hand every per-resource problem of this attempt back to the workspace, or block for real. */\n const checkpoint = (): PlanReceiptReadbackResult | { status: 'retry' } | undefined => {\n const pending = perResource.filter((item) => setByKey.has(item.key) && !demoted.has(item.key));\n for (const item of pending) demoted.set(item.key, { reason: 'unmaterialized', diagnostic: item.diagnostic });\n if (pending.length > 0) return retry;\n const rest = [...diagnostics, ...perResource.flatMap((item) => (item.diagnostic ? [item.diagnostic] : []))];\n return rest.length > 0 ? blocked(rest) : undefined;\n };\n /** A placement diagnostic keyed by one candidate preserves that candidate instead of blocking. */\n const placementFailed = (items: readonly ProjectionDiagnostic[]) => {\n // A diagnostic that names no candidate blocks on its own, so it is recorded exactly once.\n for (const item of items)\n if (setByKey.has(item.path)) perResource.push({ key: item.path, diagnostic: item });\n else diagnostics.push(item);\n return checkpoint() ?? blocked(items);\n };\n if (placed.length === 0) return finish();\n\n /**\n * Placement runs twice when a table sibling defers. The deferral set compares each allocated\n * destination with its sibling's current file, and only placement produces those destinations.\n */\n const place = (candidates: readonly Extract<EligibilityDecision, { mode: 'set' }>[]) => {\n const documents = candidates.map((candidate) => candidate.document);\n const documentKeys = candidates.map((candidate) => candidate.documentKey);\n const intents: AuthoritativePlacementIntent[] = candidates.map((candidate, documentIndex) =>\n candidate.placement === 'replace-proven'\n ? {\n mode: 'replace-proven',\n documentIndex,\n documentKey: candidate.documentKey,\n current: candidate.current!,\n expectedCurrentHash: candidate.expectedCurrentHash!,\n }\n : {\n mode: 'insert-authoritative',\n documentIndex,\n documentKey: candidate.documentKey,\n ...(candidate.reinsert ? { reinsert: true } : {}),\n },\n );\n return planAuthoritativePlacement({\n placement: input.current.context.placement,\n scan: input.current.context.scan,\n detachedDocumentProofs: input.current.context.evidence.detachedDocumentProofs,\n detachedFileProofs: input.current.context.evidence.detachedFileProofs,\n canonicalBaseline: input.current.context.evidence.canonicalBaseline,\n groupedRoutes: input.current.context.evidence.groupedRoutes,\n ...(input.head ? { head: input.head, headDocuments: head } : {}),\n documents,\n documentKeys,\n intents,\n currentGrouped: input.current.grouped,\n currentBinary: input.current.binary,\n });\n };\n const placement = place(placed);\n if (placement.status === 'blocked') return placementFailed(placement.diagnostics);\n\n const placedKeys = new Set(placed.map((candidate) => candidate.documentKey));\n const decidedSourceByKey = new Map(\n eligibility.decisions.flatMap((decision) =>\n (decision.mode === 'set' || decision.mode === 'remove' || decision.mode === 'preserve') &&\n decision.documentKey\n ? [[decision.documentKey, decision.source] as const]\n : [],\n ),\n );\n const relocationDeferred = new Set<string>();\n for (const source of placement.groupedSources) {\n const siblingKey = tableSiblingKey(source.documentKey);\n if (!siblingKey || placedKeys.has(siblingKey)) continue;\n const siblingSource =\n decidedSourceByKey.get(siblingKey) ??\n eligibility.submittedSources?.[siblingKey] ??\n stableSource(siblingKey);\n let siblingMappings = siblingSource\n ? input.current.grouped.sources.filter(\n (candidate) => sourceIdentityKey(candidate.source) === sourceIdentityKey(siblingSource),\n )\n : [];\n // A promoted create has no sibling key yet, so the shared container names the other half.\n const currentSource = setByKey.get(source.documentKey)?.current;\n if (siblingMappings.length !== 1 && currentSource?.codec === 'grouped') {\n const slot = currentSource.mapping.selector.slot === 'table-definition' ? 'member-set' : 'table-definition';\n siblingMappings = input.current.grouped.sources.filter(\n (candidate) =>\n candidate.selector.file === currentSource.mapping.selector.file && candidate.selector.slot === slot,\n );\n }\n if (siblingMappings.length !== 1) {\n // The sibling that shares this file has no exact evidence, so its host waits too.\n perResource.push({\n key: source.documentKey,\n diagnostic: diagnostic(\n 'unsupported-table-sibling',\n siblingKey,\n 'Preserved table sibling has no exact current mapping',\n ),\n });\n continue;\n }\n if (source.destination.file !== siblingMappings[0].selector.file) relocationDeferred.add(source.documentKey);\n }\n const afterSiblings = checkpoint();\n if (afterSiblings) return afterSiblings;\n if (relocationDeferred.size > 0) {\n for (const documentKey of relocationDeferred)\n demoted.set(documentKey, { reason: 'shared-container-relocation' });\n return retry;\n }\n\n // A source this plan writes at another destination, or removes, leaves its current file behind.\n const vacating = placement.groupedSources\n .filter((source) => source.mapping.selector.file !== source.destination.file)\n .map((source) => source.mapping.source)\n .concat(deletes.sources);\n const grouped = decomposeGroupedLayout({\n documents: placement.groupedDocuments,\n documentKeys: placement.groupedDocumentKeys,\n sources: placement.groupedSources.map((source) => source.mapping),\n currentArtifacts: input.current.context.groupedArtifacts,\n current: input.current.grouped,\n vacating,\n ...(eligibility.submissionProofs ? { submissionProofs: eligibility.submissionProofs.grouped } : {}),\n });\n if (grouped.diagnostics.length > 0) return blocked(grouped.diagnostics);\n\n const groupedCompanions: GroupedCompanionMaterialization[] = [];\n const companionTargets = new Set<string>();\n for (const patch of grouped.patches.filter((candidate) => candidate.selector.slot === 'share-group-owner')) {\n const target = canonicalText(patch.selector);\n if (companionTargets.has(target))\n return blocked([\n diagnostic(\n 'duplicate-share-group-companion',\n patch.selector.file,\n 'Share group header candidate is duplicated',\n ),\n ]);\n companionTargets.add(target);\n const headerProofs = input.current.grouped.observations.filter(\n (observation) =>\n observation.selector.slot === 'share-group-owner' &&\n sameSelector(observation.selector, patch.selector) &&\n sourceIdentityKey(observation.source) === sourceIdentityKey(patch.source) &&\n observation.currentHash !== undefined &&\n observation.currentHash === patch.expectedCurrentHash,\n );\n const authorizers = placement.groupedSources.filter((source) => {\n if (source.mapping.selector.slot !== 'share-entry' || source.mapping.selector.file !== patch.selector.file)\n return false;\n const document = placement.groupedDocuments[source.mapping.documentIndex];\n const entryPatch = grouped.patches.filter(\n (candidate) =>\n sameSelector(candidate.selector, source.mapping.selector) &&\n sourceIdentityKey(candidate.source) === sourceIdentityKey(source.mapping.source),\n );\n return document.kind === 'share' && entryPatch.length === 1 && same(document.owner, patch.value);\n });\n // A freshly inserted group has no current header to prove; its entries are the only authority.\n const insertedGroup =\n authorizers.length > 0 &&\n authorizers.every((source) => setByKey.get(source.documentKey)?.placement === 'insert-authoritative');\n if ((headerProofs.length !== 1 && !insertedGroup) || authorizers.length === 0)\n return failMany(\n placement.groupedSources\n .filter((source) => source.mapping.selector.file === patch.selector.file)\n .map((source) => source.documentKey),\n diagnostic(\n 'unbound-share-group-companion',\n patch.selector.file,\n 'Share group header candidate lacks exact accepted-entry proof',\n ),\n );\n groupedCompanions.push({\n kind: 'share-group-owner',\n authorizingDocumentKeys: authorizers.map((source) => source.documentKey),\n patch: clone(patch),\n });\n }\n\n const ownerDocuments = placement.groupedSources.flatMap((placedSource) => {\n const document = placement.groupedDocuments[placedSource.mapping.documentIndex];\n return ownerField(document)\n ? [\n {\n source: placedSource.mapping.source,\n ownerFile: placedSource.mapping.selector.file,\n document,\n },\n ]\n : [];\n });\n const binary = decomposeBinaryLayout({\n rawDocuments: placement.rawDocuments,\n rawSources: placement.rawSources.map((source) => source.mapping),\n ownerDocuments,\n ownerFields: placement.attachments.flatMap((attachment) => (attachment.current ? [attachment.current] : [])),\n ownerInsertions: placement.ownerInsertions,\n current: input.current.binary,\n vacating: placement.rawSources\n .filter((source) => !sameRawSelector(source.mapping.selector, source.destination))\n .map((source) => source.mapping.source)\n .concat(deletes.sources),\n ...(eligibility.submissionProofs ? { submissionProofs: eligibility.submissionProofs.binary } : {}),\n });\n if (binary.diagnostics.length > 0) return blocked(binary.diagnostics);\n\n const physicallySet = new Set(placed.map((candidate) => candidate.documentKey));\n const physicallySetSources = new Set(\n placement.groupedSources\n .map((item) => sourceIdentityKey(item.mapping.source))\n .concat(placement.rawSources.map((item) => sourceIdentityKey(item.mapping.source))),\n );\n const decidedDocumentKeys = new Set(materializations.map((decision) => decision.documentKey));\n const decidedSources = new Set(\n materializations.flatMap((decision) =>\n decision.mode === 'preserve' ? [sourceIdentityKey(decision.source)] : [],\n ),\n );\n // A sibling with incomplete evidence takes its host out of the plan: the container is never\n // written half rendered, and the host resource keeps its own content until the sibling is sound.\n const preserveSharedSource = (source: LayoutSubmissionSource, hostKey: string): void => {\n const documentKey = stableSourceKey(source.mapping.source);\n const sourceKey = sourceIdentityKey(source.mapping.source);\n if (\n (documentKey && (physicallySet.has(documentKey) || decidedDocumentKeys.has(documentKey))) ||\n physicallySetSources.has(sourceKey) ||\n decidedSources.has(sourceKey)\n )\n return;\n const document = mappingDocument(currentIndex.snapshot, source);\n const contributors = contributorsForMapping(currentIndex, source);\n if (!document || contributors.length === 0) {\n perResource.push({\n key: hostKey,\n diagnostic: diagnostic(\n 'unsupported-shared-sibling',\n documentKey ?? sourceKey,\n 'Shared-container sibling evidence is incomplete',\n ),\n });\n return;\n }\n materializations.push({\n mode: 'preserve',\n ...(documentKey ? { documentKey } : {}),\n source: clone(source.mapping.source),\n document: clone(document),\n contributors: clone(contributors),\n reason: 'shared-container-sibling',\n });\n if (documentKey) decidedDocumentKeys.add(documentKey);\n decidedSources.add(sourceKey);\n };\n for (const placedSource of placement.groupedSources) {\n const files = new Set([placedSource.mapping.selector.file, placedSource.destination.file]);\n for (const source of input.current.sources)\n if (source.codec === 'grouped' && files.has(source.mapping.selector.file))\n preserveSharedSource(source, placedSource.documentKey);\n }\n const afterSiblingSources = checkpoint();\n if (afterSiblingSources) return afterSiblingSources;\n\n const attachmentDestinations = new Map<string, AllocatedAttachmentCorrespondence['destination']>();\n for (const patch of binary.ownerPatches) {\n const placedOwner = placement.groupedSources.filter(\n (source) =>\n sourceIdentityKey(source.mapping.source) === sourceIdentityKey(patch.source) &&\n source.mapping.selector.file === patch.ownerFile &&\n ownerField(placement.groupedDocuments[source.mapping.documentIndex]) === patch.field,\n );\n const placedAttachment = placement.attachments.filter(\n (attachment) =>\n sourceIdentityKey(attachment.source) === sourceIdentityKey(patch.source) &&\n attachment.field === patch.field &&\n (patch.origin === 'authoritative-insertion'\n ? attachment.current === undefined && attachment.destination.ownerFile === patch.ownerFile\n : attachment.current?.ownerFile === patch.ownerFile),\n );\n const ownerSet = placedOwner.flatMap((source) =>\n grouped.patches.filter(\n (candidate) =>\n candidate.action === 'set' &&\n sourceIdentityKey(candidate.source) === sourceIdentityKey(source.mapping.source) &&\n sameSelector(candidate.selector, source.mapping.selector) &&\n same(candidate.value, placement.groupedDocuments[source.mapping.documentIndex]),\n ),\n );\n const authoritativeValue =\n placedOwner.length === 1\n ? placement.groupedDocuments[placedOwner[0].mapping.documentIndex][patch.field]\n : undefined;\n const descriptorMatches =\n patch.action === 'set'\n ? same(patch.value, authoritativeValue)\n : authoritativeValue === null || (authoritativeValue === undefined && patch.field === 'icon');\n const currentHashMatches =\n patch.origin === 'authoritative-insertion'\n ? placedAttachment.length === 1 &&\n placedAttachment[0].current === undefined &&\n placedOwner[0]?.mode === 'insert-authoritative' &&\n patch.groupedSelector.file === placedOwner[0]?.destination.file\n : placedAttachment.length === 1 &&\n patch.expectedCurrentHash === placedAttachment[0].current?.currentHash;\n if (\n placedOwner.length !== 1 ||\n placedAttachment.length !== 1 ||\n ownerSet.length !== 1 ||\n !same(patch.ownerDocument, placement.groupedDocuments[placedOwner[0]?.mapping.documentIndex]) ||\n !descriptorMatches ||\n !currentHashMatches\n )\n return fail(\n placedOwner[0]?.documentKey ?? stableSourceKey(patch.source),\n diagnostic(\n 'unpaired-attachment-patch',\n patch.ownerFile,\n 'Attachment candidate does not match one whole-owner set',\n ),\n );\n attachmentDestinations.set(\n `${sourceIdentityKey(patch.source)}/${patch.field}`,\n clone(placedAttachment[0].destination),\n );\n }\n\n for (const source of placement.groupedSources) {\n const candidate = setByKey.get(source.documentKey)!;\n const patches = grouped.patches.filter(\n (patch) =>\n sourceIdentityKey(patch.source) === sourceIdentityKey(source.mapping.source) &&\n sameSelector(patch.selector, source.mapping.selector),\n );\n const expectedValue = mappingValue(candidate.document, source.mapping);\n if (\n patches.length !== 1 ||\n patches[0].action !== 'set' ||\n expectedValue === undefined ||\n !same(patches[0].value, expectedValue)\n )\n return fail(\n source.documentKey,\n diagnostic(\n 'invalid-accepted-patch',\n source.documentKey,\n 'Grouped set does not match accepted current and authoritative evidence',\n ),\n );\n materializations.push({\n mode: 'set',\n codec: 'grouped',\n documentKey: source.documentKey,\n outcomeKey: candidate.outcomeKey ?? candidate.documentKey,\n placement: source.mode,\n document: clone(candidate.document),\n destination: clone(source.destination),\n ...(sameSelector(source.mapping.selector, source.destination)\n ? {}\n : { origin: clone(source.mapping.selector) }),\n patches: clone(patches),\n });\n }\n for (const source of placement.rawSources) {\n const candidate = setByKey.get(source.documentKey)!;\n const patches = binary.rawPatches.filter(\n (patch) => sourceIdentityKey(patch.source) === sourceIdentityKey(source.mapping.source),\n );\n if (\n patches.length !== 1 ||\n patches[0].action !== 'set' ||\n !sameBinarySelector(patches[0].selector, source.mapping.selector) ||\n !same(patches[0].document, candidate.document) ||\n patches[0].bytes !== source.mapping.bytes ||\n !same(patches[0].content, candidate.document.content)\n )\n return fail(\n source.documentKey,\n diagnostic(\n 'invalid-accepted-patch',\n source.documentKey,\n 'Raw set does not match accepted current and authoritative evidence',\n ),\n );\n materializations.push({\n mode: 'set',\n codec: 'raw',\n documentKey: source.documentKey,\n outcomeKey: candidate.outcomeKey ?? candidate.documentKey,\n placement: source.mode,\n document: clone(candidate.document),\n destination: clone(source.destination),\n ...(sameRawSelector(source.mapping.selector, source.destination)\n ? {}\n : { origin: clone(source.mapping.selector) }),\n bytes: source.bytes,\n patch: clone(patches[0]),\n });\n }\n\n const attachments: AttachmentMaterialization[] = binary.ownerPatches.map((patch) => {\n const ownerDocumentKey =\n placement.groupedSources.find(\n (source) => sourceIdentityKey(source.mapping.source) === sourceIdentityKey(patch.source),\n )?.documentKey ?? stableSourceKey(patch.source)!;\n const destination = attachmentDestinations.get(`${sourceIdentityKey(patch.source)}/${patch.field}`)!;\n const retainedNull =\n patch.action === 'clear' &&\n input.current.binary.ownerFields.some(\n (field) =>\n sourceIdentityKey(field.ownerSource) === sourceIdentityKey(patch.source) &&\n field.field === patch.field &&\n field.status === 'value' &&\n field.value === null,\n );\n return retainedNull\n ? {\n mode: 'known-null' as const,\n ownerDocumentKey,\n source: clone(patch.source) as StableSource,\n ownerFile: destination.ownerFile,\n field: patch.field,\n }\n : { mode: patch.action, ownerDocumentKey, patch: clone(patch), destination };\n });\n for (const source of placement.groupedSources) {\n const document = placement.groupedDocuments[source.mapping.documentIndex];\n const nullField = knownNull(document);\n if (\n nullField &&\n !attachments.some(\n (candidate) =>\n candidate.ownerDocumentKey === source.documentKey &&\n ('patch' in candidate ? candidate.patch.field : candidate.field) === nullField.field,\n )\n )\n attachments.push({\n mode: 'known-null',\n ownerDocumentKey: source.documentKey,\n source: clone(source.mapping.source) as StableSource,\n ownerFile: source.destination.file,\n field: nullField.field,\n });\n }\n\n // Attachment readback is accepted with its whole owner, so every accepted owner decides its field.\n for (const source of placement.groupedSources) {\n const document = placement.groupedDocuments[source.mapping.documentIndex];\n const field = ownerField(document);\n if (\n !field ||\n attachments.some(\n (candidate) =>\n candidate.ownerDocumentKey === source.documentKey &&\n ('patch' in candidate ? candidate.patch.field : candidate.field) === field,\n )\n )\n continue;\n const projection = coherentPreservedAttachment(\n input.current,\n source.mapping.source,\n source.mapping.selector.file,\n field,\n document[field],\n );\n if (!projection)\n return fail(\n source.documentKey,\n diagnostic(\n 'incoherent-accepted-attachment',\n source.destination.file,\n 'Accepted owner attachment has no coherent current association',\n ),\n );\n attachments.push({\n mode: 'preserve',\n ownerDocumentKey: source.documentKey,\n source: clone(source.mapping.source) as StableSource,\n ownerFile: source.destination.file,\n field,\n ...(projection.bytes ? { bytes: projection.bytes } : {}),\n });\n }\n\n const setKeys = new Set(\n materializations.filter((decision) => decision.mode === 'set').map((decision) => decision.documentKey),\n );\n const pendingDamage = placement.damagePlacements.filter((damage) => setKeys.has(damage.evidence.documentKey));\n\n const derivedSourceProofs: DerivedSourceProof[] = [];\n for (const source of placement.groupedSources) {\n const document = placement.groupedDocuments[source.mapping.documentIndex];\n const identity = source.mapping.source;\n const selectorHash = derivedSourceSelectorHash(document);\n if (\n source.mode !== 'insert-authoritative' ||\n !selectorHash ||\n identity.type !== 'resource' ||\n !('id' in identity.resource) ||\n identity.resource.kind !== 'user_permissions'\n )\n continue;\n derivedSourceProofs.push({\n source: { type: 'resource', resource: { kind: 'user_permissions', id: identity.resource.id } },\n selectorHash,\n });\n }\n return finish({\n groupedPatches: grouped.patches,\n groupedCompanions,\n rawPatches: binary.rawPatches,\n attachments,\n pendingDamage,\n derivedSourceProofs,\n });\n}\n\n/** A navigation pointer is representation, so it never dirties its resource; every other fact does. */\nfunction contributorIsClean(contributor: LayoutReadbackContributor): boolean {\n if (contributor.kind === 'grouped-navigation' || contributor.kind === 'raw-navigation') return true;\n if (contributor.kind === 'owner-field') return contributor.state === undefined || contributor.state === 'clean';\n return contributor.state === 'clean';\n}\n\n/** A locally deleted share group is proven by an absent group observation for the head share's owner. */\nfunction ownerGroupDeleted(current: CompleteComposition, document: Document): boolean {\n if (document.kind !== 'share' || !document.owner) return false;\n const owner = ownerKey(document.owner as unknown as GroupOwnerSelector);\n return current.grouped.observations.some(\n (observation) =>\n observation.state === 'absent' &&\n observation.source.type === 'group' &&\n ownerKey(observation.source.owner) === owner,\n );\n}\n\n/** Every workspace path one contributor occupies, so a decision can be read as a set of paths. */\nfunction contributorPaths(contributor: LayoutReadbackContributor): string[] {\n if (contributor.kind === 'raw')\n return [contributor.selector.sidecar, ...(contributor.bytes ? [contributor.bytes] : [])];\n if (contributor.kind === 'owner-field') return contributor.bytes ? [contributor.bytes] : [];\n if (contributor.kind === 'attachment')\n return [contributor.selector.ownerFile, ...(contributor.bytes ? [contributor.bytes] : [])];\n if (contributor.kind === 'raw-navigation') return [contributor.selector.sidecar];\n return [contributor.selector.file];\n}\n\nfunction decisionPaths(decision: EligibilityDecision): string[] {\n return 'contributors' in decision ? decision.contributors.flatMap(contributorPaths) : [];\n}\n\n/**\n * Hold a folder whose head route changed together with everything under it, unless its directory can\n * be emptied by this plan alone. A folder is written at a new directory by writing its marker and\n * every descendant there and deleting the old files; anything the plan does not write elsewhere or\n * delete would stay in a directory that has lost its marker, which puts it out of the workspace's\n * reach. So a preserved descendant, a local-only file or an opaque subtree keeps the whole folder\n * where the author has it, and the author resolves it and pulls again.\n */\ninterface HeldFolderCandidate {\n decision: EligibilityDecision;\n mapping: WireSourceMapping;\n directory: string;\n semanticPath: string[] | undefined;\n}\n\nfunction holdFolders(\n current: CompleteComposition,\n decisions: readonly EligibilityDecision[],\n): { decisions: EligibilityDecision[]; notices: LayoutReadbackNotice[] } {\n const scan = current.context.scan;\n const evidence = current.context.evidence;\n const candidates = decisions.flatMap((decision): HeldFolderCandidate[] => {\n // A folder the head deleted leaves its directory by rmdir too, so it is held the same way.\n if (decision.mode === 'remove') {\n const source = decision.current;\n if (\n decision.document?.kind !== 'folder' ||\n source?.codec !== 'grouped' ||\n !source.mapping.selector.file.endsWith('/_folder.json')\n )\n return [];\n return [\n {\n decision,\n mapping: source.mapping,\n directory: folderDirectory(source.mapping.selector.file),\n semanticPath: Array.isArray(decision.document.path)\n ? (decision.document.path as string[])\n : undefined,\n },\n ];\n }\n if (decision.mode !== 'set' || decision.document.kind !== 'folder') return [];\n // A folder changed only in its own fields keeps its directory, so it is written in place.\n if (!folderRouteChanged(decision.currentDocument, decision.document)) return [];\n const source = decision.current;\n if (source?.codec !== 'grouped' || !source.mapping.selector.file.endsWith('/_folder.json')) return [];\n return [\n {\n decision,\n mapping: source.mapping,\n directory: folderDirectory(source.mapping.selector.file),\n semanticPath: Array.isArray(decision.document.path) ? (decision.document.path as string[]) : undefined,\n },\n ];\n });\n if (candidates.length === 0) return { decisions: [...decisions], notices: [] };\n\n const inside = (path: string, directory: string) => pathInside(path, directory);\n // Every path that physically sits in the workspace today, whatever the plan makes of it.\n const occupied = [\n ...scan.artifacts.filter((artifact) => artifact.present).map((artifact) => artifact.path),\n ...scan.localOnlyFiles,\n ...scan.opaqueDirectories,\n ];\n const heldKeys = new Set<string>();\n const heldDirectories = new Set<string>();\n for (let changed = true; changed; ) {\n changed = false;\n for (const candidate of candidates) {\n if (heldDirectories.has(candidate.directory)) continue;\n // A held descendant keeps its files, so it holds every folder it sits in as well.\n const leaving = new Set(\n decisions.flatMap((decision) =>\n (decision.mode === 'set' || decision.mode === 'remove') && !heldKeys.has(decision.documentKey)\n ? decisionPaths(decision)\n : [],\n ),\n );\n const blockers = occupied\n .filter((path) => inside(path, candidate.directory) && !leaving.has(path))\n .sort(compareText);\n const detached = hasDetachedDescendants(\n candidate.mapping,\n candidate.directory,\n candidate.semanticPath,\n evidence.detachedDocumentProofs,\n evidence.detachedFileProofs,\n );\n if (blockers.length === 0 && !detached) continue;\n heldDirectories.add(candidate.directory);\n heldKeys.add(candidate.decision.documentKey!);\n for (const decision of decisions)\n if (\n decision.mode === 'set' &&\n decisionPaths(decision).some((path) => inside(path, candidate.directory))\n )\n heldKeys.add(decision.documentKey);\n changed = true;\n }\n }\n if (heldKeys.size === 0) return { decisions: [...decisions], notices: [] };\n // One notice per outermost held directory: a folder held only because its parent is stays silent,\n // and the paths it names are the ones the author resolves, never a held descendant's own files.\n const heldRemoval = (decision: EligibilityDecision): decision is Extract<EligibilityDecision, { mode: 'remove' }> =>\n decision.mode === 'remove' && decision.document?.kind === 'folder';\n const held = decisions.filter(\n (decision) => (decision.mode === 'set' || heldRemoval(decision)) && heldKeys.has(decision.documentKey ?? ''),\n );\n const spared = new Set([\n ...decisions.flatMap((decision) =>\n (decision.mode === 'set' || decision.mode === 'remove') && !heldKeys.has(decision.documentKey)\n ? decisionPaths(decision)\n : [],\n ),\n ...held.flatMap(decisionPaths),\n ]);\n const notices: LayoutReadbackNotice[] = [...heldDirectories]\n .filter((directory) => ![...heldDirectories].some((other) => inside(directory, other)))\n .map((directory) => ({\n status: 'kept-in-place' as const,\n path: directory,\n paths: occupied.filter((path) => inside(path, directory) && !spared.has(path)).sort(compareText),\n }));\n const output = decisions.map((decision) =>\n (decision.mode === 'set' || heldRemoval(decision)) && heldKeys.has(decision.documentKey ?? '')\n ? ({\n mode: 'preserve',\n documentKey: decision.documentKey,\n source: clone(decision.source),\n ...(decision.mode === 'set'\n ? decision.currentDocument\n ? { document: clone(decision.currentDocument) }\n : {}\n : decision.document\n ? { document: clone(decision.document) }\n : {}),\n contributors: clone(decision.contributors),\n reason: 'folder-held',\n } as EligibilityDecision)\n : decision,\n );\n return { decisions: output, notices: notices.sort((left, right) => compareText(left.path, right.path)) };\n}\n\nexport interface DecideCheckoutEligibilityInput {\n head: Head;\n /** The server baseline hashes this workspace last adopted, keyed by canonical resource. */\n baseline: Readonly<Record<string, string>>;\n current: CompleteComposition;\n /** Discard every local difference, mirroring `pull --force`. */\n force?: boolean;\n}\n\n/**\n * The pull rules over the layout's own observations. Per key in `baseline \u222A head`, decide whether the\n * head document may be written, the local content stays, or a tracked resource leaves the workspace.\n */\nexport function decideCheckoutEligibility(input: DecideCheckoutEligibilityInput): EligibilityResult {\n let head: Map<string, Document>;\n try {\n head = headDocuments(input.head);\n } catch (error) {\n return blocked([diagnostic('invalid-selected-head', '.', (error as Error).message)]);\n }\n const currentIndex = indexSnapshot(resourceEvidence(input.current));\n const currentRawSources = groupBySource(input.current.binary.rawSources, (mapping) =>\n sourceIdentityKey(mapping.source),\n );\n const diagnostics: ProjectionDiagnostic[] = [];\n /** Per-resource problems this decision skips; the resource keeps its content and its facts. */\n const warnings: ProjectionDiagnostic[] = [];\n const decisions: EligibilityDecision[] = [];\n\n for (const documentKey of [...new Set([...Object.keys(input.baseline), ...head.keys()])].sort()) {\n const source = stableSource(documentKey);\n if (!source) {\n warnings.push(\n diagnostic('unsupported-checkout-key', documentKey, 'Canonical key has no stable resource identity'),\n );\n continue;\n }\n const authoritative = head.get(documentKey);\n const resource = currentResource(currentIndex, currentRawSources, source);\n const tracked = input.baseline[documentKey] !== undefined;\n const headMatchesBaseline = input.head.manifest[documentKey] === input.baseline[documentKey];\n const preserve = (reason: PreserveReason): void => {\n decisions.push({\n mode: 'preserve',\n documentKey,\n source: clone(source),\n ...(resource.document ? { document: clone(resource.document) } : {}),\n contributors: clone(resource.contributors),\n reason,\n });\n };\n const set = (): void => {\n decisions.push({\n mode: 'set',\n documentKey,\n placement: resource.presence === 'present' ? 'replace-proven' : 'insert-authoritative',\n ...(input.force && resource.presence !== 'present' ? { reinsert: true } : {}),\n document: clone(authoritative!),\n source: clone(source),\n contributors: clone(resource.contributors),\n ...(resource.presence === 'present'\n ? { current: clone(resource.current!), expectedCurrentHash: resource.currentHash! }\n : {}),\n ...(resource.document ? { currentDocument: clone(resource.document) } : {}),\n });\n };\n const remove = (): void => {\n decisions.push({\n mode: 'remove',\n documentKey,\n source: clone(source),\n contributors: clone(resource.contributors),\n ...(resource.current ? { current: clone(resource.current) } : {}),\n ...(resource.document ? { document: clone(resource.document) } : {}),\n ...(input.force ? { force: true } : {}),\n });\n };\n\n // Ambiguous evidence is this resource's problem, never the whole command's.\n if (resource.presence === 'unsupported' && tracked) {\n preserve('unsupported-evidence');\n continue;\n }\n if (input.force) {\n if (authoritative) set();\n else remove();\n continue;\n }\n if (!authoritative) {\n if (resource.presence === 'absent') decisions.push({ mode: 'noop', documentKey });\n else if (resource.contributors.every(contributorIsClean)) remove();\n else preserve('kept-local-edits');\n continue;\n }\n if (resource.presence === 'absent') {\n // Never recreate a locally deleted file or share group; the baseline does not advance.\n preserve(!tracked || headMatchesBaseline ? 'local-deletion-pending' : 'conflict');\n continue;\n }\n if (resource.presence === 'unsupported') {\n if (ownerGroupDeleted(input.current, authoritative)) preserve('local-deletion-pending');\n else set();\n continue;\n }\n const clean = resource.contributors.every(contributorIsClean);\n // A resource the workspace already holds exactly as the head has it needs no write. Its\n // placement is part of that: a renamed folder gives every clean descendant a new path, and\n // the descendant reaches it by being written there, never by being moved.\n if (clean && tracked && headMatchesBaseline && placedAsAuthoritative(resource.document, authoritative)) {\n decisions.push({ mode: 'noop', documentKey });\n continue;\n }\n if (!clean && !same(resource.document, authoritative)) {\n preserve(tracked && headMatchesBaseline ? 'kept-local' : 'conflict');\n continue;\n }\n set();\n }\n\n if (diagnostics.length > 0) return blocked(diagnostics);\n const held = holdFolders(input.current, decisions);\n return {\n status: 'complete',\n decisions: held.decisions,\n receiptResults: [],\n assignments: [],\n headDocuments: head,\n warnings,\n notices: held.notices,\n };\n}\ntype CompleteReadback = Extract<PlanReceiptReadbackResult, { status: 'complete' }>;\ntype GroupedSet = Extract<PhysicalMaterialization, { mode: 'set'; codec: 'grouped' }>;\ntype RawSet = Extract<PhysicalMaterialization, { mode: 'set'; codec: 'raw' }>;\ntype AttachmentSet = Extract<AttachmentMaterialization, { mode: 'set' | 'clear' }>;\n\nexport interface PlanReceiptRenderingInput {\n readback: CompleteReadback;\n /** Why earlier attempts dropped a resource; the loop carries them into the final result. */\n unmaterializedDiagnostics?: readonly ProjectionDiagnostic[];\n}\n\nexport interface RenderedLayoutJson {\n path: string;\n role: 'document' | 'combined-table' | 'share-group' | 'raw-metadata';\n value: JsonObject;\n authorizingDocumentKeys: readonly string[];\n}\n\nexport type LayoutByteMaterialization =\n | {\n kind: 'raw';\n documentKey: string;\n destination: string;\n descriptor: BlobContent;\n }\n | {\n kind: 'attachment';\n ownerDocumentKey: string;\n field: 'icon' | 'template';\n destination: string;\n descriptor: BlobContent;\n };\n\n/**\n * One physical effect of a removal. A `rewrite` keeps a shared container that outlives the resource;\n * every other kind takes a path out of the workspace. A directory leaves only when it ends up empty.\n */\nexport type LayoutRemoval =\n | {\n kind: 'rewrite';\n path: string;\n role: RenderedLayoutJson['role'];\n value: JsonObject;\n documentKeys: readonly string[];\n }\n | { kind: 'file' | 'bytes' | 'directory'; path: string; documentKeys: readonly string[] };\n\n/** What a caller reports about a document the writer could not finish. */\nexport type LayoutReadbackNotice =\n | { status: 'ambiguous-patch'; path: string; key: string }\n | { status: 'unmaterialized'; path: string; key: string }\n | { status: 'unpatched-create'; path: string; key: string }\n | { status: 'stale-temporary'; path: string }\n | { status: 'unmanageable-path'; path: string }\n /** A folder that stays where the workspace has it, and every path that holds it there. */\n | { status: 'kept-in-place'; path: string; paths: readonly string[] };\n\nexport type PlanReceiptRenderingResult =\n | {\n status: 'complete';\n json: readonly RenderedLayoutJson[];\n bytes: readonly LayoutByteMaterialization[];\n removals: readonly LayoutRemoval[];\n /** Canonical keys whose removal could not be rendered, so their saved facts have to stay. */\n retainedRemovalKeys: readonly string[];\n /** Resources this rendering left out; they keep their current content and their facts. */\n unmaterializedKeys: readonly string[];\n unmaterializedDiagnostics: readonly ProjectionDiagnostic[];\n notices: readonly LayoutReadbackNotice[];\n /** Folder directories whose spelling changes only in case, shallowest first. */\n directoryRenames: readonly LayoutDirectoryRename[];\n }\n | { status: 'blocked'; diagnostics: readonly ProjectionDiagnostic[] };\n\n/**\n * A folder directory whose spelling changes only in case. Every other part of the pull writes at the\n * destination and deletes the origin; this entry is renamed where the filesystem folds case.\n */\nexport interface LayoutDirectoryRename {\n from: string;\n to: string;\n}\n\nfunction sameRawSelector(left: RawFileSelector, right: RawFileSelector): boolean {\n return left.sidecar === right.sidecar && canonicalText(left.identity) === canonicalText(right.identity);\n}\n\n/** One index of the rendering context, built once per plan and threaded through every lookup. */\ninterface RenderingIndex {\n grouped: ReadonlyMap<string, FragmentObservation[]>;\n raw: ReadonlyMap<string, BinaryFragmentObservation[]>;\n attachments: ReadonlyMap<string, BinaryFragmentObservation[]>;\n bytes: ReadonlyMap<string, LayoutByteFact[]>;\n artifacts: ReadonlyMap<string, LayoutArtifact[]>;\n ownerFields: ReadonlyMap<string, OwnerFieldProjection[]>;\n}\n\nfunction renderingIndex(context: LayoutReadbackRenderingContext): RenderingIndex {\n return {\n grouped: groupBySource(context.grouped.observations, (observation) => sourceIdentityKey(observation.source)),\n raw: groupBySource(context.binary.rawObservations, (observation) => sourceIdentityKey(observation.source)),\n attachments: groupBySource(context.binary.attachmentObservations, (observation) =>\n sourceIdentityKey(observation.source),\n ),\n bytes: groupBySource(context.byteFacts, (fact) => fact.path),\n artifacts: groupBySource(\n context.authored.artifacts.filter((artifact) => artifact.present),\n (artifact) => artifact.path,\n ),\n ownerFields: groupBySource(context.binary.ownerFields, (field) => sourceIdentityKey(field.ownerSource)),\n };\n}\n\nfunction observationForGrouped(\n index: RenderingIndex,\n source: SourceIdentity,\n selector: FragmentSelector,\n): FragmentObservation | undefined {\n const matches = (index.grouped.get(sourceIdentityKey(source)) ?? []).filter((observation) =>\n sameSelector(observation.selector, selector),\n );\n return matches.length === 1 ? matches[0] : undefined;\n}\n\nfunction observationForRaw(\n index: RenderingIndex,\n source: SourceIdentity,\n selector: RawFileSelector,\n): BinaryFragmentObservation | undefined {\n const matches = (index.raw.get(sourceIdentityKey(source)) ?? []).filter(\n (observation) => observation.selector.slot === 'file-entry' && sameRawSelector(observation.selector, selector),\n );\n return matches.length === 1 ? matches[0] : undefined;\n}\n\nfunction observationForAttachment(\n index: RenderingIndex,\n patch: AttachmentSet['patch'],\n): BinaryFragmentObservation | undefined {\n const matches = (index.attachments.get(sourceIdentityKey(patch.source)) ?? []).filter(\n (observation) =>\n observation.selector.slot === 'owner-attachment' &&\n observation.selector.ownerFile === patch.ownerFile &&\n observation.selector.field === patch.field,\n );\n return matches.length === 1 ? matches[0] : undefined;\n}\n\nfunction originalBytesMatch(index: RenderingIndex, observation: BinaryFragmentObservation): boolean {\n if (!observation.contributor) return observation.bytes === undefined && observation.byteHash === undefined;\n if (!observation.bytes || !observation.byteHash) return false;\n const matches = index.bytes.get(observation.bytes) ?? [];\n return (\n matches.length === 1 &&\n matches[0].state === 'present' &&\n canonicalFragmentHash(matches[0].content as unknown as Json) === observation.byteHash\n );\n}\n\nfunction authoredArtifact(index: RenderingIndex, path: string, role?: LayoutArtifactRole): LayoutArtifact | undefined {\n const matches = (index.artifacts.get(path) ?? []).filter(\n (artifact) => role === undefined || artifact.role === role,\n );\n return matches.length === 1 && object(matches[0].json) ? matches[0] : undefined;\n}\n\n/** The adapter root that owns a destination the placement allocated for a fresh insert. */\nconst INSERTED_ROLES: readonly (readonly [string, LayoutArtifactRole])[] = [\n ['access/shares/', 'share-group'],\n ['access/groups/', 'user-group'],\n ['access/labels/', 'label'],\n ['access/grants/', 'user-grant'],\n ['definitions/datasets/', 'dataset'],\n ['definitions/exports/', 'export'],\n ['detached/', 'detached-document'],\n];\n\nfunction insertedRole(file: string): LayoutArtifactRole {\n if (file.endsWith('/_folder.json')) return 'folder-control';\n if (isRawSidecarPath(file)) return 'raw-metadata';\n if (file === 'definitions/settings.json') return 'settings';\n for (const [root, role] of INSERTED_ROLES) if (file.startsWith(root)) return role;\n return 'document';\n}\n\n/** An empty container for a destination nothing authored yet. Rendering lowers the head into it. */\nfunction insertedArtifact(file: string, owner: Json | undefined): LayoutArtifact {\n const role = insertedRole(file);\n const json: JsonObject =\n role === 'share-group' ? { owner: clone(owner ?? null), shares: [] } : role === 'raw-metadata' ? {} : {};\n return { path: file, kind: 'file', role, present: false, json };\n}\n\n/**\n * The `detached/` directories above an origin that leaves them. Each leaves only through `rmdir`,\n * so a bucket that still holds anything stays, and an emptied one leaves as a fresh checkout has it.\n */\nfunction detachedBuckets(origin: string): { kind: 'directory'; path: string }[] {\n if (!origin.startsWith('detached/')) return [];\n return pathAncestors(origin).map((path) => ({ kind: 'directory' as const, path }));\n}\n\nfunction component(file: string): string {\n return file.slice(file.lastIndexOf('/') + 1);\n}\n\nfunction directoryComponent(folderControl: string): string {\n const directory = folderDirectory(folderControl);\n return component(directory);\n}\n\nfunction requiredNameOverride(\n physicalComponent: string,\n role: 'directory' | 'document' | 'raw',\n extension: string,\n semanticName: string,\n): string | undefined {\n if (layoutNameNeedsOverride(semanticName)) return semanticName;\n try {\n return decodeLayoutName(physicalComponent, role, extension) === semanticName ? undefined : semanticName;\n } catch {\n return semanticName;\n }\n}\n\nfunction withLocalField(authoritative: JsonObject, authored: JsonObject, field: string, value: Json): JsonObject {\n if (own(authoritative, field)) {\n const replaced: JsonObject = {};\n for (const [key, entry] of Object.entries(authoritative)) replaced[key] = key === field ? clone(value) : entry;\n return replaced;\n }\n const authoredKeys = Object.keys(authored);\n const localIndex = authoredKeys.indexOf(field);\n if (localIndex < 0) return { ...authoritative, [field]: clone(value) };\n const insertBefore = Object.keys(authoritative).find((key) => authoredKeys.indexOf(key) > localIndex);\n const result: JsonObject = {};\n for (const [key, entry] of Object.entries(authoritative)) {\n if (key === insertBefore) result[field] = clone(value);\n result[key] = entry;\n }\n if (!own(result, field)) result[field] = clone(value);\n return result;\n}\n\n/**\n * Lower one head document into the container at `destination`. The destination's role decides the\n * fields its path supplies, never the origin container's: a resource that moves between detached\n * and the tree renders exactly as a fresh write at the destination would.\n */\nfunction lowerGroupedValue(\n document: Document,\n artifact: LayoutArtifact,\n attachment: AttachmentMaterialization | undefined,\n destination: string,\n): JsonObject | undefined {\n const authored = object(artifact.json);\n if (!authored) return undefined;\n const role = destination === artifact.path ? artifact.role : insertedRole(destination);\n const output: JsonObject = {};\n const field = attachmentField(document);\n const preservedAttachment =\n field && (!attachment || attachment.mode === 'preserve') && own(authored, field) ? authored[field] : undefined;\n for (const [key, rawValue] of Object.entries(document)) {\n if (role === 'folder-control') {\n if (key === 'kind') continue;\n if (key === 'path') {\n const path = document.path;\n const name = Array.isArray(path) ? path.at(-1) : undefined;\n if (typeof name !== 'string') return undefined;\n const override = requiredNameOverride(directoryComponent(destination), 'directory', '', name);\n if (override !== undefined) output.name = override;\n continue;\n }\n } else if (role === 'document') {\n if (key === 'folder') continue;\n if (key === 'name') {\n if (typeof rawValue !== 'string') return undefined;\n const override = requiredNameOverride(component(destination), 'document', '.json', rawValue);\n if (override !== undefined) output.name = override;\n continue;\n }\n } else if (FILENAME_NAME_ROLES.has(role) && key === 'name') {\n if (typeof rawValue !== 'string') return undefined;\n const override = requiredNameOverride(component(destination), 'document', '.json', rawValue);\n if (override !== undefined) output.name = override;\n continue;\n }\n\n if (field === key && attachment?.mode === 'set') {\n if (!attachment.destination.bytes) return undefined;\n output[key] = { file: attachment.destination.bytes };\n } else if (field === key && preservedAttachment !== undefined) output[key] = clone(preservedAttachment);\n else output[key] = clone(rawValue);\n }\n let lowered = output;\n if (field && preservedAttachment !== undefined && !own(lowered, field))\n lowered = withLocalField(lowered, authored, field, preservedAttachment);\n if (own(authored, 'shares')) lowered = withLocalField(lowered, authored, 'shares', authored.shares);\n return lowered;\n}\n\nfunction outputRole(artifact: LayoutArtifact, value: JsonObject): RenderedLayoutJson['role'] {\n if (artifact.role === 'raw-metadata') return 'raw-metadata';\n if (artifact.role === 'share-group') return 'share-group';\n return value.kind === 'dimension_table' ? 'combined-table' : 'document';\n}\n\n/**\n * Where a share entry sits in its group. An entry authored with neither id nor key has only a\n * transient identity, so it is located by its observed source path, and only while the submission\n * saved exactly one proof of that token at that path with the entry's current hash.\n */\nfunction shareEntryIndex(\n index: RenderingIndex,\n proofs: readonly SubmissionCorrespondence[],\n entries: readonly Json[],\n selector: Extract<FragmentSelector, { slot: 'share-entry' }>,\n source: SourceIdentity,\n): number {\n if (!('transient' in selector.identity)) return shareIdentityIndex(entries, selector);\n const observation = observationForGrouped(index, source, selector);\n if (!observation?.currentHash) return -1;\n const proven = proofs.filter(\n (proof) =>\n proof.source.token === (selector.identity as { transient: string }).transient &&\n sameSelector(proof.selector, selector) &&\n samePath(proof.sourcePath, observation.sourcePath) &&\n proof.fragmentHash === observation.currentHash,\n );\n if (proven.length !== 1) return -1;\n const sourcePath = observation.sourcePath;\n const position = sourcePath.length === 2 && sourcePath[0] === 'shares' ? sourcePath[1] : undefined;\n const entry = typeof position === 'number' ? object(entries[position]) : undefined;\n return entry && entry.id === undefined && entry.key === undefined ? (position as number) : -1;\n}\n\nfunction shareIdentityIndex(entries: readonly Json[], selector: Extract<FragmentSelector, { slot: 'share-entry' }>) {\n if ('transient' in selector.identity) return -1;\n const field = 'id' in selector.identity ? 'id' : 'key';\n const value = 'id' in selector.identity ? selector.identity.id : selector.identity.key;\n const matches = entries.flatMap((entry, index) => {\n const candidate = object(entry);\n return candidate?.[field] === value ? [index] : [];\n });\n return matches.length === 1 ? matches[0] : -1;\n}\n\nfunction groupedPatchKey(selector: FragmentSelector): string {\n return canonicalText(selector as unknown as Json);\n}\n\nfunction rawPatchKey(set: RawSet): string {\n return set.destination.sidecar;\n}\n\n/** Where one owner's local navigation pointer lives: its own document, or a raw file's sidecar. */\nfunction ownerNavigationTarget(\n context: LayoutReadbackRenderingContext,\n ownerKey: string,\n): { file: string } | undefined {\n const source = stableSource(ownerKey);\n if (!source) return undefined;\n const key = sourceIdentityKey(source);\n const grouped = context.grouped.sources.filter(\n (mapping) => sourceIdentityKey(mapping.source) === key && mapping.selector.slot === 'document',\n );\n if (grouped.length === 1) return { file: grouped[0].selector.file };\n const raw = context.binary.rawSources.filter((mapping) => sourceIdentityKey(mapping.source) === key);\n return raw.length === 1 ? { file: raw[0].selector.sidecar } : undefined;\n}\n\n/** Every fragment of one physical container is exactly the proven one. */\nfunction containerFragmentsAreClean(context: LayoutReadbackRenderingContext, file: string): boolean {\n return (\n context.grouped.observations.every(\n (observation) => observation.selector.file !== file || observation.state === 'clean',\n ) &&\n context.binary.rawObservations.every(\n (observation) =>\n observation.selector.slot !== 'file-entry' ||\n observation.selector.sidecar !== file ||\n observation.state === 'clean',\n )\n );\n}\n\n/**\n * Identity patching for a create whose container changed since submission. It writes only the\n * assigned ids, using the same rules as the flat `receipts.ts` writer: array positions are not\n * identity, so a child matches only by a proven id or by being the unchanged submitted child.\n */\ninterface PatchLocation {\n actual: JsonObject;\n submitted: JsonObject;\n siblings?: Json[];\n}\n\nconst KEYED_CHILD_KINDS = new Set(['sheet_line', 'tile']);\n\nfunction withoutId(value: JsonObject): JsonObject {\n return without(value, ['id']);\n}\n\nfunction setAssignedId(document: Json, location: Handle, id: string): void {\n let value: Json = document;\n for (const part of location.path.slice(0, -1)) value = (value as JsonObject)[part as string];\n (value as JsonObject)[String(location.path[location.path.length - 1])] = id;\n}\n\n/** Drop the author-local `key` of every assigned child and rewrite the sibling references to it. */\nfunction removeAssignedLocalKeys(patches: readonly { target: PatchLocation; kind: string; id: string }[]): void {\n const references = new Map<Json[], Map<Json, Map<string, string>>>();\n for (const { target, kind, id } of patches) {\n const key = target.actual.key;\n if (!KEYED_CHILD_KINDS.has(kind) || typeof key !== 'string' || target.submitted.id !== undefined) continue;\n delete target.actual.key;\n if (kind !== 'sheet_line' || !target.siblings) continue;\n const axes = references.get(target.siblings) ?? new Map<Json, Map<string, string>>();\n const keys = axes.get(target.actual.axis) ?? new Map<string, string>();\n keys.set(key, id);\n axes.set(target.actual.axis, keys);\n references.set(target.siblings, axes);\n }\n // Rewrite once: an assigned id may itself equal another line's temporary key.\n for (const [siblings, axes] of references)\n for (const sibling of siblings) {\n const line = object(sibling);\n if (!line) continue;\n const keys = axes.get(line.axis);\n if (!keys) continue;\n if (typeof line.parent === 'string' && keys.has(line.parent)) line.parent = keys.get(line.parent)!;\n const comparison = object(line.comparison);\n if (comparison)\n for (const field of ['line1', 'line2'])\n if (typeof comparison[field] === 'string' && keys.has(comparison[field] as string))\n comparison[field] = keys.get(comparison[field] as string)!;\n }\n}\n\nfunction locatePatchTarget(\n current: Json,\n original: Json,\n expected: Json,\n location: Handle,\n assignedId: string,\n): PatchLocation | undefined {\n let actual: Json = current;\n let submitted: Json = original;\n let assigned: Json = expected;\n let siblings: Json[] | undefined;\n let field = '';\n for (const part of location.path.slice(0, -1)) {\n if (typeof part === 'number') {\n if (!Array.isArray(actual) || !Array.isArray(submitted) || !Array.isArray(assigned)) return undefined;\n const child = object(submitted[part]);\n const expectedChild = object(assigned[part]);\n if (!child || !expectedChild) return undefined;\n const keyed =\n (field === 'tiles' || field === 'lines') && typeof child.key === 'string' && child.id === undefined;\n const sameKey = (candidate: JsonObject) =>\n candidate.key === child.key && (field !== 'lines' || candidate.axis === child.axis);\n if (keyed && actual.filter((item) => object(item) && sameKey(object(item)!)).length > 1) return undefined;\n const matches = actual.filter((item) => {\n const candidate = object(item);\n if (!candidate) return false;\n return (\n (expectedChild.id !== undefined && candidate.id === expectedChild.id) ||\n (child.id !== undefined && candidate.id === child.id) ||\n (candidate.id === undefined &&\n ((keyed && sameKey(candidate)) ||\n canonicalText(withoutId(candidate)) === canonicalText(withoutId(child)) ||\n canonicalText(withoutId(candidate)) === canonicalText(withoutId(expectedChild))))\n );\n });\n if (matches.length !== 1) return undefined;\n siblings = actual;\n actual = matches[0];\n submitted = child;\n assigned = expectedChild;\n } else {\n if (!object(actual) || !object(submitted) || !object(assigned)) return undefined;\n actual = (actual as JsonObject)[part];\n submitted = (submitted as JsonObject)[part];\n assigned = (assigned as JsonObject)[part];\n field = part;\n }\n }\n const target = object(actual);\n const source = object(submitted);\n if (!target || !source) return undefined;\n if (location.path[location.path.length - 1] !== 'id' || (target.id !== undefined && target.id !== assignedId))\n return undefined;\n if (KEYED_CHILD_KINDS.has(location.kind) && target.key !== undefined && target.key !== source.key) return undefined;\n return { actual: target, submitted: source, siblings };\n}\n\n/**\n * Patch every assigned id into one live container fragment. It proves each path against the\n * unchanged submitted document before it mutates anything, so an ambiguous child leaves the whole\n * fragment untouched.\n */\nfunction applyIdentityPatch(\n host: JsonObject,\n patch: PlannedIdentityPatch,\n): { status: 'patched' } | { status: 'ambiguous'; keys: string[] } {\n const expected = clone(patch.submittedDocument) as Json;\n for (const item of patch.assignments) setAssignedId(expected, item.location, item.assignment.id);\n removeAssignedLocalKeys(\n patch.assignments.map((item) => ({\n target: {\n actual: object(pathValue(expected, item.location.path.slice(0, -1)))!,\n submitted: object(pathValue(patch.submittedDocument as Json, item.location.path.slice(0, -1)))!,\n siblings:\n item.location.kind === 'sheet_line'\n ? (pathValue(expected, item.location.path.slice(0, -2)) as Json[])\n : undefined,\n },\n kind: item.location.kind,\n id: item.assignment.id,\n })),\n );\n const located = patch.assignments.map((item) => ({\n item,\n target: locatePatchTarget(host, patch.submittedDocument, expected, item.location, item.assignment.id),\n }));\n const ambiguous = located.filter((entry) => !entry.target);\n if (ambiguous.length > 0)\n return {\n status: 'ambiguous',\n keys: ambiguous.map((entry) => `${entry.item.assignment.kind}/${entry.item.assignment.id}`),\n };\n for (const entry of located) entry.target!.actual.id = entry.item.assignment.id;\n removeAssignedLocalKeys(\n located.map((entry) => ({\n target: entry.target!,\n kind: entry.item.location.kind,\n id: entry.item.assignment.id,\n })),\n );\n // A top-level committed key is replaced by the identity the server assigned to it.\n if (patch.assignments.some((item) => item.location.path.length === 1)) delete host.key;\n return { status: 'patched' };\n}\n\nfunction pathValue(value: Json, parts: readonly (string | number)[]): Json {\n return parts.reduce<Json>((current, part) => (current as JsonObject)[part as string], value);\n}\n\n/**\n * Write the assigned ids of every deferred document into its live container. Each container is\n * taken from this plan's output when it already has one, so one file is only ever written once.\n */\nfunction renderIdentityPatches(\n readback: CompleteReadback,\n index: RenderingIndex,\n json: RenderedLayoutJson[],\n notices: LayoutReadbackNotice[],\n): void {\n const removed = new Set(\n readback.deletes.json\n .map((removal) => removal.path)\n .concat(readback.deletes.bytes.map((removal) => removal.path)),\n );\n for (const patch of readback.identityPatches) {\n if (removed.has(patch.container)) continue;\n const target = json.find((candidate) => candidate.path === patch.container);\n const artifact = authoredArtifact(index, patch.container);\n const authored = artifact && object(artifact.json);\n if (!artifact || !authored) {\n // The container this id belongs in is gone, so the assignment is reported, never silent.\n for (const item of patch.assignments)\n notices.push({\n status: 'ambiguous-patch',\n path: patch.container,\n key: `${item.assignment.kind}/${item.assignment.id}`,\n });\n continue;\n }\n const container = target ? target.value : clone(authored);\n let host: JsonObject | undefined;\n if (patch.slot === 'share-entry') {\n const shares = Array.isArray(container.shares) ? container.shares : [];\n const at = patch.shareIdentity\n ? shareEntryIndex(\n index,\n readback.submissionProofs,\n shares,\n { file: patch.container, slot: 'share-entry', identity: patch.shareIdentity },\n patch.source,\n )\n : -1;\n host = at < 0 ? undefined : object(shares[at]);\n } else host = container;\n if (!host) {\n notices.push({\n status: 'ambiguous-patch',\n path: patch.container,\n key: `${patch.assignments[0].assignment.kind}/${patch.assignments[0].assignment.id}`,\n });\n continue;\n }\n const result = applyIdentityPatch(host, patch);\n if (result.status === 'ambiguous') {\n for (const key of result.keys) notices.push({ status: 'ambiguous-patch', path: patch.container, key });\n continue;\n }\n if (!target)\n json.push({\n path: patch.container,\n role: outputRole(artifact, container),\n value: container,\n authorizingDocumentKeys: [],\n });\n }\n}\n\n/**\n * Turn one planned removal set into physical effects. A container that outlives its resource is\n * rewritten in place, folded into an accepted set when the same plan already writes that file.\n */\nfunction renderRemovals(\n readback: CompleteReadback,\n index: RenderingIndex,\n json: RenderedLayoutJson[],\n diagnostics: ProjectionDiagnostic[],\n notices: LayoutReadbackNotice[],\n retainedKeys: string[],\n): LayoutRemoval[] {\n const { deletes } = readback;\n const removals: LayoutRemoval[] = [];\n const rendered = new Map(json.map((artifact) => [artifact.path, artifact]));\n const rewrites = new Map<string, { role: RenderedLayoutJson['role']; value: JsonObject; keys: Set<string> }>();\n const deletedPaths = new Set(deletes.json.map((removal) => removal.path));\n\n /** The mutable value of one surviving container, taken from this plan's output or from disk. */\n const container = (path: string, role: RenderedLayoutJson['role'], documentKey: string): JsonObject | undefined => {\n const target = rendered.get(path);\n if (target) return target.value;\n const existing = rewrites.get(path);\n if (existing) {\n existing.keys.add(documentKey);\n return existing.value;\n }\n const artifact = authoredArtifact(index, path);\n const authored = artifact && object(artifact.json);\n if (!artifact || !authored) {\n // The container is gone, so this resource keeps its baseline instead of failing the command.\n notices.push({ status: 'unmaterialized', path, key: documentKey });\n retainedKeys.push(documentKey);\n return undefined;\n }\n const entry = { role, value: clone(authored), keys: new Set([documentKey]) };\n rewrites.set(path, entry);\n return entry.value;\n };\n\n for (const removal of deletes.groupEntries) {\n const selector = removal.entry as FragmentSelector;\n const value = container(removal.container, 'share-group', removal.documentKey);\n if (!value) continue;\n const shares = Array.isArray(value.shares) ? value.shares : undefined;\n const at = selector.slot === 'share-entry' && shares ? shareIdentityIndex(shares, selector) : -1;\n if (!shares || at < 0) {\n // The entry is already gone from the container, so this resource only keeps its facts.\n notices.push({ status: 'unmaterialized', path: removal.container, key: removal.documentKey });\n retainedKeys.push(removal.documentKey);\n continue;\n }\n value.shares = shares.filter((_, position) => position !== at);\n }\n\n for (const pointer of deletes.pointers) {\n if (deletedPaths.has(pointer.owner)) continue;\n const artifact = authoredArtifact(index, pointer.owner);\n const authored = artifact && object(artifact.json);\n const value = container(\n pointer.owner,\n artifact && authored ? outputRole(artifact, authored) : 'document',\n pointer.documentKey,\n );\n if (value) delete value.shares;\n }\n\n for (const [path, entry] of rewrites)\n removals.push({\n kind: 'rewrite',\n path,\n role: entry.role,\n value: entry.value,\n documentKeys: [...entry.keys].sort(compareText),\n });\n for (const removal of deletes.json)\n removals.push({ kind: 'file', path: removal.path, documentKeys: [...removal.documentKeys] });\n for (const removal of deletes.bytes)\n removals.push({ kind: 'bytes', path: removal.path, documentKeys: [...removal.documentKeys] });\n for (const removal of deletes.directories)\n removals.push({ kind: 'directory', path: removal.path, documentKeys: [...removal.documentKeys] });\n return removals;\n}\n\n/**\n * Assemble accepted stable, in-place readback changes into complete JSON values and byte intents.\n * Creates, deletes, missing-share insertion, navigation changes, cleanup, persistence,\n * filesystem access, network access, and writing are intentionally unsupported.\n */\nexport function planReceiptRendering(input: PlanReceiptRenderingInput): PlanReceiptRenderingResult {\n const excluded = new Set<string>();\n const reasons: ProjectionDiagnostic[] = [];\n for (;;) {\n const result = renderReceiptAttempt(input, excluded);\n if (result.status !== 'retry') return result;\n for (const key of result.keys) excluded.add(key);\n reasons.push(...result.diagnostics);\n input = { ...input, unmaterializedDiagnostics: reasons } as PlanReceiptRenderingInput;\n }\n}\n\nfunction renderReceiptAttempt(\n input: PlanReceiptRenderingInput,\n excluded: ReadonlySet<string>,\n): PlanReceiptRenderingResult | { status: 'retry'; keys: string[]; diagnostics: ProjectionDiagnostic[] } {\n const { readback } = input;\n const context = readback.renderingContext;\n const index = renderingIndex(context);\n const diagnostics: ProjectionDiagnostic[] = [];\n /** One resource the rendering cannot finish: it drops out and the container is planned again. */\n const perResource: { keys: readonly string[]; diagnostic: ProjectionDiagnostic }[] = [];\n const groupedSets = readback.materializations.filter(\n (item): item is GroupedSet =>\n item.mode === 'set' && item.codec === 'grouped' && !excluded.has(item.documentKey),\n );\n const rawSets = readback.materializations.filter(\n (item): item is RawSet => item.mode === 'set' && item.codec === 'raw' && !excluded.has(item.documentKey),\n );\n const groupedTargets = new Set<string>();\n const rawTargets = new Set<string>();\n const groupedByFile = new Map<string, Array<{ set: GroupedSet; patch: ArtifactPatch }>>();\n const placedRaw: RawSet[] = [];\n const notices: LayoutReadbackNotice[] = [];\n /** One resource the writer cannot materialize keeps its current content; the command says so. */\n const unmaterialized = (path: string, keys: readonly string[]): void => {\n for (const key of keys.length > 0 ? keys : ['workspace']) notices.push({ status: 'unmaterialized', path, key });\n };\n /** Record a per-resource rendering problem: the named resources leave this plan, nothing blocks. */\n const unplaceable = (keys: readonly string[], item: ProjectionDiagnostic): void => {\n perResource.push({ keys, diagnostic: item });\n unmaterialized(item.path, keys);\n };\n /** The authored container every destination is rendered from: its own path, or the one it left. */\n const groupedOrigin = new Map<string, string>();\n /**\n * Where a resource the server renamed or moved used to live. The plan writes the head content at\n * the new destination and takes the origin out afterwards, so no artifact is ever renamed.\n */\n const origins: { kind: 'file' | 'bytes' | 'directory'; path: string }[] = [];\n const directoryRenames: LayoutDirectoryRename[] = [];\n\n for (const set of groupedSets) {\n if (set.patches.length !== 1) {\n unplaceable(\n [set.documentKey],\n diagnostic('invalid-render-patches', set.destination.file, 'Grouped set needs one patch'),\n );\n continue;\n }\n const patch = set.patches[0];\n // Two sets collide over what they write, not over what they leave: the destination is the key.\n const key = groupedPatchKey(set.destination);\n if (groupedTargets.has(key)) {\n unplaceable(\n [set.documentKey],\n diagnostic('duplicate-render-target', set.destination.file, 'Grouped target is duplicated'),\n );\n continue;\n }\n groupedTargets.add(key);\n const inserted = set.placement === 'insert-authoritative';\n const observation = observationForGrouped(index, patch.source, patch.selector);\n if (\n patch.action !== 'set' ||\n patch.value === undefined ||\n !sameSelector(patch.selector, set.origin ?? set.destination) ||\n (!inserted && !observation?.currentHash)\n ) {\n unplaceable(\n [set.documentKey],\n diagnostic('stale-render-source', patch.selector.file, 'Grouped patch does not match captured current'),\n );\n continue;\n }\n const originFile = (set.origin ?? set.destination).file;\n const known = groupedOrigin.get(set.destination.file);\n if (known !== undefined && known !== originFile) {\n unplaceable(\n [set.documentKey],\n diagnostic(\n 'invalid-render-container',\n set.destination.file,\n 'Container fragments disagree about their current file',\n ),\n );\n continue;\n }\n groupedOrigin.set(set.destination.file, originFile);\n groupedByFile.set(set.destination.file, [...(groupedByFile.get(set.destination.file) ?? []), { set, patch }]);\n }\n\n for (const set of rawSets) {\n const patch = set.patch;\n const key = rawPatchKey(set);\n if (rawTargets.has(key)) {\n unplaceable(\n [set.documentKey],\n diagnostic('duplicate-render-target', set.destination.sidecar, 'Raw sidecar is duplicated'),\n );\n continue;\n }\n rawTargets.add(key);\n const inserted = set.placement === 'insert-authoritative';\n const observation = observationForRaw(index, patch.source, patch.selector);\n if (\n patch.action !== 'set' ||\n !patch.document ||\n !patch.metadata ||\n !patch.content ||\n !sameRawSelector(patch.selector, set.origin ?? set.destination) ||\n // The patch names the bytes its current source has; the set names where they end up.\n patch.bytes !== (inserted ? set.bytes : (observation?.bytes ?? set.bytes)) ||\n (!inserted && (!observation?.currentHash || !originalBytesMatch(index, observation)))\n ) {\n unplaceable(\n [set.documentKey],\n diagnostic('stale-render-source', patch.selector.sidecar, 'Raw patch does not match captured current'),\n );\n continue;\n }\n if (observation?.bytes && observation.bytes !== set.bytes)\n origins.push({ kind: 'bytes', path: observation.bytes });\n placedRaw.push(set);\n }\n\n const attachmentByOwner = new Map<string, AttachmentMaterialization>();\n const bytes: LayoutByteMaterialization[] = [];\n const ownerSets = new Map(groupedSets.map((set) => [set.documentKey, set]));\n for (const attachment of readback.attachments) {\n const owner = ownerSets.get(attachment.ownerDocumentKey);\n const field = 'patch' in attachment ? attachment.patch.field : attachment.field;\n const target = canonicalText([attachment.ownerDocumentKey, field]);\n if (attachmentByOwner.has(target)) {\n unplaceable(\n [attachment.ownerDocumentKey],\n diagnostic('duplicate-render-target', attachment.ownerDocumentKey, 'Attachment field is duplicated'),\n );\n continue;\n }\n attachmentByOwner.set(target, attachment);\n if (\n !owner ||\n owner.destination.file !==\n ('destination' in attachment ? attachment.destination.ownerFile : attachment.ownerFile)\n ) {\n unplaceable(\n [attachment.ownerDocumentKey],\n diagnostic('unpaired-render-attachment', attachment.ownerDocumentKey, 'Attachment lacks its owner set'),\n );\n continue;\n }\n if (!('patch' in attachment)) continue;\n const patch = attachment.patch;\n // Acceptance already paired this patch with its owner set; only the original byte evidence is new here.\n const observation = observationForAttachment(index, patch);\n if (\n owner.placement !== 'insert-authoritative' &&\n (!observation?.currentHash || !originalBytesMatch(index, observation))\n ) {\n unplaceable(\n [attachment.ownerDocumentKey],\n diagnostic('stale-render-source', patch.ownerFile, 'Attachment patch does not match captured current'),\n );\n continue;\n }\n if (attachment.mode === 'set') {\n if (!attachment.destination.bytes || patch.value === null) {\n unplaceable(\n [attachment.ownerDocumentKey],\n diagnostic('invalid-render-bytes', patch.ownerFile, 'Attachment set lacks final bytes'),\n );\n continue;\n }\n if (observation?.bytes && observation.bytes !== attachment.destination.bytes)\n origins.push({ kind: 'bytes', path: observation.bytes });\n bytes.push({\n kind: 'attachment',\n ownerDocumentKey: attachment.ownerDocumentKey,\n field: patch.field,\n destination: attachment.destination.bytes,\n descriptor: clone(patch.value),\n });\n }\n }\n\n const companionsByFile = new Map<string, ArtifactPatch>();\n for (const companion of readback.groupedCompanions) {\n const patch = companion.patch;\n const selectedShares = groupedSets.filter(\n (set) =>\n set.destination.file === patch.selector.file &&\n set.destination.slot === 'share-entry' &&\n companion.authorizingDocumentKeys.includes(set.documentKey),\n );\n const allAuthorizersSelected =\n companion.authorizingDocumentKeys.length > 0 &&\n companion.authorizingDocumentKeys.every((key) =>\n groupedSets.some(\n (set) =>\n set.documentKey === key &&\n set.destination.file === patch.selector.file &&\n set.destination.slot === 'share-entry',\n ),\n );\n const observation = observationForGrouped(index, patch.source, patch.selector);\n const insertedGroup = selectedShares.every((set) => set.placement === 'insert-authoritative');\n if (\n patch.action !== 'set' ||\n patch.selector.slot !== 'share-group-owner' ||\n selectedShares.length === 0 ||\n !allAuthorizersSelected ||\n companionsByFile.has(patch.selector.file) ||\n (!insertedGroup && !observation?.currentHash)\n ) {\n unplaceable(\n groupedSets.filter((set) => set.destination.file === patch.selector.file).map((set) => set.documentKey),\n diagnostic('invalid-render-companion', patch.selector.file, 'Share header is not fully authorized'),\n );\n continue;\n }\n companionsByFile.set(patch.selector.file, patch);\n }\n\n // A file another set leaves behind belongs to no one once this plan is written, so an insert that\n // takes it renders a fresh container instead of inheriting the local fields of the source leaving.\n const vacatedFiles = new Set(\n [...groupedOrigin.entries()].flatMap(([destination, origin]) => (origin === destination ? [] : [origin])),\n );\n for (const removal of readback.deletes.json) vacatedFiles.add(removal.path);\n\n const json: RenderedLayoutJson[] = [];\n const insertedShareGroups = new Set<string>();\n for (const [file, selected] of groupedByFile) {\n const insertedFile = selected.every(({ set }) => set.placement === 'insert-authoritative');\n const owner = selected.find(({ patch }) => patch.selector.slot === 'share-entry')\n ? object(selected[0].set.document)?.owner\n : undefined;\n const origin = groupedOrigin.get(file) ?? file;\n const takesVacated = insertedFile && origin === file && vacatedFiles.has(file);\n const artifact =\n (takesVacated ? undefined : authoredArtifact(index, origin)) ??\n (insertedFile ? insertedArtifact(file, owner) : undefined);\n const authored = artifact && object(artifact.json);\n if (!artifact || !authored || artifact.role === 'raw-metadata' || artifact.role === 'raw') {\n unmaterialized(\n origin,\n selected.map(({ set }) => set.documentKey),\n );\n continue;\n }\n // A filesystem that folds case gives both spellings of a directory one entry, so writing\n // the marker cannot change the spelling: the writer renames that one directory entry.\n if (\n origin !== file &&\n artifact.role === 'folder-control' &&\n folderDirectory(origin) !== folderDirectory(file) &&\n layoutCollisionKey(folderDirectory(origin)) === layoutCollisionKey(folderDirectory(file))\n )\n directoryRenames.push({ from: folderDirectory(origin), to: folderDirectory(file) });\n const slots = new Set(selected.map(({ patch }) => patch.selector.slot));\n let value: JsonObject | undefined;\n if (slots.has('table-definition') || slots.has('member-set')) {\n if (\n artifact.role === 'share-group' ||\n [...slots].some((slot) => slot !== 'table-definition' && slot !== 'member-set') ||\n !(Array.isArray(authored.members) || (insertedFile && authored.members === undefined))\n ) {\n unplaceable(\n selected.map(({ set }) => set.documentKey),\n diagnostic('invalid-render-container', file, 'Table container is incomplete'),\n );\n continue;\n }\n const definition = selected.find(({ patch }) => patch.selector.slot === 'table-definition');\n const members = selected.find(({ patch }) => patch.selector.slot === 'member-set');\n const definitionDocument = definition?.patch.value;\n const lowered = definitionDocument\n ? lowerGroupedValue(definitionDocument as Document, artifact, undefined, file)\n : clone(authored);\n const memberValue = members?.patch.value ?? authored.members ?? [];\n if (!lowered || !Array.isArray(memberValue)) {\n unplaceable(\n selected.map(({ set }) => set.documentKey),\n diagnostic('invalid-render-container', file, 'Table fragments are invalid'),\n );\n continue;\n }\n delete lowered.members;\n value = { ...lowered, members: clone(memberValue) };\n } else if (slots.has('share-entry')) {\n if (artifact.role !== 'share-group' || [...slots].some((slot) => slot !== 'share-entry')) {\n unplaceable(\n selected.map(({ set }) => set.documentKey),\n diagnostic('invalid-render-container', file, 'Share container is invalid'),\n );\n continue;\n }\n if (!object(authored.owner) || !Array.isArray(authored.shares)) {\n unplaceable(\n selected.map(({ set }) => set.documentKey),\n diagnostic('invalid-render-container', file, 'Share container is incomplete'),\n );\n continue;\n }\n const shares = clone(authored.shares);\n let invalid = false;\n for (const { set, patch } of selected) {\n const entry = object(patch.value);\n if (patch.selector.slot !== 'share-entry' || !entry) {\n invalid = true;\n break;\n }\n const at = shareEntryIndex(index, readback.submissionProofs, shares, patch.selector, patch.source);\n if (at < 0 && set.placement !== 'insert-authoritative') {\n invalid = true;\n break;\n }\n if (at < 0) shares.push(clone(entry));\n else shares[at] = clone(entry);\n }\n const companion = companionsByFile.get(file);\n if (invalid || (companion && !object(companion.value))) {\n unplaceable(\n selected.map(({ set }) => set.documentKey),\n diagnostic('invalid-render-container', file, 'Selected share entry is missing'),\n );\n continue;\n }\n value = clone(authored);\n value.owner = clone((companion?.value ?? authored.owner) as Json);\n value.shares = shares;\n if (insertedFile) insertedShareGroups.add(file);\n } else {\n if (selected.length !== 1 || selected[0].patch.selector.slot !== 'document') {\n unplaceable(\n selected.map(({ set }) => set.documentKey),\n diagnostic('invalid-render-container', file, 'Document container is ambiguous'),\n );\n continue;\n }\n const { set, patch } = selected[0];\n if (!object(patch.value)) {\n unplaceable(\n selected.map(({ set }) => set.documentKey),\n diagnostic('invalid-render-container', file, 'Document patch is not an object'),\n );\n continue;\n }\n const field = attachmentField(set.document);\n const attachment = field ? attachmentByOwner.get(canonicalText([set.documentKey, field])) : undefined;\n if (field && !attachment) {\n unmaterialized(file, [set.documentKey]);\n continue;\n }\n value = lowerGroupedValue(patch.value as Document, artifact, attachment, file);\n if (!value) {\n unplaceable(\n selected.map(({ set }) => set.documentKey),\n diagnostic('invalid-render-container', file, 'Document cannot be lowered'),\n );\n continue;\n }\n }\n json.push({\n path: file,\n role: outputRole(artifact, value),\n value,\n authorizingDocumentKeys: selected.map(({ set }) => set.documentKey),\n });\n // Each descendant is its own resource and finds its own new destination, so a renamed folder\n // gives up its marker and then its directory, which survives whatever stayed behind.\n if (origin !== file) {\n origins.push({ kind: 'file', path: origin });\n if (artifact.role === 'folder-control') origins.push({ kind: 'directory', path: folderDirectory(origin) });\n origins.push(...detachedBuckets(origin));\n }\n }\n\n // Each raw file owns its own sidecar, so one set renders one whole control file beside its bytes.\n // A sidecar another raw file leaves belongs to no one once this plan is written, so an insert\n // that takes its path renders a fresh sidecar instead of the leaving file's share pointer.\n const vacatedSidecars = new Set(readback.deletes.json.map((removal) => removal.path));\n for (const set of placedRaw)\n if (set.origin && set.origin.sidecar !== set.destination.sidecar) vacatedSidecars.add(set.origin.sidecar);\n for (const set of placedRaw) {\n const destination = set.destination.sidecar;\n const origin = (set.origin ?? set.destination).sidecar;\n const inserted = set.placement === 'insert-authoritative';\n const takesVacated = inserted && origin === destination && vacatedSidecars.has(destination);\n const artifact =\n (takesVacated ? undefined : authoredArtifact(index, origin, 'raw-metadata')) ??\n (inserted ? insertedArtifact(destination, undefined) : undefined);\n const authored = artifact && object(artifact.json);\n if (!artifact || !authored) {\n unmaterialized(origin, [set.documentKey]);\n continue;\n }\n const patchMetadata = set.patch.metadata!;\n let value: JsonObject = clone(patchMetadata);\n if (own(authored, 'shares')) value = withLocalField(value, authored, 'shares', authored.shares);\n json.push({ path: destination, role: 'raw-metadata', value, authorizingDocumentKeys: [set.documentKey] });\n bytes.push({\n kind: 'raw',\n documentKey: set.documentKey,\n destination: set.bytes,\n descriptor: clone(set.patch.content!),\n });\n // The sidecar describes the bytes beside it, so both leave the path the pair came from.\n if (origin !== destination) origins.push({ kind: 'file', path: origin }, ...detachedBuckets(origin));\n }\n\n // A freshly inserted share group has no authored owner pointer, so rendering adds that route once.\n const renderedOwners = new Map<string, RenderedLayoutJson>();\n for (const artifact of json)\n if (artifact.role !== 'share-group')\n for (const key of artifact.authorizingDocumentKeys) renderedOwners.set(key, artifact);\n // A group its owner cannot point at is an unlinked group the next scan refuses, so it is never\n // written: the share keeps its facts and the command says the workspace has to pull again.\n const pointsHere = (host: JsonObject | undefined, file: string) =>\n !!host && own(host, 'shares') && canonicalText(host.shares as Json) === canonicalText({ file });\n const dropGroup = (artifact: RenderedLayoutJson): void => {\n json.splice(json.indexOf(artifact), 1);\n unplaceable(\n artifact.authorizingDocumentKeys,\n diagnostic('unlinked-generated-share', artifact.path, 'The owner cannot point to this new share group'),\n );\n };\n for (const artifact of [...json]) {\n if (!insertedShareGroups.has(artifact.path)) continue;\n const owner = object(artifact.value.owner);\n const ownerKey =\n owner && typeof owner.kind === 'string' && typeof owner.id === 'string'\n ? `${owner.kind}/${owner.id}`\n : undefined;\n const ownerArtifact = ownerKey ? renderedOwners.get(ownerKey) : undefined;\n if (ownerArtifact) {\n const host = ownerArtifact.value;\n if (!own(host, 'shares')) ownerArtifact.value = { ...host, shares: { file: artifact.path } };\n else if (!pointsHere(host, artifact.path)) dropGroup(artifact);\n continue;\n }\n // An id patched into a container makes it the owner, so the route is the one after the write.\n const patched = readback.identityPatches.find((patch) => patch.documentKey === ownerKey);\n const route = patched\n ? { file: patched.container }\n : ownerKey\n ? ownerNavigationTarget(context, ownerKey)\n : undefined;\n // No local owner artifact at all: the group stands alone, which the scanner accepts.\n if (!route) continue;\n const authored = authoredArtifact(index, route.file);\n const value = authored && object(authored.json);\n const host = value;\n if (pointsHere(host, artifact.path)) continue;\n if (!containerFragmentsAreClean(context, route.file) || !authored || !value || !host || own(host, 'shares')) {\n dropGroup(artifact);\n continue;\n }\n const target = json.find((candidate) => candidate.path === route.file);\n const container = target ? target.value : clone(value);\n container.shares = { file: artifact.path };\n if (!target)\n json.push({\n path: route.file,\n role: outputRole(authored, container),\n value: container,\n authorizingDocumentKeys: [...artifact.authorizingDocumentKeys],\n });\n }\n\n renderIdentityPatches(readback, index, json, notices);\n const retainedRemovalKeys: string[] = [];\n const removals = renderRemovals(readback, index, json, diagnostics, notices, retainedRemovalKeys);\n\n const jsonTargets = new Set<string>();\n for (const artifact of json) {\n if (jsonTargets.has(artifact.path))\n diagnostics.push(diagnostic('duplicate-render-target', artifact.path, 'JSON output path is duplicated'));\n jsonTargets.add(artifact.path);\n }\n const byteTargets = new Set<string>();\n for (const materialization of bytes) {\n if (byteTargets.has(materialization.destination) || jsonTargets.has(materialization.destination))\n diagnostics.push(\n diagnostic('duplicate-render-target', materialization.destination, 'Byte output path is duplicated'),\n );\n byteTargets.add(materialization.destination);\n }\n for (const removal of removals)\n if (removal.kind !== 'rewrite' && (jsonTargets.has(removal.path) || byteTargets.has(removal.path)))\n diagnostics.push(\n diagnostic('conflicting-removal-target', removal.path, 'Removed path is also a rendered output'),\n );\n // An origin this plan also writes is a swap: the write owns the path and nothing removes it.\n const outputs = [...jsonTargets, ...byteTargets];\n const holdsOutput = (directory: string) =>\n outputs.some((target) => target === directory || pathInside(target, directory));\n const vacated = new Set(removals.filter((removal) => removal.kind !== 'rewrite').map((removal) => removal.path));\n for (const origin of origins) {\n if (jsonTargets.has(origin.path) || byteTargets.has(origin.path) || vacated.has(origin.path)) continue;\n if (origin.kind === 'directory' && holdsOutput(origin.path)) continue;\n vacated.add(origin.path);\n removals.push({ kind: origin.kind, path: origin.path, documentKeys: [] });\n }\n\n // A resource the rendering could not place leaves the plan; the containers are rendered again.\n const pending = [...new Set(perResource.flatMap((item) => item.keys))].filter((key) => !excluded.has(key));\n if (pending.length > 0)\n return { status: 'retry', keys: pending, diagnostics: perResource.map((item) => item.diagnostic) };\n // A keyed problem this loop already preserved cannot be preserved again, so it blocks here as\n // it does in the placement loop instead of disappearing with the resource it named.\n const repeated = perResource.filter((item) => item.keys.length > 0).map((item) => item.diagnostic);\n if (diagnostics.length > 0 || repeated.length > 0)\n return { status: 'blocked', diagnostics: [...diagnostics, ...repeated] };\n return {\n status: 'complete',\n json: json.sort((left, right) => left.path.localeCompare(right.path)),\n bytes: bytes.sort((left, right) => left.destination.localeCompare(right.destination)),\n removals,\n retainedRemovalKeys: [...new Set(retainedRemovalKeys)].sort(compareText),\n unmaterializedKeys: [...excluded].sort(compareText),\n unmaterializedDiagnostics: input.unmaterializedDiagnostics ?? [],\n notices,\n directoryRenames: directoryRenames.sort(\n (left, right) => left.from.split('/').length - right.from.split('/').length,\n ),\n };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,uBAA6C;AAC7C,oCAWO;AACP,wBAuBO;AACP,yBAOO;AACP,8BAaO;AACP,qCAMO;AAOP,4BAAqE;AA0ZrE,SAAS,mBAAmB,M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