farseer-cli 1.15.0 → 1.17.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 (55) hide show
  1. package/README.md +328 -0
  2. package/dist/commands/code.js +104 -0
  3. package/dist/commands/code.js.map +7 -0
  4. package/dist/commands/model.js +14 -4
  5. package/dist/commands/model.js.map +2 -2
  6. package/dist/index.js +16 -0
  7. package/dist/index.js.map +2 -2
  8. package/dist/pipeline/generated-reference.json +30 -30
  9. package/dist/pipeline/service.js +2 -2
  10. package/dist/pipeline/service.js.map +2 -2
  11. package/dist/services/codefirst/api.js +269 -0
  12. package/dist/services/codefirst/api.js.map +7 -0
  13. package/dist/services/codefirst/binaryDisk.js +67 -0
  14. package/dist/services/codefirst/binaryDisk.js.map +7 -0
  15. package/dist/services/codefirst/byteHashes.js +129 -0
  16. package/dist/services/codefirst/byteHashes.js.map +7 -0
  17. package/dist/services/codefirst/documents.js +563 -0
  18. package/dist/services/codefirst/documents.js.map +7 -0
  19. package/dist/services/codefirst/layoutBinaryProjection.js +974 -0
  20. package/dist/services/codefirst/layoutBinaryProjection.js.map +7 -0
  21. package/dist/services/codefirst/layoutCompose.js +593 -0
  22. package/dist/services/codefirst/layoutCompose.js.map +7 -0
  23. package/dist/services/codefirst/layoutCore.js +260 -0
  24. package/dist/services/codefirst/layoutCore.js.map +7 -0
  25. package/dist/services/codefirst/layoutPaths.js +492 -0
  26. package/dist/services/codefirst/layoutPaths.js.map +7 -0
  27. package/dist/services/codefirst/layoutProjection.js +995 -0
  28. package/dist/services/codefirst/layoutProjection.js.map +7 -0
  29. package/dist/services/codefirst/layoutReadback.js +2552 -0
  30. package/dist/services/codefirst/layoutReadback.js.map +7 -0
  31. package/dist/services/codefirst/layoutReadbackPlacement.js +1517 -0
  32. package/dist/services/codefirst/layoutReadbackPlacement.js.map +7 -0
  33. package/dist/services/codefirst/layoutReceipt.js +1592 -0
  34. package/dist/services/codefirst/layoutReceipt.js.map +7 -0
  35. package/dist/services/codefirst/layoutScan.js +882 -0
  36. package/dist/services/codefirst/layoutScan.js.map +7 -0
  37. package/dist/services/codefirst/output.js +179 -0
  38. package/dist/services/codefirst/output.js.map +7 -0
  39. package/dist/services/codefirst/types.js +17 -0
  40. package/dist/services/codefirst/types.js.map +7 -0
  41. package/dist/services/codefirst/workflow.js +581 -0
  42. package/dist/services/codefirst/workflow.js.map +7 -0
  43. package/dist/services/codefirst/workspace.js +310 -0
  44. package/dist/services/codefirst/workspace.js.map +7 -0
  45. package/dist/services/codefirst/workspaceLock.js +148 -0
  46. package/dist/services/codefirst/workspaceLock.js.map +7 -0
  47. package/dist/services/codefirst/workspaceRoot.js +147 -0
  48. package/dist/services/codefirst/workspaceRoot.js.map +7 -0
  49. package/dist/utils/logger.js +9 -3
  50. package/dist/utils/logger.js.map +2 -2
  51. package/docs/pipeline-client-guide.md +2 -2
  52. package/docs/pipeline-reference.md +156 -99
  53. package/package.json +3 -2
  54. package/skills/pipeline-authoring/SKILL.md +10 -8
  55. package/skills/pipeline-authoring/practices.md +39 -25
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/services/codefirst/layoutReceipt.ts"],
4
+ "sourcesContent": ["/**\n * The one writer for every layout command. It captures the workspace, turns the caller's decisions\n * into placed containers, writes JSON, bytes and removals, then rescans the result: only a resource\n * whose recomposed document equals the authoritative one advances its baseline, routes and claims.\n * Capture lives in layoutScan; the decisions it materializes come from layoutReadback.\n */\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { randomUUID } from 'crypto';\nimport { hashFile, sameBytes, type BlobApi } from './binaryDisk';\nimport { canonicalEqual, canonicalText, parseState } from './documents';\nimport type { BinaryFragmentObservation, BinaryFragmentRoute, LayoutByteFact } from './layoutBinaryProjection';\nimport {\n composeLayoutSubmission,\n type ComposeLayoutSubmissionResult,\n type LayoutSubmissionEvidence,\n type ProvenRawShareNavigationRoute,\n} from './layoutCompose';\nimport {\n blocked,\n canonicalFragmentHash,\n clone,\n compareText,\n diagnostic,\n groupBySource,\n pathAncestors,\n sourceIdentityKey,\n stableSource as sourceForDocumentKey,\n type StableSource,\n} from './layoutCore';\nimport {\n encodeLayoutSegment,\n isIgnoredLayoutName,\n isPortableWorkspacePointer,\n isTemporaryLayoutPath,\n layoutCollisionKey,\n layoutNameNeedsOverride,\n parseWorkspacePointer,\n rawSidecarPath,\n} from './layoutPaths';\nimport {\n derivedSourceSelectorHash,\n type DerivedSourceProof,\n type FragmentObservation,\n type ProjectionDiagnostic,\n type ProvenFragmentRoute,\n type SourceIdentity,\n} from './layoutProjection';\nimport {\n decideCheckoutEligibility,\n decideReceiptEligibility,\n planMaterialization,\n planReceiptRendering,\n withoutContainerSuppliedFields,\n type LayoutByteMaterialization,\n type LayoutDirectoryRename,\n type LayoutReadbackNotice,\n type LayoutReceiptSubmission,\n type LayoutRemoval,\n type PhysicalMaterialization,\n type PlannedLayoutDeletes,\n type PlanReceiptReadbackResult,\n type PlanReceiptRenderingResult,\n} from './layoutReadback';\nimport {\n captureLayoutWorkspace,\n captureLayoutWorkspaceSeed,\n hashLayoutPath,\n loadLayoutByteEvidence,\n probeLayoutPath,\n resolveLayoutPath,\n sameValue,\n scanLayout,\n stateText,\n type LayoutPhysicalPathFact,\n type LayoutScanResult,\n type TrackedLayoutPath,\n type TrackedLayoutRole,\n} from './layoutScan';\nimport { OperationOutcomeOutcomeEnum } from 'farseer-client';\nimport type { BlobContent, Document, Head, Json, PersistedLayoutEvidence, State } from './types';\nimport {\n atomicReplaceText,\n saveLearnedByteHashes,\n saveState,\n stageDownloadedFile,\n stageText,\n stageVerifiedFile,\n type StagedWorkspaceFile,\n} from './workspace';\ntype CompleteComposition = Extract<ComposeLayoutSubmissionResult, { status: 'complete' }>;\ntype CompleteReadback = Extract<PlanReceiptReadbackResult, { status: 'complete' }>;\ntype CompleteRendering = Extract<PlanReceiptRenderingResult, { status: 'complete' }>;\ntype StateWithLayout = State & { layout: NonNullable<State['layout']> };\n\nexport interface LayoutWorkspaceSnapshot {\n scan: LayoutScanResult;\n jsonText: Readonly<Record<string, string>>;\n byteFacts: readonly LayoutByteFact[];\n pathFacts: readonly LayoutPhysicalPathFact[];\n stateText: string;\n}\n\nexport type LayoutWorkspaceSnapshotSeed = Omit<LayoutWorkspaceSnapshot, 'pathFacts'>;\n\nexport interface LayoutJsonWrite {\n path: string;\n text: string;\n authorizingDocumentKeys: readonly string[];\n}\n\nexport interface LayoutByteWrite {\n path: string;\n descriptor: BlobContent;\n authorizingDocumentKey: string;\n}\n\nfunction same(left: unknown, right: unknown): boolean {\n try {\n return canonicalEqual(left as Json, right as Json);\n } catch {\n return false;\n }\n}\n\nfunction persistedEvidence(state: State): LayoutSubmissionEvidence {\n const evidence = state.layout!.evidence;\n return {\n groupedRoutes: clone(evidence.groupedRoutes),\n binaryRoutes: clone(evidence.binaryRoutes),\n groupedSubmissionProofs: [],\n binarySubmissionProofs: [],\n derivedSourceProofs: clone(evidence.derivedSourceProofs),\n rawNavigationRoutes: clone(evidence.rawNavigationRoutes),\n canonicalBaseline: clone(state.baseline),\n detachedFileProofs: clone(evidence.detachedFileProofs),\n detachedDocumentProofs: clone(evidence.detachedDocumentProofs),\n };\n}\n\nfunction managedJsonArtifacts(scan: LayoutScanResult) {\n return scan.artifacts.filter(\n (artifact) => artifact.present && !['raw', 'attachment'].includes(artifact.role) && artifact.json !== undefined,\n );\n}\n\nfunction expectedBytePaths(scan: LayoutScanResult, evidence: LayoutSubmissionEvidence): Set<string> {\n const expected = new Set(\n scan.artifacts\n .filter((artifact) => artifact.role === 'raw' || artifact.role === 'attachment')\n .map((artifact) => artifact.path),\n );\n for (const route of evidence.binaryRoutes) if (route.bytes) expected.add(route.bytes);\n return expected;\n}\n\n/** The capture boundary owns byte-fact completeness; this validates the saved state against the scan. */\nfunction snapshotSeedDiagnostics(state: State, snapshot: LayoutWorkspaceSnapshotSeed): ProjectionDiagnostic[] {\n const diagnostics: ProjectionDiagnostic[] = [];\n const expectedJson = new Map(managedJsonArtifacts(snapshot.scan).map((artifact) => [artifact.path, artifact]));\n const actualJsonPaths = Object.keys(snapshot.jsonText);\n for (const [file, artifact] of expectedJson) {\n const text = snapshot.jsonText[file];\n if (typeof text !== 'string') {\n diagnostics.push(diagnostic('missing-layout-json-text', file, 'Managed JSON text is missing'));\n continue;\n }\n try {\n if (!same(JSON.parse(text), artifact.json))\n diagnostics.push(\n diagnostic('layout-json-text-mismatch', file, 'Managed JSON text does not match scan'),\n );\n } catch {\n diagnostics.push(diagnostic('invalid-layout-json-text', file, 'Managed JSON text is invalid'));\n }\n }\n for (const file of actualJsonPaths)\n if (!expectedJson.has(file))\n diagnostics.push(\n diagnostic('extra-layout-json-text', file, 'JSON text does not identify a managed JSON artifact'),\n );\n\n const persistentTracked = new Map(state.layout?.tracked.map((item) => [item.route, item]));\n if (persistentTracked.size !== snapshot.scan.tracked.length)\n diagnostics.push(\n diagnostic('layout-tracking-mismatch', '.', 'Tracked mapping does not match the supplied scan'),\n );\n for (const tracked of snapshot.scan.tracked) {\n const original = persistentTracked.get(tracked.route);\n if (!original || original.path !== tracked.path)\n diagnostics.push(\n diagnostic('layout-tracking-mismatch', tracked.path, 'Tracked mapping does not match the scan'),\n );\n }\n return diagnostics;\n}\n\nfunction snapshotPathDiagnostics(\n state: State,\n snapshot: LayoutWorkspaceSnapshot,\n evidence: LayoutSubmissionEvidence,\n): ProjectionDiagnostic[] {\n const diagnostics: ProjectionDiagnostic[] = [];\n const expectedBytes = expectedBytePaths(snapshot.scan, evidence);\n const byteFacts = new Map(snapshot.byteFacts.map((fact) => [fact.path, fact]));\n\n const pathFacts = new Map<string, LayoutPhysicalPathFact>();\n for (const fact of snapshot.pathFacts) {\n if (pathFacts.has(fact.path)) throw new Error(`Path fact ${JSON.stringify(fact.path)} is duplicated`);\n pathFacts.set(fact.path, fact);\n }\n const requireState = (file: string, state: LayoutPhysicalPathFact['state'], message: string) => {\n if (pathFacts.get(file)?.state !== state)\n diagnostics.push(diagnostic('layout-path-fact-mismatch', file, message));\n };\n for (const artifact of snapshot.scan.artifacts)\n requireState(artifact.path, artifact.present ? 'file' : 'absent', 'Artifact path fact does not match scan');\n for (const directory of snapshot.scan.opaqueDirectories)\n if (isPortableWorkspacePointer(directory))\n requireState(directory, 'directory', 'Opaque directory fact is missing');\n const persistentTracked = new Map(state.layout?.tracked.map((item) => [item.route, item]));\n for (const tracked of snapshot.scan.tracked) {\n const original = persistentTracked.get(tracked.route);\n if (!original || original.path !== tracked.path) continue;\n const fact = pathFacts.get(original.path);\n if (tracked.status === 'present') {\n requireState(tracked.path, original.kind, 'Tracked path fact does not match scan');\n } else if (\n fact?.state !== 'absent' ||\n (tracked.status === 'missing-subtree' && fact.missingAncestor !== tracked.missingAncestor)\n )\n diagnostics.push(\n diagnostic('layout-path-fact-mismatch', tracked.path, 'Tracked absence fact does not match scan'),\n );\n }\n for (const file of expectedBytes) {\n const byte = byteFacts.get(file);\n const physical = pathFacts.get(file);\n if (\n byte &&\n ((byte.state === 'present' && physical?.state !== 'file') ||\n (byte.state === 'absent' && physical?.state !== 'absent'))\n )\n diagnostics.push(diagnostic('layout-byte-path-mismatch', file, 'Byte and path facts disagree'));\n }\n return diagnostics;\n}\n\n/** One index per composition. Every reconciliation lookup reads it instead of rescanning the composition. */\ninterface CompositionIndex {\n composition: CompleteComposition;\n sources: ReadonlyMap<string, CompleteComposition['sources'][number][]>;\n groupedObservations: ReadonlyMap<string, FragmentObservation[]>;\n rawObservations: ReadonlyMap<string, BinaryFragmentObservation[]>;\n attachmentObservations: ReadonlyMap<string, BinaryFragmentObservation[]>;\n ownerFields: ReadonlyMap<string, CompleteComposition['binary']['ownerFields'][number][]>;\n binaryRoutes: ReadonlyMap<string, LayoutSubmissionEvidence['binaryRoutes'][number][]>;\n groupedRoutes: ReadonlyMap<string, LayoutSubmissionEvidence['groupedRoutes'][number][]>;\n}\n\nfunction compositionIndex(composition: CompleteComposition): CompositionIndex {\n const bySource = <T>(items: readonly T[], key: (item: T) => string) => groupBySource(items, key);\n return {\n composition,\n sources: bySource(composition.sources, (item) => sourceIdentityKey(item.mapping.source)),\n groupedObservations: bySource(composition.grouped.observations, (item) => sourceIdentityKey(item.source)),\n rawObservations: bySource(composition.binary.rawObservations, (item) => sourceIdentityKey(item.source)),\n attachmentObservations: bySource(composition.binary.attachmentObservations, (item) =>\n sourceIdentityKey(item.source),\n ),\n ownerFields: bySource(composition.binary.ownerFields, (item) => sourceIdentityKey(item.ownerSource)),\n binaryRoutes: bySource(composition.context.evidence.binaryRoutes, (item) => sourceIdentityKey(item.source)),\n groupedRoutes: bySource(composition.context.evidence.groupedRoutes, (item) => sourceIdentityKey(item.source)),\n };\n}\n\nfunction observationForSource(index: CompositionIndex, source: StableSource) {\n const key = sourceIdentityKey(source);\n const mappings = index.sources.get(key) ?? [];\n if (mappings.length !== 1) return undefined;\n const selected = mappings[0];\n const candidates = selected.codec === 'grouped' ? index.groupedObservations : index.rawObservations;\n const observations = (candidates.get(key) ?? []).filter((item) => same(item.selector, selected.mapping.selector));\n return observations.length === 1 ? { source: selected, observation: observations[0] } : undefined;\n}\n\n/** Resolve one document key to its single current mapping and observation. */\nfunction observationForDocumentKey(index: CompositionIndex, documentKey: string) {\n const source = sourceForDocumentKey(documentKey);\n return source ? observationForSource(index, source) : undefined;\n}\n\nfunction sameLogicalSelector(\n left: FragmentObservation['selector'] | BinaryFragmentObservation['selector'],\n right: FragmentObservation['selector'] | BinaryFragmentObservation['selector'],\n): boolean {\n if (left.slot !== right.slot) return false;\n if (left.slot === 'owner-attachment' && right.slot === 'owner-attachment') return left.field === right.field;\n return true;\n}\n\nfunction retainedRouteFor(index: CompositionIndex, selected: NonNullable<ReturnType<typeof observationForSource>>) {\n const routes = selected.source.codec === 'grouped' ? index.groupedRoutes : index.binaryRoutes;\n const matches = (routes.get(sourceIdentityKey(selected.source.mapping.source)) ?? []).filter((route) =>\n sameLogicalSelector(route.selector, selected.observation.selector),\n );\n return matches.length === 1 ? matches[0] : undefined;\n}\n\nfunction replayMappingValid(index: CompositionIndex, documentKey: string): boolean {\n const source = sourceForDocumentKey(documentKey);\n const selected = source && observationForSource(index, source);\n if (\n !source ||\n !selected?.observation.currentHash ||\n !selected.observation.contributor ||\n !['clean', 'dirty', 'new'].includes(selected.observation.state)\n )\n return false;\n const route = retainedRouteFor(index, selected);\n return !!route && route.contributor && attachmentReplayValid(index, source);\n}\n\nfunction attachmentReplayValid(index: CompositionIndex, source: StableSource): boolean {\n const key = sourceIdentityKey(source);\n for (const field of index.ownerFields.get(key) ?? []) {\n if (!field.currentHash && !field.bytes) continue;\n const matches = (index.attachmentObservations.get(key) ?? []).filter(\n (item) =>\n item.selector.slot === 'owner-attachment' &&\n item.selector.ownerFile === field.ownerFile &&\n item.selector.field === field.field,\n );\n const routes = (index.binaryRoutes.get(key) ?? []).filter(\n (route) => route.selector.slot === 'owner-attachment' && route.selector.field === field.field,\n );\n if (\n matches.length !== 1 ||\n !matches[0].currentHash ||\n !['clean', 'dirty', 'new'].includes(matches[0].state) ||\n routes.length !== 1\n )\n return false;\n }\n return true;\n}\n\nfunction filterReplay(readback: CompleteReadback, replayed: ReadonlySet<string>): CompleteReadback {\n const materializations = readback.materializations.filter(\n (item) => !('documentKey' in item && item.documentKey && replayed.has(item.documentKey)),\n );\n const setKeys = new Set(\n materializations\n .filter((item): item is Extract<PhysicalMaterialization, { mode: 'set' }> => item.mode === 'set')\n .map((item) => item.documentKey),\n );\n const groupedCompanions = readback.groupedCompanions.flatMap((companion) => {\n const authorizingDocumentKeys = companion.authorizingDocumentKeys.filter((key) => setKeys.has(key));\n return authorizingDocumentKeys.length > 0 ? [{ ...clone(companion), authorizingDocumentKeys }] : [];\n });\n const attachments = readback.attachments.filter((item) => setKeys.has(item.ownerDocumentKey));\n return {\n ...readback,\n materializations,\n groupedCompanions,\n attachments,\n pendingDamage: readback.pendingDamage.filter((item) => setKeys.has(item.evidence.documentKey)),\n groupedPatches: [\n ...materializations.flatMap((item) =>\n item.mode === 'set' && item.codec === 'grouped' ? [...item.patches] : [],\n ),\n ...groupedCompanions.map((item) => item.patch),\n ],\n rawPatches: materializations.flatMap((item) =>\n item.mode === 'set' && item.codec === 'raw' ? [item.patch] : [],\n ),\n };\n}\n\n/** The classifications that may advance a baseline: the two eligible ones and a generated share. */\nconst ADOPTABLE = new Set(['eligible-stable-set', 'eligible-assigned-create', 'generated-share-deferred']);\n\nfunction receiptHash(readback: CompleteReadback, key: string): string | undefined {\n const matches = readback.receiptResults.filter(\n (item) => item.documentKey === key && ADOPTABLE.has(item.classification),\n );\n return matches.length === 1 && matches[0].receiptHash === matches[0].headHash ? matches[0].receiptHash : undefined;\n}\n\ninterface PersistentPhysicalClaim {\n logical: string;\n path: string;\n kind: 'file';\n role: TrackedLayoutRole;\n}\n\nfunction trackedRole(scan: LayoutScanResult, path: string, fallback: TrackedLayoutRole): TrackedLayoutRole {\n const roles = [\n ...new Set(\n scan.artifacts\n .filter((artifact) => artifact.path === path)\n .map((artifact): TrackedLayoutRole => {\n if (['folder-control', 'raw-metadata', 'raw', 'attachment'].includes(artifact.role))\n return artifact.role as TrackedLayoutRole;\n return 'document';\n }),\n ),\n ];\n return roles.length === 1 ? roles[0] : fallback;\n}\n\nfunction evidenceClaims(evidence: PersistedLayoutEvidence, scan: LayoutScanResult): PersistentPhysicalClaim[] {\n const claims: PersistentPhysicalClaim[] = [];\n for (const route of evidence.groupedRoutes) {\n const role = trackedRole(\n scan,\n route.selector.file,\n route.selector.file.endsWith('/_folder.json') ? 'folder-control' : 'document',\n );\n claims.push({\n logical: `grouped:${sourceIdentityKey(route.source)}:${route.selector.slot}`,\n path: route.selector.file,\n kind: 'file',\n role,\n });\n }\n for (const route of evidence.binaryRoutes) {\n const source = sourceIdentityKey(route.source);\n if (route.selector.slot === 'file-entry') {\n claims.push({\n logical: `binary:${source}:file-entry:sidecar`,\n path: route.selector.sidecar,\n kind: 'file',\n role: 'raw-metadata',\n });\n if (route.bytes)\n claims.push({\n logical: `binary:${source}:file-entry:bytes`,\n path: route.bytes,\n kind: 'file',\n role: 'raw',\n });\n } else if (route.bytes) {\n claims.push({\n logical: `binary:${source}:owner-attachment:${route.selector.field}`,\n path: route.bytes,\n kind: 'file',\n role: 'attachment',\n });\n }\n }\n for (const route of evidence.rawNavigationRoutes)\n claims.push({\n logical: `navigation:${sourceIdentityKey(route.source)}:raw-share`,\n path: route.groupFile,\n kind: 'file',\n role: trackedRole(scan, route.groupFile, 'document'),\n });\n const unique = new Map<string, PersistentPhysicalClaim>();\n for (const claim of claims) unique.set(canonicalText([claim.logical, claim.path, claim.kind, claim.role]), claim);\n return [...unique.values()];\n}\n\nfunction physicalClaimKey(claim: { path: string; kind: string; role: string }): string {\n return canonicalText([claim.path, claim.kind, claim.role]);\n}\n\nfunction trackedRoute(logical: string): string {\n // Generated IDs are deterministic. Existing opaque IDs remain unchanged when their prior claim is unambiguous.\n return `layout/v1/${canonicalFragmentHash(logical)}`;\n}\n\nfunction trackedAfter(input: {\n tracked: readonly TrackedLayoutPath[];\n before: PersistedLayoutEvidence;\n beforeScan: LayoutScanResult;\n after: PersistedLayoutEvidence;\n afterScan: LayoutScanResult;\n}): { tracked: TrackedLayoutPath[] } | { diagnostics: ProjectionDiagnostic[] } {\n const beforeClaims = evidenceClaims(input.before, input.beforeScan);\n const afterClaims = evidenceClaims(input.after, input.afterScan);\n const beforeByPhysical = new Map<string, PersistentPhysicalClaim[]>();\n const beforeByRoute = new Map(beforeClaims.map((claim) => [trackedRoute(claim.logical), claim]));\n const afterByLogical = new Map<string, PersistentPhysicalClaim[]>();\n for (const claim of beforeClaims)\n beforeByPhysical.set(physicalClaimKey(claim), [\n ...(beforeByPhysical.get(physicalClaimKey(claim)) ?? []),\n claim,\n ]);\n for (const claim of afterClaims)\n afterByLogical.set(claim.logical, [...(afterByLogical.get(claim.logical) ?? []), claim]);\n\n const output: TrackedLayoutPath[] = [];\n const represented = new Set<string>();\n const diagnostics: ProjectionDiagnostic[] = [];\n for (const claims of afterByLogical.values())\n if (new Set(claims.map(physicalClaimKey)).size !== 1)\n diagnostics.push(\n diagnostic(\n 'ambiguous-layout-tracking',\n claims[0].path,\n 'One logical route has multiple projected physical claims',\n ),\n );\n if (diagnostics.length > 0) return { diagnostics };\n for (const item of input.tracked) {\n const exact = beforeByRoute.get(item.route);\n const matched = exact ? [exact] : (beforeByPhysical.get(physicalClaimKey(item)) ?? []);\n if (matched.length === 0) {\n output.push(clone(item));\n continue;\n }\n const next = new Map<string, PersistentPhysicalClaim>();\n for (const prior of matched)\n for (const claim of afterByLogical.get(prior.logical) ?? []) next.set(physicalClaimKey(claim), claim);\n if (next.size === 0) continue;\n if (next.size !== 1) {\n if (exact) {\n diagnostics.push(\n diagnostic(\n 'ambiguous-layout-tracking',\n item.path,\n 'Generated tracked route maps to multiple projected physical claims',\n ),\n );\n continue;\n }\n const currentKey = physicalClaimKey(item);\n const retained = matched.filter((prior) =>\n (afterByLogical.get(prior.logical) ?? []).some((claim) => physicalClaimKey(claim) === currentKey),\n );\n if (retained.length > 0) {\n output.push(clone(item));\n for (const claim of retained) represented.add(claim.logical);\n }\n continue;\n }\n const claim = [...next.values()][0];\n output.push({ route: item.route, path: claim.path, kind: claim.kind, role: claim.role });\n if (exact || matched.length === 1) represented.add(claim.logical);\n }\n if (diagnostics.length > 0) return { diagnostics };\n\n const usedRoutes = new Set(output.map((item) => item.route));\n for (const claim of [...afterClaims].sort((left, right) => left.logical.localeCompare(right.logical))) {\n if (represented.has(claim.logical)) continue;\n const route = trackedRoute(claim.logical);\n if (usedRoutes.has(route))\n return {\n diagnostics: [\n diagnostic('duplicate-layout-tracking', claim.path, 'Generated tracked route collides with state'),\n ],\n };\n usedRoutes.add(route);\n represented.add(claim.logical);\n output.push({ route, path: claim.path, kind: claim.kind, role: claim.role });\n }\n output.sort((left, right) => left.route.localeCompare(right.route));\n return { tracked: output };\n}\n\nfunction byteWrite(materialization: LayoutByteMaterialization): LayoutByteWrite {\n return {\n path: materialization.destination,\n descriptor: clone(materialization.descriptor),\n authorizingDocumentKey:\n materialization.kind === 'raw' ? materialization.documentKey : materialization.ownerDocumentKey,\n };\n}\n\n/** What a guard reads out of one saved draft, whether the state reader trusted it or set it aside. */\ninterface GuardDraft {\n applying?: boolean;\n /** Whether the draft holds a receipt that is not written into the workspace yet. */\n receipt?: unknown;\n /** The state reader set the draft aside, so neither an apply nor a pull can write its receipt. */\n quarantined?: boolean;\n}\n\n/**\n * The way out of a set-aside draft whose apply was in flight. Nothing can write its receipt, so\n * only `pull --force`, which drops set-aside drafts and resets the workspace to the head, clears it.\n */\nexport function quarantinedApplyAdvice(planId: string): string {\n return (\n `The saved receipt for plan p${planId} could not be read while its apply was in flight; ` +\n 'run farseer code pull --force to reset the workspace to the head, then plan again'\n );\n}\n\n/**\n * One quarantined draft read as leniently as a guard allows: the flag that says an apply is in\n * flight, and whether a receipt arrived. Nothing else of it is ever trusted.\n */\nfunction quarantinedDraft(value: Json): GuardDraft {\n const draft = (value ?? {}) as Record<string, Json>;\n const receipt = (draft.receipt ?? undefined) as Record<string, Json> | undefined;\n const applying = draft.applying === true;\n return typeof receipt?.revisionId === 'string'\n ? { applying, receipt: true, quarantined: true }\n : { applying, quarantined: true };\n}\n\n/** Every saved draft one guard has to see: the readable ones and the quarantined ones alike. */\nexport function layoutReceiptDrafts(state: State): [string, GuardDraft][] {\n return [\n ...Object.entries(state.layout?.receipts ?? {}),\n ...Object.entries(state.layout?.unreadableReceipts ?? {}).map(([planId, draft]): [string, GuardDraft] => [\n planId,\n quarantinedDraft(draft),\n ]),\n ];\n}\n\n/**\n * Refuse a new plan while an apply's creates are not bound to their files yet: a plan now would\n * ask for the same creates again.\n */\nexport function refuseUnwrittenReceipts(state: State): void {\n for (const [planId, draft] of layoutReceiptDrafts(state)) {\n if (draft.applying && draft.quarantined) throw new Error(quarantinedApplyAdvice(planId));\n if (draft.applying && !draft.receipt)\n throw new Error(`Resume farseer code apply p${planId} before creating another plan`);\n if (draft.applying)\n throw new Error(`Run farseer code pull to write the receipt of p${planId} before creating another plan`);\n }\n}\n\nexport interface LayoutRemovalOutcome {\n /** Paths this writer took out of the workspace. */\n removed: readonly string[];\n /** Shared containers it rewrote in place because they outlive the removed resource. */\n rewritten: readonly string[];\n /** Paths it left alone. A local change after planning, or remaining content, always wins. */\n kept: readonly string[];\n /** Canonical keys whose removal did not happen, so their saved facts have to stay as well. */\n retained: readonly string[];\n}\n\n/** The identity of one path on disk, so two spellings of one inode are never mistaken for two files. */\nfunction fileIdentity(root: string, relative: string): string | undefined {\n try {\n const stat = fs.lstatSync(resolveLayoutPath(root, relative));\n return stat.isFile() ? `${stat.dev}:${stat.ino}` : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The identity of one directory on disk, so two spellings of one entry are recognised as one. */\nfunction directoryIdentity(root: string, relative: string): string | undefined {\n try {\n const stat = fs.lstatSync(resolveLayoutPath(root, relative));\n return stat.isDirectory() ? `${stat.dev}:${stat.ino}` : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Give one folder directory its new spelling where the filesystem folds case. There both spellings\n * name one entry, so no write can change it, and this is the one directory the pull renames: through\n * a temporary sibling, because a rename between two spellings of one entry need not take effect.\n * Where the two spellings are two directories, the ordinary writes and the removal pass apply.\n */\nfunction renameDirectorySpelling(root: string, rename: LayoutDirectoryRename): void {\n const identity = directoryIdentity(root, rename.from);\n if (identity === undefined || identity !== directoryIdentity(root, rename.to)) return;\n const slash = rename.to.lastIndexOf('/');\n const parent = rename.to.slice(0, slash),\n name = rename.to.slice(slash + 1),\n oldName = rename.from.slice(rename.from.lastIndexOf('/') + 1);\n if (fs.readdirSync(resolveLayoutPath(root, parent)).includes(name)) return;\n // The writer's own temporary spelling, so a crash between the renames leaves a stale temporary.\n const temporary = path.join(resolveLayoutPath(root, parent), `${oldName}.tmp-${randomUUID()}`);\n fs.renameSync(resolveLayoutPath(root, rename.from), temporary);\n try {\n fs.renameSync(temporary, resolveLayoutPath(root, rename.to));\n } catch (error) {\n // The entry goes back to the spelling the captured state still names.\n fs.renameSync(temporary, resolveLayoutPath(root, rename.from));\n throw error;\n }\n}\n\nfunction readLayoutText(root: string, relative: string): string | undefined {\n try {\n const absolute = resolveLayoutPath(root, relative);\n return fs.lstatSync(absolute).isFile() ? fs.readFileSync(absolute, 'utf8') : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction unlinkLayoutFile(root: string, relative: string): boolean {\n const absolute = resolveLayoutPath(root, relative);\n if (!fs.lstatSync(absolute).isFile()) return false;\n fs.unlinkSync(absolute);\n return true;\n}\n\n/** Whether one removal target still holds exactly what the capture recorded for it. */\nfunction removalMatchesCapture(\n root: string,\n snapshot: LayoutWorkspaceSnapshot,\n removal: Pick<LayoutRemoval, 'kind' | 'path'>,\n): boolean {\n if (removal.kind === 'directory' || removal.kind === 'rewrite') return true;\n if (removal.kind === 'bytes') {\n const expected = snapshot.byteFacts.find((fact) => fact.path === removal.path);\n const actual = hashLayoutPath(root, removal.path);\n return (\n expected?.state === 'present' && actual.state === 'present' && sameBytes(actual.content, expected.content)\n );\n }\n const captured = snapshot.jsonText[removal.path];\n return captured !== undefined && readLayoutText(root, removal.path) === captured;\n}\n\n/**\n * Take one directory out with `rmdir`, after the OS and tool files the scan ignores when they are\n * all it still holds, so a Finder `.DS_Store` or a `__pycache__` never keeps a moved folder's old\n * directory behind. A `.git` and anything else keep the directory.\n */\nfunction removeLayoutDirectory(absolute: string): void {\n const entries = fs.readdirSync(absolute, { withFileTypes: true });\n const ignored = entries.filter(\n (entry) =>\n entry.name !== '.git' &&\n isIgnoredLayoutName(entry.name) &&\n (entry.isFile() || (entry.isDirectory() && entry.name === '__pycache__')),\n );\n if (ignored.length === entries.length)\n for (const entry of ignored) fs.rmSync(path.join(absolute, entry.name), { recursive: entry.isDirectory() });\n fs.rmdirSync(absolute);\n}\n\n/**\n * Apply one rendered removal set. Every path is read again immediately before it changes and stays\n * untouched unless it still equals the capture the plan saw. A directory leaves only through\n * `rmdir`, so unknown local content survives as an opaque subtree instead of being deleted. A path\n * this write already produced is never removed, not even under a second spelling of its inode: on a\n * case-insensitive filesystem the origin of a case-only rename IS the destination.\n */\nexport function materializeLayoutRemovals(input: {\n root: string;\n snapshot: LayoutWorkspaceSnapshot;\n removals: readonly LayoutRemoval[];\n /** Paths this write produced. They belong to the head now, whatever a removal calls them. */\n written?: readonly string[];\n /** Keys whose new destination was not written, so every path that still holds them stays. */\n keep?: readonly string[];\n}): LayoutRemovalOutcome {\n const removed: string[] = [];\n const rewritten: string[] = [];\n const kept: string[] = [];\n const writtenPaths = new Set(input.written ?? []);\n const writtenIdentities = new Set(\n [...writtenPaths].flatMap((path) => {\n const identity = fileIdentity(input.root, path);\n return identity ? [identity] : [];\n }),\n );\n const capturedStill = (removal: LayoutRemoval): boolean =>\n removalMatchesCapture(input.root, input.snapshot, removal);\n // One group per canonical resource: bytes and the manifest row that names them leave together.\n const groupKeys = (removal: LayoutRemoval) =>\n removal.documentKeys.length > 0 ? removal.documentKeys : [`path:${removal.kind}:${removal.path}`];\n const proven = new Map(input.removals.map((removal) => [removal, capturedStill(removal)]));\n const failed = new Set<string>(input.keep ?? []);\n for (const removal of input.removals)\n if (!proven.get(removal)) for (const key of groupKeys(removal)) failed.add(key);\n // A kept removal closes over every key it hosts, so a shared container never orphans a sibling.\n for (let changed = true; changed; ) {\n changed = false;\n for (const removal of input.removals) {\n const keys = groupKeys(removal);\n if (!keys.some((key) => failed.has(key))) continue;\n for (const key of keys)\n if (!failed.has(key)) {\n failed.add(key);\n changed = true;\n }\n }\n }\n const retained = [...failed].filter((key) => !key.startsWith('path:')).sort(compareText);\n\n const order: Record<LayoutRemoval['kind'], number> = { bytes: 0, file: 0, rewrite: 1, directory: 2 };\n // A directory can only leave after everything under it, so the deepest path goes first.\n const ordered = [...input.removals].sort(\n (left, right) =>\n order[left.kind] - order[right.kind] ||\n (left.kind === 'directory' ? compareText(right.path, left.path) : compareText(left.path, right.path)),\n );\n for (const removal of ordered) {\n if (groupKeys(removal).some((key) => failed.has(key))) {\n kept.push(removal.path);\n continue;\n }\n if (removal.kind === 'directory') {\n try {\n removeLayoutDirectory(resolveLayoutPath(input.root, removal.path));\n removed.push(removal.path);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== 'ENOTEMPTY' && code !== 'ENOENT' && code !== 'EEXIST') throw error;\n kept.push(removal.path);\n }\n continue;\n }\n const identity = fileIdentity(input.root, removal.path);\n if (writtenPaths.has(removal.path) || (identity !== undefined && writtenIdentities.has(identity))) {\n kept.push(removal.path);\n continue;\n }\n if (removal.kind === 'rewrite') {\n atomicReplaceText(\n resolveLayoutPath(input.root, removal.path),\n `${JSON.stringify(removal.value, null, 2)}\\n`,\n );\n rewritten.push(removal.path);\n continue;\n }\n if (unlinkLayoutFile(input.root, removal.path)) removed.push(removal.path);\n else kept.push(removal.path);\n }\n return { removed, rewritten, kept, retained };\n}\n\n/**\n * Drop every saved fact a materialized removal invalidates: the canonical baseline of each removed\n * key, the routes, proofs and derived provenance of each removed source, and every tracked claim or\n * detached proof on a path that is gone.\n */\nexport function removeLayoutState(state: State, deletes: PlannedLayoutDeletes, removedPaths: readonly string[]): State {\n const sources = new Set(deletes.sources.map((source) => sourceIdentityKey(source)));\n const gone = new Set(removedPaths);\n const baseline = { ...state.baseline };\n for (const key of deletes.keys) delete baseline[key];\n if (!state.layout) return { ...state, baseline };\n const kept = <T extends { source: { type: string } }>(items: readonly T[]) =>\n items.filter((item) => !sources.has(sourceIdentityKey(item.source as SourceIdentity)));\n const evidence = state.layout.evidence;\n const detachedDocumentProofs = Object.fromEntries(\n Object.entries(evidence.detachedDocumentProofs).filter(\n ([file, proof]) => !gone.has(file) && !sources.has(proof.sourceKey),\n ),\n );\n const detachedFileProofs = Object.fromEntries(\n Object.entries(evidence.detachedFileProofs).filter(\n ([file, proof]) => !gone.has(file) && !sources.has(proof.sourceKey),\n ),\n );\n return {\n ...state,\n baseline,\n layout: {\n ...state.layout,\n evidence: {\n groupedRoutes: kept(evidence.groupedRoutes),\n binaryRoutes: kept(evidence.binaryRoutes),\n derivedSourceProofs: kept(evidence.derivedSourceProofs),\n rawNavigationRoutes: kept(evidence.rawNavigationRoutes),\n detachedDocumentProofs,\n detachedFileProofs,\n },\n tracked: state.layout.tracked.filter((item) => !gone.has(item.path)),\n },\n };\n}\n\n/**\n * Free a destination whose origin is the same file. A rename that changes only the case of a name\n * resolves to one inode on a case-insensitive filesystem, so writing the destination there would\n * keep the old spelling. The origin entry goes first, while it still equals the capture, and the\n * write then creates the destination under the name the plan allocated.\n */\nexport function vacateLayoutAliases(\n root: string,\n snapshot: LayoutWorkspaceSnapshot,\n removals: readonly LayoutRemoval[],\n written: readonly string[],\n): string[] {\n const destinations = new Set(written);\n const identities = new Set(\n written.flatMap((path) => {\n const identity = fileIdentity(root, path);\n return identity ? [identity] : [];\n }),\n );\n if (identities.size === 0) return [];\n const vacated: string[] = [];\n for (const removal of removals) {\n if (removal.kind !== 'file' && removal.kind !== 'bytes') continue;\n if (destinations.has(removal.path)) continue;\n const identity = fileIdentity(root, removal.path);\n if (identity === undefined || !identities.has(identity)) continue;\n if (!removalMatchesCapture(root, snapshot, removal)) continue;\n unlinkLayoutFile(root, removal.path);\n vacated.push(removal.path);\n }\n return vacated;\n}\n\n/**\n * Create the managed ancestors of every destination inside the workspace root. A checkout needs\n * this; the receipt writer never does. Each directory is resolved again immediately before it is\n * created, so an ancestor replaced by a symlink after the capture is refused instead of followed.\n * Returns the directories it created, so a write that fails before using them can take them out.\n */\nexport function createLayoutDestinationDirectories(root: string, destinations: readonly string[]): string[] {\n const directories = new Set<string>();\n const created: string[] = [];\n for (const destination of destinations)\n for (const ancestor of pathAncestors(parseWorkspacePointer(destination))) directories.add(ancestor);\n for (const relative of [...directories].sort(compareText)) {\n const absolute = resolveLayoutPath(root, relative);\n try {\n fs.mkdirSync(absolute, { mode: 0o755 });\n created.push(relative);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n if (!fs.lstatSync(absolute).isDirectory())\n throw new Error(`Managed destination ancestor is not a directory: ${relative}`);\n }\n }\n return created;\n}\n\n/** Take out the directories a failed write created and left empty, deepest first; never throws. */\nfunction removeEmptyDirectories(root: string, created: readonly string[]): void {\n for (const relative of [...created].sort((left, right) => compareText(right, left)))\n try {\n fs.rmdirSync(resolveLayoutPath(root, relative));\n } catch {\n // A directory that holds anything now stays.\n }\n}\n\nfunction descriptorKey(content: BlobContent): string {\n return `${content.sha256}/${content.size}`;\n}\n\n/** Every byte write staged beside its destination, and each raw file's sidecar staged with it. */\ninterface StagedByteWrites {\n staged: { path: string; file: StagedWorkspaceFile }[];\n sidecars: Map<string, StagedWorkspaceFile>;\n /** The sidecar paths staged with their bytes, which no plain JSON write may write again. */\n paired: Set<string>;\n /** Stops the download streaming now and removes its partial temporary (Ctrl-C mid-stream). */\n inFlight?: () => void;\n}\n\n/**\n * Stage every byte write in a temporary beside its destination: a workspace twin or a blob\n * streamed from the server and verified on the way. Nothing lands outside the workspace,\n * and a descriptor is downloaded once; its other destinations copy the first verified temporary.\n * Every source is read before any origin leaves: on a case-insensitive filesystem the origin of a\n * case-only rename IS the file the destination is copied from. A raw file's sidecar is staged with\n * its own bytes, so one unlink and one rename stand between the pair.\n */\nasync function stageByteWrites(\n input: Pick<MaterializeLayoutPlanInput, 'root' | 'api'>,\n snapshot: LayoutWorkspaceSnapshot,\n prepared: Pick<PreparedLayoutPlan, 'byteWrites' | 'jsonWrites'>,\n into: StagedByteWrites,\n): Promise<void> {\n const local = snapshot.byteFacts.filter(\n (fact): fact is Extract<(typeof snapshot.byteFacts)[number], { state: 'present' }> => fact.state === 'present',\n );\n const sources = new Map<string, string>();\n const sidecars = new Map(prepared.jsonWrites.map((item) => [item.path, item]));\n for (const write of prepared.byteWrites) {\n const key = descriptorKey(write.descriptor);\n const destination = resolveLayoutPath(input.root, write.path);\n const supplied = sources.get(key);\n const reusable = local.find((fact) => sameBytes(fact.content, write.descriptor));\n let file: StagedWorkspaceFile;\n if (supplied) file = stageVerifiedFile(supplied, destination, write.descriptor, write.path);\n else if (reusable)\n file = stageVerifiedFile(\n resolveLayoutPath(input.root, reusable.path),\n destination,\n write.descriptor,\n write.path,\n );\n else {\n if (!input.api) throw new Error(`No byte source for ${write.path}`);\n try {\n file = await stageDownloadedFile(input.api, destination, write.descriptor, (abandon) => {\n into.inFlight = abandon;\n });\n } finally {\n into.inFlight = undefined;\n }\n }\n into.staged.push({ path: write.path, file });\n if (!sources.has(key)) sources.set(key, file.temporary);\n const sidecar = sidecars.get(rawSidecarPath(write.path));\n if (!sidecar) continue;\n into.sidecars.set(write.path, stageText(resolveLayoutPath(input.root, sidecar.path), sidecar.text));\n into.paired.add(sidecar.path);\n }\n}\n\n/** Every destination must still be replaceable or creatable, and no component may be a symlink. */\nfunction validateDestinations(snapshot: LayoutWorkspaceSnapshot, prepared: PreparedLayoutPlan): void {\n const facts = new Map(snapshot.pathFacts.map((fact) => [fact.path, fact]));\n const destination = (path: string, label: string) => {\n const fact = facts.get(path);\n if (!fact) throw new Error(`${label} destination was never probed: ${path}`);\n if (fact.state !== 'file' && fact.state !== 'absent')\n throw new Error(`${label} destination is not replaceable: ${path}`);\n for (const ancestor of pathAncestors(path)) {\n const parent = facts.get(ancestor);\n if (!parent || (parent.state !== 'directory' && parent.state !== 'absent'))\n throw new Error(`${label} destination ancestor is unavailable: ${ancestor}`);\n }\n };\n for (const write of prepared.byteWrites) destination(write.path, 'Byte');\n for (const write of prepared.jsonWrites) destination(write.path, 'JSON');\n}\n\n/** What one command asks the writer to materialize. */\nexport type LayoutPlanSource = { kind: 'receipt'; planId: string } | { kind: 'checkout'; force?: boolean };\n\nexport interface MaterializeLayoutPlanInput {\n root: string;\n /** The selected Head. A receipt and a checkout read their authoritative documents from it. */\n head?: Head;\n source: LayoutPlanSource;\n api?: Pick<BlobApi, 'downloadBlob'>;\n}\n\nexport interface LayoutPlanOutcome {\n status: 'complete';\n action: 'noop' | 'write';\n materializations: readonly PhysicalMaterialization[];\n deletes: PlannedLayoutDeletes;\n adoptedDocumentKeys: readonly string[];\n /** Adopted keys whose recomposition did not reproduce the authoritative document. */\n unverifiedDocumentKeys: readonly string[];\n /** Why the written workspace could not be recomposed, when that is what blocked adoption. */\n verificationDiagnostics: readonly ProjectionDiagnostic[];\n /** Per-resource composition problems the command reports without failing. */\n compositionWarnings: readonly ProjectionDiagnostic[];\n jsonWrites: readonly LayoutJsonWrite[];\n byteWrites: readonly LayoutByteWrite[];\n removals: LayoutRemovalOutcome;\n notices: readonly LayoutReadbackNotice[];\n /** Temporary files the writer could not remove after the state was already saved. */\n cleanupWarnings?: readonly string[];\n}\n\nexport type MaterializeLayoutPlanResult =\n | LayoutPlanOutcome\n | { status: 'blocked'; diagnostics: readonly ProjectionDiagnostic[] };\n\ninterface PreparedLayoutPlan {\n state: StateWithLayout;\n current: CompleteComposition;\n readback: CompleteReadback;\n rendering: CompleteRendering;\n authoritative?: Head;\n authoritativeDocuments: ReadonlyMap<string, Document>;\n adoptedKeys: readonly string[];\n baselineSet: Readonly<Record<string, string>>;\n /**\n * Applied resources, and assigned creates that did not apply, whose baseline advances even when\n * the workspace could not take the text. Each advances only with its id on disk.\n */\n appliedBaseline: Readonly<Record<string, string>>;\n jsonWrites: readonly LayoutJsonWrite[];\n byteWrites: readonly LayoutByteWrite[];\n requiredPaths: readonly string[];\n notices: readonly LayoutReadbackNotice[];\n compositionWarnings: readonly ProjectionDiagnostic[];\n /** A forced checkout discards the drafts the state reader quarantined; nothing else may. */\n dropQuarantinedReceipts: boolean;\n action: 'noop' | 'write';\n}\n\n/**\n * Local paths the writer names once and then ignores everywhere else: the atomic temporary a\n * crashed write left behind, and a marked directory whose own name no managed path can carry.\n */\nfunction localPathNotices(scan: LayoutScanResult): LayoutReadbackNotice[] {\n const temporaries = [...scan.localOnlyFiles, ...scan.opaqueDirectories]\n .filter((file) => isTemporaryLayoutPath(file))\n .sort(compareText)\n .map((path) => ({ status: 'stale-temporary' as const, path }));\n const unmanageable = [...(scan.unmanageableDirectories ?? [])]\n .sort(compareText)\n .map((path) => ({ status: 'unmanageable-path' as const, path }));\n return [...temporaries, ...unmanageable];\n}\n\n/** The canonical key one source stands for, when it names a real resource identity. */\nfunction stableSourceKeyOf(source: SourceIdentity): string | undefined {\n return source.type === 'resource' && 'id' in source.resource\n ? `${source.resource.kind}/${source.resource.id}`\n : undefined;\n}\n\n/** The command's own copy of the captured state, from the exact text the capture read. */\nfunction parsedLayoutState(text: string): StateWithLayout | ProjectionDiagnostic[] {\n let parsed: State;\n try {\n parsed = parseState(text);\n } catch (error) {\n return [diagnostic('invalid-layout-state', '.', error instanceof Error ? error.message : 'invalid state')];\n }\n return parsed as StateWithLayout;\n}\n\nfunction receiptDecisions(\n state: StateWithLayout,\n planId: string,\n head: Head,\n current: CompleteComposition,\n): { readback: CompleteReadback } | { diagnostics: ProjectionDiagnostic[] } {\n const draft = state.layout.receipts?.[planId];\n if (!draft?.receipt || !draft.submission || draft.submission.planId !== planId)\n return { diagnostics: [diagnostic('missing-layout-receipt', planId, 'Stored layout receipt is incomplete')] };\n const submission = draft.submission as LayoutReceiptSubmission;\n const eligibility = decideReceiptEligibility({ head, receipt: draft.receipt, submission, current });\n if (eligibility.status === 'blocked') return { diagnostics: [...eligibility.diagnostics] };\n const readback = planMaterialization({ eligibility, head, current });\n if (readback.status === 'blocked') return { diagnostics: [...readback.diagnostics] };\n const index = compositionIndex(current);\n const replayed = new Set<string>();\n for (const item of readback.receiptResults)\n if (\n (item.classification === 'eligible-stable-set' || item.classification === 'eligible-assigned-create') &&\n item.documentKey &&\n item.receiptHash &&\n state.baseline[item.documentKey] === item.receiptHash &&\n replayMappingValid(index, item.documentKey)\n )\n replayed.add(item.documentKey);\n return { readback: filterReplay(readback, replayed) };\n}\n\nfunction planSubmissionProofs(state: StateWithLayout, source: LayoutPlanSource): Partial<LayoutSubmissionEvidence> {\n if (source.kind !== 'receipt') return {};\n const draft = state.layout.receipts?.[source.planId];\n return {\n groupedSubmissionProofs: clone(draft?.submission?.composition.groupedSubmissions ?? []),\n binarySubmissionProofs: clone(draft?.submission?.composition.binarySubmissions ?? []),\n reservedTransientTokens: (draft?.submission?.composition.sources ?? []).flatMap((item) =>\n item.mapping.source.type === 'transient' ? [item.mapping.source.token] : [],\n ),\n };\n}\n\nfunction requiredPathsFor(\n snapshot: LayoutWorkspaceSnapshotSeed,\n state: StateWithLayout,\n rendering: CompleteRendering,\n): string[] {\n const paths = new Set<string>();\n const add = (candidate: string) => {\n paths.add(candidate);\n for (const ancestor of pathAncestors(candidate)) paths.add(ancestor);\n };\n // A local-only file is never a managed path, so it never reaches portable-path validation.\n for (const artifact of snapshot.scan.artifacts) add(artifact.path);\n for (const directory of snapshot.scan.opaqueDirectories) if (isPortableWorkspacePointer(directory)) add(directory);\n for (const tracked of snapshot.scan.tracked) {\n add(tracked.path);\n if (tracked.missingAncestor) add(tracked.missingAncestor);\n }\n for (const tracked of state.layout.tracked) add(tracked.path);\n for (const file of Object.keys(snapshot.jsonText)) add(file);\n for (const fact of snapshot.byteFacts) add(fact.path);\n for (const rendered of rendering.json) add(rendered.path);\n for (const rendered of rendering.bytes) add(rendered.destination);\n for (const removal of rendering.removals) add(removal.path);\n return [...paths].sort(compareText);\n}\n\n/** Kinds whose file sits at one route the head's own name and folder decide, with nothing beside it. */\nconst PLAIN_ROUTE_KINDS = new Set(['variable', 'sheet', 'dashboard', 'remote_job']);\n\n/** The route a head document occupies when its name and folder need no fallback spelling. */\nfunction plainHeadRoute(document: Document): string | undefined {\n const value = document as unknown as Record<string, unknown>;\n const folder = value.folder;\n if (!PLAIN_ROUTE_KINDS.has(document.kind) || typeof value.name !== 'string') return undefined;\n if (!Array.isArray(folder) || folder.some((segment) => typeof segment !== 'string')) return undefined;\n const segments = [...(folder as string[]), value.name];\n if (segments.some((segment) => layoutNameNeedsOverride(segment))) return undefined;\n try {\n return `tree/${segments.map(encodeLayoutSegment).join('/')}.json`;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The origins a checkout that threw mid-write left behind. Such a throw writes the destination and\n * keeps the origin, so one id occupies two equal files: the survivor sits at the route the head\n * allocates and the doomed copy at the route this workspace last proved, which the write was\n * leaving. Anything else \u2014 an author's own copy of a file, two copies that differ \u2014 still blocks,\n * naming both paths, because the tool cannot tell which one the author means to keep.\n */\nfunction staleDuplicateOrigins(\n scan: LayoutScanResult,\n diagnostics: readonly ProjectionDiagnostic[],\n head: Head,\n provenRoutes: readonly ProvenFragmentRoute[],\n): string[] {\n const artifact = (path: string) => scan.artifacts.find((candidate) => candidate.path === path && candidate.present);\n const stale: string[] = [];\n for (const item of diagnostics) {\n if (item.code !== 'duplicate-resource-identity' || !item.relatedPath) return [];\n const pair = [artifact(item.path), artifact(item.relatedPath)];\n const [left, right] = pair;\n if (!left?.json || !right?.json || canonicalText(left.json as Json) !== canonicalText(right.json as Json))\n return [];\n const identity = left.json as { kind?: unknown; id?: unknown };\n if (typeof identity.kind !== 'string' || typeof identity.id !== 'string') return [];\n const index = head.documentKeys.indexOf(`${identity.kind}/${identity.id}`);\n const route = index < 0 ? undefined : plainHeadRoute(head.documents[index]);\n const origins = pair.filter((candidate) => candidate!.path !== route);\n if (route === undefined || origins.length !== 1) return [];\n const proven = provenRoutes.filter(\n (candidate) =>\n candidate.selector.slot === 'document' &&\n candidate.source.type === 'resource' &&\n 'id' in candidate.source.resource &&\n candidate.source.resource.kind === identity.kind &&\n candidate.source.resource.id === identity.id,\n );\n if (proven.length !== 1 || proven[0].selector.file !== origins[0]!.path) return [];\n stale.push(origins[0]!.path);\n }\n return stale;\n}\n\n/**\n * Put back every artifact this write freed and never replaced, and name the ones it could not. The\n * captured text of a JSON artifact and the staged temporary of a byte destination are both still in\n * hand at this point, so the workspace keeps the artifact it had instead of losing it to a throw.\n * A sidecar is freed only after its own bytes are committed, so it goes back beside them, at the\n * destination; everything else goes back where the capture had it.\n */\nfunction restoreVacatedOrigins(\n root: string,\n snapshot: LayoutWorkspaceSnapshotSeed,\n vacated: readonly { origin: string; destination: string }[],\n staged: readonly { path: string; file: StagedWorkspaceFile; beside?: true }[],\n): string[] {\n const temporaries = new Map(staged.map((item) => [item.path, item.file.temporary]));\n const beside = new Set(staged.flatMap((item) => (item.beside ? [item.path] : [])));\n const lost: string[] = [];\n for (const { origin, destination } of vacated) {\n // A committed destination is the same directory entry as its origin, so nothing is missing.\n if (fs.existsSync(resolveLayoutPath(root, origin))) continue;\n const target = beside.has(destination) ? destination : origin;\n const absolute = resolveLayoutPath(root, target);\n const text = beside.has(destination) ? undefined : snapshot.jsonText[origin];\n const temporary = temporaries.get(destination);\n try {\n if (text !== undefined) atomicReplaceText(absolute, text);\n else if (temporary !== undefined) fs.copyFileSync(temporary, absolute);\n } catch {\n // The restore is best effort: a path it cannot reach is reported, never thrown again.\n }\n if (!fs.existsSync(absolute)) lost.push(target);\n }\n return [...new Set(lost)].sort(compareText);\n}\n\n/**\n * Take back raw bytes this write created at a path the capture had empty, when their sidecar never\n * followed. Bytes without a sidecar read as a file the author added, so the next pull would route\n * around its own copy and never adopt the pair; without them the capture's pair is intact, and\n * the next pull renames it. Bytes that replaced a captured file, or whose spelling a vacated\n * origin shares, stay: there they are the only copy. Returns the path when it could not go.\n */\nfunction withdrawUnpairedBytes(\n root: string,\n snapshot: LayoutWorkspaceSnapshot,\n vacated: readonly { origin: string; destination: string }[],\n unpaired: { path: string; identity: string | undefined } | undefined,\n): string[] {\n if (unpaired === undefined || unpaired.identity === undefined) return [];\n const sidecar = rawSidecarPath(unpaired.path);\n if (snapshot.pathFacts.find((fact) => fact.path === unpaired.path)?.state !== 'absent') return [];\n if (vacated.some(({ destination }) => destination === unpaired.path || destination === sidecar)) return [];\n if (fileIdentity(root, unpaired.path) !== unpaired.identity) return [];\n try {\n unlinkLayoutFile(root, unpaired.path);\n } catch {\n // Best effort, like the restore: a path that stays is reported, never thrown again.\n }\n return fileIdentity(root, unpaired.path) === unpaired.identity ? [unpaired.path] : [];\n}\n\n/** What to remove when Ctrl-C ends the process while a write is still staging. */\nconst activeWrites = new Set<() => void>();\n\n/** The writer's SIGINT listener: remove what a write is staging, then exit as Ctrl-C does. */\nexport function exitAfterWrites(): void {\n for (const abandon of activeWrites)\n try {\n abandon();\n } catch {\n // Exiting anyway; a temporary left behind is named by the next command.\n }\n process.exit(130);\n}\n\n/**\n * Make Ctrl-C end the process only between writer phases. Node calls a SIGINT listener on a later\n * turn of the event loop, never inside synchronous code, and the writes run synchronously from the\n * first commit to the saved state, so a signal that arrives during them is handled after the state\n * is saved; without a listener the signal would end the process between two writes. During the\n * asynchronous staging before them, the listener removes what was staged and exits. The listener\n * stays for the life of the process: removed right after the writes, it could drop a signal that\n * arrived during them and that Node had not delivered yet.\n */\nfunction deferInterrupts(): void {\n if (!process.listeners('SIGINT').includes(exitAfterWrites)) process.on('SIGINT', exitAfterWrites);\n}\n\n/** The resources each captured path holds, keyed by the spelling a case-folding filesystem shares. */\nfunction currentHolders(current: CompleteComposition): Map<string, Set<string>> {\n const holders = new Map<string, Set<string>>();\n const hold = (path: string, key: string) => {\n const folded = layoutCollisionKey(path);\n holders.set(folded, (holders.get(folded) ?? new Set<string>()).add(key));\n };\n for (const item of current.sources) {\n const key = stableSourceKeyOf(item.mapping.source);\n if (!key) continue;\n if (item.codec === 'grouped') hold(item.mapping.selector.file, key);\n else {\n hold(item.mapping.selector.sidecar, key);\n hold(item.mapping.bytes, key);\n }\n }\n return holders;\n}\n\n/**\n * Whether one destination still holds what the capture recorded, read immediately before its\n * replace, as a removal is: an editor can save into it while large bytes stage. JSON is compared\n * by its text, bytes by their hash, and a destination the capture found absent must still be.\n */\nfunction destinationsMatchCapture(root: string, snapshot: LayoutWorkspaceSnapshot): (path: string) => boolean {\n const bytesAt = new Map(snapshot.byteFacts.map((fact) => [fact.path, fact]));\n const factAt = new Map(snapshot.pathFacts.map((fact) => [fact.path, fact]));\n return (path) => {\n const text = snapshot.jsonText[path];\n if (text !== undefined) return readLayoutText(root, path) === text;\n const bytes = bytesAt.get(path);\n if (bytes) {\n const actual = hashLayoutPath(root, path);\n return bytes.state === 'present'\n ? actual.state === 'present' && sameBytes(actual.content, bytes.content)\n : actual.state === bytes.state;\n }\n return factAt.get(path)?.state !== 'absent' || probeLayoutPath(root, path).state === 'absent';\n };\n}\n\n/** One replace the writer commits as a whole: a JSON file, or raw bytes with their sidecar. */\ninterface WriteUnit {\n paths: readonly string[];\n /** The resources the written files hold. */\n keys: ReadonlySet<string>;\n /** Stage the content ahead of its turn, to break a cycle; staged bytes need nothing more. */\n hold?: () => void;\n run: () => void;\n}\n\ninterface WriteOrder {\n run(): void;\n /** Keys whose destination the writer left alone: it changed after the capture, or it waits on one that did. */\n readonly skipped: ReadonlySet<string>;\n notices(): LayoutReadbackNotice[];\n /**\n * Undo every written unit that waited on a unit which did not end written, or that wrote part of\n * a resource another unit kept, until none is left: the first overwrote an origin whose resource\n * exists only in a staged temporary, which the cleanup deletes, and the second left a resource\n * half written. `revert` restores one unit's destinations; the undone units count as skipped.\n * Returns the paths that could not be restored.\n */\n revertUnfinished(revert: (unit: WriteUnit) => string[]): string[];\n}\n\n/**\n * Order the replaces so that a destination holding another resource's origin is written only after\n * that resource reached its own destination: a rename of A plus a new B at A's old path writes A's\n * new file first, so a write that stops in between leaves A twice, never nowhere, and the next pull\n * converges. When resources move into each other's paths (a cycle), one of them is staged under a\n * temporary name first, the same idea as the server's temporary names for rename cycles. Each\n * destination is compared with the capture before the first replace and again right before its\n * own; a changed one is kept and reported, and so is every other unit of its resources and every\n * replace that waits on one of them, because those resources never left. A held unit\n * can end skipped after another unit of its cycle overwrote its origin, and a throw can stop the\n * writes before it is written; either way `revertUnfinished` puts those origins back, on the\n * success path and in the catch alike.\n */\nfunction orderedWrites(\n units: readonly WriteUnit[],\n holders: ReadonlyMap<string, ReadonlySet<string>>,\n unchanged: (path: string) => boolean,\n): WriteOrder {\n const writers = new Map<string, number[]>();\n units.forEach((unit, index) => {\n for (const key of unit.keys) writers.set(key, [...(writers.get(key) ?? []), index]);\n });\n const folded = units.map((unit) => unit.paths.map(layoutCollisionKey));\n const waits = units.map((unit, index) => {\n const wait = new Set<number>();\n for (const path of folded[index])\n for (const key of holders.get(path) ?? [])\n if (!unit.keys.has(key))\n for (const other of writers.get(key) ?? [])\n if (other !== index && !folded[other].includes(path)) wait.add(other);\n return wait;\n });\n const dependents = units.map((): number[] => []);\n waits.forEach((wait, index) => {\n for (const other of wait) dependents[other].push(index);\n });\n const unsettled = waits.map((wait) => wait.size);\n const done = new Set<number>(),\n held = new Set<number>(),\n skippedUnits = new Set<number>(),\n released = new Set<number>();\n const skipped = new Set<string>();\n\n const ready: number[] = [];\n let next = 0;\n /** A unit that is written, held or skipped no longer keeps the units that wait on it. */\n const release = (index: number) => {\n if (released.has(index)) return;\n released.add(index);\n for (const dependent of dependents[index]) if (--unsettled[dependent] === 0) ready.push(dependent);\n };\n const skip = (index: number) => {\n skippedUnits.add(index);\n for (const key of units[index].keys) skipped.add(key);\n release(index);\n };\n return {\n skipped,\n run() {\n // Every destination is compared before the first replace as well: a unit whose\n // destination changed is kept with every unit of its resources and every unit that waits\n // on one of them, so no write starts a move or a resource that cannot finish.\n const kept = new Set(units.flatMap((unit, index) => (unit.paths.every(unchanged) ? [] : [index])));\n for (const queue = [...kept]; queue.length > 0; ) {\n const index = queue.pop()!;\n const keys = [...units[index].keys];\n for (const other of [...dependents[index], ...keys.flatMap((key) => writers.get(key) ?? [])])\n if (!kept.has(other)) {\n kept.add(other);\n queue.push(other);\n }\n }\n for (const index of kept) skip(index);\n units.forEach((_, index) => {\n if (unsettled[index] === 0) ready.push(index);\n });\n let finished = kept.size;\n while (finished < units.length) {\n const unit = next < ready.length ? ready[next++] : undefined;\n if (unit === undefined) {\n // A cycle: stage the first unit another unfinished one waits on, so that one can go.\n const open = (index: number) => !done.has(index) && !skippedUnits.has(index);\n const cycle = units.findIndex(\n (_, index) => open(index) && !held.has(index) && dependents[index].some((other) => open(other)),\n );\n if (cycle < 0) throw new Error('Layout writes wait on each other with nothing left to stage');\n if (units[cycle].paths.every(unchanged)) {\n units[cycle].hold?.();\n held.add(cycle);\n release(cycle);\n } else {\n skip(cycle);\n finished++;\n }\n continue;\n }\n if (done.has(unit) || skippedUnits.has(unit)) continue;\n finished++;\n const blockers = [...waits[unit]];\n if (\n blockers.some((index) => skippedUnits.has(index)) ||\n [...units[unit].keys].some((key) => skipped.has(key)) ||\n (!held.has(unit) && !units[unit].paths.every(unchanged))\n ) {\n skip(unit);\n continue;\n }\n units[unit].run();\n done.add(unit);\n release(unit);\n }\n },\n notices() {\n return [...skippedUnits].flatMap((index) =>\n [...units[index].keys]\n .sort(compareText)\n .map(\n (key): LayoutReadbackNotice => ({ status: 'unmaterialized', path: units[index].paths[0], key }),\n ),\n );\n },\n revertUnfinished(revert) {\n const lost: string[] = [];\n for (let changed = true; changed; ) {\n changed = false;\n for (const index of [...done])\n if (\n [...waits[index]].some((blocker) => !done.has(blocker)) ||\n [...units[index].keys].some((key) => skipped.has(key))\n ) {\n done.delete(index);\n lost.push(...revert(units[index]));\n skippedUnits.add(index);\n for (const key of units[index].keys) skipped.add(key);\n changed = true;\n }\n }\n return [...new Set(lost)];\n },\n };\n}\n\n/** The content of one file, or undefined when it is gone or unreadable; never throws. */\nfunction contentOf(file: string): BlobContent | undefined {\n try {\n return hashFile(file);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Put one written unit's destinations back to what the capture held there (`revertUnfinished`). A\n * destination the capture did not hold was created by the write and goes; the captured artifact at\n * the same path, under any spelling a case-folding filesystem shares, returns: JSON from its\n * captured text, bytes from a staged temporary or a written destination of the same content.\n * Returns the paths it could not restore; never throws.\n */\nfunction restoreCapturedPaths(\n root: string,\n snapshot: LayoutWorkspaceSnapshot,\n paths: readonly string[],\n staged: readonly { path: string; file: StagedWorkspaceFile }[],\n): string[] {\n const lost: string[] = [];\n const bytesAt = new Map(\n snapshot.byteFacts.flatMap((fact) => (fact.state === 'present' ? [[fact.path, fact.content] as const] : [])),\n );\n const captured = [...Object.keys(snapshot.jsonText), ...bytesAt.keys()];\n const sources = staged.flatMap((item) => [item.file.temporary, resolveLayoutPath(root, item.path)]);\n for (const path of paths) {\n const origins = captured.filter((origin) => layoutCollisionKey(origin) === layoutCollisionKey(path));\n try {\n if (!origins.includes(path) && fs.existsSync(resolveLayoutPath(root, path))) unlinkLayoutFile(root, path);\n for (const origin of origins) {\n const text = snapshot.jsonText[origin];\n const bytes = bytesAt.get(origin);\n const twin = bytes && sources.find((file) => sameBytes(contentOf(file), bytes));\n if (text !== undefined) atomicReplaceText(resolveLayoutPath(root, origin), text);\n else if (twin) fs.copyFileSync(twin, resolveLayoutPath(root, origin));\n else lost.push(origin);\n }\n } catch {\n lost.push(path);\n }\n }\n return lost;\n}\n\n/** Compose the captured workspace, decide what it may receive and render the containers that result. */\nfunction prepareLayoutPlan(\n input: MaterializeLayoutPlanInput,\n captured: { snapshot: LayoutWorkspaceSnapshotSeed },\n): { status: 'complete'; prepared: PreparedLayoutPlan } | { status: 'blocked'; diagnostics: ProjectionDiagnostic[] } {\n const parsed = parsedLayoutState(captured.snapshot.stateText);\n if (Array.isArray(parsed)) return { status: 'blocked', diagnostics: parsed };\n const state = parsed;\n const evidence = { ...persistedEvidence(state), ...planSubmissionProofs(state, input.source) };\n const diagnostics = snapshotSeedDiagnostics(state, captured.snapshot);\n if (diagnostics.length > 0) return { status: 'blocked', diagnostics };\n\n const byteEvidence = { facts: captured.snapshot.byteFacts, diagnostics: [] };\n const composed = composeLayoutSubmission({ scan: captured.snapshot.scan, byteEvidence, evidence });\n let staleOrigins: readonly string[] = [];\n let current = composed;\n if (composed.status === 'blocked' && input.source.kind === 'checkout' && input.head) {\n staleOrigins = staleDuplicateOrigins(\n captured.snapshot.scan,\n composed.diagnostics,\n input.head,\n evidence.groupedRoutes,\n );\n const dropped = new Set(staleOrigins);\n const retry = dropped.size\n ? composeLayoutSubmission({\n scan: {\n ...captured.snapshot.scan,\n artifacts: captured.snapshot.scan.artifacts.filter((item) => !dropped.has(item.path)),\n },\n byteEvidence,\n evidence,\n })\n : composed;\n if (retry.status === 'complete') current = retry;\n else staleOrigins = [];\n }\n if (current.status === 'blocked') return { status: 'blocked', diagnostics: current.diagnostics };\n\n let readback: CompleteReadback;\n const authoritative = input.head;\n if (input.source.kind === 'receipt' || input.source.kind === 'checkout') {\n if (!input.head)\n return { status: 'blocked', diagnostics: [diagnostic('missing-head', '.', 'This plan needs a Head')] };\n }\n if (input.source.kind === 'receipt') {\n const decided = receiptDecisions(state, input.source.planId, input.head!, current);\n if ('diagnostics' in decided) return { status: 'blocked', diagnostics: decided.diagnostics };\n readback = decided.readback;\n } else {\n const eligibility = decideCheckoutEligibility({\n head: input.head!,\n baseline: state.baseline,\n current,\n force: input.source.force,\n });\n if (eligibility.status === 'blocked') return { status: 'blocked', diagnostics: [...eligibility.diagnostics] };\n const materialized = planMaterialization({\n eligibility,\n ...(authoritative ? { head: authoritative } : {}),\n current,\n });\n if (materialized.status === 'blocked') return { status: 'blocked', diagnostics: [...materialized.diagnostics] };\n readback = materialized;\n }\n\n // A stale origin belongs to no resource any more, so it joins the ordinary deletes: the removal\n // pass takes it out under capture and the command reports it as a deletion, never in silence.\n // One that a resource of this pull is written to needs no removal: the write replaces it.\n const destinations = new Set(\n readback.materializations.flatMap((item) =>\n item.mode === 'set' ? [item.codec === 'grouped' ? item.destination.file : item.bytes] : [],\n ),\n );\n const staleRemovals = staleOrigins.filter((path) => !destinations.has(path));\n if (staleRemovals.length > 0)\n readback = {\n ...readback,\n deletes: {\n ...readback.deletes,\n json: [...readback.deletes.json, ...staleRemovals.map((path) => ({ path, documentKeys: [] }))],\n },\n };\n const rendering = planReceiptRendering({ readback });\n if (rendering.status === 'blocked') return { status: 'blocked', diagnostics: [...rendering.diagnostics] };\n // A removal rendering could not produce keeps its canonical facts, so it leaves the delete set.\n if (rendering.retainedRemovalKeys.length > 0) {\n const retained = new Set(rendering.retainedRemovalKeys);\n readback = {\n ...readback,\n deletes: {\n ...readback.deletes,\n keys: readback.deletes.keys.filter((key) => !retained.has(key)),\n sources: readback.deletes.sources.filter((source) => {\n const key = stableSourceKeyOf(source);\n return key === undefined || !retained.has(key);\n }),\n },\n };\n }\n\n // A resource the rendering left out keeps its content, so it is neither written nor adopted.\n if (rendering.unmaterializedKeys.length > 0) {\n const dropped = new Set(rendering.unmaterializedKeys);\n readback = {\n ...readback,\n materializations: readback.materializations.filter(\n (item) => !(item.mode === 'set' && dropped.has(item.documentKey)),\n ),\n };\n }\n\n const sets = readback.materializations.filter(\n (item): item is Extract<PhysicalMaterialization, { mode: 'set' }> => item.mode === 'set',\n );\n const authoritativeDocuments = new Map(sets.map((item) => [item.documentKey, item.document]));\n const adoptedKeys = sets.map((item) => item.documentKey).sort(compareText);\n const baselineSet: Record<string, string> = {};\n for (const key of adoptedKeys) {\n const hash = input.source.kind === 'receipt' ? receiptHash(readback, key) : input.head!.manifest[key];\n if (!hash)\n return {\n status: 'blocked',\n diagnostics: [diagnostic('missing-adopted-baseline', key, 'Accepted resource has no baseline hash')],\n };\n baselineSet[key] = hash;\n }\n\n // An applied resource, and an assigned create the receipt lists, advance whatever the workspace\n // did with its text: the next plan reads the file as an ordinary update of the server's version.\n const appliedBaseline: Record<string, string> = {};\n if (input.source.kind === 'receipt') {\n const deleted = new Set(readback.deletes.keys);\n for (const item of readback.receiptResults)\n if (\n (item.outcome === OperationOutcomeOutcomeEnum.Applied ||\n (item.handle !== undefined && item.assignment !== undefined)) &&\n item.documentKey &&\n item.receiptHash &&\n !deleted.has(item.documentKey) &&\n baselineSet[item.documentKey] === undefined &&\n state.baseline[item.documentKey] !== item.receiptHash\n )\n appliedBaseline[item.documentKey] = item.receiptHash;\n }\n\n const currentBytes = new Map(captured.snapshot.byteFacts.map((fact) => [fact.path, fact]));\n const jsonWrites = rendering.json.flatMap((item) => {\n const text = `${JSON.stringify(item.value, null, 2)}\\n`;\n return captured.snapshot.jsonText[item.path] === text\n ? []\n : [{ path: item.path, text, authorizingDocumentKeys: [...item.authorizingDocumentKeys] }];\n });\n const byteWrites = rendering.bytes.flatMap((item) => {\n const fact = currentBytes.get(item.destination);\n return fact?.state === 'present' && same(fact.content, item.descriptor) ? [] : [byteWrite(item)];\n });\n // A removal the author already performed writes nothing, but its baseline still has to go.\n const pending =\n jsonWrites.length +\n byteWrites.length +\n rendering.removals.length +\n readback.identityPatches.length +\n adoptedKeys.length +\n Object.keys(appliedBaseline).length +\n readback.deletes.keys.length;\n const action = pending === 0 ? 'noop' : 'write';\n return {\n status: 'complete',\n prepared: {\n state,\n current,\n readback,\n rendering,\n authoritative,\n authoritativeDocuments,\n adoptedKeys,\n baselineSet,\n appliedBaseline,\n jsonWrites,\n byteWrites,\n requiredPaths: requiredPathsFor(captured.snapshot, state, rendering),\n notices: [...readback.notices, ...rendering.notices, ...localPathNotices(captured.snapshot.scan)],\n dropQuarantinedReceipts: input.source.kind === 'checkout' && input.source.force === true,\n compositionWarnings: [\n ...(clone(current.warnings) as ProjectionDiagnostic[]),\n ...readback.unmaterializedDiagnostics,\n ...rendering.unmaterializedDiagnostics,\n ],\n action,\n },\n };\n}\n\ninterface HarvestedRoutes {\n grouped: ProvenFragmentRoute[];\n binary: BinaryFragmentRoute[];\n navigation: ProvenRawShareNavigationRoute[];\n}\n\n/** Turn the recomposed observations of the named sources into the routes that make them clean. */\nfunction harvestRoutes(\n recomposed: CompleteComposition,\n sources: ReadonlySet<string>,\n rewritten: ReadonlySet<string>,\n): HarvestedRoutes {\n const mine = (source: SourceIdentity) => sources.has(sourceIdentityKey(source));\n return {\n grouped: recomposed.grouped.observations.flatMap((observation): ProvenFragmentRoute[] =>\n (mine(observation.source) || groupHeader(observation.source, observation.selector.file, rewritten)) &&\n observation.currentHash\n ? [\n {\n source: clone(observation.source),\n selector: clone(observation.selector),\n sourcePath: clone(observation.sourcePath),\n priorCleanHash: observation.currentHash,\n ...(observation.derivedSelectorHash\n ? { derivedSelectorHash: observation.derivedSelectorHash }\n : {}),\n contributor: observation.contributor,\n },\n ]\n : [],\n ),\n binary: [...recomposed.binary.rawObservations, ...recomposed.binary.attachmentObservations].flatMap(\n (observation): BinaryFragmentRoute[] =>\n mine(observation.source) && observation.currentHash\n ? [\n {\n source: clone(observation.source),\n selector: clone(observation.selector),\n sourcePath: clone(observation.sourcePath),\n ...(observation.bytes ? { bytes: observation.bytes } : {}),\n priorCleanHash: observation.currentHash,\n contributor: observation.contributor,\n ...(observation.entryHash ? { entryHash: observation.entryHash } : {}),\n ...(observation.byteHash ? { byteHash: observation.byteHash } : {}),\n },\n ]\n : [],\n ),\n navigation: recomposed.rawNavigation.flatMap((observation): ProvenRawShareNavigationRoute[] =>\n mine(observation.source) && observation.groupFile && observation.currentHash\n ? [\n {\n source: clone(observation.source),\n selector: clone(observation.selector),\n sourcePath: clone(observation.sourcePath),\n groupFile: observation.groupFile,\n priorCleanHash: observation.currentHash,\n },\n ]\n : [],\n ),\n };\n}\n\n/** A share group's owner header has no canonical resource; the file this plan wrote authorizes it. */\nfunction groupHeader(source: SourceIdentity, file: string, rewritten: ReadonlySet<string>): boolean {\n return source.type === 'group' && rewritten.has(file);\n}\n\nfunction observedCleanly(recomposed: CompleteComposition, source: StableSource): boolean {\n const key = sourceIdentityKey(source);\n const observations = [\n ...recomposed.grouped.observations,\n ...recomposed.binary.rawObservations,\n ...recomposed.binary.attachmentObservations,\n ].filter((observation) => sourceIdentityKey(observation.source) === key);\n return observations.every(\n (observation) => !!observation.currentHash && ['clean', 'new'].includes(observation.state),\n );\n}\n\nfunction sameDocument(left: Document, right: Document): boolean {\n return (\n canonicalText(withoutContainerSuppliedFields(left) as Json) ===\n canonicalText(withoutContainerSuppliedFields(right) as Json)\n );\n}\n\n/**\n * Rescan the written workspace and recompose it. A resource advances its baseline, routes and claims\n * only when its recomposed document is the authoritative one and every contributor observes cleanly;\n * anything else keeps the facts it had.\n */\nfunction adoptLayoutPlan(\n root: string,\n captured: { snapshot: LayoutWorkspaceSnapshot },\n prepared: PreparedLayoutPlan,\n removal: LayoutRemovalOutcome,\n deletes: PlannedLayoutDeletes,\n): {\n state: State;\n unverified: string[];\n diagnostics: readonly ProjectionDiagnostic[];\n notices: readonly LayoutReadbackNotice[];\n} {\n const original = parseState(captured.snapshot.stateText) as StateWithLayout;\n const base = removeLayoutState(original, deletes, removal.removed) as StateWithLayout;\n const previous = base.layout.evidence;\n const sourceOf = (key: string) => sourceForDocumentKey(key);\n const adoptedSources = new Set(\n prepared.adoptedKeys.flatMap((key) => {\n const source = sourceOf(key);\n return source ? [sourceIdentityKey(source)] : [];\n }),\n );\n const rewrittenFiles = new Set(prepared.rendering.json.map((item) => item.path));\n // Every resource the server renamed or moved was written at its new destination, so it is one\n // of the adopted keys and the rescan harvests its route from the path that now holds it.\n const refreshed = new Set(adoptedSources);\n const untouched = <T extends { source: SourceIdentity }>(items: readonly T[]) =>\n items.filter((item) => !refreshed.has(sourceIdentityKey(item.source)));\n const untouchedGrouped = (items: readonly ProvenFragmentRoute[]) =>\n items.filter(\n (item) =>\n !refreshed.has(sourceIdentityKey(item.source)) &&\n !groupHeader(item.source, item.selector.file, rewrittenFiles),\n );\n const derived: DerivedSourceProof[] = [...untouched(previous.derivedSourceProofs)];\n for (const proof of prepared.readback.derivedSourceProofs) derived.push(clone(proof));\n for (const key of prepared.adoptedKeys) {\n if (!key.startsWith('user_permissions/')) continue;\n const source = sourceOf(key);\n const document = prepared.authoritativeDocuments.get(key);\n const selectorHash = document && derivedSourceSelectorHash(document);\n if (!source || !selectorHash) continue;\n if (derived.some((proof) => sourceIdentityKey(proof.source) === sourceIdentityKey(source))) continue;\n derived.push({\n source: { type: 'resource', resource: { kind: 'user_permissions', id: source.resource.id } },\n selectorHash,\n });\n }\n let detachedDocumentProofs = { ...previous.detachedDocumentProofs };\n let detachedFileProofs = { ...previous.detachedFileProofs };\n for (const damage of prepared.readback.pendingDamage) {\n const proof = {\n reason: 'damage-proof' as const,\n sourceKey: sourceIdentityKey(damage.evidence.source),\n placementHash: damage.evidence.locationHash,\n baselineHash: damage.evidence.canonicalHash,\n };\n if (damage.codec === 'grouped')\n detachedDocumentProofs = { ...detachedDocumentProofs, [damage.destination.file]: proof };\n else detachedFileProofs = { ...detachedFileProofs, [damage.destination.sidecar]: proof };\n }\n const candidate: LayoutSubmissionEvidence = {\n groupedRoutes: untouchedGrouped(previous.groupedRoutes),\n binaryRoutes: untouched(previous.binaryRoutes),\n groupedSubmissionProofs: [],\n binarySubmissionProofs: [],\n derivedSourceProofs: derived,\n rawNavigationRoutes: untouched(previous.rawNavigationRoutes),\n canonicalBaseline: { ...base.baseline, ...prepared.appliedBaseline, ...prepared.baselineSet },\n detachedFileProofs,\n detachedDocumentProofs,\n };\n\n const scan = scanLayout({ root, tracked: base.layout.tracked });\n const recomposed = composeLayoutSubmission({\n scan,\n byteEvidence: loadLayoutByteEvidence({ root, scan, evidence: candidate }),\n evidence: candidate,\n });\n const keep = (\n state: State,\n unverified: string[],\n diagnostics: readonly ProjectionDiagnostic[] = [],\n notices: readonly LayoutReadbackNotice[] = [],\n ) => ({ state, unverified, diagnostics, notices });\n if (recomposed.status === 'blocked')\n return keep(\n { ...base, revisionId: prepared.authoritative!.revisionId },\n [...prepared.adoptedKeys],\n recomposed.diagnostics,\n );\n\n const bySource = groupBySource(recomposed.sources, (item) => sourceIdentityKey(item.mapping.source));\n const verified: string[] = [];\n const unverified: string[] = [];\n for (const key of prepared.adoptedKeys) {\n const source = sourceOf(key);\n const mappings = source ? (bySource.get(sourceIdentityKey(source)) ?? []) : [];\n const composed = mappings.length === 1 ? recomposed.documents[mappings[0].mapping.documentIndex] : undefined;\n const expected = prepared.authoritativeDocuments.get(key);\n if (source && composed && expected && sameDocument(composed, expected) && observedCleanly(recomposed, source))\n verified.push(key);\n else unverified.push(key);\n }\n const verifiedSources = new Set(\n verified.flatMap((key) => {\n const source = sourceOf(key);\n return source ? [sourceIdentityKey(source)] : [];\n }),\n );\n\n // An applied or assigned resource advances only while the written workspace carries its identity.\n const appliedNotices: LayoutReadbackNotice[] = [];\n const applied: Record<string, string> = {};\n const appliedPath = (key: string): string | undefined => {\n for (const patch of prepared.readback.identityPatches) if (patch.documentKey === key) return patch.container;\n for (const artifact of prepared.rendering.json)\n if (artifact.authorizingDocumentKeys.includes(key)) return artifact.path;\n return undefined;\n };\n for (const [key, hash] of Object.entries(prepared.appliedBaseline)) {\n const source = sourceOf(key);\n const mappings = source ? (bySource.get(sourceIdentityKey(source)) ?? []) : [];\n const path = appliedPath(key);\n // A file that exists but has no id is repairable by hand; one the plan never wrote is not.\n if (mappings.length === 1) applied[key] = hash;\n else appliedNotices.push({ status: path ? 'unpatched-create' : 'unmaterialized', path: path ?? key, key });\n }\n\n const restored = new Set([...refreshed].filter((key) => !verifiedSources.has(key)));\n const mineAgain = <T extends { source: SourceIdentity }>(items: readonly T[]) =>\n items.filter((item) => restored.has(sourceIdentityKey(item.source)));\n const harvested = harvestRoutes(recomposed, verifiedSources, rewrittenFiles);\n const evidence: PersistedLayoutEvidence = {\n groupedRoutes: [...candidate.groupedRoutes, ...harvested.grouped, ...mineAgain(previous.groupedRoutes)],\n binaryRoutes: [...candidate.binaryRoutes, ...harvested.binary, ...mineAgain(previous.binaryRoutes)],\n derivedSourceProofs: derived,\n rawNavigationRoutes: [\n ...candidate.rawNavigationRoutes,\n ...harvested.navigation,\n ...mineAgain(previous.rawNavigationRoutes),\n ],\n detachedFileProofs,\n detachedDocumentProofs,\n };\n // The claims before the removal, so a tracked path whose only claim is gone leaves the state.\n const tracking = trackedAfter({\n tracked: base.layout.tracked,\n before: original.layout.evidence,\n beforeScan: captured.snapshot.scan,\n after: evidence,\n afterScan: scan,\n });\n const baseline = { ...base.baseline, ...applied };\n for (const key of verified) baseline[key] = prepared.baselineSet[key];\n const layout = {\n ...base.layout,\n evidence,\n tracked: 'tracked' in tracking ? tracking.tracked : clone(base.layout.tracked),\n };\n if (prepared.dropQuarantinedReceipts) delete layout.unreadableReceipts;\n return keep(\n {\n ...base,\n revisionId: prepared.authoritative!.revisionId,\n baseline,\n layout,\n },\n unverified,\n [],\n appliedNotices,\n );\n}\n\n/**\n * Capture, decide, render, write, then rescan and save. Every destination is resolved again\n * immediately before it changes, no directory leaves except through `rmdir`, and the state file is\n * written last and only while it still equals the capture the plan was built on.\n */\nexport async function materializeLayoutPlan(input: MaterializeLayoutPlanInput): Promise<MaterializeLayoutPlanResult> {\n const seed = captureLayoutWorkspaceSeed(input.root);\n const first = prepareLayoutPlan(input, seed);\n if (first.status === 'blocked') return first;\n const captured = captureLayoutWorkspace(input.root, first.prepared.requiredPaths);\n const second = prepareLayoutPlan(input, captured);\n if (second.status === 'blocked') return second;\n const prepared = second.prepared;\n if (prepared.action !== first.prepared.action || !sameValue(prepared.requiredPaths, first.prepared.requiredPaths))\n return blocked([\n diagnostic('layout-path-requirements-changed', '.', 'Layout paths changed while preparing the plan'),\n ]);\n const pathDiagnostics = snapshotPathDiagnostics(prepared.state, captured.snapshot, {\n ...persistedEvidence(prepared.state),\n ...planSubmissionProofs(prepared.state, input.source),\n });\n if (pathDiagnostics.length > 0) return blocked(pathDiagnostics);\n\n /** A removal the writer kept keeps its canonical facts, so the delete set shrinks to what left. */\n const performedDeletes = (removals: LayoutRemovalOutcome): PlannedLayoutDeletes => {\n const retained = new Set(removals.retained);\n if (retained.size === 0) return prepared.readback.deletes;\n return {\n ...prepared.readback.deletes,\n keys: prepared.readback.deletes.keys.filter((key) => !retained.has(key)),\n sources: prepared.readback.deletes.sources.filter((source) => {\n const key = stableSourceKeyOf(source);\n return key === undefined || !retained.has(key);\n }),\n };\n };\n const outcome = (\n removals: LayoutRemovalOutcome,\n unverified: readonly string[],\n verificationDiagnostics: readonly ProjectionDiagnostic[] = [],\n extraNotices: readonly LayoutReadbackNotice[] = [],\n unwritten: ReadonlySet<string> = new Set(),\n ): LayoutPlanOutcome => ({\n status: 'complete',\n action: prepared.action,\n // A set the writer left unwritten is reported as `unmaterialized`, never as written.\n materializations: prepared.readback.materializations.filter(\n (item) => item.mode !== 'set' || !unwritten.has(item.documentKey),\n ),\n deletes: performedDeletes(removals),\n adoptedDocumentKeys: prepared.adoptedKeys.filter((key) => !unverified.includes(key)),\n unverifiedDocumentKeys: [...unverified],\n verificationDiagnostics,\n compositionWarnings: prepared.compositionWarnings,\n jsonWrites: prepared.jsonWrites,\n byteWrites: prepared.byteWrites,\n removals,\n notices: [...prepared.notices, ...extraNotices],\n });\n if (prepared.action === 'noop') {\n saveLearnedByteHashes(input.root, captured.snapshot.stateText);\n return outcome({ removed: [], rewritten: [], kept: [], retained: [] }, []);\n }\n\n const written = [\n ...prepared.jsonWrites.map((write) => write.path),\n ...prepared.byteWrites.map((write) => write.path),\n ];\n const bytes: StagedByteWrites = { staged: [], sidecars: new Map(), paired: new Set() };\n /** JSON destinations staged ahead of their turn, to break a cycle of resources moving into each other. */\n const held = new Map<string, StagedWorkspaceFile>();\n const cleanupWarnings: string[] = [];\n const vacated: { origin: string; destination: string }[] = [];\n let createdDirectories: string[] = [];\n /** Committed raw bytes whose sidecar has not yet been committed beside them. */\n let unpaired: { path: string; identity: string | undefined } | undefined;\n let order: WriteOrder | undefined;\n let result: LayoutPlanOutcome;\n // Ctrl-C during the staging below removes what this write staged and created; see `deferInterrupts`.\n const abandon = () => {\n bytes.inFlight?.();\n for (const item of [...bytes.staged.map((entry) => entry.file), ...bytes.sidecars.values(), ...held.values()])\n item.cleanup();\n removeEmptyDirectories(input.root, createdDirectories);\n };\n deferInterrupts();\n activeWrites.add(abandon);\n try {\n const current = captureLayoutWorkspace(input.root, prepared.requiredPaths);\n if (!sameValue(current.snapshot, captured.snapshot)) throw new Error('Layout changed before materialization');\n validateDestinations(current.snapshot, prepared);\n createdDirectories = createLayoutDestinationDirectories(input.root, written);\n await stageByteWrites(input, captured.snapshot, prepared, bytes);\n // From here to the saved state nothing awaits, so a Ctrl-C is handled only after it.\n activeWrites.delete(abandon);\n // Every source is staged, so a directory that only changes case can now take its new spelling.\n for (const rename of prepared.rendering.directoryRenames) renameDirectorySpelling(input.root, rename);\n /** Free the spelling one destination needs, immediately before that destination is written. */\n const vacate = (destination: string) => {\n for (const origin of vacateLayoutAliases(input.root, captured.snapshot, prepared.rendering.removals, [\n destination,\n ]))\n vacated.push({ origin, destination });\n };\n const byteWriteAt = new Map(prepared.byteWrites.map((write) => [write.path, write]));\n const jsonWriteAt = new Map(prepared.jsonWrites.map((write) => [write.path, write]));\n const units: WriteUnit[] = [\n ...bytes.staged.map((item): WriteUnit => {\n const sidecar = bytes.sidecars.get(item.path);\n const write = byteWriteAt.get(item.path)!;\n const sidecarWrite = sidecar && jsonWriteAt.get(rawSidecarPath(item.path));\n return {\n paths: sidecar ? [item.path, rawSidecarPath(item.path)] : [item.path],\n keys: new Set([write.authorizingDocumentKey, ...(sidecarWrite?.authorizingDocumentKeys ?? [])]),\n run: () => {\n vacate(item.path);\n item.file.commit(resolveLayoutPath(input.root, item.path));\n // The sidecar is already staged, so one unlink and one rename stand between the pair.\n if (!sidecar) return;\n unpaired = { path: item.path, identity: fileIdentity(input.root, item.path) };\n vacate(rawSidecarPath(item.path));\n sidecar.commit(sidecar.destination);\n unpaired = undefined;\n },\n };\n }),\n ...prepared.jsonWrites\n .filter((item) => !bytes.paired.has(item.path))\n .map(\n (item): WriteUnit => ({\n paths: [item.path],\n keys: new Set(item.authorizingDocumentKeys),\n hold: () => held.set(item.path, stageText(resolveLayoutPath(input.root, item.path), item.text)),\n run: () => {\n vacate(item.path);\n const staged = held.get(item.path);\n if (staged) staged.commit(resolveLayoutPath(input.root, item.path));\n else atomicReplaceText(resolveLayoutPath(input.root, item.path), item.text);\n },\n }),\n ),\n ];\n order = orderedWrites(\n units,\n currentHolders(prepared.current),\n destinationsMatchCapture(input.root, captured.snapshot),\n );\n order.run();\n const unrestored = order.revertUnfinished((unit) =>\n restoreCapturedPaths(input.root, captured.snapshot, unit.paths, bytes.staged),\n );\n if (unrestored.length > 0)\n throw new Error(\n `A changed destination stopped a rename cycle, and it could not put back ${unrestored.join(', ')}`,\n );\n const removals = materializeLayoutRemovals({\n root: input.root,\n snapshot: captured.snapshot,\n removals: prepared.rendering.removals,\n written,\n keep: [...order.skipped],\n });\n const changed = order.notices();\n const adopted = adoptLayoutPlan(input.root, captured, prepared, removals, performedDeletes(removals));\n if (stateText(input.root) !== captured.snapshot.stateText)\n throw new Error('Layout state changed before the final save');\n saveState(input.root, adopted.state);\n result = outcome(\n removals,\n adopted.unverified,\n adopted.diagnostics,\n [...adopted.notices, ...changed],\n order.skipped,\n );\n } catch (error) {\n activeWrites.delete(abandon);\n // A vacated origin shares its inode with the destination, so the throw left no copy of it on\n // disk, and an absent artifact reads as the author's own deletion. The writer therefore puts\n // back what it still holds \u2014 the captured text, or the temporary the commit never renamed \u2014\n // and the error names only the paths it could not restore. An origin a cycle overwrote while\n // its own resource was only held goes back to its captured text for the same reason.\n const lost = [\n ...restoreVacatedOrigins(input.root, captured.snapshot, vacated, [\n ...bytes.staged,\n ...[...bytes.sidecars].map(([path, file]) => ({\n path: rawSidecarPath(path),\n file,\n beside: true as const,\n })),\n ]),\n ...(order?.revertUnfinished((unit) =>\n restoreCapturedPaths(input.root, captured.snapshot, unit.paths, bytes.staged),\n ) ?? []),\n ];\n const stray = withdrawUnpairedBytes(input.root, captured.snapshot, vacated, unpaired);\n if (lost.length === 0 && stray.length === 0) throw error;\n const message = [\n error instanceof Error ? error.message : String(error),\n ...(lost.length > 0 ? [`freed for a rename before the write: ${[...new Set(lost)].join(', ')}`] : []),\n ...(stray.length > 0 ? [`written without its sidecar: ${stray.join(', ')}`] : []),\n ];\n throw new Error(message.join('; '), { cause: error });\n } finally {\n // The state is already saved, so a failed temporary cleanup is reported and never thrown.\n const clean = (remove: () => void, label: string) => {\n try {\n remove();\n } catch (error) {\n cleanupWarnings.push(`${label}: ${error instanceof Error ? error.message : String(error)}`);\n }\n };\n for (const item of bytes.staged) clean(() => item.file.cleanup(), `temporary file for ${item.path}`);\n for (const [path, sidecar] of bytes.sidecars)\n clean(() => sidecar.cleanup(), `temporary file for ${rawSidecarPath(path)}`);\n for (const [path, item] of held) clean(() => item.cleanup(), `temporary file for ${path}`);\n // A created directory nothing was written into (a failure, a kept destination) goes again.\n removeEmptyDirectories(input.root, createdDirectories);\n }\n return { ...result, cleanupWarnings };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,SAAoB;AACpB,WAAsB;AACtB,oBAA2B;AAC3B,wBAAkD;AAClD,uBAA0D;AAE1D,2BAKO;AACP,wBAWO;AACP,yBASO;AACP,8BAOO;AACP,4BAeO;AACP,wBAcO;AACP,4BAA4C;AAE5C,uBAQO;AA4BP,SAAS,KAAK,MAAe,OAAyB;AAClD,MAAI;AACA,eAAO,iCAAe,MAAc,KAAa;AAAA,EACrD,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAEA,SAAS,kBAAkB,OAAwC;AAC/D,QAAM,WAAW,MAAM,OAAQ;AAC/B,SAAO;AAAA,IACH,mBAAe,yBAAM,SAAS,aAAa;AAAA,IAC3C,kBAAc,yBAAM,SAAS,YAAY;AAAA,IACzC,yBAAyB,CAAC;AAAA,IAC1B,wBAAwB,CAAC;AAAA,IACzB,yBAAqB,yBAAM,SAAS,mBAAmB;AAAA,IACvD,yBAAqB,yBAAM,SAAS,mBAAmB;AAAA,IACvD,uBAAmB,yBAAM,MAAM,QAAQ;AAAA,IACvC,wBAAoB,yBAAM,SAAS,kBAAkB;AAAA,IACrD,4BAAwB,yBAAM,SAAS,sBAAsB;AAAA,EACjE;AACJ;AAEA,SAAS,qBAAqB,MAAwB;AAClD,SAAO,KAAK,UAAU;AAAA,IAClB,CAAC,aAAa,SAAS,WAAW,CAAC,CAAC,OAAO,YAAY,EAAE,SAAS,SAAS,IAAI,KAAK,SAAS,SAAS;AAAA,EAC1G;AACJ;AAEA,SAAS,kBAAkB,MAAwB,UAAiD;AAChG,QAAM,WAAW,IAAI;AAAA,IACjB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