@orkestrel/scaffold 0.0.23 → 0.0.24

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 (39) hide show
  1. package/README.md +84 -99
  2. package/dist/bin/main.js +1094 -0
  3. package/dist/bin/main.js.map +1 -0
  4. package/dist/host/CLAUDE.md +3 -1
  5. package/dist/host/agents/orchestration.md +61 -4
  6. package/dist/host/agents/skills/orkestrel-align-packages/SKILL.md +1 -1
  7. package/dist/host/agents/skills/orkestrel-falsify/SKILL.md +7 -5
  8. package/dist/host/agents/skills/orkestrel-harden-package/SKILL.md +1 -1
  9. package/dist/host/agents/skills/orkestrel-harden-package/references/contract.md +1 -1
  10. package/dist/host/claude/agents/orkestrel.md +4 -4
  11. package/dist/host/claude/rules/architecture.md +45 -3
  12. package/dist/host/claude/rules/quality.md +4 -0
  13. package/dist/host/claude/rules/tests.md +57 -1
  14. package/dist/host/claude/rules/workspace.md +50 -17
  15. package/dist/host/codex/agents/orkestrel.toml +1 -1
  16. package/dist/host/configs/helpers.ts +762 -0
  17. package/dist/host/dotfiles/oxlintrc.json +2 -1
  18. package/dist/host/guides/scaffold.md +862 -0
  19. package/dist/host/manifest.json +40 -33
  20. package/dist/host/tests/config.test.ts +544 -0
  21. package/dist/host/tests/policy.test.ts +46 -0
  22. package/dist/host/tests/setupPolicy.ts +529 -701
  23. package/dist/src/core/index.cjs +3568 -10576
  24. package/dist/src/core/index.cjs.map +1 -1
  25. package/dist/src/core/index.d.cts +2361 -2800
  26. package/dist/src/core/index.d.ts +2361 -2800
  27. package/dist/src/core/index.js +3512 -10440
  28. package/dist/src/core/index.js.map +1 -1
  29. package/dist/src/server/index.cjs +2855 -3765
  30. package/dist/src/server/index.cjs.map +1 -1
  31. package/dist/src/server/index.d.cts +1915 -1330
  32. package/dist/src/server/index.d.ts +1915 -1330
  33. package/dist/src/server/index.js +2812 -3680
  34. package/dist/src/server/index.js.map +1 -1
  35. package/package.json +16 -23
  36. package/dist/bin/scaffold.js +0 -1896
  37. package/dist/bin/scaffold.js.map +0 -1
  38. package/dist/host/guides/src/scaffold.md +0 -2922
  39. /package/dist/host/guides/{src/guide.md → guide.md} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#token","#target","#root","#stage","#backup","#expectations","#parents","#directories","#anchor","#existing","#emitter","#host","#ensureAlive","#prepare","#apply","#destroyed","#copy","#write","#manifest","#manifestLoaded","#manifestValue","#emitter","#guidesBase","#branch","#guidesTimeout","#registryBase","#registryTimeout","#concurrency","#retries","#strict","#limit","#items","#budget","#controller","#ensureAlive","#lookup","#guides","#versions","#runPool","#guideUrl","#fetchText","#toGuideSync","#toVersionSync","#registryUrl","#toVersionLookup","#packages","#toPackument","#toGuideDescription","#combineNote","#destroyed","#orgUrl","#toOrgPackages","#drain","#cancel","#readBounded","#transportNote","#causeCode","#parseLatest"],"sources":["../../../src/server/constants.ts","../../../src/server/shapers.ts","../../../src/server/contracts.ts","../../../src/server/validators.ts","../../../src/server/parsers.ts","../../../src/server/WriteTransaction.ts","../../../src/server/helpers.ts","../../../src/server/Materializer.ts","../../../src/server/Sync.ts","../../../src/server/factories.ts"],"sourcesContent":["import { MAX_ARTIFACT_BYTES } from '@src/core'\n\n/**\n * The prune-owned directories. Files outside these roots are never candidates\n * for removal, including project-owned skills under `.agents/skills` and\n * `.claude/skills`.\n *\n * @example\n * ```ts\n * import { PRUNE_DIRECTORIES } from '@orkestrel/scaffold/server'\n *\n * PRUNE_DIRECTORIES // ['.claude/agents', '.codex/agents', 'scripts']\n * ```\n */\nexport const PRUNE_DIRECTORIES: readonly string[] = Object.freeze([\n\t'.claude/agents',\n\t'.codex/agents',\n\t'scripts',\n])\n\n/** Reserved metadata file written at the root of every staged host. */\nexport const HOST_MANIFEST_PATH = 'manifest.json'\n\n/** Local configuration and credential-like paths that must never enter a vendored host. */\nexport const SENSITIVE_HOST_PATH_PATTERN =\n\t/(?:^|\\/)(?:(?:\\.git|\\.ssh|\\.aws|\\.azure|\\.docker|\\.kube|\\.gnupg|\\.env(?:\\.[^/]*)?)(?:\\/|$)|(?:\\.npmrc|\\.pypirc|\\.netrc|\\.git-credentials|settings\\.local\\.json|auth\\.json|credentials(?:\\.json)?|application_default_credentials\\.json|id_rsa|id_ed25519|kubeconfig)(?:\\/|$)|\\.config\\/(?:gh|gcloud)(?:\\/|$)|\\.local\\/share\\/keyrings(?:\\/|$)|[^/]*service-account[^/]*\\.json$|[^/]*\\.(?:jks|key|p12|pem|pfx|pkcs12)$)/i\n\n/** Existing repository metadata that a materialization target must never own. */\nexport const RESERVED_TARGET_PATH_PATTERN = /(?:^|\\/)\\.git(?:\\/|$)/i\n\n/** Maximum normalized package-catalog description length. */\nexport const MAX_CATALOG_DESCRIPTION_LENGTH = 500\n\n/** Maximum UTF-8 bytes parsed from one local package guide. */\nexport const MAX_GUIDE_BYTES = MAX_ARTIFACT_BYTES\n\n/** Maximum filesystem entries accepted by one vendored-host traversal. */\nexport const MAX_HOST_ENTRIES = 4_096\n\n/** Maximum directory nesting accepted by one vendored-host traversal. */\nexport const MAX_HOST_DEPTH = 32\n\n/** Maximum caller-controlled filesystem path depth accepted before filesystem work. */\nexport const MAX_FILESYSTEM_DEPTH = 64\n\n/** Maximum UTF-8 bytes accepted in one portable filesystem path segment. */\nexport const MAX_PATH_SEGMENT_BYTES = 255\n\n/** Windows device names that remain reserved even when followed by an extension. */\nexport const RESERVED_PATH_SEGMENT_PATTERN =\n\t/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9]|conin\\$|conout\\$)(?:\\..*)?$/i\n\n/** Maximum simultaneous upstream requests accepted by `Sync`. */\nexport const MAX_SYNC_CONCURRENCY = 64\n\n/** Default simultaneous upstream requests used by `Sync`. */\nexport const DEFAULT_SYNC_CONCURRENCY = 6\n\n/** Maximum retry count accepted by `Sync`. */\nexport const MAX_SYNC_RETRIES = 5\n\n/** Maximum per-request timeout accepted by `Sync`, in milliseconds. */\nexport const MAX_SYNC_TIMEOUT = 300_000\n\n/** Default per-request timeout used by `Sync`, in milliseconds. */\nexport const DEFAULT_SYNC_TIMEOUT = 10_000\n\n/** Maximum response body accepted by `Sync`, in bytes. */\nexport const MAX_SYNC_LIMIT = MAX_ARTIFACT_BYTES\n\n/** Default per-response byte limit used by `Sync`. */\nexport const DEFAULT_SYNC_LIMIT = MAX_ARTIFACT_BYTES\n\n/** Default maximum dependencies or catalog entries retained by one Sync operation. */\nexport const DEFAULT_SYNC_ITEMS = 256\n\n/** Maximum configurable dependencies or catalog entries for one Sync operation. */\nexport const MAX_SYNC_ITEMS = 1_000\n\n/** Default cumulative response bytes retained by one Sync operation. */\nexport const DEFAULT_SYNC_BUDGET = 16_777_216\n\n/** Maximum configurable cumulative response bytes retained by one Sync operation. */\nexport const MAX_SYNC_BUDGET = 104_857_600\n\n/** Maximum caller-supplied endpoint characters inspected before URL allocation. */\nexport const MAX_SYNC_BASE_LENGTH = 2_048\n\n/** Maximum portable Git branch characters accepted by the guide endpoint. */\nexport const MAX_SYNC_BRANCH_LENGTH = 255\n\n/** Exact SHA-256 digest accepted by write preconditions. */\nexport const WRITE_DIGEST_PATTERN = /^[0-9a-f]{64}$/\n\n/** Safe ASCII branch alphabet accepted before Git ref-component validation. */\nexport const SYNC_BRANCH_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/\n","import {\n\tbooleanShape,\n\tintegerShape,\n\tobjectShape,\n\toptionalShape,\n\tstringShape,\n} from '@orkestrel/contract'\nimport { MAX_PATH_LENGTH } from '@src/core'\nimport {\n\tMAX_SYNC_BASE_LENGTH,\n\tMAX_SYNC_BRANCH_LENGTH,\n\tMAX_SYNC_CONCURRENCY,\n\tMAX_SYNC_BUDGET,\n\tMAX_SYNC_ITEMS,\n\tMAX_SYNC_LIMIT,\n\tMAX_SYNC_RETRIES,\n\tMAX_SYNC_TIMEOUT,\n} from './constants.js'\n\n/** Build the closed upstream-guide endpoint options shape. */\nexport function syncGuideOptionsShape() {\n\treturn objectShape({\n\t\tbase: optionalShape(stringShape({ min: 1, max: MAX_SYNC_BASE_LENGTH })),\n\t\tbranch: optionalShape(stringShape({ min: 1, max: MAX_SYNC_BRANCH_LENGTH })),\n\t\ttimeout: optionalShape(integerShape({ min: 1, max: MAX_SYNC_TIMEOUT })),\n\t})\n}\n\n/** Build the closed registry endpoint options shape. */\nexport function syncRegistryOptionsShape() {\n\treturn objectShape({\n\t\tbase: optionalShape(stringShape({ min: 1, max: MAX_SYNC_BASE_LENGTH })),\n\t\ttimeout: optionalShape(integerShape({ min: 1, max: MAX_SYNC_TIMEOUT })),\n\t})\n}\n\n/** Build the closed data-only `SyncOptions` shape. */\nexport function syncOptionsShape() {\n\treturn objectShape({\n\t\tguides: optionalShape(syncGuideOptionsShape()),\n\t\tregistry: optionalShape(syncRegistryOptionsShape()),\n\t\tconcurrency: optionalShape(integerShape({ min: 1, max: MAX_SYNC_CONCURRENCY })),\n\t\tretries: optionalShape(integerShape({ min: 0, max: MAX_SYNC_RETRIES })),\n\t\tstrict: optionalShape(booleanShape()),\n\t\tlimit: optionalShape(integerShape({ min: 1, max: MAX_SYNC_LIMIT })),\n\t\titems: optionalShape(integerShape({ min: 1, max: MAX_SYNC_ITEMS })),\n\t\tbudget: optionalShape(integerShape({ min: 1, max: MAX_SYNC_BUDGET })),\n\t})\n}\n\n/** Build the closed data-only `MaterializerOptions` shape. */\nexport function materializerOptionsShape() {\n\treturn objectShape({\n\t\thost: optionalShape(stringShape({ min: 1, max: MAX_PATH_LENGTH })),\n\t})\n}\n","import { createContract } from '@orkestrel/contract'\nimport { materializerOptionsShape, syncOptionsShape } from './shapers.js'\n\n/** The compiled, closed data-only `SyncOptions` contract. */\nexport const syncOptionsContract = createContract(syncOptionsShape())\n\n/** The compiled, closed data-only `MaterializerOptions` contract. */\nexport const materializerOptionsContract = createContract(materializerOptionsShape())\n","import type { EmitterHooks } from '@orkestrel/emitter'\nimport type { Dependency } from '@src/core'\nimport type {\n\tCatalogAllowance,\n\tHostManifest,\n\tManifestEntry,\n\tMaterializerEventMap,\n\tSyncEventMap,\n\tWritePrecondition,\n} from './types.js'\nimport { attempt, isError, isFunction, isRecord, isString } from '@orkestrel/contract'\nimport {\n\tCONTROL_CHARACTER_PATTERN,\n\tcontentByteLength,\n\thasOnlyDataProperties,\n\tINVALID_PATH_CHARACTER_PATTERN,\n\tisDenseDataArray,\n\tisDependency,\n\tMAX_PATH_LENGTH,\n} from '@src/core'\nimport {\n\tMAX_CATALOG_DESCRIPTION_LENGTH,\n\tMAX_FILESYSTEM_DEPTH,\n\tMAX_HOST_ENTRIES,\n\tMAX_PATH_SEGMENT_BYTES,\n\tRESERVED_PATH_SEGMENT_PATTERN,\n\tRESERVED_TARGET_PATH_PATTERN,\n\tSENSITIVE_HOST_PATH_PATTERN,\n\tWRITE_DIGEST_PATTERN,\n} from './constants.js'\n\n/** Narrow one exact aggregate fleet traversal allowance. */\nexport function isCatalogAllowance(value: unknown): value is CatalogAllowance {\n\tconst result = attempt(() => {\n\t\tconst bufferGetter = Object.getOwnPropertyDescriptor(\n\t\t\tObject.getPrototypeOf(Float64Array.prototype),\n\t\t\t'buffer',\n\t\t)?.get\n\t\tif (\n\t\t\tbufferGetter === undefined ||\n\t\t\t!ArrayBuffer.isView(value) ||\n\t\t\t!(value instanceof Float64Array) ||\n\t\t\t!(Reflect.apply(bufferGetter, value, []) instanceof ArrayBuffer) ||\n\t\t\tvalue.length !== 1\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tconst remaining = value[0]\n\t\treturn (\n\t\t\tremaining !== undefined &&\n\t\t\tNumber.isSafeInteger(remaining) &&\n\t\t\tremaining >= 0 &&\n\t\t\tremaining <= MAX_HOST_ENTRIES\n\t\t)\n\t})\n\treturn result.success && result.value\n}\n\n/**\n * Determine whether a value is a non-empty portable relative POSIX path.\n *\n * @param value - The candidate path.\n * @returns `true` when every path segment is safe and portable.\n */\nexport function isPortablePath(value: unknown): value is string {\n\tif (!isString(value) || value.length === 0 || value.length > MAX_PATH_LENGTH) return false\n\tif (INVALID_PATH_CHARACTER_PATTERN.test(value) || CONTROL_CHARACTER_PATTERN.test(value)) {\n\t\treturn false\n\t}\n\tconst segments = value.split('/')\n\treturn (\n\t\tsegments.length <= MAX_FILESYSTEM_DEPTH &&\n\t\t!segments.some(\n\t\t\t(segment) =>\n\t\t\t\tsegment === '' ||\n\t\t\t\tsegment === '.' ||\n\t\t\t\tsegment === '..' ||\n\t\t\t\tsegment.endsWith('.') ||\n\t\t\t\tsegment.endsWith(' ') ||\n\t\t\t\tcontentByteLength(segment) > MAX_PATH_SEGMENT_BYTES ||\n\t\t\t\tRESERVED_PATH_SEGMENT_PATTERN.test(segment),\n\t\t)\n\t)\n}\n\n/** Whether one host filesystem path is bounded, non-empty, and safe to render in a terminal. */\nexport function isFilesystemPath(value: unknown): value is string {\n\tif (\n\t\t!isString(value) ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > MAX_PATH_LENGTH ||\n\t\tCONTROL_CHARACTER_PATTERN.test(value)\n\t) {\n\t\treturn false\n\t}\n\tconst normalized = value.replaceAll('\\\\', '/')\n\tconst withoutRoot = normalized.startsWith('//')\n\t\t? normalized.slice(2)\n\t\t: normalized.startsWith('/')\n\t\t\t? normalized.slice(1)\n\t\t\t: normalized\n\tif (withoutRoot.includes('//')) return false\n\tconst segments = withoutRoot.split('/').filter((segment) => segment.length > 0)\n\tif (segments.length > MAX_FILESYSTEM_DEPTH) return false\n\treturn !segments.some((segment, index) => {\n\t\tif (segment === '.' || segment === '..') return false\n\t\tif (index === 0 && /^[A-Za-z]:$/u.test(segment)) return false\n\t\treturn (\n\t\t\t/[<>:\"|?*]/u.test(segment) ||\n\t\t\tsegment.endsWith('.') ||\n\t\t\tsegment.endsWith(' ') ||\n\t\t\tcontentByteLength(segment) > MAX_PATH_SEGMENT_BYTES ||\n\t\t\tRESERVED_PATH_SEGMENT_PATTERN.test(segment)\n\t\t)\n\t})\n}\n\n/** Whether one externally supplied string is safe to render in terminal or JSON diagnostics. */\nexport function isTerminalText(value: unknown): value is string {\n\treturn isString(value) && !CONTROL_CHARACTER_PATTERN.test(value)\n}\n\n/** Whether one dependency is an exact data-property record safe to snapshot. */\nexport function isDependencyData(value: unknown): value is Dependency {\n\treturn hasOnlyDataProperties(value) && isDependency(value)\n}\n\n/**\n * Determine whether a host-relative path resembles local configuration or credentials.\n *\n * @param value - The portable candidate path.\n * @returns `true` when the path must be excluded from vendored host output.\n */\nexport function isSensitiveHostPath(value: string): boolean {\n\treturn SENSITIVE_HOST_PATH_PATTERN.test(value.replaceAll('\\\\', '/'))\n}\n\n/** Determine whether a target-relative path addresses preserved repository metadata. */\nexport function isReservedTargetPath(value: string): boolean {\n\treturn RESERVED_TARGET_PATH_PATTERN.test(value.replaceAll('\\\\', '/'))\n}\n\n/** Whether a normalized catalog description is bounded and contains no controls. */\nexport function isCatalogDescription(value: unknown): value is string {\n\treturn (\n\t\tisString(value) &&\n\t\tvalue.length <= MAX_CATALOG_DESCRIPTION_LENGTH &&\n\t\t!CONTROL_CHARACTER_PATTERN.test(value)\n\t)\n}\n\n/**\n * Determine whether a caught filesystem error reports an absent path.\n *\n * @param value - The caught value.\n * @returns `true` only for an `Error` whose `code` is exactly `ENOENT`.\n */\nexport function isMissingPathError(value: unknown): boolean {\n\tconst result = attempt(() => isError(value) && Reflect.get(value, 'code') === 'ENOENT')\n\treturn result.success && result.value\n}\n\n/** Narrow one exact transaction destination precondition. */\nexport function isWritePrecondition(value: unknown): value is WritePrecondition {\n\tconst result = attempt(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst keys = Reflect.ownKeys(value)\n\t\tif (\n\t\t\tkeys.some((key) => key !== 'path' && key !== 'shape' && key !== 'digest') ||\n\t\t\tkeys.length < 2 ||\n\t\t\tkeys.length > 3\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tconst path = Reflect.getOwnPropertyDescriptor(value, 'path')\n\t\tconst shape = Reflect.getOwnPropertyDescriptor(value, 'shape')\n\t\tconst digest = Reflect.getOwnPropertyDescriptor(value, 'digest')\n\t\tif (\n\t\t\tpath === undefined ||\n\t\t\t!Reflect.has(path, 'value') ||\n\t\t\tshape === undefined ||\n\t\t\t!Reflect.has(shape, 'value') ||\n\t\t\t(digest !== undefined && !Reflect.has(digest, 'value')) ||\n\t\t\t!isPortablePath(path.value)\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\treturn shape.value === 'absent'\n\t\t\t? digest === undefined\n\t\t\t: shape.value === 'file' &&\n\t\t\t\t\tdigest !== undefined &&\n\t\t\t\t\ttypeof digest.value === 'string' &&\n\t\t\t\t\tWRITE_DIGEST_PATTERN.test(digest.value)\n\t})\n\treturn result.success && result.value\n}\n\n/**\n * Narrow a value to one exact vendored-host manifest entry.\n *\n * @param value - The candidate raw manifest entry.\n * @returns `true` only for the exact safe entry shape.\n */\nexport function isManifestEntry(value: unknown): value is ManifestEntry {\n\tconst result = attempt(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst keys = Reflect.ownKeys(value)\n\t\tconst storage = Reflect.getOwnPropertyDescriptor(value, 'storage')\n\t\tconst destination = Reflect.getOwnPropertyDescriptor(value, 'destination')\n\t\tconst executable = Reflect.getOwnPropertyDescriptor(value, 'executable')\n\t\treturn (\n\t\t\tkeys.length === 3 &&\n\t\t\tkeys.every((key) => key === 'storage' || key === 'destination' || key === 'executable') &&\n\t\t\tstorage !== undefined &&\n\t\t\tReflect.has(storage, 'value') &&\n\t\t\tdestination !== undefined &&\n\t\t\tReflect.has(destination, 'value') &&\n\t\t\texecutable !== undefined &&\n\t\t\tReflect.has(executable, 'value') &&\n\t\t\tisPortablePath(storage.value) &&\n\t\t\tisPortablePath(destination.value) &&\n\t\t\ttypeof executable.value === 'boolean'\n\t\t)\n\t})\n\treturn result.success && result.value\n}\n\n/**\n * Narrow a value to one exact complete vendored-host manifest.\n *\n * @param value - The candidate manifest value.\n * @returns `true` only for an exact `{ entries, roots, digest }` record with safe paths.\n */\nexport function isHostManifest(value: unknown): value is HostManifest {\n\tconst result = attempt(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst keys = Reflect.ownKeys(value)\n\t\tconst entries = Reflect.getOwnPropertyDescriptor(value, 'entries')\n\t\tconst roots = Reflect.getOwnPropertyDescriptor(value, 'roots')\n\t\tconst digest = Reflect.getOwnPropertyDescriptor(value, 'digest')\n\t\treturn (\n\t\t\tkeys.length === 3 &&\n\t\t\tkeys.every((key) => key === 'entries' || key === 'roots' || key === 'digest') &&\n\t\t\tentries !== undefined &&\n\t\t\tReflect.has(entries, 'value') &&\n\t\t\troots !== undefined &&\n\t\t\tReflect.has(roots, 'value') &&\n\t\t\tdigest !== undefined &&\n\t\t\tReflect.has(digest, 'value') &&\n\t\t\tisDenseDataArray(entries.value, MAX_HOST_ENTRIES, isManifestEntry) &&\n\t\t\tisDenseDataArray(roots.value, MAX_HOST_ENTRIES, isPortablePath) &&\n\t\t\ttypeof digest.value === 'string' &&\n\t\t\tWRITE_DIGEST_PATTERN.test(digest.value)\n\t\t)\n\t})\n\treturn result.success && result.value\n}\n\n/** Narrow an exact initial-listener record for `Sync`. */\nexport function isSyncEventHooks(value: unknown): value is EmitterHooks<SyncEventMap> {\n\tconst result = attempt(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst keys = Reflect.ownKeys(value)\n\t\tif (\n\t\t\tkeys.some(\n\t\t\t\t(key) =>\n\t\t\t\t\tkey !== 'guide' &&\n\t\t\t\t\tkey !== 'version' &&\n\t\t\t\t\tkey !== 'package' &&\n\t\t\t\t\tkey !== 'write' &&\n\t\t\t\t\tkey !== 'done' &&\n\t\t\t\t\tkey !== 'error' &&\n\t\t\t\t\tkey !== 'destroy',\n\t\t\t)\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\treturn keys.every((key) => {\n\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(value, key)\n\t\t\treturn (\n\t\t\t\tdescriptor !== undefined && Reflect.has(descriptor, 'value') && isFunction(descriptor.value)\n\t\t\t)\n\t\t})\n\t})\n\treturn result.success && result.value\n}\n\n/** Narrow an exact initial-listener record for `Materializer`. */\nexport function isMaterializerEventHooks(\n\tvalue: unknown,\n): value is EmitterHooks<MaterializerEventMap> {\n\tconst result = attempt(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst keys = Reflect.ownKeys(value)\n\t\tif (\n\t\t\tkeys.some(\n\t\t\t\t(key) =>\n\t\t\t\t\tkey !== 'copy' &&\n\t\t\t\t\tkey !== 'write' &&\n\t\t\t\t\tkey !== 'remove' &&\n\t\t\t\t\tkey !== 'done' &&\n\t\t\t\t\tkey !== 'error' &&\n\t\t\t\t\tkey !== 'destroy',\n\t\t\t)\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\treturn keys.every((key) => {\n\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(value, key)\n\t\t\treturn (\n\t\t\t\tdescriptor !== undefined && Reflect.has(descriptor, 'value') && isFunction(descriptor.value)\n\t\t\t)\n\t\t})\n\t})\n\treturn result.success && result.value\n}\n","import type { Dependency } from '@src/core'\nimport type {\n\tMaterializerEventMap,\n\tMaterializerOptions,\n\tSyncBase,\n\tSyncBranch,\n\tSyncEventMap,\n\tSyncOptions,\n\tWritePrecondition,\n} from './types.js'\nimport type { EmitterHooks } from '@orkestrel/emitter'\nimport { attempt, isFunction, isRecord } from '@orkestrel/contract'\nimport {\n\tcontentByteLength,\n\tEXTRA_NAME_PATTERN,\n\tisDenseDataArray,\n\tisEmitterErrorHandler,\n\tMAX_ARTIFACT_BYTES,\n\tMAX_DEPENDENCY_NAME_LENGTH,\n\tScaffoldError,\n\tvalidateDependencyArray,\n} from '@src/core'\nimport {\n\tMAX_SYNC_BASE_LENGTH,\n\tMAX_SYNC_BRANCH_LENGTH,\n\tMAX_SYNC_ITEMS,\n\tSYNC_BRANCH_PATTERN,\n} from './constants.js'\nimport { materializerOptionsContract, syncOptionsContract } from './contracts.js'\nimport {\n\tisDependencyData,\n\tisFilesystemPath,\n\tisMaterializerEventHooks,\n\tisPortablePath,\n\tisSyncEventHooks,\n\tisWritePrecondition,\n} from './validators.js'\n\n/**\n * Parse and semantically validate bare registry package names before Sync performs network I/O.\n *\n * @param value - Untrusted package-name collection.\n * @returns A frozen owned snapshot of valid unique npm package names.\n */\nexport function parseSyncNames(value: unknown): readonly string[] {\n\tconst owned = attempt(() => {\n\t\tif (\n\t\t\t!isDenseDataArray(\n\t\t\t\tvalue,\n\t\t\t\tMAX_SYNC_ITEMS,\n\t\t\t\t(candidate): candidate is string => typeof candidate === 'string',\n\t\t\t)\n\t\t) {\n\t\t\tthrow new Error('package names are malformed')\n\t\t}\n\t\tconst length = Reflect.getOwnPropertyDescriptor(value, 'length')?.value\n\t\tif (\n\t\t\ttypeof length !== 'number' ||\n\t\t\t!Number.isSafeInteger(length) ||\n\t\t\tlength < 0 ||\n\t\t\tlength > MAX_SYNC_ITEMS\n\t\t) {\n\t\t\tthrow new Error('package name length is malformed')\n\t\t}\n\t\tconst names: string[] = []\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(value, String(index))\n\t\t\tif (\n\t\t\t\tdescriptor === undefined ||\n\t\t\t\t!Reflect.has(descriptor, 'value') ||\n\t\t\t\ttypeof descriptor.value !== 'string'\n\t\t\t) {\n\t\t\t\tthrow new Error('package name is malformed')\n\t\t\t}\n\t\t\tnames.push(descriptor.value)\n\t\t}\n\t\treturn Object.freeze(names)\n\t})\n\tif (!owned.success) {\n\t\tthrow new ScaffoldError('INVALID', 'Sync package names are malformed', {\n\t\t\terror: owned.error,\n\t\t})\n\t}\n\tconst snapshot = owned.value\n\tconst seen = new Set<string>()\n\tfor (const name of snapshot) {\n\t\tif (\n\t\t\tname.length === 0 ||\n\t\t\tname.length > MAX_DEPENDENCY_NAME_LENGTH ||\n\t\t\t!EXTRA_NAME_PATTERN.test(name) ||\n\t\t\tseen.has(name)\n\t\t) {\n\t\t\tthrow new ScaffoldError('INVALID', 'Sync package names are invalid', { name })\n\t\t}\n\t\tseen.add(name)\n\t}\n\treturn snapshot\n}\n\n/** Parse and semantically validate dependency data before Sync performs network I/O. */\nexport function parseSyncDependencies(value: unknown, external: boolean): readonly Dependency[] {\n\tconst owned = attempt(() => {\n\t\tif (!isDenseDataArray(value, MAX_SYNC_ITEMS, isDependencyData)) {\n\t\t\tthrow new Error('dependencies are malformed')\n\t\t}\n\t\tconst length = Reflect.getOwnPropertyDescriptor(value, 'length')?.value\n\t\tif (\n\t\t\ttypeof length !== 'number' ||\n\t\t\t!Number.isSafeInteger(length) ||\n\t\t\tlength < 0 ||\n\t\t\tlength > MAX_SYNC_ITEMS\n\t\t) {\n\t\t\tthrow new Error('dependency length is malformed')\n\t\t}\n\t\tconst dependencies: Dependency[] = []\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(value, String(index))\n\t\t\tif (\n\t\t\t\tdescriptor === undefined ||\n\t\t\t\t!Reflect.has(descriptor, 'value') ||\n\t\t\t\t!isDependencyData(descriptor.value)\n\t\t\t) {\n\t\t\t\tthrow new Error('dependency is malformed')\n\t\t\t}\n\t\t\tconst name = Reflect.getOwnPropertyDescriptor(descriptor.value, 'name')?.value\n\t\t\tconst range = Reflect.getOwnPropertyDescriptor(descriptor.value, 'range')?.value\n\t\t\tconst optional = Reflect.getOwnPropertyDescriptor(descriptor.value, 'optional')?.value\n\t\t\tif (\n\t\t\t\ttypeof name !== 'string' ||\n\t\t\t\ttypeof range !== 'string' ||\n\t\t\t\t(optional !== undefined && typeof optional !== 'boolean')\n\t\t\t) {\n\t\t\t\tthrow new Error('dependency is malformed')\n\t\t\t}\n\t\t\tdependencies.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tname,\n\t\t\t\t\trange,\n\t\t\t\t\t...(optional === undefined ? {} : { optional }),\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\treturn Object.freeze(dependencies)\n\t})\n\tif (!owned.success) {\n\t\tthrow new ScaffoldError('INVALID', 'Sync dependencies are malformed', {\n\t\t\terror: owned.error,\n\t\t})\n\t}\n\tconst snapshot = owned.value\n\tconst validation = validateDependencyArray(external ? 'extras' : 'dependencies', snapshot)\n\tif (validation.questions.length > 0) {\n\t\tthrow new ScaffoldError('INVALID', 'Sync dependencies are invalid', {\n\t\t\tquestions: validation.questions,\n\t\t})\n\t}\n\treturn snapshot\n}\n\n/** Parse a bounded dense array of host filesystem paths without invoking caller methods. */\nexport function parseFilesystemPaths(value: unknown, limit: number): readonly string[] | undefined {\n\tconst parsed = attempt(() => {\n\t\tif (\n\t\t\t!Number.isSafeInteger(limit) ||\n\t\t\tlimit < 0 ||\n\t\t\t!isDenseDataArray(value, limit, isFilesystemPath)\n\t\t) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst length = Reflect.getOwnPropertyDescriptor(value, 'length')?.value\n\t\tif (\n\t\t\ttypeof length !== 'number' ||\n\t\t\t!Number.isSafeInteger(length) ||\n\t\t\tlength < 0 ||\n\t\t\tlength > limit\n\t\t) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst paths: string[] = []\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(value, String(index))\n\t\t\tif (\n\t\t\t\tdescriptor === undefined ||\n\t\t\t\t!Reflect.has(descriptor, 'value') ||\n\t\t\t\t!isFilesystemPath(descriptor.value)\n\t\t\t) {\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t\tpaths.push(descriptor.value)\n\t\t}\n\t\treturn Object.freeze(paths)\n\t})\n\treturn parsed.success ? parsed.value : undefined\n}\n\n/** Parse a bounded dense array of portable paths without invoking caller methods. */\nexport function parsePortablePaths(value: unknown, limit: number): readonly string[] | undefined {\n\tconst parsed = attempt(() => {\n\t\tif (\n\t\t\t!Number.isSafeInteger(limit) ||\n\t\t\tlimit < 0 ||\n\t\t\t!isDenseDataArray(value, limit, isPortablePath)\n\t\t) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst length = Reflect.getOwnPropertyDescriptor(value, 'length')?.value\n\t\tif (\n\t\t\ttypeof length !== 'number' ||\n\t\t\t!Number.isSafeInteger(length) ||\n\t\t\tlength < 0 ||\n\t\t\tlength > limit\n\t\t) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst paths: string[] = []\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(value, String(index))\n\t\t\tif (\n\t\t\t\tdescriptor === undefined ||\n\t\t\t\t!Reflect.has(descriptor, 'value') ||\n\t\t\t\t!isPortablePath(descriptor.value)\n\t\t\t) {\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t\tpaths.push(descriptor.value)\n\t\t}\n\t\treturn Object.freeze(paths)\n\t})\n\treturn parsed.success ? parsed.value : undefined\n}\n\n/** Parse bounded exact transaction preconditions without invoking caller methods. */\nexport function parseWritePreconditions(\n\tvalue: unknown,\n\tlimit: number,\n): readonly WritePrecondition[] | undefined {\n\tconst parsed = attempt(() => {\n\t\tif (\n\t\t\t!Number.isSafeInteger(limit) ||\n\t\t\tlimit < 0 ||\n\t\t\t!isDenseDataArray(value, limit, isWritePrecondition)\n\t\t) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst length = Reflect.getOwnPropertyDescriptor(value, 'length')?.value\n\t\tif (\n\t\t\ttypeof length !== 'number' ||\n\t\t\t!Number.isSafeInteger(length) ||\n\t\t\tlength < 0 ||\n\t\t\tlength > limit\n\t\t) {\n\t\t\treturn undefined\n\t\t}\n\t\tconst preconditions: WritePrecondition[] = []\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(value, String(index))\n\t\t\tif (\n\t\t\t\tdescriptor === undefined ||\n\t\t\t\t!Reflect.has(descriptor, 'value') ||\n\t\t\t\t!isWritePrecondition(descriptor.value)\n\t\t\t) {\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t\tconst precondition = descriptor.value\n\t\t\tconst path = Reflect.getOwnPropertyDescriptor(precondition, 'path')?.value\n\t\t\tconst shape = Reflect.getOwnPropertyDescriptor(precondition, 'shape')?.value\n\t\t\tconst digest = Reflect.getOwnPropertyDescriptor(precondition, 'digest')?.value\n\t\t\tif (typeof path !== 'string') return undefined\n\t\t\tif (shape === 'absent' && digest === undefined) {\n\t\t\t\tconst copy: WritePrecondition = { path, shape }\n\t\t\t\tif (!isWritePrecondition(copy)) return undefined\n\t\t\t\tpreconditions.push(Object.freeze(copy))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (shape !== 'file' || typeof digest !== 'string') return undefined\n\t\t\tconst copy: WritePrecondition = { path, shape, digest }\n\t\t\tif (!isWritePrecondition(copy)) return undefined\n\t\t\tpreconditions.push(Object.freeze(copy))\n\t\t}\n\t\treturn Object.freeze(preconditions)\n\t})\n\treturn parsed.success ? parsed.value : undefined\n}\n\n/** Parse and normalize one upstream HTTP(S) endpoint base. */\nexport function parseSyncBase(value: unknown): SyncBase {\n\tif (\n\t\ttypeof value !== 'string' ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > MAX_SYNC_BASE_LENGTH ||\n\t\tvalue !== value.trim() ||\n\t\t(/^[A-Za-z][A-Za-z0-9+.-]*:\\/\\//i.test(value) && !/^https?:\\/\\//i.test(value))\n\t) {\n\t\tthrow new ScaffoldError('INVALID', 'Invalid Sync endpoint base', { value })\n\t}\n\tconst normalized = /^https?:\\/\\//i.test(value) ? value : `https://${value}`\n\tconst parsed = attempt(() => new URL(normalized))\n\tif (\n\t\t!parsed.success ||\n\t\t(parsed.value.protocol !== 'http:' && parsed.value.protocol !== 'https:') ||\n\t\tparsed.value.username.length > 0 ||\n\t\tparsed.value.password.length > 0 ||\n\t\tparsed.value.search.length > 0 ||\n\t\tparsed.value.hash.length > 0 ||\n\t\t(parsed.value.protocol === 'http:' &&\n\t\t\t!['127.0.0.1', '[::1]', 'localhost'].includes(parsed.value.hostname.toLowerCase()))\n\t) {\n\t\tthrow new ScaffoldError('INVALID', 'Invalid Sync endpoint base', { value })\n\t}\n\tconst base = parsed.value.href.replace(/\\/+$/, '')\n\tif (base.length > MAX_SYNC_BASE_LENGTH) {\n\t\tthrow new ScaffoldError('INVALID', 'Invalid Sync endpoint base', { value })\n\t}\n\treturn base\n}\n\n/**\n * Snapshot only declared guide references while enforcing per-file and cumulative byte limits.\n *\n * @param value - The caller-supplied guide content map.\n * @param names - Exact dependency names eligible for selection.\n * @param budget - Maximum cumulative UTF-8 bytes.\n * @returns A frozen selected map, or `undefined` when no map was supplied.\n */\nexport function parseSyncCurrent(\n\tvalue: Readonly<Record<string, string>> | undefined,\n\tnames: readonly string[],\n\tbudget: number,\n): Readonly<Record<string, string>> | undefined {\n\tif (value === undefined) return undefined\n\tconst snapshot = attempt(() => {\n\t\tif (!isRecord(value)) throw new Error('current must be a plain record')\n\t\tconst selected: Record<string, string> = {}\n\t\tlet consumed = 0\n\t\tfor (const name of names) {\n\t\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(value, name)\n\t\t\tif (descriptor === undefined) continue\n\t\t\tif (!Reflect.has(descriptor, 'value') || typeof descriptor.value !== 'string') {\n\t\t\t\tthrow new Error('current values must be string data properties')\n\t\t\t}\n\t\t\tconst bytes = contentByteLength(descriptor.value)\n\t\t\tconsumed += bytes\n\t\t\tif (bytes > MAX_ARTIFACT_BYTES || consumed > budget) {\n\t\t\t\tthrow new Error('current guide content exceeds its byte allowance')\n\t\t\t}\n\t\t\tselected[name] = descriptor.value\n\t\t}\n\t\treturn Object.freeze(selected)\n\t})\n\tif (!snapshot.success) {\n\t\tthrow new ScaffoldError('INVALID', 'Sync current guides are malformed', {\n\t\t\terror: snapshot.error,\n\t\t})\n\t}\n\treturn snapshot.value\n}\n\n/** Parse a safe Git branch path for the canonical raw-guide URL. */\nexport function parseSyncBranch(value: unknown): SyncBranch {\n\tconst segments = typeof value === 'string' ? value.split('/') : []\n\tif (\n\t\ttypeof value !== 'string' ||\n\t\tvalue.length === 0 ||\n\t\tvalue.length > MAX_SYNC_BRANCH_LENGTH ||\n\t\t!SYNC_BRANCH_PATTERN.test(value) ||\n\t\tvalue.includes('..') ||\n\t\tvalue.includes('@{') ||\n\t\tvalue === '@' ||\n\t\tsegments.some(\n\t\t\t(segment) =>\n\t\t\t\tsegment === '' ||\n\t\t\t\tsegment.startsWith('.') ||\n\t\t\t\tsegment.endsWith('.') ||\n\t\t\t\t/\\.lock$/iu.test(segment),\n\t\t)\n\t) {\n\t\tthrow new ScaffoldError('INVALID', 'Invalid Sync guide branch', { value })\n\t}\n\treturn value\n}\n\n/** Parse exact materializer options before allocating its emitter. */\nexport function parseMaterializerOptions(value: unknown): MaterializerOptions {\n\tif (value === undefined) return {}\n\tconst read = attempt(() => {\n\t\tif (!isRecord(value)) throw new Error('options must be a plain record')\n\t\tconst keys = Reflect.ownKeys(value)\n\t\tif (keys.some((key) => key !== 'host' && key !== 'on' && key !== 'error')) {\n\t\t\tthrow new Error('options contain an unknown key')\n\t\t}\n\t\tconst descriptors = keys.map((key) => Reflect.getOwnPropertyDescriptor(value, key))\n\t\tif (\n\t\t\tdescriptors.some(\n\t\t\t\t(descriptor) => descriptor === undefined || !Reflect.has(descriptor, 'value'),\n\t\t\t)\n\t\t) {\n\t\t\tthrow new Error('options must use data properties')\n\t\t}\n\t\treturn {\n\t\t\thost: Reflect.getOwnPropertyDescriptor(value, 'host')?.value,\n\t\t\ton: Reflect.getOwnPropertyDescriptor(value, 'on')?.value,\n\t\t\terror: Reflect.getOwnPropertyDescriptor(value, 'error')?.value,\n\t\t}\n\t})\n\tif (!read.success) {\n\t\tthrow new ScaffoldError('INVALID', 'Materializer options are malformed', {\n\t\t\terror: read.error,\n\t\t})\n\t}\n\tconst parsed = materializerOptionsContract.parse({\n\t\t...(read.value.host === undefined ? {} : { host: read.value.host }),\n\t})\n\tif (parsed === undefined || (parsed.host !== undefined && !isFilesystemPath(parsed.host))) {\n\t\tthrow new ScaffoldError('INVALID', 'Materializer host is malformed')\n\t}\n\tif (read.value.on !== undefined && !isMaterializerEventHooks(read.value.on)) {\n\t\tthrow new ScaffoldError('INVALID', 'Materializer event hooks are malformed')\n\t}\n\tconst ownedHooks = attempt(() => {\n\t\tconst sourceHooks = read.value.on\n\t\tif (sourceHooks === undefined) return undefined\n\t\tif (typeof sourceHooks !== 'object' || sourceHooks === null) {\n\t\t\tthrow new Error('event hooks are malformed')\n\t\t}\n\t\tconst copy = Reflect.getOwnPropertyDescriptor(sourceHooks, 'copy')?.value\n\t\tconst write = Reflect.getOwnPropertyDescriptor(sourceHooks, 'write')?.value\n\t\tconst remove = Reflect.getOwnPropertyDescriptor(sourceHooks, 'remove')?.value\n\t\tconst done = Reflect.getOwnPropertyDescriptor(sourceHooks, 'done')?.value\n\t\tconst error = Reflect.getOwnPropertyDescriptor(sourceHooks, 'error')?.value\n\t\tconst destroy = Reflect.getOwnPropertyDescriptor(sourceHooks, 'destroy')?.value\n\t\tif (\n\t\t\t(copy !== undefined && !isFunction(copy)) ||\n\t\t\t(write !== undefined && !isFunction(write)) ||\n\t\t\t(remove !== undefined && !isFunction(remove)) ||\n\t\t\t(done !== undefined && !isFunction(done)) ||\n\t\t\t(error !== undefined && !isFunction(error)) ||\n\t\t\t(destroy !== undefined && !isFunction(destroy))\n\t\t) {\n\t\t\tthrow new Error('event hooks are malformed')\n\t\t}\n\t\treturn Object.freeze({\n\t\t\t...(copy === undefined ? {} : { copy }),\n\t\t\t...(write === undefined ? {} : { write }),\n\t\t\t...(remove === undefined ? {} : { remove }),\n\t\t\t...(done === undefined ? {} : { done }),\n\t\t\t...(error === undefined ? {} : { error }),\n\t\t\t...(destroy === undefined ? {} : { destroy }),\n\t\t})\n\t})\n\tif (!ownedHooks.success) {\n\t\tthrow new ScaffoldError('INVALID', 'Materializer event hooks are malformed', {\n\t\t\terror: ownedHooks.error,\n\t\t})\n\t}\n\tconst on: EmitterHooks<MaterializerEventMap> | undefined = ownedHooks.value\n\tif (read.value.error !== undefined && !isEmitterErrorHandler(read.value.error)) {\n\t\tthrow new ScaffoldError('INVALID', 'Materializer error handler is malformed')\n\t}\n\treturn {\n\t\t...(parsed.host === undefined ? {} : { host: parsed.host }),\n\t\t...(on === undefined ? {} : { on }),\n\t\t...(read.value.error === undefined ? {} : { error: read.value.error }),\n\t}\n}\n\n/**\n * Parse the exact bounded `SyncOptions` boundary before allocating resources.\n *\n * @param value - Caller-supplied options.\n * @returns A fresh, validated options record.\n */\nexport function parseSyncOptions(value: unknown): SyncOptions {\n\tif (value === undefined) return {}\n\tconst read = attempt(() => {\n\t\tif (!isRecord(value)) throw new Error('options must be a plain record')\n\t\tconst keys = Reflect.ownKeys(value)\n\t\tif (\n\t\t\tkeys.some(\n\t\t\t\t(key) =>\n\t\t\t\t\tkey !== 'guides' &&\n\t\t\t\t\tkey !== 'registry' &&\n\t\t\t\t\tkey !== 'concurrency' &&\n\t\t\t\t\tkey !== 'retries' &&\n\t\t\t\t\tkey !== 'strict' &&\n\t\t\t\t\tkey !== 'limit' &&\n\t\t\t\t\tkey !== 'items' &&\n\t\t\t\t\tkey !== 'budget' &&\n\t\t\t\t\tkey !== 'on' &&\n\t\t\t\t\tkey !== 'error',\n\t\t\t)\n\t\t) {\n\t\t\tthrow new Error('options contain an unknown key')\n\t\t}\n\t\tconst descriptors = keys.map((key) => Reflect.getOwnPropertyDescriptor(value, key))\n\t\tif (\n\t\t\tdescriptors.some(\n\t\t\t\t(descriptor) => descriptor === undefined || !Reflect.has(descriptor, 'value'),\n\t\t\t)\n\t\t) {\n\t\t\tthrow new Error('options must use data properties')\n\t\t}\n\t\treturn {\n\t\t\tguides: Reflect.getOwnPropertyDescriptor(value, 'guides')?.value,\n\t\t\tregistry: Reflect.getOwnPropertyDescriptor(value, 'registry')?.value,\n\t\t\tconcurrency: Reflect.getOwnPropertyDescriptor(value, 'concurrency')?.value,\n\t\t\tretries: Reflect.getOwnPropertyDescriptor(value, 'retries')?.value,\n\t\t\tstrict: Reflect.getOwnPropertyDescriptor(value, 'strict')?.value,\n\t\t\tlimit: Reflect.getOwnPropertyDescriptor(value, 'limit')?.value,\n\t\t\titems: Reflect.getOwnPropertyDescriptor(value, 'items')?.value,\n\t\t\tbudget: Reflect.getOwnPropertyDescriptor(value, 'budget')?.value,\n\t\t\ton: Reflect.getOwnPropertyDescriptor(value, 'on')?.value,\n\t\t\terror: Reflect.getOwnPropertyDescriptor(value, 'error')?.value,\n\t\t}\n\t})\n\tif (!read.success) {\n\t\tthrow new ScaffoldError('INVALID', 'Sync options are malformed', { error: read.error })\n\t}\n\tconst nested = attempt(() => {\n\t\tlet guides: Record<string, unknown> | undefined\n\t\tif (read.value.guides !== undefined) {\n\t\t\tconst source = read.value.guides\n\t\t\tif (!isRecord(source)) throw new Error('guides must be a plain record')\n\t\t\tconst keys = Reflect.ownKeys(source)\n\t\t\tif (keys.some((key) => key !== 'base' && key !== 'branch' && key !== 'timeout')) {\n\t\t\t\tthrow new Error('guides contain an unknown key')\n\t\t\t}\n\t\t\tconst descriptors = keys.map((key) => Reflect.getOwnPropertyDescriptor(source, key))\n\t\t\tif (\n\t\t\t\tdescriptors.some(\n\t\t\t\t\t(descriptor) => descriptor === undefined || !Reflect.has(descriptor, 'value'),\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tthrow new Error('guides must use data properties')\n\t\t\t}\n\t\t\tguides = {\n\t\t\t\tbase: Reflect.getOwnPropertyDescriptor(source, 'base')?.value,\n\t\t\t\tbranch: Reflect.getOwnPropertyDescriptor(source, 'branch')?.value,\n\t\t\t\ttimeout: Reflect.getOwnPropertyDescriptor(source, 'timeout')?.value,\n\t\t\t}\n\t\t}\n\t\tlet registry: Record<string, unknown> | undefined\n\t\tif (read.value.registry !== undefined) {\n\t\t\tconst source = read.value.registry\n\t\t\tif (!isRecord(source)) throw new Error('registry must be a plain record')\n\t\t\tconst keys = Reflect.ownKeys(source)\n\t\t\tif (keys.some((key) => key !== 'base' && key !== 'timeout')) {\n\t\t\t\tthrow new Error('registry contains an unknown key')\n\t\t\t}\n\t\t\tconst descriptors = keys.map((key) => Reflect.getOwnPropertyDescriptor(source, key))\n\t\t\tif (\n\t\t\t\tdescriptors.some(\n\t\t\t\t\t(descriptor) => descriptor === undefined || !Reflect.has(descriptor, 'value'),\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tthrow new Error('registry must use data properties')\n\t\t\t}\n\t\t\tregistry = {\n\t\t\t\tbase: Reflect.getOwnPropertyDescriptor(source, 'base')?.value,\n\t\t\t\ttimeout: Reflect.getOwnPropertyDescriptor(source, 'timeout')?.value,\n\t\t\t}\n\t\t}\n\t\treturn { guides, registry }\n\t})\n\tif (!nested.success) {\n\t\tthrow new ScaffoldError('INVALID', 'Sync endpoint options are malformed', {\n\t\t\terror: nested.error,\n\t\t})\n\t}\n\tconst configuration = {\n\t\t...(nested.value.guides === undefined ? {} : { guides: nested.value.guides }),\n\t\t...(nested.value.registry === undefined ? {} : { registry: nested.value.registry }),\n\t\t...(read.value.concurrency === undefined ? {} : { concurrency: read.value.concurrency }),\n\t\t...(read.value.retries === undefined ? {} : { retries: read.value.retries }),\n\t\t...(read.value.strict === undefined ? {} : { strict: read.value.strict }),\n\t\t...(read.value.limit === undefined ? {} : { limit: read.value.limit }),\n\t\t...(read.value.items === undefined ? {} : { items: read.value.items }),\n\t\t...(read.value.budget === undefined ? {} : { budget: read.value.budget }),\n\t}\n\tconst parsed = syncOptionsContract.parse(configuration)\n\tif (parsed === undefined) {\n\t\tthrow new ScaffoldError('INVALID', 'Sync options are malformed')\n\t}\n\tif (read.value.on !== undefined && !isSyncEventHooks(read.value.on)) {\n\t\tthrow new ScaffoldError('INVALID', 'Sync event hooks are malformed')\n\t}\n\tconst ownedHooks = attempt(() => {\n\t\tconst sourceHooks = read.value.on\n\t\tif (sourceHooks === undefined) return undefined\n\t\tif (typeof sourceHooks !== 'object' || sourceHooks === null) {\n\t\t\tthrow new Error('event hooks are malformed')\n\t\t}\n\t\tconst guide = Reflect.getOwnPropertyDescriptor(sourceHooks, 'guide')?.value\n\t\tconst version = Reflect.getOwnPropertyDescriptor(sourceHooks, 'version')?.value\n\t\tconst packageListener = Reflect.getOwnPropertyDescriptor(sourceHooks, 'package')?.value\n\t\tconst write = Reflect.getOwnPropertyDescriptor(sourceHooks, 'write')?.value\n\t\tconst done = Reflect.getOwnPropertyDescriptor(sourceHooks, 'done')?.value\n\t\tconst error = Reflect.getOwnPropertyDescriptor(sourceHooks, 'error')?.value\n\t\tconst destroy = Reflect.getOwnPropertyDescriptor(sourceHooks, 'destroy')?.value\n\t\tif (\n\t\t\t(guide !== undefined && !isFunction(guide)) ||\n\t\t\t(version !== undefined && !isFunction(version)) ||\n\t\t\t(packageListener !== undefined && !isFunction(packageListener)) ||\n\t\t\t(write !== undefined && !isFunction(write)) ||\n\t\t\t(done !== undefined && !isFunction(done)) ||\n\t\t\t(error !== undefined && !isFunction(error)) ||\n\t\t\t(destroy !== undefined && !isFunction(destroy))\n\t\t) {\n\t\t\tthrow new Error('event hooks are malformed')\n\t\t}\n\t\treturn Object.freeze({\n\t\t\t...(guide === undefined ? {} : { guide }),\n\t\t\t...(version === undefined ? {} : { version }),\n\t\t\t...(packageListener === undefined ? {} : { package: packageListener }),\n\t\t\t...(write === undefined ? {} : { write }),\n\t\t\t...(done === undefined ? {} : { done }),\n\t\t\t...(error === undefined ? {} : { error }),\n\t\t\t...(destroy === undefined ? {} : { destroy }),\n\t\t})\n\t})\n\tif (!ownedHooks.success) {\n\t\tthrow new ScaffoldError('INVALID', 'Sync event hooks are malformed', {\n\t\t\terror: ownedHooks.error,\n\t\t})\n\t}\n\tconst on: EmitterHooks<SyncEventMap> | undefined = ownedHooks.value\n\tif (read.value.error !== undefined && !isEmitterErrorHandler(read.value.error)) {\n\t\tthrow new ScaffoldError('INVALID', 'Sync error handler is malformed')\n\t}\n\tconst guides =\n\t\tparsed.guides === undefined\n\t\t\t? undefined\n\t\t\t: {\n\t\t\t\t\t...(parsed.guides.base === undefined ? {} : { base: parseSyncBase(parsed.guides.base) }),\n\t\t\t\t\t...(parsed.guides.branch === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { branch: parseSyncBranch(parsed.guides.branch) }),\n\t\t\t\t\t...(parsed.guides.timeout === undefined ? {} : { timeout: parsed.guides.timeout }),\n\t\t\t\t}\n\tconst registry =\n\t\tparsed.registry === undefined\n\t\t\t? undefined\n\t\t\t: {\n\t\t\t\t\t...(parsed.registry.base === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { base: parseSyncBase(parsed.registry.base) }),\n\t\t\t\t\t...(parsed.registry.timeout === undefined ? {} : { timeout: parsed.registry.timeout }),\n\t\t\t\t}\n\treturn {\n\t\t...(guides === undefined ? {} : { guides }),\n\t\t...(registry === undefined ? {} : { registry }),\n\t\t...(parsed.concurrency === undefined ? {} : { concurrency: parsed.concurrency }),\n\t\t...(parsed.retries === undefined ? {} : { retries: parsed.retries }),\n\t\t...(parsed.strict === undefined ? {} : { strict: parsed.strict }),\n\t\t...(parsed.limit === undefined ? {} : { limit: parsed.limit }),\n\t\t...(parsed.items === undefined ? {} : { items: parsed.items }),\n\t\t...(parsed.budget === undefined ? {} : { budget: parsed.budget }),\n\t\t...(on === undefined ? {} : { on }),\n\t\t...(read.value.error === undefined ? {} : { error: read.value.error }),\n\t}\n}\n","import type { WriteAnchor, WriteExpectation, WritePrecondition } from './types.js'\nimport { randomUUID } from 'node:crypto'\nimport { lstatSync, mkdirSync, rmdirSync, rmSync } from 'node:fs'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport { attempt } from '@orkestrel/contract'\nimport { findFileConflict, MAX_COLLECTION_ITEMS, ScaffoldError } from '@src/core'\nimport { WRITE_DIGEST_PATTERN } from './constants.js'\nimport { digestFile, resolvePhysicalPath } from './helpers.js'\nimport { parsePortablePaths, parseWritePreconditions } from './parsers.js'\nimport { isFilesystemPath, isMissingPathError, isPortablePath } from './validators.js'\n\n/**\n * Nominal, same-volume write-transaction state. Construction derives every\n * filesystem path from a target and portable relative paths; callers cannot\n * supply a deletion root or mutate captured arrays.\n */\nexport class WriteTransaction {\n\tstatic readonly #token = Object.freeze({})\n\n\treadonly #target: string\n\treadonly #root: string\n\treadonly #stage: string\n\treadonly #backup: string\n\treadonly #expectations: readonly WriteExpectation[]\n\treadonly #parents: readonly WriteAnchor[]\n\treadonly #directories: readonly WriteAnchor[]\n\treadonly #anchor: WriteAnchor\n\treadonly #existing: WriteAnchor | undefined\n\n\tconstructor(\n\t\ttoken: unknown,\n\t\ttarget: string,\n\t\troot: string,\n\t\tstage: string,\n\t\tbackup: string,\n\t\texpectations: readonly WriteExpectation[],\n\t\tparents: readonly WriteAnchor[],\n\t\tdirectories: readonly WriteAnchor[],\n\t\tanchor: WriteAnchor,\n\t\texisting: WriteAnchor | undefined,\n\t) {\n\t\tif (token !== WriteTransaction.#token) {\n\t\t\tthrow new ScaffoldError('WRITE', 'WriteTransaction must be created through create()')\n\t\t}\n\t\tthis.#target = target\n\t\tthis.#root = root\n\t\tthis.#stage = stage\n\t\tthis.#backup = backup\n\t\tthis.#expectations = Object.freeze([...expectations])\n\t\tthis.#parents = Object.freeze(parents.map((parent) => Object.freeze({ ...parent })))\n\t\tthis.#directories = Object.freeze(\n\t\t\tdirectories.map((directory) => Object.freeze({ ...directory })),\n\t\t)\n\t\tthis.#anchor = Object.freeze({ ...anchor })\n\t\tthis.#existing = existing === undefined ? undefined : Object.freeze({ ...existing })\n\t}\n\n\t/** Create private staging state and snapshot every destination before mutation. */\n\tstatic create(\n\t\ttarget: string,\n\t\tpaths: readonly string[],\n\t\tpreconditions?: readonly WritePrecondition[],\n\t): WriteTransaction {\n\t\tif (!isFilesystemPath(target)) {\n\t\t\tthrow new ScaffoldError('WRITE', 'Write transaction target is malformed', { target })\n\t\t}\n\t\tconst resolvedTarget = resolve(target)\n\t\tconst requested = parsePortablePaths(paths, MAX_COLLECTION_ITEMS)\n\t\tif (requested === undefined) {\n\t\t\tthrow new ScaffoldError('WRITE', 'Write transaction paths are malformed', {\n\t\t\t\ttarget: resolvedTarget,\n\t\t\t})\n\t\t}\n\t\tconst conditions =\n\t\t\tpreconditions === undefined\n\t\t\t\t? undefined\n\t\t\t\t: parseWritePreconditions(preconditions, MAX_COLLECTION_ITEMS)\n\t\tif (preconditions !== undefined && conditions === undefined) {\n\t\t\tthrow new ScaffoldError('WRITE', 'Write transaction preconditions are malformed', {\n\t\t\t\ttarget: resolvedTarget,\n\t\t\t})\n\t\t}\n\t\tconst conflict = findFileConflict(requested)\n\t\tif (conflict !== undefined) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'WRITE',\n\t\t\t\t`Write transaction collision between \"${conflict[0]}\" and \"${conflict[1]}\"`,\n\t\t\t\t{ paths: conflict, committed: false },\n\t\t\t)\n\t\t}\n\t\tif (\n\t\t\tconditions !== undefined &&\n\t\t\t(conditions.length !== requested.length ||\n\t\t\t\trequested.some((path) => !conditions.some((condition) => condition.path === path)) ||\n\t\t\t\tconditions.some(\n\t\t\t\t\t(condition) =>\n\t\t\t\t\t\t!isPortablePath(condition.path) ||\n\t\t\t\t\t\t(condition.shape === 'file' &&\n\t\t\t\t\t\t\t(condition.digest === undefined || !WRITE_DIGEST_PATTERN.test(condition.digest))) ||\n\t\t\t\t\t\t(condition.shape === 'absent' && condition.digest !== undefined),\n\t\t\t\t))\n\t\t) {\n\t\t\tthrow new ScaffoldError('WRITE', 'Write transaction preconditions are malformed', {\n\t\t\t\tpaths: requested,\n\t\t\t})\n\t\t}\n\t\tconst parent = dirname(resolvedTarget)\n\t\tconst missingParents: string[] = []\n\t\tlet ancestor = parent\n\t\tlet anchor: WriteAnchor | undefined\n\t\twhile (anchor === undefined) {\n\t\t\tconst status = attempt(() => lstatSync(ancestor))\n\t\t\tif (status.success) {\n\t\t\t\tif (!status.value.isDirectory() || status.value.isSymbolicLink()) {\n\t\t\t\t\tthrow new ScaffoldError('WRITE', 'Write transaction parent is not a real directory', {\n\t\t\t\t\t\ttarget: resolvedTarget,\n\t\t\t\t\t\tparent: ancestor,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tanchor = Object.freeze({\n\t\t\t\t\tpath: ancestor,\n\t\t\t\t\tdevice: status.value.dev,\n\t\t\t\t\tinode: status.value.ino,\n\t\t\t\t})\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif (!isMissingPathError(status.error)) {\n\t\t\t\tthrow new ScaffoldError('WRITE', 'Failed to inspect write transaction parent', {\n\t\t\t\t\ttarget: resolvedTarget,\n\t\t\t\t\tparent: ancestor,\n\t\t\t\t\terror: status.error,\n\t\t\t\t})\n\t\t\t}\n\t\t\tmissingParents.push(ancestor)\n\t\t\tconst next = dirname(ancestor)\n\t\t\tif (next === ancestor) {\n\t\t\t\tthrow new ScaffoldError('WRITE', 'Write transaction has no existing parent', {\n\t\t\t\t\ttarget: resolvedTarget,\n\t\t\t\t})\n\t\t\t}\n\t\t\tancestor = next\n\t\t}\n\t\tconst targetStatus = attempt(() => lstatSync(resolvedTarget))\n\t\tconst existing =\n\t\t\ttargetStatus.success &&\n\t\t\ttargetStatus.value.isDirectory() &&\n\t\t\t!targetStatus.value.isSymbolicLink()\n\t\t\t\t? Object.freeze({\n\t\t\t\t\t\tpath: resolvedTarget,\n\t\t\t\t\t\tdevice: targetStatus.value.dev,\n\t\t\t\t\t\tinode: targetStatus.value.ino,\n\t\t\t\t\t})\n\t\t\t\t: undefined\n\t\tif (!targetStatus.success && !isMissingPathError(targetStatus.error)) {\n\t\t\tthrow new ScaffoldError('WRITE', 'Failed to inspect write transaction target', {\n\t\t\t\ttarget: resolvedTarget,\n\t\t\t\terror: targetStatus.error,\n\t\t\t})\n\t\t}\n\t\tif (targetStatus.success && existing === undefined) {\n\t\t\tthrow new ScaffoldError('WRITE', 'Write transaction target is not a real directory', {\n\t\t\t\ttarget: resolvedTarget,\n\t\t\t})\n\t\t}\n\t\tconst expectations: WriteExpectation[] = []\n\t\tfor (const path of requested) {\n\t\t\tif (!isPortablePath(path)) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Invalid transaction path at ${path}`, { path })\n\t\t\t}\n\t\t\tconst precondition = conditions?.find((condition) => condition.path === path)\n\t\t\tconst destination = resolvePhysicalPath(resolvedTarget, path, 'WRITE', 'target')\n\t\t\tconst current = attempt(() => lstatSync(destination))\n\t\t\tif (!current.success) {\n\t\t\t\tif (!isMissingPathError(current.error)) {\n\t\t\t\t\tthrow new ScaffoldError('WRITE', `Failed to inspect transaction destination at ${path}`, {\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\terror: current.error,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (precondition?.shape === 'file') {\n\t\t\t\t\tthrow new ScaffoldError('WRITE', `Write precondition changed at ${path}`, {\n\t\t\t\t\t\tpath,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\texpectations.push(Object.freeze({ path, shape: 'absent' }))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (\n\t\t\t\tcurrent.value.isSymbolicLink() ||\n\t\t\t\t(current.value.isFile() && current.value.nlink !== 1) ||\n\t\t\t\t(!current.value.isFile() && !current.value.isDirectory())\n\t\t\t) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Unsafe transaction destination at ${path}`, {\n\t\t\t\t\tpath,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (current.value.isDirectory()) {\n\t\t\t\tif (precondition !== undefined) {\n\t\t\t\t\tthrow new ScaffoldError('WRITE', `Write precondition changed at ${path}`, {\n\t\t\t\t\t\tpath,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\texpectations.push(\n\t\t\t\t\tObject.freeze({\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tshape: 'directory',\n\t\t\t\t\t\tdevice: current.value.dev,\n\t\t\t\t\t\tinode: current.value.ino,\n\t\t\t\t\t\tmodified: current.value.mtimeMs,\n\t\t\t\t\t\tsize: current.value.size,\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst content = attempt(() => digestFile(destination))\n\t\t\tif (!content.success) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Failed to snapshot transaction destination at ${path}`, {\n\t\t\t\t\tpath,\n\t\t\t\t\terror: content.error,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (\n\t\t\t\tprecondition?.shape === 'absent' ||\n\t\t\t\t(precondition?.shape === 'file' && precondition.digest !== content.value)\n\t\t\t) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Write precondition changed at ${path}`, {\n\t\t\t\t\tpath,\n\t\t\t\t})\n\t\t\t}\n\t\t\texpectations.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tpath,\n\t\t\t\t\tshape: 'file',\n\t\t\t\t\tdevice: current.value.dev,\n\t\t\t\t\tinode: current.value.ino,\n\t\t\t\t\tmodified: current.value.mtimeMs,\n\t\t\t\t\tsize: current.value.size,\n\t\t\t\t\tdigest: content.value,\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t\tconst token = randomUUID()\n\t\tconst root = join(parent, `.${basename(resolvedTarget)}.write-${token}`)\n\t\tconst stage = join(root, 'stage')\n\t\tconst backup = join(root, 'backup')\n\t\tconst parents: WriteAnchor[] = []\n\t\tconst directories: WriteAnchor[] = []\n\t\tconst created = attempt(() => {\n\t\t\tconst anchored = lstatSync(anchor.path)\n\t\t\tif (\n\t\t\t\t!anchored.isDirectory() ||\n\t\t\t\tanchored.isSymbolicLink() ||\n\t\t\t\tanchored.dev !== anchor.device ||\n\t\t\t\tanchored.ino !== anchor.inode\n\t\t\t) {\n\t\t\t\tthrow new Error('write transaction anchor changed')\n\t\t\t}\n\t\t\tfor (const directory of [...missingParents].reverse()) {\n\t\t\t\tmkdirSync(directory)\n\t\t\t\tconst status = lstatSync(directory)\n\t\t\t\tif (!status.isDirectory() || status.isSymbolicLink()) {\n\t\t\t\t\tthrow new Error(`write transaction parent changed at ${directory}`)\n\t\t\t\t}\n\t\t\t\tparents.push(Object.freeze({ path: directory, device: status.dev, inode: status.ino }))\n\t\t\t}\n\t\t\tmkdirSync(root, { mode: 0o700 })\n\t\t\tconst rootStatus = lstatSync(root)\n\t\t\tif (!rootStatus.isDirectory() || rootStatus.isSymbolicLink()) {\n\t\t\t\tthrow new Error('write transaction root is not a real directory')\n\t\t\t}\n\t\t\tdirectories.push(Object.freeze({ path: root, device: rootStatus.dev, inode: rootStatus.ino }))\n\t\t\tmkdirSync(stage, { mode: 0o700 })\n\t\t\tconst stageStatus = lstatSync(stage)\n\t\t\tif (!stageStatus.isDirectory() || stageStatus.isSymbolicLink()) {\n\t\t\t\tthrow new Error('write transaction stage is not a real directory')\n\t\t\t}\n\t\t\tdirectories.push(\n\t\t\t\tObject.freeze({ path: stage, device: stageStatus.dev, inode: stageStatus.ino }),\n\t\t\t)\n\t\t\tmkdirSync(backup, { mode: 0o700 })\n\t\t\tconst backupStatus = lstatSync(backup)\n\t\t\tif (!backupStatus.isDirectory() || backupStatus.isSymbolicLink()) {\n\t\t\t\tthrow new Error('write transaction backup is not a real directory')\n\t\t\t}\n\t\t\tdirectories.push(\n\t\t\t\tObject.freeze({ path: backup, device: backupStatus.dev, inode: backupStatus.ino }),\n\t\t\t)\n\t\t\tfor (const directory of [...parents, ...directories]) {\n\t\t\t\tconst status = lstatSync(directory.path)\n\t\t\t\tif (\n\t\t\t\t\t!status.isDirectory() ||\n\t\t\t\t\tstatus.isSymbolicLink() ||\n\t\t\t\t\tstatus.dev !== directory.device ||\n\t\t\t\t\tstatus.ino !== directory.inode\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(`write transaction directory changed at ${directory.path}`)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\tif (!created.success) {\n\t\t\tconst privateState = attempt(() => {\n\t\t\t\tfor (const directory of directories) {\n\t\t\t\t\tconst status = lstatSync(directory.path)\n\t\t\t\t\tif (\n\t\t\t\t\t\t!status.isDirectory() ||\n\t\t\t\t\t\tstatus.isSymbolicLink() ||\n\t\t\t\t\t\tstatus.dev !== directory.device ||\n\t\t\t\t\t\tstatus.ino !== directory.inode\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new Error(`write transaction directory changed at ${directory.path}`)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (directories.length > 0) rmSync(root, { recursive: true })\n\t\t\t})\n\t\t\tif (privateState.success) {\n\t\t\t\tfor (const directory of [...parents].reverse()) {\n\t\t\t\t\tattempt(() => {\n\t\t\t\t\t\tconst status = lstatSync(directory.path)\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!status.isDirectory() ||\n\t\t\t\t\t\t\tstatus.isSymbolicLink() ||\n\t\t\t\t\t\t\tstatus.dev !== directory.device ||\n\t\t\t\t\t\t\tstatus.ino !== directory.inode\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new Error(`write transaction parent changed at ${directory.path}`)\n\t\t\t\t\t\t}\n\t\t\t\t\t\trmdirSync(directory.path)\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new ScaffoldError('WRITE', 'Failed to create write transaction', {\n\t\t\t\ttarget: resolvedTarget,\n\t\t\t\troot,\n\t\t\t\terror: created.error,\n\t\t\t})\n\t\t}\n\t\treturn new WriteTransaction(\n\t\t\tWriteTransaction.#token,\n\t\t\tresolvedTarget,\n\t\t\troot,\n\t\t\tstage,\n\t\t\tbackup,\n\t\t\texpectations,\n\t\t\tparents,\n\t\t\tdirectories,\n\t\t\tanchor,\n\t\t\texisting,\n\t\t)\n\t}\n\n\tget target(): string {\n\t\treturn this.#target\n\t}\n\n\tget root(): string {\n\t\treturn this.#root\n\t}\n\n\tget stage(): string {\n\t\treturn this.#stage\n\t}\n\n\tget backup(): string {\n\t\treturn this.#backup\n\t}\n\n\tget expectations(): readonly WriteExpectation[] {\n\t\treturn this.#expectations\n\t}\n\n\tget parents(): readonly WriteAnchor[] {\n\t\treturn this.#parents\n\t}\n\n\tget directories(): readonly WriteAnchor[] {\n\t\treturn this.#directories\n\t}\n\n\tget anchor(): WriteAnchor {\n\t\treturn this.#anchor\n\t}\n\n\tget existing(): WriteAnchor | undefined {\n\t\treturn this.#existing\n\t}\n}\n","import type {\n\tArtifact,\n\tBlueprint,\n\tCatalogEntry,\n\tDependency,\n\tGuideSync,\n\tHostArtifact,\n\tPlan,\n\tScaffoldErrorCode,\n\tSnapshot,\n\tSyncReport,\n\tVersionSync,\n} from '@src/core'\nimport type { BlockquoteNode } from '@orkestrel/markdown'\nimport type {\n\tCatalogAllowance,\n\tGuideWrite,\n\tHostManifest,\n\tManifestEntry,\n\tWriteAnchor,\n\tWriteDirectoryResult,\n\tWriteExpectation,\n} from './types.js'\nimport { createHash, randomUUID } from 'node:crypto'\nimport {\n\tcloseSync,\n\tconstants as FS_CONSTANTS,\n\tcopyFileSync,\n\texistsSync,\n\tfstatSync,\n\tlinkSync,\n\tlstatSync,\n\tmkdirSync,\n\topenSync,\n\topendirSync,\n\treaddirSync,\n\treadSync,\n\trealpathSync,\n\trenameSync,\n\trmdirSync,\n\trmSync,\n\twriteFileSync,\n} from 'node:fs'\nimport { basename, dirname, join, relative as relativeOf, resolve, sep } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { attempt, isRecord, parseJSON, parseJSONAs } from '@orkestrel/contract'\nimport {\n\tflattenText,\n\tisBlockquoteNode,\n\tisParagraphNode,\n\tparseDocument,\n\twalkNodes,\n} from '@orkestrel/markdown'\nimport {\n\tblueprint,\n\tbytesToHex,\n\tcontentByteLength,\n\tDEFAULT_ENGINES,\n\tDEFAULT_VERSION,\n\tDEPENDENCY_NAME_PATTERN,\n\tdevDependenciesFor,\n\tfindFileConflict,\n\tfindPathConflict,\n\tGLOBAL_SETUP_PATH,\n\tHOST_PATHS,\n\tHEX_PATTERN,\n\tisWorkspaceName,\n\tMAX_ARTIFACT_BYTES,\n\tMAX_ARTIFACT_HEX_LENGTH,\n\tMAX_COLLECTION_ITEMS,\n\tMAX_MANIFEST_BYTES,\n\tMAX_TOTAL_ARTIFACT_BYTES,\n\tisPlan,\n\townDataValue,\n\tScaffoldError,\n\tSHOWCASE_CONFIG_PATH,\n\tsnapshotPlan,\n\tENVIRONMENTS,\n\tstableStringify,\n\tVERSION_PATTERN,\n} from '@src/core'\nimport {\n\tHOST_MANIFEST_PATH,\n\tMAX_FILESYSTEM_DEPTH,\n\tMAX_GUIDE_BYTES,\n\tMAX_HOST_DEPTH,\n\tMAX_HOST_ENTRIES,\n\tPRUNE_DIRECTORIES,\n} from './constants.js'\nimport {\n\tisHostManifest,\n\tisCatalogDescription,\n\tisCatalogAllowance,\n\tisFilesystemPath,\n\tisMissingPathError,\n\tisPortablePath,\n\tisSensitiveHostPath,\n\tisTerminalText,\n} from './validators.js'\nimport { parseFilesystemPaths, parsePortablePaths } from './parsers.js'\nimport { WriteTransaction } from './WriteTransaction.js'\n\n/**\n * Whether a path is an existing physical directory rather than a file or link.\n *\n * @param path - The filesystem path to inspect without following links.\n * @returns `true` only for a successful `lstat` reporting a directory.\n */\nexport function isRealDirectory(path: string): boolean {\n\tconst status = attempt(() => lstatSync(path).isDirectory())\n\treturn status.success && status.value\n}\n\n/**\n * Whether a path is an existing physical file rather than a directory or link.\n *\n * @param path - The filesystem path to inspect without following links.\n * @returns `true` only for a successful `lstat` reporting a single-link file.\n */\nexport function isRealFile(path: string): boolean {\n\tconst status = attempt(() => lstatSync(path))\n\treturn (\n\t\tstatus.success &&\n\t\tstatus.value.isFile() &&\n\t\t!status.value.isSymbolicLink() &&\n\t\tstatus.value.nlink === 1\n\t)\n}\n\n/**\n * Compute a bounded-memory SHA-256 digest for one file.\n *\n * @param path - The file to read.\n * @returns Its lowercase SHA-256 digest.\n */\nexport function digestFile(path: string): string {\n\tconst initial = lstatSync(path)\n\tif (!initial.isFile() || initial.isSymbolicLink() || initial.nlink !== 1) {\n\t\tthrow new Error(`Digest source is not a physical file at ${path}`)\n\t}\n\tif (initial.size > MAX_ARTIFACT_BYTES) {\n\t\tthrow new Error(`Digest source exceeds ${MAX_ARTIFACT_BYTES} bytes at ${path}`)\n\t}\n\tconst handle = openSync(path, 'r')\n\tconst hash = createHash('sha256')\n\tconst buffer = Buffer.allocUnsafe(65_536)\n\tconst read = attempt(() => {\n\t\tconst current = fstatSync(handle)\n\t\tif (\n\t\t\t!current.isFile() ||\n\t\t\tcurrent.nlink !== 1 ||\n\t\t\tcurrent.dev !== initial.dev ||\n\t\t\tcurrent.ino !== initial.ino\n\t\t) {\n\t\t\tthrow new Error(`Digest source changed before reading at ${path}`)\n\t\t}\n\t\tlet size = 0\n\t\tfor (;;) {\n\t\t\tconst length = readSync(handle, buffer, 0, buffer.byteLength, null)\n\t\t\tif (length === 0) break\n\t\t\tsize += length\n\t\t\tif (size > MAX_ARTIFACT_BYTES) {\n\t\t\t\tthrow new Error(`Digest source exceeds ${MAX_ARTIFACT_BYTES} bytes at ${path}`)\n\t\t\t}\n\t\t\thash.update(buffer.subarray(0, length))\n\t\t}\n\t\tconst after = fstatSync(handle)\n\t\tconst pathStatus = lstatSync(path)\n\t\tif (\n\t\t\tsize !== current.size ||\n\t\t\tafter.dev !== current.dev ||\n\t\t\tafter.ino !== current.ino ||\n\t\t\tafter.mtimeMs !== current.mtimeMs ||\n\t\t\tafter.size !== current.size ||\n\t\t\t!pathStatus.isFile() ||\n\t\t\tpathStatus.isSymbolicLink() ||\n\t\t\tpathStatus.nlink !== 1 ||\n\t\t\tpathStatus.dev !== current.dev ||\n\t\t\tpathStatus.ino !== current.ino\n\t\t) {\n\t\t\tthrow new Error(`Digest source changed while reading at ${path}`)\n\t\t}\n\t\treturn hash.digest('hex')\n\t})\n\tconst closed = attempt(() => closeSync(handle))\n\tif (!read.success) throw read.error\n\tif (!closed.success) throw closed.error\n\treturn read.value\n}\n\n/**\n * Compute SHA-256 from exact lowercase hexadecimal bytes without decoding the whole value at once.\n *\n * @param hex - Exact hexadecimal bytes.\n * @returns Their lowercase SHA-256 digest.\n */\nexport function digestHex(hex: string): string {\n\tif (hex.length > MAX_ARTIFACT_HEX_LENGTH || !HEX_PATTERN.test(hex)) {\n\t\tthrow new Error('Digest input is not bounded exact hexadecimal bytes')\n\t}\n\tconst hash = createHash('sha256')\n\tfor (let offset = 0; offset < hex.length; offset += 131_072) {\n\t\thash.update(Buffer.from(hex.slice(offset, offset + 131_072), 'hex'))\n\t}\n\treturn hash.digest('hex')\n}\n\n/**\n * Compute SHA-256 from UTF-8 text.\n *\n * @param value - The text to hash.\n * @returns Its lowercase SHA-256 digest.\n */\nexport function digestText(value: string): string {\n\treturn createHash('sha256').update(value, 'utf8').digest('hex')\n}\n\n/**\n * Digest the exact declared membership of a vendored host manifest.\n *\n * @param entries - The ordered file membership declarations.\n * @param roots - The ordered directory membership declarations.\n * @returns A SHA-256 digest independent of the manifest's stored digest field.\n */\nexport function digestHostManifest(\n\tentries: readonly ManifestEntry[],\n\troots: readonly string[],\n): string {\n\treturn digestText(stableStringify({ entries, roots }))\n}\n\n/**\n * Render the local pointer written when an upstream dependency guide is not vendored yet.\n *\n * @param source - The canonical `guides/src/<name>.md` source path.\n * @returns The deterministic pointer content.\n */\nexport function guideStub(source: string): string {\n\tconst short = source.slice('guides/src/'.length, source.length - '.md'.length)\n\treturn `> Vendored guide for @orkestrel/${short} — run \\`scaffold pull\\` to fetch it.\\n`\n}\n\n/**\n * Remove the canonical Orkestrel scope from a dependency name.\n *\n * @param name - A dependency name.\n * @returns Its unscoped member when canonical, otherwise the original name.\n */\nexport function packageShortName(name: string): string {\n\tconst prefix = '@orkestrel/'\n\treturn name.startsWith(prefix) ? name.slice(prefix.length) : name\n}\n\n/**\n * Read bounded physical local guide mirrors for package names.\n *\n * @param target - The package root.\n * @param names - The package names whose mirrors are eligible.\n * @returns Existing guide content keyed by package name.\n */\nexport function readGuideReferences(\n\ttarget: string,\n\tnames: readonly string[],\n): Readonly<Record<string, string>> {\n\tconst current: Record<string, string> = {}\n\tfor (const name of names) {\n\t\tconst path = `guides/src/${packageShortName(name)}.md`\n\t\tconst full = resolvePhysicalPath(target, path, 'TARGET', 'target')\n\t\tconst status = attempt(() => lstatSync(full))\n\t\tif (!status.success) {\n\t\t\tif (isMissingPathError(status.error)) continue\n\t\t\tthrow new ScaffoldError('TARGET', `Failed to inspect local guide at ${path}`, {\n\t\t\t\tpath,\n\t\t\t\terror: status.error,\n\t\t\t})\n\t\t}\n\t\tif (!status.value.isFile() || status.value.isSymbolicLink() || status.value.nlink !== 1) {\n\t\t\tthrow new ScaffoldError('TARGET', `Local guide is not a physical file at ${path}`, {\n\t\t\t\tpath,\n\t\t\t})\n\t\t}\n\t\tcurrent[name] = readFileText(target, path, 'TARGET', 'target')\n\t}\n\treturn Object.freeze(current)\n}\n\n/**\n * Assemble one synchronization report from already ordered guide and version outcomes.\n *\n * @param target - The target package root.\n * @param guides - Guide outcomes.\n * @param versions - Version outcomes.\n * @returns The derived whole report.\n */\nexport function syncReportOf(\n\ttarget: string,\n\tguides: readonly GuideSync[],\n\tversions: readonly VersionSync[],\n): SyncReport {\n\tconst failed = [...guides, ...versions].filter(\n\t\t(entry) => entry.freshness === 'missing' || entry.freshness === 'failed',\n\t).length\n\tconst clean =\n\t\tfailed === 0 &&\n\t\tguides.every((guide) => guide.freshness === 'current') &&\n\t\tversions.every((version) => version.freshness === 'current')\n\treturn { target, guides, versions, clean, failed }\n}\n\n// ============================================================================\n// @orkestrel/scaffold/server — helpers.ts (AGENTS §5 source of truth). The\n// server-only helpers `blueprintToPlan`'s green-field target law, the\n// `diffPlan`-feeding target reader, `Sync`'s manifest reader, the\n// `Materializer`'s vendored-host manifest, the vendored-host BUILD staging\n// primitive (`stageHost`), and the\n// `catalog` bin verb depend on: `isVacant`, `readTarget`, `readManifest`,\n// `readHostManifest`, `readFileHex`, `listFiles`, `hydratePlan`,\n// `discoverPackages`, `hostRoot`, `deriveBlueprint`, and `catalogPackages`.\n// `selectOrkestrelEntries`, `locateHostSource`, and\n// `storagePath` are exported module-scope helpers per AGENTS §5's\n// no-nested-functions law — single-call-site status is not an exemption.\n// ============================================================================\n\n/**\n * Locate this MODULE's own installed package root — the nearest ancestor of\n * `import.meta.url` holding a `package.json` — and return its vendored\n * `dist/host` data root. THE single source of truth for the default\n * `Materializer` / `scaffold` bin host: once installed, walking up from the\n * module's own file (not `process.cwd()`, which points at whichever project\n * happens to be running) resolves to `node_modules/@orkestrel/scaffold`, the\n * correct default host — the package ships its vendored data with itself.\n * `dist/host` may not exist yet when this resolves from SOURCE under a test\n * runner; that is fine — existence is checked at the point of use, not here.\n *\n * @returns The absolute vendored `dist/host` path.\n * @throws `ScaffoldError('TARGET', …)` when no ancestor of this module's own\n * location holds a `package.json`.\n *\n * @example\n * ```ts\n * import { hostRoot } from '@orkestrel/scaffold/server'\n *\n * hostRoot() // '/…/node_modules/@orkestrel/scaffold/dist/host'\n * ```\n */\nexport function hostRoot(): string {\n\tlet dir = dirname(fileURLToPath(import.meta.url))\n\tfor (;;) {\n\t\tif (existsSync(join(dir, 'package.json'))) return join(dir, 'dist', 'host')\n\t\tconst parent = dirname(dir)\n\t\tif (parent === dir) {\n\t\t\tthrow new ScaffoldError('TARGET', 'No package root found above the module location', {\n\t\t\t\tmodule: import.meta.url,\n\t\t\t})\n\t\t}\n\t\tdir = parent\n\t}\n}\n\n/**\n * Resolve the deepest existing ancestor of a path through the real filesystem.\n *\n * @param path - The absolute or relative path to resolve.\n * @returns A path whose existing prefix has been resolved through symlinks.\n */\nexport function resolveRealPath(path: string): string {\n\tif (!isFilesystemPath(path)) {\n\t\tthrow new ScaffoldError('TARGET', 'Filesystem path is malformed or exceeds its bounds')\n\t}\n\tlet current = resolve(path)\n\tconst unresolved: string[] = []\n\twhile (!existsSync(current)) {\n\t\tconst parent = dirname(current)\n\t\tif (parent === current || unresolved.length >= MAX_FILESYSTEM_DEPTH) {\n\t\t\tthrow new ScaffoldError('TARGET', 'Filesystem path has no bounded existing ancestor', {\n\t\t\t\tpath,\n\t\t\t\tlimit: MAX_FILESYSTEM_DEPTH,\n\t\t\t})\n\t\t}\n\t\tunresolved.unshift(relativeOf(parent, current))\n\t\tcurrent = parent\n\t}\n\tlet physical = realpathSync(current)\n\tfor (const segment of unresolved) physical = join(physical, segment)\n\treturn physical\n}\n\n/**\n * Resolve a path beneath a declared root and reject lexical or symlink escape.\n *\n * @param root - The containing filesystem root.\n * @param path - The candidate path, relative or absolute.\n * @param code - The coded error to raise on escape.\n * @param boundary - The boundary name used in diagnostics.\n * @returns The lexically resolved candidate after realpath-aware validation.\n */\nexport function resolveContainedPath(\n\troot: string,\n\tpath: string,\n\tcode: ScaffoldErrorCode,\n\tboundary: string,\n): string {\n\tif (!isFilesystemPath(root) || !isFilesystemPath(path)) {\n\t\tthrow new ScaffoldError(code, `${boundary} path is malformed or exceeds its bounds`, {\n\t\t\tpath,\n\t\t\troot,\n\t\t})\n\t}\n\tconst resolvedRoot = resolveRealPath(resolve(root))\n\tconst resolvedCandidate = resolveRealPath(resolve(root, path))\n\tif (resolvedCandidate !== resolvedRoot && !resolvedCandidate.startsWith(resolvedRoot + sep)) {\n\t\tthrow new ScaffoldError(code, `Path \"${path}\" escapes the ${boundary} root`, {\n\t\t\tpath,\n\t\t\troot,\n\t\t})\n\t}\n\treturn resolve(root, path)\n}\n\n/**\n * Resolve a contained path whose existing ancestor chain contains no links.\n *\n * @param root - The trusted lexical and physical root.\n * @param path - The portable root-relative path.\n * @param code - The coded error to raise on failure.\n * @param boundary - The boundary name used in diagnostics.\n * @returns The contained destination.\n * @throws `ScaffoldError` when containment fails or an ancestor is not a real directory.\n */\nexport function resolvePhysicalPath(\n\troot: string,\n\tpath: string,\n\tcode: ScaffoldErrorCode,\n\tboundary: string,\n): string {\n\tconst resolvedRoot = resolve(root)\n\tconst destination = resolveContainedPath(resolvedRoot, path, code, boundary)\n\tif (destination === resolvedRoot) {\n\t\tconst status = attempt(() => lstatSync(resolvedRoot))\n\t\tif (!status.success || !status.value.isDirectory() || status.value.isSymbolicLink()) {\n\t\t\tthrow new ScaffoldError(code, `${boundary} root is not a real directory`, {\n\t\t\t\tpath,\n\t\t\t\troot,\n\t\t\t\t...(status.success ? {} : { error: status.error }),\n\t\t\t})\n\t\t}\n\t\treturn destination\n\t}\n\tlet parent = dirname(destination)\n\tfor (;;) {\n\t\tif (existsSync(parent)) {\n\t\t\tconst status = attempt(() => lstatSync(parent))\n\t\t\tif (!status.success || !status.value.isDirectory() || status.value.isSymbolicLink()) {\n\t\t\t\tthrow new ScaffoldError(code, `${boundary} parent is not a real directory`, {\n\t\t\t\t\tpath,\n\t\t\t\t\tparent,\n\t\t\t\t\t...(status.success ? {} : { error: status.error }),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tif (parent === resolvedRoot) break\n\t\tconst next = dirname(parent)\n\t\tif (next === parent) {\n\t\t\tthrow new ScaffoldError(code, `${boundary} parent escapes its root`, {\n\t\t\t\tpath,\n\t\t\t\troot,\n\t\t\t})\n\t\t}\n\t\tparent = next\n\t}\n\treturn destination\n}\n\n/**\n * Revalidate one captured physical-directory identity without following links.\n *\n * @param anchor - The captured path, device, and inode.\n * @param boundary - The boundary name used in diagnostics.\n * @throws `ScaffoldError('WRITE', ...)` when the directory is missing or changed.\n */\nexport function validateWriteAnchor(anchor: WriteAnchor, boundary: string): void {\n\tconst status = attempt(() => lstatSync(anchor.path))\n\tif (\n\t\t!status.success ||\n\t\t!status.value.isDirectory() ||\n\t\tstatus.value.isSymbolicLink() ||\n\t\tstatus.value.dev !== anchor.device ||\n\t\tstatus.value.ino !== anchor.inode\n\t) {\n\t\tthrow new ScaffoldError('WRITE', `Write transaction ${boundary} changed`, {\n\t\t\tpath: anchor.path,\n\t\t\t...(status.success ? {} : { error: status.error }),\n\t\t})\n\t}\n}\n\n/**\n * Create a physical directory path one segment at a time behind captured identities.\n *\n * @param path - The absolute directory path to establish.\n * @param boundary - The boundary name used in diagnostics.\n * @returns The final directory anchor and the subset created by this call.\n */\nexport function createWriteDirectory(path: string, boundary: string): WriteDirectoryResult {\n\tconst destination = resolve(path)\n\tconst missing: string[] = []\n\tlet current = destination\n\tlet existing: WriteAnchor | undefined\n\tfor (;;) {\n\t\tconst status = attempt(() => lstatSync(current))\n\t\tif (status.success) {\n\t\t\tif (!status.value.isDirectory() || status.value.isSymbolicLink()) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `${boundary} is not a physical directory`, {\n\t\t\t\t\tpath: current,\n\t\t\t\t})\n\t\t\t}\n\t\t\texisting = Object.freeze({\n\t\t\t\tpath: current,\n\t\t\t\tdevice: status.value.dev,\n\t\t\t\tinode: status.value.ino,\n\t\t\t})\n\t\t\tbreak\n\t\t}\n\t\tif (!isMissingPathError(status.error)) {\n\t\t\tthrow new ScaffoldError('WRITE', `Failed to inspect ${boundary}`, {\n\t\t\t\tpath: current,\n\t\t\t\terror: status.error,\n\t\t\t})\n\t\t}\n\t\tmissing.push(current)\n\t\tconst parent = dirname(current)\n\t\tif (parent === current) {\n\t\t\tthrow new ScaffoldError('WRITE', `Cannot establish ${boundary}`, { path: destination })\n\t\t}\n\t\tcurrent = parent\n\t}\n\tconst created: WriteAnchor[] = []\n\tlet anchor = existing\n\tfor (const directory of [...missing].reverse()) {\n\t\tvalidateWriteAnchor(anchor, boundary)\n\t\tmkdirSync(directory)\n\t\tvalidateWriteAnchor(anchor, boundary)\n\t\tconst status = lstatSync(directory)\n\t\tif (!status.isDirectory() || status.isSymbolicLink()) {\n\t\t\tthrow new ScaffoldError('WRITE', `${boundary} changed while creating it`, {\n\t\t\t\tpath: directory,\n\t\t\t})\n\t\t}\n\t\tanchor = Object.freeze({\n\t\t\tpath: directory,\n\t\t\tdevice: status.dev,\n\t\t\tinode: status.ino,\n\t\t})\n\t\tcreated.push(anchor)\n\t}\n\treturn { anchor, created }\n}\n\n/**\n * Revalidate every private directory owned by a write transaction.\n *\n * @param transaction - The nominal transaction state.\n * @throws `ScaffoldError('WRITE', ...)` when any private directory changed.\n */\nexport function validateWriteDirectories(transaction: WriteTransaction): void {\n\tvalidateWriteAnchor(transaction.anchor, 'anchor')\n\tfor (const parent of transaction.parents) validateWriteAnchor(parent, 'parent')\n\tfor (const directory of transaction.directories) {\n\t\tvalidateWriteAnchor(directory, 'private directory')\n\t}\n}\n\n/**\n * Revalidate the transaction target against its original or transaction-owned identity.\n *\n * @param transaction - The nominal transaction state.\n * @param owned - A target directory created by the current commit.\n * @throws `ScaffoldError('WRITE', ...)` when the target identity changed.\n */\nexport function validateWriteTarget(\n\ttransaction: WriteTransaction,\n\towned: WriteAnchor | undefined,\n): void {\n\tvalidateWriteDirectories(transaction)\n\tconst expected = transaction.existing ?? owned\n\tconst status = attempt(() => lstatSync(transaction.target))\n\tif (expected === undefined) {\n\t\tif (status.success || !isMissingPathError(status.error)) {\n\t\t\tthrow new ScaffoldError('WRITE', 'Write transaction target changed', {\n\t\t\t\ttarget: transaction.target,\n\t\t\t\t...(status.success ? {} : { error: status.error }),\n\t\t\t})\n\t\t}\n\t\treturn\n\t}\n\tif (\n\t\t!status.success ||\n\t\t!status.value.isDirectory() ||\n\t\tstatus.value.isSymbolicLink() ||\n\t\tstatus.value.dev !== expected.device ||\n\t\tstatus.value.ino !== expected.inode\n\t) {\n\t\tthrow new ScaffoldError('WRITE', 'Write transaction target changed', {\n\t\t\ttarget: transaction.target,\n\t\t\t...(status.success ? {} : { error: status.error }),\n\t\t})\n\t}\n}\n\n/**\n * Remove an uncommitted or already-committed write transaction's private residue.\n *\n * @param transaction - The transaction to discard.\n * @throws `ScaffoldError('WRITE', ...)` when its private root cannot be removed.\n */\nexport function discardWriteTransaction(transaction: WriteTransaction): void {\n\tif (!(transaction instanceof WriteTransaction)) {\n\t\tthrow new ScaffoldError('WRITE', 'Write transaction identity is invalid')\n\t}\n\tvalidateWriteDirectories(transaction)\n\tconst discarded = attempt(() => rmSync(transaction.root, { recursive: true }))\n\tif (!discarded.success) {\n\t\tthrow new ScaffoldError('WRITE', 'Failed to discard write transaction', {\n\t\t\ttarget: transaction.target,\n\t\t\troot: transaction.root,\n\t\t\terror: discarded.error,\n\t\t})\n\t}\n\tfor (const parent of [...transaction.parents].reverse()) {\n\t\tconst removed = attempt(() => {\n\t\t\tconst status = lstatSync(parent.path)\n\t\t\tif (\n\t\t\t\t!status.isDirectory() ||\n\t\t\t\tstatus.isSymbolicLink() ||\n\t\t\t\tstatus.dev !== parent.device ||\n\t\t\t\tstatus.ino !== parent.inode\n\t\t\t) {\n\t\t\t\tthrow new Error(`write transaction parent changed at ${parent.path}`)\n\t\t\t}\n\t\t\trmdirSync(parent.path)\n\t\t})\n\t\tif (!removed.success && !isMissingPathError(removed.error)) {\n\t\t\tthrow new ScaffoldError('WRITE', 'Failed to discard write transaction parent', {\n\t\t\t\ttarget: transaction.target,\n\t\t\t\troot: transaction.root,\n\t\t\t\tparent: parent.path,\n\t\t\t\terror: removed.error,\n\t\t\t})\n\t\t}\n\t}\n}\n\n/**\n * Promote a complete staged set and roll every earlier destination back when\n * any later promotion fails.\n *\n * @param transaction - Same-volume sibling staging state.\n * @param paths - Portable target-relative files to promote.\n * @throws `ScaffoldError('WRITE', ...)` with recovery details on failure.\n */\nexport function commitWriteTransaction(\n\ttransaction: WriteTransaction,\n\tpaths: readonly string[],\n): void {\n\tif (!(transaction instanceof WriteTransaction)) {\n\t\tthrow new ScaffoldError('WRITE', 'Write transaction identity is invalid')\n\t}\n\tconst requested = parsePortablePaths(paths, MAX_COLLECTION_ITEMS)\n\tconst conflict = requested === undefined ? undefined : findFileConflict(requested)\n\tif (\n\t\trequested === undefined ||\n\t\tconflict !== undefined ||\n\t\trequested.length !== transaction.expectations.length ||\n\t\trequested.some(\n\t\t\t(path) => !transaction.expectations.some((expectation) => expectation.path === path),\n\t\t) ||\n\t\ttransaction.expectations.some(\n\t\t\t(expectation) => !requested.some((path) => path === expectation.path),\n\t\t)\n\t) {\n\t\tdiscardWriteTransaction(transaction)\n\t\tthrow new ScaffoldError(\n\t\t\t'WRITE',\n\t\t\trequested !== undefined && conflict === undefined\n\t\t\t\t? 'Write transaction paths do not match its expectations'\n\t\t\t\t: requested !== undefined\n\t\t\t\t\t? `Write transaction collision between \"${conflict?.[0]}\" and \"${conflict?.[1]}\"`\n\t\t\t\t\t: 'Write transaction paths are malformed',\n\t\t\t{\n\t\t\t\tpaths: conflict ?? requested ?? [],\n\t\t\t\tcommitted: false,\n\t\t\t},\n\t\t)\n\t}\n\tconst preflight = attempt(() => {\n\t\tvalidateWriteTarget(transaction, undefined)\n\t\tvalidateWriteDirectories(transaction)\n\t\tfor (const path of requested) {\n\t\t\tif (!isPortablePath(path)) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Invalid transaction path at ${path}`, { path })\n\t\t\t}\n\t\t\tconst expectation = transaction.expectations.find((candidate) => candidate.path === path)\n\t\t\tif (expectation === undefined) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Missing transaction expectation at ${path}`, { path })\n\t\t\t}\n\t\t\tconst staged = resolvePhysicalPath(transaction.stage, path, 'WRITE', 'staging')\n\t\t\tconst stagedStatus = attempt(() => lstatSync(staged))\n\t\t\tif (\n\t\t\t\t!stagedStatus.success ||\n\t\t\t\tstagedStatus.value.isSymbolicLink() ||\n\t\t\t\t!stagedStatus.value.isFile() ||\n\t\t\t\tstagedStatus.value.nlink !== 1\n\t\t\t) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Invalid staged transaction entry at ${path}`, {\n\t\t\t\t\tpath,\n\t\t\t\t\terror: stagedStatus.success ? undefined : stagedStatus.error,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst destination = resolvePhysicalPath(transaction.target, path, 'WRITE', 'target')\n\t\t\tconst current = attempt(() => lstatSync(destination))\n\t\t\tif (expectation.shape === 'absent') {\n\t\t\t\tif (current.success || !isMissingPathError(current.error)) {\n\t\t\t\t\tthrow new ScaffoldError('WRITE', `Transaction destination changed at ${path}`, {\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\terror: current.success ? undefined : current.error,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (!current.success) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Transaction destination changed at ${path}`, {\n\t\t\t\t\tpath,\n\t\t\t\t\terror: current.error,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst shape = current.value.isDirectory() ? 'directory' : 'file'\n\t\t\tconst content = shape === 'file' ? attempt(() => digestFile(destination)) : undefined\n\t\t\tif (\n\t\t\t\tcurrent.value.isSymbolicLink() ||\n\t\t\t\t(current.value.isFile() && current.value.nlink !== 1) ||\n\t\t\t\tcurrent.value.isDirectory() !== stagedStatus.value.isDirectory() ||\n\t\t\t\tcurrent.value.isDirectory() ||\n\t\t\t\tshape !== expectation.shape ||\n\t\t\t\tcurrent.value.dev !== expectation.device ||\n\t\t\t\tcurrent.value.ino !== expectation.inode ||\n\t\t\t\tcurrent.value.mtimeMs !== expectation.modified ||\n\t\t\t\tcurrent.value.size !== expectation.size ||\n\t\t\t\t(content !== undefined && (!content.success || content.value !== expectation.digest))\n\t\t\t) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Transaction destination changed at ${path}`, {\n\t\t\t\t\tpath,\n\t\t\t\t\t...(content?.success === false ? { error: content.error } : {}),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t})\n\tif (!preflight.success) {\n\t\tconst cleanup = attempt(() => discardWriteTransaction(transaction))\n\t\tthrow new ScaffoldError('WRITE', 'Write transaction failed preflight', {\n\t\t\ttarget: transaction.target,\n\t\t\terror: preflight.error,\n\t\t\tcommitted: false,\n\t\t\t...(cleanup.success ? {} : { cleanup: cleanup.error }),\n\t\t})\n\t}\n\tconst preserved: string[] = []\n\tconst promoted: WriteExpectation[] = []\n\tconst createdParents: WriteAnchor[] = []\n\tlet ownedTarget: WriteAnchor | undefined\n\tconst committed = attempt(() => {\n\t\tfor (const path of requested) {\n\t\t\tvalidateWriteTarget(transaction, ownedTarget)\n\t\t\tvalidateWriteDirectories(transaction)\n\t\t\tif (!isPortablePath(path)) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Invalid transaction path at ${path}`, { path })\n\t\t\t}\n\t\t\tconst staged = resolvePhysicalPath(transaction.stage, path, 'WRITE', 'staging')\n\t\t\tconst stagedStatus = attempt(() => lstatSync(staged))\n\t\t\tif (\n\t\t\t\t!stagedStatus.success ||\n\t\t\t\tstagedStatus.value.isSymbolicLink() ||\n\t\t\t\t!stagedStatus.value.isFile() ||\n\t\t\t\tstagedStatus.value.nlink !== 1\n\t\t\t) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Invalid staged transaction entry at ${path}`, {\n\t\t\t\t\tpath,\n\t\t\t\t\terror: stagedStatus.success ? undefined : stagedStatus.error,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst destination = resolvePhysicalPath(transaction.target, path, 'WRITE', 'target')\n\t\t\tconst backup = resolvePhysicalPath(transaction.backup, path, 'WRITE', 'backup')\n\t\t\tconst expectation = transaction.expectations.find((candidate) => candidate.path === path)\n\t\t\tif (expectation === undefined) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Missing transaction expectation at ${path}`, { path })\n\t\t\t}\n\t\t\tconst current = attempt(() => lstatSync(destination))\n\t\t\tif (expectation.shape === 'absent') {\n\t\t\t\tif (current.success || !isMissingPathError(current.error)) {\n\t\t\t\t\tthrow new ScaffoldError('WRITE', `Transaction destination changed at ${path}`, {\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\terror: current.success ? undefined : current.error,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t} else if (current.success) {\n\t\t\t\tconst shape = current.value.isDirectory() ? 'directory' : 'file'\n\t\t\t\tconst content = shape === 'file' ? attempt(() => digestFile(destination)) : undefined\n\t\t\t\tif (\n\t\t\t\t\tcurrent.value.isSymbolicLink() ||\n\t\t\t\t\t(current.value.isFile() && current.value.nlink !== 1) ||\n\t\t\t\t\tcurrent.value.isDirectory() !== stagedStatus.value.isDirectory() ||\n\t\t\t\t\tcurrent.value.isDirectory() ||\n\t\t\t\t\tshape !== expectation.shape ||\n\t\t\t\t\tcurrent.value.dev !== expectation.device ||\n\t\t\t\t\tcurrent.value.ino !== expectation.inode ||\n\t\t\t\t\tcurrent.value.mtimeMs !== expectation.modified ||\n\t\t\t\t\tcurrent.value.size !== expectation.size ||\n\t\t\t\t\t(content !== undefined && (!content.success || content.value !== expectation.digest))\n\t\t\t\t) {\n\t\t\t\t\tthrow new ScaffoldError('WRITE', `Transaction destination changed at ${path}`, {\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\t...(content?.success === false ? { error: content.error } : {}),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tmkdirSync(dirname(backup), { recursive: true })\n\t\t\t\trenameSync(destination, backup)\n\t\t\t\tpreserved.push(path)\n\t\t\t\tconst capturedStatus = lstatSync(backup)\n\t\t\t\tconst capturedContent = digestFile(backup)\n\t\t\t\tif (\n\t\t\t\t\t!capturedStatus.isFile() ||\n\t\t\t\t\tcapturedStatus.isSymbolicLink() ||\n\t\t\t\t\tcapturedStatus.nlink !== 1 ||\n\t\t\t\t\tcapturedStatus.dev !== expectation.device ||\n\t\t\t\t\tcapturedStatus.ino !== expectation.inode ||\n\t\t\t\t\tcapturedStatus.mtimeMs !== expectation.modified ||\n\t\t\t\t\tcapturedStatus.size !== expectation.size ||\n\t\t\t\t\tcapturedContent !== expectation.digest\n\t\t\t\t) {\n\t\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t\t'WRITE',\n\t\t\t\t\t\t`Transaction destination changed during preservation at ${path}`,\n\t\t\t\t\t\t{ path },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Transaction destination changed at ${path}`, {\n\t\t\t\t\tpath,\n\t\t\t\t\terror: current.error,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst missingParents: string[] = []\n\t\t\tlet parent = dirname(destination)\n\t\t\twhile (parent !== dirname(transaction.target)) {\n\t\t\t\tconst status = attempt(() => lstatSync(parent))\n\t\t\t\tif (status.success) {\n\t\t\t\t\tif (\n\t\t\t\t\t\ttransaction.existing === undefined &&\n\t\t\t\t\t\townedTarget === undefined &&\n\t\t\t\t\t\tparent === transaction.target\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new ScaffoldError('WRITE', 'Write transaction target changed', {\n\t\t\t\t\t\t\ttarget: transaction.target,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif (!isMissingPathError(status.error)) throw status.error\n\t\t\t\tmissingParents.push(parent)\n\t\t\t\tparent = dirname(parent)\n\t\t\t}\n\t\t\tfor (const createdParent of [...missingParents].reverse()) {\n\t\t\t\tmkdirSync(createdParent)\n\t\t\t\tconst status = lstatSync(createdParent)\n\t\t\t\tif (!status.isDirectory() || status.isSymbolicLink()) {\n\t\t\t\t\tthrow new ScaffoldError('WRITE', `Write transaction parent changed at ${createdParent}`, {\n\t\t\t\t\t\ttarget: transaction.target,\n\t\t\t\t\t\tparent: createdParent,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (!createdParents.some((candidate) => candidate.path === createdParent)) {\n\t\t\t\t\tconst captured = Object.freeze({\n\t\t\t\t\t\tpath: createdParent,\n\t\t\t\t\t\tdevice: status.dev,\n\t\t\t\t\t\tinode: status.ino,\n\t\t\t\t\t})\n\t\t\t\t\tcreatedParents.push(captured)\n\t\t\t\t\tif (createdParent === transaction.target) ownedTarget = captured\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (transaction.existing === undefined && ownedTarget === undefined) {\n\t\t\t\tthrow new ScaffoldError('WRITE', 'Write transaction target was not created safely', {\n\t\t\t\t\ttarget: transaction.target,\n\t\t\t\t})\n\t\t\t}\n\t\t\tlinkSync(staged, destination)\n\t\t\tconst linkedStatus = lstatSync(destination)\n\t\t\tconst stagedAfterLink = lstatSync(staged)\n\t\t\tif (\n\t\t\t\t!linkedStatus.isFile() ||\n\t\t\t\tlinkedStatus.isSymbolicLink() ||\n\t\t\t\tlinkedStatus.dev !== stagedStatus.value.dev ||\n\t\t\t\tlinkedStatus.ino !== stagedStatus.value.ino ||\n\t\t\t\tstagedAfterLink.dev !== linkedStatus.dev ||\n\t\t\t\tstagedAfterLink.ino !== linkedStatus.ino\n\t\t\t) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Staged promotion changed at ${path}`, { path })\n\t\t\t}\n\t\t\tconst unlinked = attempt(() => rmSync(staged))\n\t\t\tif (!unlinked.success) {\n\t\t\t\tconst cleanup = attempt(() => {\n\t\t\t\t\tconst destinationStatus = lstatSync(destination)\n\t\t\t\t\tif (\n\t\t\t\t\t\tdestinationStatus.dev !== linkedStatus.dev ||\n\t\t\t\t\t\tdestinationStatus.ino !== linkedStatus.ino\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new Error(`promoted file changed at ${path}`)\n\t\t\t\t\t}\n\t\t\t\t\trmSync(destination)\n\t\t\t\t})\n\t\t\t\tthrow new ScaffoldError('WRITE', `Failed to release staged link at ${path}`, {\n\t\t\t\t\tpath,\n\t\t\t\t\terror: unlinked.error,\n\t\t\t\t\tcleanup: cleanup.success ? undefined : cleanup.error,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst promotedStatus = lstatSync(destination)\n\t\t\tpromoted.push(\n\t\t\t\tObject.freeze({\n\t\t\t\t\tpath,\n\t\t\t\t\tshape: 'file',\n\t\t\t\t\tdevice: promotedStatus.dev,\n\t\t\t\t\tinode: promotedStatus.ino,\n\t\t\t\t\tmodified: promotedStatus.mtimeMs,\n\t\t\t\t\tsize: promotedStatus.size,\n\t\t\t\t\tdigest: digestFile(destination),\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\t})\n\tif (!committed.success) {\n\t\tconst recoveryErrors: unknown[] = []\n\t\tlet preserveResidue = false\n\t\tfor (const promotion of [...promoted].reverse()) {\n\t\t\tconst removed = attempt(() => {\n\t\t\t\tvalidateWriteTarget(transaction, ownedTarget)\n\t\t\t\tconst destination = resolvePhysicalPath(\n\t\t\t\t\ttransaction.target,\n\t\t\t\t\tpromotion.path,\n\t\t\t\t\t'WRITE',\n\t\t\t\t\t'target',\n\t\t\t\t)\n\t\t\t\tconst status = lstatSync(destination)\n\t\t\t\tconst shape = status.isDirectory() ? 'directory' : 'file'\n\t\t\t\tconst digest = shape === 'file' ? attempt(() => digestFile(destination)) : undefined\n\t\t\t\tif (\n\t\t\t\t\tstatus.isSymbolicLink() ||\n\t\t\t\t\tshape !== promotion.shape ||\n\t\t\t\t\tstatus.dev !== promotion.device ||\n\t\t\t\t\tstatus.ino !== promotion.inode ||\n\t\t\t\t\t(digest !== undefined &&\n\t\t\t\t\t\t(!digest.success ||\n\t\t\t\t\t\t\tstatus.mtimeMs !== promotion.modified ||\n\t\t\t\t\t\t\tstatus.size !== promotion.size ||\n\t\t\t\t\t\t\tdigest.value !== promotion.digest))\n\t\t\t\t) {\n\t\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t\t'WRITE',\n\t\t\t\t\t\t`Promoted transaction destination changed at ${promotion.path}`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: promotion.path,\n\t\t\t\t\t\t\t...(digest?.success === false ? { error: digest.error } : {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (shape === 'directory') {\n\t\t\t\t\tconst recovery = resolvePhysicalPath(\n\t\t\t\t\t\ttransaction.stage,\n\t\t\t\t\t\t`.rollback/${promotion.path}`,\n\t\t\t\t\t\t'WRITE',\n\t\t\t\t\t\t'rollback',\n\t\t\t\t\t)\n\t\t\t\t\tmkdirSync(dirname(recovery), { recursive: true })\n\t\t\t\t\tvalidateWriteTarget(transaction, ownedTarget)\n\t\t\t\t\trenameSync(destination, recovery)\n\t\t\t\t\tpreserveResidue = true\n\t\t\t\t} else {\n\t\t\t\t\trmSync(destination)\n\t\t\t\t}\n\t\t\t})\n\t\t\tif (!removed.success) recoveryErrors.push(removed.error)\n\t\t}\n\t\tfor (const path of [...preserved].reverse()) {\n\t\t\tconst restored = attempt(() => {\n\t\t\t\tvalidateWriteTarget(transaction, ownedTarget)\n\t\t\t\tvalidateWriteDirectories(transaction)\n\t\t\t\tconst destination = resolvePhysicalPath(transaction.target, path, 'WRITE', 'target')\n\t\t\t\tconst backup = resolvePhysicalPath(transaction.backup, path, 'WRITE', 'backup')\n\t\t\t\tmkdirSync(dirname(destination), { recursive: true })\n\t\t\t\tlinkSync(backup, destination)\n\t\t\t\trmSync(backup)\n\t\t\t})\n\t\t\tif (!restored.success) recoveryErrors.push(restored.error)\n\t\t}\n\t\tfor (const parent of [...createdParents].reverse()) {\n\t\t\tconst removed = attempt(() => {\n\t\t\t\tvalidateWriteTarget(transaction, ownedTarget)\n\t\t\t\tvalidateWriteDirectories(transaction)\n\t\t\t\tvalidateWriteAnchor(parent, 'created parent')\n\t\t\t\trmdirSync(parent.path)\n\t\t\t})\n\t\t\tif (!removed.success && !isMissingPathError(removed.error)) recoveryErrors.push(removed.error)\n\t\t}\n\t\tconst cleanup =\n\t\t\trecoveryErrors.length === 0 && !preserveResidue\n\t\t\t\t? attempt(() => discardWriteTransaction(transaction))\n\t\t\t\t: undefined\n\t\tthrow new ScaffoldError('WRITE', 'Write transaction failed before commit', {\n\t\t\ttarget: transaction.target,\n\t\t\troot: transaction.root,\n\t\t\terror: committed.error,\n\t\t\tcommitted: false,\n\t\t\trecovery: recoveryErrors,\n\t\t\tresidue: preserveResidue ? transaction.root : undefined,\n\t\t\tcleanup: cleanup?.success === false ? cleanup.error : undefined,\n\t\t})\n\t}\n\tvalidateWriteDirectories(transaction)\n\tconst cleanup = attempt(() => rmSync(transaction.root, { recursive: true }))\n\tif (!cleanup.success) {\n\t\tthrow new ScaffoldError('WRITE', 'Write transaction committed with cleanup residue', {\n\t\t\ttarget: transaction.target,\n\t\t\troot: transaction.root,\n\t\t\terror: cleanup.error,\n\t\t\tcommitted: true,\n\t\t})\n\t}\n}\n\n/**\n * Resolve and completely preflight the canonical guide destinations a sync may write.\n *\n * @param guides - Structurally validated behind guide results.\n * @param target - The repository root that owns `guides/src`.\n * @returns Each guide paired with its contained destination.\n * @throws `ScaffoldError('WRITE', ...)` before mutation for ownership, collision,\n * containment, or existing filesystem-shape violations.\n */\nexport function resolveGuideWrites(\n\tguides: readonly GuideSync[],\n\ttarget: string,\n): readonly GuideWrite[] {\n\tconst copied = attempt(() =>\n\t\tguides.map((guide) => {\n\t\t\tconst name = guide.name\n\t\t\tconst path = guide.path\n\t\t\tconst content = guide.content\n\t\t\tconst freshness = guide.freshness\n\t\t\tconst note = guide.note\n\t\t\tconst baseline = guide.baseline\n\t\t\treturn {\n\t\t\t\tname,\n\t\t\t\tpath,\n\t\t\t\tcontent,\n\t\t\t\tfreshness,\n\t\t\t\t...(note === undefined ? {} : { note }),\n\t\t\t\t...(baseline === undefined ? {} : { baseline }),\n\t\t\t}\n\t\t}),\n\t)\n\tif (!copied.success) {\n\t\tthrow new ScaffoldError('WRITE', 'Sync guides could not be read safely', {\n\t\t\terror: copied.error,\n\t\t})\n\t}\n\tconst behind = copied.value.filter((guide) => guide.freshness === 'behind')\n\tconst paths: string[] = []\n\tfor (const guide of behind) {\n\t\tif (!DEPENDENCY_NAME_PATTERN.test(guide.name)) {\n\t\t\tthrow new ScaffoldError('WRITE', `Invalid guide dependency name at ${guide.name}`, {\n\t\t\t\tname: guide.name,\n\t\t\t})\n\t\t}\n\t\tconst short = packageShortName(guide.name)\n\t\tconst expected = `guides/src/${short}.md`\n\t\tif (guide.path !== expected) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'WRITE',\n\t\t\t\t`Guide path \"${guide.path}\" does not match dependency ${guide.name}`,\n\t\t\t\t{ path: guide.path, expected },\n\t\t\t)\n\t\t}\n\t\tpaths.push(guide.path)\n\t}\n\tconst conflict = findFileConflict(paths)\n\tif (conflict !== undefined) {\n\t\tthrow new ScaffoldError(\n\t\t\t'WRITE',\n\t\t\t`Guide destination collision between \"${conflict[0]}\" and \"${conflict[1]}\"`,\n\t\t\t{ paths: conflict },\n\t\t)\n\t}\n\tconst resolvedTarget = resolve(target)\n\tconst destinations = behind.map((guide) => ({\n\t\tguide,\n\t\tdestination: resolvePhysicalPath(target, guide.path, 'WRITE', 'target'),\n\t}))\n\tfor (const { guide, destination } of destinations) {\n\t\tif (existsSync(destination)) {\n\t\t\tconst status = attempt(() => lstatSync(destination))\n\t\t\tif (\n\t\t\t\t!status.success ||\n\t\t\t\t!status.value.isFile() ||\n\t\t\t\tstatus.value.isSymbolicLink() ||\n\t\t\t\tstatus.value.nlink !== 1\n\t\t\t) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Guide destination is not a file at ${guide.path}`, {\n\t\t\t\t\tpath: guide.path,\n\t\t\t\t\t...(status.success ? {} : { error: status.error }),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tif (!destination.startsWith(resolvedTarget + sep)) {\n\t\t\tthrow new ScaffoldError('WRITE', `Guide destination escapes the target for ${guide.path}`, {\n\t\t\t\tpath: guide.path,\n\t\t\t\ttarget,\n\t\t\t})\n\t\t}\n\t}\n\treturn destinations\n}\n\n/**\n * Restore quarantined files to their original target-relative paths.\n *\n * @param transaction - The nominal transaction that owns the quarantine and target.\n * @param paths - The relative paths to restore, in their original move order.\n * @throws `ScaffoldError('WRITE', …)` after attempting every reverse-order\n * restoration when one or more files could not be restored.\n */\nexport function restoreFiles(transaction: WriteTransaction, paths: readonly string[]): void {\n\tconst requested = parsePortablePaths(paths, MAX_COLLECTION_ITEMS)\n\tif (requested === undefined) {\n\t\tthrow new ScaffoldError('WRITE', 'Quarantine restore paths are malformed', {\n\t\t\tlimit: MAX_COLLECTION_ITEMS,\n\t\t})\n\t}\n\tconst failed: string[] = []\n\tconst errors: unknown[] = []\n\tfor (const path of [...requested].reverse()) {\n\t\tconst restored = attempt(() => {\n\t\t\tvalidateWriteTarget(transaction, undefined)\n\t\t\tconst from = resolvePhysicalPath(transaction.backup, path, 'WRITE', 'quarantine')\n\t\t\tconst to = resolvePhysicalPath(transaction.target, path, 'WRITE', 'target')\n\t\t\tconst sourceStatus = lstatSync(from)\n\t\t\tif (!sourceStatus.isFile() || sourceStatus.isSymbolicLink() || sourceStatus.nlink !== 1) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Invalid quarantined file at ${path}`, { path })\n\t\t\t}\n\t\t\tmkdirSync(dirname(to), { recursive: true })\n\t\t\tvalidateWriteTarget(transaction, undefined)\n\t\t\tlinkSync(from, to)\n\t\t\tvalidateWriteTarget(transaction, undefined)\n\t\t\trmSync(from)\n\t\t})\n\t\tif (!restored.success) {\n\t\t\tfailed.push(path)\n\t\t\terrors.push(restored.error)\n\t\t}\n\t}\n\tif (failed.length > 0) {\n\t\tthrow new ScaffoldError('WRITE', 'Failed to restore quarantined files', {\n\t\t\tsource: transaction.backup,\n\t\t\ttarget: transaction.target,\n\t\t\tpaths: failed,\n\t\t\terrors,\n\t\t})\n\t}\n}\n\n/**\n * Atomically promote a staged sibling directory while preserving recoverable state.\n *\n * @param staging - The completed staging directory.\n * @param target - The destination directory to replace.\n * @param backup - The sibling path reserved for the prior target.\n * @throws `ScaffoldError('WRITE', …)` with explicit `committed` and recovery paths.\n */\nexport function replaceDirectory(staging: string, target: string, backup: string): void {\n\tconst resolvedStaging = resolve(staging)\n\tconst resolvedTarget = resolve(target)\n\tconst resolvedBackup = resolve(backup)\n\tconst parent = dirname(resolvedTarget)\n\tconst paths = [resolvedStaging, resolvedTarget, resolvedBackup]\n\tif (dirname(resolvedStaging) !== parent || dirname(resolvedBackup) !== parent) {\n\t\tthrow new ScaffoldError('WRITE', 'Directory replacement paths must share one parent', {\n\t\t\tstaging: resolvedStaging,\n\t\t\ttarget: resolvedTarget,\n\t\t\tbackup: resolvedBackup,\n\t\t\tcommitted: false,\n\t\t})\n\t}\n\tif (new Set(paths.map((path) => path.toLowerCase())).size !== paths.length) {\n\t\tthrow new ScaffoldError('WRITE', 'Directory replacement paths must be distinct', {\n\t\t\tstaging: resolvedStaging,\n\t\t\ttarget: resolvedTarget,\n\t\t\tbackup: resolvedBackup,\n\t\t\tcommitted: false,\n\t\t})\n\t}\n\tconst parentStatus = attempt(() => lstatSync(parent))\n\tif (\n\t\t!parentStatus.success ||\n\t\t!parentStatus.value.isDirectory() ||\n\t\tparentStatus.value.isSymbolicLink()\n\t) {\n\t\tthrow new ScaffoldError('WRITE', 'Directory replacement parent must be a real directory', {\n\t\t\tstaging: resolvedStaging,\n\t\t\ttarget: resolvedTarget,\n\t\t\tbackup: resolvedBackup,\n\t\t\tcommitted: false,\n\t\t\t...(parentStatus.success ? {} : { error: parentStatus.error }),\n\t\t})\n\t}\n\tconst parentAnchor: WriteAnchor = Object.freeze({\n\t\tpath: parent,\n\t\tdevice: parentStatus.value.dev,\n\t\tinode: parentStatus.value.ino,\n\t})\n\tconst reserved = attempt(() => lstatSync(resolvedBackup))\n\tif (reserved.success) {\n\t\tthrow new ScaffoldError('WRITE', 'Directory replacement backup already exists', {\n\t\t\tstaging: resolvedStaging,\n\t\t\ttarget: resolvedTarget,\n\t\t\tbackup: resolvedBackup,\n\t\t\tcommitted: false,\n\t\t})\n\t}\n\tif (!isMissingPathError(reserved.error)) {\n\t\tthrow new ScaffoldError('WRITE', 'Failed to inspect directory replacement backup', {\n\t\t\tstaging: resolvedStaging,\n\t\t\ttarget: resolvedTarget,\n\t\t\tbackup: resolvedBackup,\n\t\t\tcommitted: false,\n\t\t\terror: reserved.error,\n\t\t})\n\t}\n\tconst staged = attempt(() => lstatSync(resolvedStaging))\n\tif (!staged.success || !staged.value.isDirectory() || staged.value.isSymbolicLink()) {\n\t\tthrow new ScaffoldError('WRITE', 'Directory replacement staging must be a real directory', {\n\t\t\tstaging: resolvedStaging,\n\t\t\ttarget: resolvedTarget,\n\t\t\tbackup: resolvedBackup,\n\t\t\tcommitted: false,\n\t\t\terror: staged.success ? undefined : staged.error,\n\t\t})\n\t}\n\tconst stagingAnchor: WriteAnchor = Object.freeze({\n\t\tpath: resolvedStaging,\n\t\tdevice: staged.value.dev,\n\t\tinode: staged.value.ino,\n\t})\n\tconst current = attempt(() => lstatSync(resolvedTarget))\n\tif (!current.success && !isMissingPathError(current.error)) {\n\t\tthrow new ScaffoldError('WRITE', 'Failed to inspect directory replacement target', {\n\t\t\tstaging: resolvedStaging,\n\t\t\ttarget: resolvedTarget,\n\t\t\tbackup: resolvedBackup,\n\t\t\tcommitted: false,\n\t\t\terror: current.error,\n\t\t})\n\t}\n\tif (current.success && (!current.value.isDirectory() || current.value.isSymbolicLink())) {\n\t\tthrow new ScaffoldError('WRITE', 'Directory replacement target must be a real directory', {\n\t\t\tstaging: resolvedStaging,\n\t\t\ttarget: resolvedTarget,\n\t\t\tbackup: resolvedBackup,\n\t\t\tcommitted: false,\n\t\t})\n\t}\n\tconst existing = current.success\n\tconst targetAnchor: WriteAnchor | undefined = current.success\n\t\t? Object.freeze({\n\t\t\t\tpath: resolvedTarget,\n\t\t\t\tdevice: current.value.dev,\n\t\t\t\tinode: current.value.ino,\n\t\t\t})\n\t\t: undefined\n\tlet preserved = false\n\tlet promoted = false\n\tconst replacement = attempt(() => {\n\t\tvalidateWriteAnchor(parentAnchor, 'directory replacement parent')\n\t\tvalidateWriteAnchor(stagingAnchor, 'directory replacement staging')\n\t\tif (existing) {\n\t\t\tif (targetAnchor === undefined) {\n\t\t\t\tthrow new Error('directory replacement target identity is missing')\n\t\t\t}\n\t\t\tvalidateWriteAnchor(targetAnchor, 'directory replacement target')\n\t\t\trenameSync(resolvedTarget, resolvedBackup)\n\t\t\tpreserved = true\n\t\t\tvalidateWriteAnchor(parentAnchor, 'directory replacement parent')\n\t\t\tvalidateWriteAnchor(\n\t\t\t\tObject.freeze({ ...targetAnchor, path: resolvedBackup }),\n\t\t\t\t'directory replacement backup',\n\t\t\t)\n\t\t\tconst vacated = attempt(() => lstatSync(resolvedTarget))\n\t\t\tif (vacated.success || !isMissingPathError(vacated.error)) {\n\t\t\t\tthrow new Error('directory replacement target was not vacated')\n\t\t\t}\n\t\t}\n\t\tvalidateWriteAnchor(parentAnchor, 'directory replacement parent')\n\t\tvalidateWriteAnchor(stagingAnchor, 'directory replacement staging')\n\t\trenameSync(resolvedStaging, resolvedTarget)\n\t\tpromoted = true\n\t\tvalidateWriteAnchor(parentAnchor, 'directory replacement parent')\n\t\tvalidateWriteAnchor(\n\t\t\tObject.freeze({ ...stagingAnchor, path: resolvedTarget }),\n\t\t\t'directory replacement target',\n\t\t)\n\t\tif (existing) {\n\t\t\tif (targetAnchor === undefined) {\n\t\t\t\tthrow new Error('directory replacement backup identity is missing')\n\t\t\t}\n\t\t\tvalidateWriteAnchor(\n\t\t\t\tObject.freeze({ ...targetAnchor, path: resolvedBackup }),\n\t\t\t\t'directory replacement backup',\n\t\t\t)\n\t\t\trmSync(resolvedBackup, { recursive: true, force: true })\n\t\t\tpreserved = false\n\t\t}\n\t\tvalidateWriteAnchor(parentAnchor, 'directory replacement parent')\n\t\tvalidateWriteAnchor(\n\t\t\tObject.freeze({ ...stagingAnchor, path: resolvedTarget }),\n\t\t\t'directory replacement target',\n\t\t)\n\t})\n\tif (replacement.success) return\n\tconst restored =\n\t\texisting && preserved && !promoted\n\t\t\t? attempt(() => {\n\t\t\t\t\tif (targetAnchor === undefined) {\n\t\t\t\t\t\tthrow new Error('directory replacement backup identity is missing')\n\t\t\t\t\t}\n\t\t\t\t\tvalidateWriteAnchor(parentAnchor, 'directory replacement parent')\n\t\t\t\t\tvalidateWriteAnchor(\n\t\t\t\t\t\tObject.freeze({ ...targetAnchor, path: resolvedBackup }),\n\t\t\t\t\t\t'directory replacement backup',\n\t\t\t\t\t)\n\t\t\t\t\tconst destination = attempt(() => lstatSync(resolvedTarget))\n\t\t\t\t\tif (destination.success || !isMissingPathError(destination.error)) {\n\t\t\t\t\t\tthrow new Error('directory replacement target is not vacant')\n\t\t\t\t\t}\n\t\t\t\t\trenameSync(resolvedBackup, resolvedTarget)\n\t\t\t\t\tvalidateWriteAnchor(targetAnchor, 'directory replacement target')\n\t\t\t\t\tpreserved = false\n\t\t\t\t})\n\t\t\t: undefined\n\tthrow new ScaffoldError('WRITE', 'Directory replacement failed', {\n\t\tstaging: resolvedStaging,\n\t\ttarget: resolvedTarget,\n\t\tbackup: preserved ? resolvedBackup : undefined,\n\t\tcommitted: promoted,\n\t\terror: replacement.error,\n\t\trestore: restored?.success === false ? restored.error : undefined,\n\t})\n}\n\n/**\n * Filter a manifest record's entries down to `@orkestrel/`-prefixed keys with\n * string values — the shared `dependencies` / `peerDependencies` /\n * `devDependencies` reader `deriveBlueprint` uses for every dependency-shaped\n * field.\n *\n * @param value - The candidate manifest field value (e.g. `parsed.dependencies`).\n * @returns The `@orkestrel/`-prefixed `[name, range]` entries; `[]` when\n * `value` is not a plain object (per `isRecord`).\n *\n * @example\n * ```ts\n * import { selectOrkestrelEntries } from '@orkestrel/scaffold/server'\n *\n * selectOrkestrelEntries({ '@orkestrel/core': '^1.0.0', lodash: '^4.0.0' })\n * // [['@orkestrel/core', '^1.0.0']]\n * ```\n */\nexport function selectOrkestrelEntries(value: unknown): readonly (readonly [string, string])[] {\n\tif (!isRecord(value)) return []\n\tconst selected = attempt(() => {\n\t\tconst entries: [string, string][] = []\n\t\tfor (const [name, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {\n\t\t\tif (!Reflect.has(descriptor, 'value')) return []\n\t\t\tif (typeof descriptor.value === 'string' && DEPENDENCY_NAME_PATTERN.test(name)) {\n\t\t\t\tentries.push([name, descriptor.value])\n\t\t\t}\n\t\t}\n\t\treturn entries\n\t})\n\treturn selected.success ? selected.value : []\n}\n\n/**\n * Reconstruct a `Blueprint` from an EXISTING repo at `target` — the faithful\n * inverse `audit` / `repair` / `mirror` need to diff a live package against\n * its own would-be scaffold, rather than a fresh, dependency-less stand-in.\n *\n * @param target - The existing package directory to derive a `Blueprint` from.\n * @remarks\n * A scoped package name is stripped to its bounded safe short name. An\n * unscoped name is accepted only when the target is app-only, `private: true`,\n * and the name satisfies `isWorkspaceName`; every other name is a coded\n * `TARGET` failure. `src` is derived from `src/<environment>/` and `app` from\n * `app/<environment>/`; a target with no environment on either axis is also a coded\n * `TARGET` failure. The `bin` and `integration` facts probe physical\n * directories at `src/bin` and `tests/integration`. `services` is the sorted\n * set of direct vendor directories under `tests/service` that contain a test\n * at any depth, while `global` probes the physical exact-case `tests/setupGlobal.ts` file and `showcase`\n * probes the physical exact-case `configs/app/vite.showcase.config.ts` regular file; none is\n * inferred from the workspace name. `dependencies` /\n * `peers` are the `@orkestrel/`-prefixed entries of `manifest.dependencies` /\n * `manifest.peerDependencies` (a peer flagged `peerDependenciesMeta[name]\n * .optional === true` carries `optional: true`). `extras` is EVERY entry of\n * `manifest.devDependencies` (not only `@orkestrel/`-prefixed ones — an\n * external extra like `zod` must round-trip too), EXCLUDING the complete\n * generated dependency set `devDependenciesFor` emits for the reconstructed\n * blueprint's actual environments and structural axes. A devDependency ALSO present in\n * `manifest.peerDependencies` or `manifest.dependencies` (e.g. a peer\n * dev-installed for local testing) is likewise excluded from `extras` — it\n * already appears as a `peer`/`dependency` above, and double-counting it as\n * an `extra` would land it in `peers ∩ extras`, a blocking `validateBlueprint`\n * gate. `overrides` is always `[]` — derivation cannot recover a caller's\n * artifact-override intent from repository state.\n * @returns The reconstructed `Blueprint`.\n * @throws `ScaffoldError('TARGET', …)` when `target`'s manifest is unreadable\n * (via `readManifest`), is not valid JSON, its name is unsafe for its\n * publication mode, or `target` carries no source or application environment.\n * @throws `ScaffoldError('INVALID', …)` when service tests use the retired flat\n * layout, a vendor directory has no test, or a service companion is missing.\n *\n * @example\n * ```ts\n * import { deriveBlueprint } from '@orkestrel/scaffold/server'\n *\n * deriveBlueprint('./packages/router') // { name: 'router', src: ['core', 'server'], … }\n * ```\n */\nexport function deriveBlueprint(target: string): Blueprint {\n\tconst text = readManifest(target)\n\tconst parsed = parseJSON(text)\n\tif (!isRecord(parsed)) {\n\t\tthrow new ScaffoldError('TARGET', `Manifest at ${target} is not a valid JSON object`, {\n\t\t\ttarget,\n\t\t})\n\t}\n\tconst src = ENVIRONMENTS.filter((environment) =>\n\t\tisRealDirectory(join(target, 'src', environment)),\n\t)\n\tconst app = ENVIRONMENTS.filter((environment) =>\n\t\tisRealDirectory(join(target, 'app', environment)),\n\t)\n\tif (src.length === 0 && app.length === 0) {\n\t\tthrow new ScaffoldError(\n\t\t\t'TARGET',\n\t\t\t`No source or application environment directory found under ${target}`,\n\t\t\t{ target },\n\t\t)\n\t}\n\tconst rawName = ownDataValue(parsed, 'name')\n\tif (typeof rawName !== 'string') {\n\t\tthrow new ScaffoldError('TARGET', 'Manifest name must be a string', {\n\t\t\ttarget,\n\t\t\tname: rawName,\n\t\t})\n\t}\n\tconst scopedValue = rawName.startsWith('@orkestrel/')\n\t\t? rawName.slice('@orkestrel/'.length)\n\t\t: undefined\n\tconst scopedName = isWorkspaceName(scopedValue)\n\tconst privateAppName =\n\t\tsrc.length === 0 && ownDataValue(parsed, 'private') === true && isWorkspaceName(rawName)\n\tif (!scopedName && !privateAppName) {\n\t\tthrow new ScaffoldError(\n\t\t\t'TARGET',\n\t\t\t`Manifest name \"${String(rawName)}\" is neither an @orkestrel package nor a private application`,\n\t\t\t{ target, name: rawName },\n\t\t)\n\t}\n\tconst name = scopedName ? scopedValue : rawName\n\n\tconst rawDescription = ownDataValue(parsed, 'description')\n\tconst description = typeof rawDescription === 'string' ? rawDescription : undefined\n\tconst rawKeywords = ownDataValue(parsed, 'keywords')\n\tconst keywords =\n\t\tArray.isArray(rawKeywords) && rawKeywords.every((word) => typeof word === 'string')\n\t\t\t? rawKeywords\n\t\t\t: []\n\tconst rawVersion = ownDataValue(parsed, 'version')\n\tconst version = typeof rawVersion === 'string' ? rawVersion : DEFAULT_VERSION\n\tconst rawEngines = ownDataValue(parsed, 'engines')\n\tconst rawNode = ownDataValue(rawEngines, 'node')\n\tconst engines = typeof rawNode === 'string' ? rawNode : DEFAULT_ENGINES\n\n\t// Structural only: a repo carries the self-hosting tax (bin field, scaffold\n\t// script, check/test/build:src:bin scripts, build:host, the srcBin vite\n\t// project) iff it ships its own src/bin — never derived from `name`.\n\tconst bin = isRealDirectory(join(target, 'src', 'bin'))\n\tconst integration = isRealDirectory(join(target, 'tests', 'integration'))\n\tconst serviceRoot = join(target, 'tests', 'service')\n\tconst services: string[] = []\n\tif (existsSync(serviceRoot)) {\n\t\tif (!isRealDirectory(serviceRoot)) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'INVALID',\n\t\t\t\t`Service root at ${serviceRoot} must be a physical directory`,\n\t\t\t\t{\n\t\t\t\t\ttarget,\n\t\t\t\t\tpath: 'tests/service',\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tconst serviceEntries = readdirSync(serviceRoot, { withFileTypes: true })\n\t\tconst flat = serviceEntries\n\t\t\t.filter((entry) => entry.name.endsWith('.test.ts') && !entry.isDirectory())\n\t\t\t.map((entry) => entry.name)\n\t\t\t.sort()\n\t\tif (flat.length > 0) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'INVALID',\n\t\t\t\t`Flat service tests are not supported; move ${flat.join(', ')} into tests/service/<vendor>/`,\n\t\t\t\t{ target, paths: flat.map((path) => `tests/service/${path}`) },\n\t\t\t)\n\t\t}\n\t\tfor (const entry of serviceEntries) {\n\t\t\tconst vendor = join(serviceRoot, entry.name)\n\t\t\tif (!isRealDirectory(vendor)) continue\n\t\t\tif (!isWorkspaceName(entry.name)) {\n\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Service vendor directory \"${entry.name}\" must use a bounded lowercase name`,\n\t\t\t\t\t{ target, path: `tests/service/${entry.name}` },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst tests = listFiles(vendor).filter((path) => path.endsWith('.test.ts'))\n\t\t\tif (tests.length === 0) {\n\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Service vendor \"${entry.name}\" contains no test; add tests/service/${entry.name}/**/*.test.ts or remove the directory`,\n\t\t\t\t\t{ target, service: entry.name },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst setup = `tests/service/${entry.name}/setup.ts`\n\t\t\tif (!isRealFile(join(target, setup))) {\n\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Service vendor \"${entry.name}\" is missing ${setup}; add a readiness module that probes and warms the vendor and throws when unavailable`,\n\t\t\t\t\t{ target, service: entry.name, missing: setup },\n\t\t\t\t)\n\t\t\t}\n\t\t\tservices.push(entry.name)\n\t\t}\n\t\tservices.sort()\n\t}\n\tconst showcaseRoot = join(target, dirname(SHOWCASE_CONFIG_PATH))\n\tconst showcaseEntries = attempt(() => readdirSync(showcaseRoot))\n\tconst showcase =\n\t\tshowcaseEntries.success &&\n\t\tshowcaseEntries.value.includes(basename(SHOWCASE_CONFIG_PATH)) &&\n\t\tisRealFile(join(target, SHOWCASE_CONFIG_PATH))\n\tconst tests = join(target, dirname(GLOBAL_SETUP_PATH))\n\tconst entries = attempt(() => readdirSync(tests))\n\tconst global =\n\t\tentries.success &&\n\t\tentries.value.includes(basename(GLOBAL_SETUP_PATH)) &&\n\t\tisRealFile(join(target, GLOBAL_SETUP_PATH))\n\tconst rawDependencies = ownDataValue(parsed, 'dependencies')\n\tconst rawPeerDependencies = ownDataValue(parsed, 'peerDependencies')\n\tconst dependencies: Dependency[] = selectOrkestrelEntries(rawDependencies).map(\n\t\t([depName, range]) => ({ name: depName, range }),\n\t)\n\n\tconst rawPeersMeta = ownDataValue(parsed, 'peerDependenciesMeta')\n\tconst peersMeta = isRecord(rawPeersMeta) ? rawPeersMeta : undefined\n\tconst peers: Dependency[] = selectOrkestrelEntries(rawPeerDependencies).map(\n\t\t([depName, range]) => {\n\t\t\tconst meta = ownDataValue(peersMeta, depName)\n\t\t\treturn isRecord(meta) && ownDataValue(meta, 'optional') === true\n\t\t\t\t? { name: depName, range, optional: true }\n\t\t\t\t: { name: depName, range }\n\t\t},\n\t)\n\n\t// A devDependency that ALSO appears in peerDependencies or dependencies is\n\t// excluded from extras — it already appears as a peer/dependency above,\n\t// and leaving it in extras would land it in `peers ∩ extras`, a blocking\n\t// `validateBlueprint` gate. Middleware-shaped packages dev-install a peer\n\t// for local testing.\n\tconst peerAndDependencyNames = new Set([\n\t\t...selectOrkestrelEntries(rawPeerDependencies).map(([depName]) => depName),\n\t\t...selectOrkestrelEntries(rawDependencies).map(([depName]) => depName),\n\t])\n\tconst generatedDevDependencies = new Set(\n\t\tObject.keys(\n\t\t\tdevDependenciesFor(\n\t\t\t\tblueprint(name, {\n\t\t\t\t\tsrc,\n\t\t\t\t\tapp,\n\t\t\t\t\tdependencies,\n\t\t\t\t\tpeers,\n\t\t\t\t\textras: [],\n\t\t\t\t\tbin,\n\t\t\t\t\tintegration,\n\t\t\t\t\tservices,\n\t\t\t\t\tglobal,\n\t\t\t\t\tshowcase,\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t)\n\t// EVERY devDependency, not only `@orkestrel/`-prefixed ones, is a candidate\n\t// `extras` entry — an external extra (e.g. `zod`) must round-trip through\n\t// derivation exactly like an `@orkestrel/`-scoped one, or a package with a\n\t// HAND-ADDED devDependency (recovered here from the manifest's\n\t// devDependencies minus the generated baseline) audits DRIFTED against\n\t// its own manifest.\n\tconst rawDevDependencies = ownDataValue(parsed, 'devDependencies')\n\tconst devDependencies = isRecord(rawDevDependencies) ? rawDevDependencies : {}\n\tconst extras: Dependency[] = Object.entries(devDependencies)\n\t\t.filter((entry): entry is [string, string] => typeof entry[1] === 'string')\n\t\t.filter(\n\t\t\t([depName]) => !generatedDevDependencies.has(depName) && !peerAndDependencyNames.has(depName),\n\t\t)\n\t\t.map(([depName, range]) => ({ name: depName, range }))\n\treturn blueprint(name, {\n\t\t...(description === undefined ? {} : { description }),\n\t\tkeywords,\n\t\tsrc,\n\t\tapp,\n\t\tdependencies,\n\t\tpeers,\n\t\textras,\n\t\tversion,\n\t\tengines,\n\t\toverrides: [],\n\t\tbin,\n\t\tintegration,\n\t\tservices,\n\t\tglobal,\n\t\tshowcase,\n\t})\n}\n\n/**\n * Whether a target path is absent, empty, or contains nothing but a `.git`\n * directory — the green-field target law `Materializer.materialize` enforces.\n *\n * @param target - The candidate target directory path.\n * @returns `true` when `target` is safe to materialize a fresh package into.\n *\n * @example\n * ```ts\n * import { isVacant } from '@orkestrel/scaffold/server'\n *\n * isVacant('./packages/router-new') // true — absent, empty, or only a .git dir\n * ```\n */\nexport function isVacant(target: string): boolean {\n\tif (!isFilesystemPath(target)) return false\n\tconst status = attempt(() => lstatSync(target))\n\tif (!status.success) return isMissingPathError(status.error)\n\tif (!status.value.isDirectory() || status.value.isSymbolicLink()) return false\n\tconst handle = opendirSync(target)\n\tlet first: string | undefined\n\tlet second = false\n\ttry {\n\t\tfirst = handle.readSync()?.name\n\t\tsecond = first === undefined ? false : handle.readSync() !== null\n\t} finally {\n\t\thandle.closeSync()\n\t}\n\tif (first === undefined) return true\n\tif (second || first !== '.git') return false\n\tconst metadata = lstatSync(join(target, '.git'))\n\treturn metadata.isDirectory() && !metadata.isSymbolicLink()\n}\n\n/**\n * Read a target's current bytes at a set of relative paths into a\n * byte-exact hexadecimal {@link Snapshot} — the I/O that feeds `diffPlan`.\n *\n * @param target - The target directory to read from.\n * @param paths - The plan-relative artifact paths to probe.\n * @returns A snapshot keyed by path; each file maps to its exact lowercase\n * hexadecimal bytes and a directly requested directory maps to `''`\n * (presence only). An absent path is omitted entirely.\n * @throws `ScaffoldError('TARGET', …)` when an EXISTING path fails to read\n * (e.g. `EACCES` / `EPERM`) — carries the offending relative `path` (and\n * the resolved `full` path) in `context`. An absent path is never an\n * error — it is simply omitted, per the return contract above.\n *\n * @example\n * ```ts\n * import { readTarget } from '@orkestrel/scaffold/server'\n *\n * readTarget('./packages/router', ['package.json', 'src/core/index.ts'])\n * // { 'package.json': '7b226e616d65223a…', 'src/core/index.ts': '6578706f7274…' }\n * ```\n */\nexport function readTarget(target: string, paths: readonly string[]): Snapshot {\n\tif (!isFilesystemPath(target)) {\n\t\tthrow new ScaffoldError('TARGET', 'Target path is malformed or exceeds its bounds', { target })\n\t}\n\tconst requested = parsePortablePaths(paths, MAX_COLLECTION_ITEMS)\n\tif (requested === undefined) {\n\t\tthrow new ScaffoldError('TARGET', 'Target snapshot paths are malformed', {\n\t\t\ttarget,\n\t\t\tlimit: MAX_COLLECTION_ITEMS,\n\t\t})\n\t}\n\tlet remaining = MAX_TOTAL_ARTIFACT_BYTES\n\tconst entries: [path: string, hex: string][] = []\n\tfor (const path of requested) {\n\t\tconst full = resolvePhysicalPath(target, path, 'TARGET', 'target')\n\t\tif (!existsSync(full)) continue\n\t\tconst status = attempt(() => lstatSync(full))\n\t\tif (\n\t\t\t!status.success ||\n\t\t\tstatus.value.isSymbolicLink() ||\n\t\t\t(!status.value.isDirectory() &&\n\t\t\t\t(!status.value.isFile() || status.value.nlink !== 1 || status.value.size > remaining))\n\t\t) {\n\t\t\tthrow new ScaffoldError('TARGET', `Failed to read target file at ${path}`, {\n\t\t\t\tpath,\n\t\t\t\tfull,\n\t\t\t\tlimit: MAX_TOTAL_ARTIFACT_BYTES,\n\t\t\t\t...(status.success ? {} : { error: status.error }),\n\t\t\t})\n\t\t}\n\t\tif (status.value.isDirectory()) {\n\t\t\tentries.push([path, ''])\n\t\t\tcontinue\n\t\t}\n\t\tconst hex = readFileHex(\n\t\t\ttarget,\n\t\t\tpath,\n\t\t\t'TARGET',\n\t\t\t'target',\n\t\t\tMath.min(MAX_ARTIFACT_BYTES, remaining),\n\t\t)\n\t\tremaining -= hex.length / 2\n\t\tentries.push([path, hex])\n\t}\n\treturn Object.fromEntries(entries)\n}\n\n/**\n * Read `target/package.json` text — the read that feeds `manifestToDependencies`.\n *\n * @param target - The target directory to read the manifest from.\n * @returns The manifest file's raw text.\n * @throws `ScaffoldError('TARGET', …)` when the manifest is absent or\n * unreadable (e.g. `EACCES` / `EPERM`) — carries the resolved `full` path\n * in `context`.\n *\n * @example\n * ```ts\n * import { readManifest } from '@orkestrel/scaffold/server'\n *\n * readManifest('./packages/router') // '{ \"name\": \"@orkestrel/router\", … }'\n * ```\n */\nexport function readManifest(target: string): string {\n\tif (!isFilesystemPath(target)) {\n\t\tthrow new ScaffoldError('TARGET', 'Manifest target is malformed or exceeds its bounds', {\n\t\t\ttarget,\n\t\t})\n\t}\n\tconst full = join(target, 'package.json')\n\tconst result = attempt(() =>\n\t\treadFileText(target, 'package.json', 'TARGET', 'target', MAX_MANIFEST_BYTES),\n\t)\n\tif (!result.success) {\n\t\tthrow new ScaffoldError('TARGET', `Failed to read manifest at ${full}`, {\n\t\t\ttarget,\n\t\t\tfull,\n\t\t\terror: result.error,\n\t\t})\n\t}\n\treturn result.value\n}\n\n/**\n * Read and validate a vendored host root's `manifest.json`, when present.\n *\n * @param host - The host root to probe.\n * @returns The parsed complete manifest, or `undefined` when `host` has no\n * `manifest.json` — the raw-repo-root fallback (`Materializer` then maps\n * an artifact's `source` to `host` 1:1, no vendored staging indirection).\n * @throws `ScaffoldError('TARGET', …)` when `manifest.json` exists but is\n * unreadable, malformed, membership-corrupted, collision-prone,\n * root-incomplete, or does not map bijectively and case-exactly onto real\n * contained storage files.\n *\n * @example\n * ```ts\n * import { readHostManifest } from '@orkestrel/scaffold/server'\n *\n * readHostManifest('./dist/host') // HostManifest | undefined\n * ```\n */\nexport function readHostManifest(host: string): HostManifest | undefined {\n\tif (!isFilesystemPath(host)) {\n\t\tthrow new ScaffoldError('TARGET', 'Host path is malformed or exceeds its bounds', { host })\n\t}\n\tconst full = resolvePhysicalPath(host, HOST_MANIFEST_PATH, 'TARGET', 'host')\n\tif (!existsSync(full)) return undefined\n\tconst text = attempt(() =>\n\t\treadFileText(host, HOST_MANIFEST_PATH, 'TARGET', 'host', MAX_MANIFEST_BYTES),\n\t)\n\tif (!text.success) {\n\t\tthrow new ScaffoldError('TARGET', `Failed to read host manifest at ${full}`, {\n\t\t\thost,\n\t\t\tfull,\n\t\t\terror: text.error,\n\t\t})\n\t}\n\tconst manifest = parseJSONAs(text.value, isHostManifest)\n\tif (manifest === undefined) {\n\t\tthrow new ScaffoldError('TARGET', `Host manifest at ${full} is malformed`, { host, full })\n\t}\n\tif (manifest.digest !== digestHostManifest(manifest.entries, manifest.roots)) {\n\t\tthrow new ScaffoldError('TARGET', `Host manifest membership at ${full} is corrupted`, {\n\t\t\thost,\n\t\t\tfull,\n\t\t})\n\t}\n\tconst destinationConflict = findFileConflict(manifest.entries.map((entry) => entry.destination))\n\tif (destinationConflict !== undefined) {\n\t\tthrow new ScaffoldError(\n\t\t\t'TARGET',\n\t\t\t`Host manifest destination collision between \"${destinationConflict[0]}\" and \"${destinationConflict[1]}\"`,\n\t\t\t{ host, full, field: 'destination', paths: destinationConflict },\n\t\t)\n\t}\n\tconst storageConflict = findFileConflict([\n\t\tHOST_MANIFEST_PATH,\n\t\t...manifest.entries.map((entry) => entry.storage),\n\t])\n\tif (storageConflict !== undefined) {\n\t\tthrow new ScaffoldError(\n\t\t\t'TARGET',\n\t\t\t`Host manifest storage collision between \"${storageConflict[0]}\" and \"${storageConflict[1]}\"`,\n\t\t\t{ host, full, field: 'storage', paths: storageConflict },\n\t\t)\n\t}\n\tconst rootConflict = findPathConflict(manifest.roots)\n\tif (rootConflict !== undefined) {\n\t\tthrow new ScaffoldError(\n\t\t\t'TARGET',\n\t\t\t`Host manifest root collision between \"${rootConflict[0]}\" and \"${rootConflict[1]}\"`,\n\t\t\t{ host, full, field: 'root', paths: rootConflict },\n\t\t)\n\t}\n\tconst declaredRoots = new Set(manifest.roots)\n\tfor (const entry of manifest.entries) {\n\t\tconst segments = entry.destination.split('/')\n\t\tfor (let index = 1; index < segments.length; index += 1) {\n\t\t\tconst root = segments.slice(0, index).join('/')\n\t\t\tif (!declaredRoots.has(root)) {\n\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t'TARGET',\n\t\t\t\t\t`Host manifest does not declare destination root \"${root}\"`,\n\t\t\t\t\t{ host, full, root, destination: entry.destination },\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\tfor (const root of manifest.roots) {\n\t\tconst foldedRoot = root.toLowerCase()\n\t\tconst file = manifest.entries.find((entry) => {\n\t\t\tconst destination = entry.destination.toLowerCase()\n\t\t\treturn foldedRoot === destination || foldedRoot.startsWith(`${destination}/`)\n\t\t})\n\t\tif (file !== undefined) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'TARGET',\n\t\t\t\t`Host manifest directory \"${root}\" conflicts with file \"${file.destination}\"`,\n\t\t\t\t{ host, full, root, destination: file.destination },\n\t\t\t)\n\t\t}\n\t}\n\tconst listed = attempt(() => listFiles(host))\n\tif (!listed.success) {\n\t\tthrow new ScaffoldError('TARGET', `Failed to inventory host storage at ${host}`, {\n\t\t\thost,\n\t\t\tfull,\n\t\t\terror: listed.error,\n\t\t})\n\t}\n\tconst stored = listed.value.filter((path) => path !== HOST_MANIFEST_PATH)\n\tconst storedConflict = findPathConflict(stored)\n\tif (storedConflict !== undefined) {\n\t\tthrow new ScaffoldError(\n\t\t\t'TARGET',\n\t\t\t`Host storage collision between \"${storedConflict[0]}\" and \"${storedConflict[1]}\"`,\n\t\t\t{ host, full, paths: storedConflict },\n\t\t)\n\t}\n\tconst storedByPath = new Map(stored.map((path) => [path.toLowerCase(), path]))\n\tconst declaredStorage = new Set(manifest.entries.map((entry) => entry.storage.toLowerCase()))\n\tfor (const path of stored) {\n\t\tif (!declaredStorage.has(path.toLowerCase())) {\n\t\t\tthrow new ScaffoldError('TARGET', `Host storage file \"${path}\" is not declared`, {\n\t\t\t\thost,\n\t\t\t\tfull,\n\t\t\t\tpath,\n\t\t\t})\n\t\t}\n\t}\n\tfor (const entry of manifest.entries) {\n\t\tconst storedPath = storedByPath.get(entry.storage.toLowerCase())\n\t\tif (storedPath === undefined || storedPath !== entry.storage) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'TARGET',\n\t\t\t\t`Host storage file \"${entry.storage}\" is missing or case-mismatched`,\n\t\t\t\t{ host, full, storage: entry.storage, actual: storedPath },\n\t\t\t)\n\t\t}\n\t\tconst storage = resolvePhysicalPath(host, entry.storage, 'TARGET', 'host')\n\t\tconst status = attempt(() => lstatSync(storage))\n\t\tif (\n\t\t\t!status.success ||\n\t\t\t!status.value.isFile() ||\n\t\t\tstatus.value.isSymbolicLink() ||\n\t\t\tstatus.value.nlink !== 1\n\t\t) {\n\t\t\tthrow new ScaffoldError('TARGET', `Host storage at \"${entry.storage}\" is not a file`, {\n\t\t\t\thost,\n\t\t\t\tfull,\n\t\t\t\tstorage: entry.storage,\n\t\t\t\terror: status.success ? undefined : status.error,\n\t\t\t})\n\t\t}\n\t}\n\treturn manifest\n}\n\n/**\n * Read one contained file as exact lowercase hexadecimal bytes.\n *\n * @param root - The declared containing root.\n * @param path - The root-relative file path.\n * @param code - The coded failure for containment or reading.\n * @param boundary - The boundary name used in diagnostics.\n * @returns The exact file bytes encoded as lowercase hexadecimal.\n */\nexport function readFileHex(\n\troot: string,\n\tpath: string,\n\tcode: ScaffoldErrorCode,\n\tboundary: string,\n\tlimit = MAX_ARTIFACT_BYTES,\n): string {\n\tif (!Number.isSafeInteger(limit) || limit < 0 || limit > MAX_ARTIFACT_BYTES) {\n\t\tthrow new ScaffoldError(code, `Invalid file byte limit at ${path}`, { path, root, limit })\n\t}\n\tif (!isPortablePath(path)) {\n\t\tthrow new ScaffoldError(code, `Unsafe file path at ${path}`, { path, root })\n\t}\n\tconst full = resolvePhysicalPath(root, path, code, boundary)\n\tconst status = attempt(() => lstatSync(full))\n\tif (\n\t\t!status.success ||\n\t\t!status.value.isFile() ||\n\t\tstatus.value.isSymbolicLink() ||\n\t\tstatus.value.nlink !== 1\n\t) {\n\t\tthrow new ScaffoldError(code, `File is not a physical readable file at ${path}`, {\n\t\t\tpath,\n\t\t\tfull,\n\t\t\t...(status.success ? {} : { error: status.error }),\n\t\t})\n\t}\n\tconst opened = attempt(() => openSync(full, 'r'))\n\tif (!opened.success) {\n\t\tthrow new ScaffoldError(code, `Failed to read file at ${path}`, {\n\t\t\tpath,\n\t\t\tfull,\n\t\t\terror: opened.error,\n\t\t})\n\t}\n\tconst handle = opened.value\n\tconst result = attempt(() => {\n\t\tconst current = fstatSync(handle)\n\t\tif (\n\t\t\t!current.isFile() ||\n\t\t\tcurrent.nlink !== 1 ||\n\t\t\tcurrent.dev !== status.value.dev ||\n\t\t\tcurrent.ino !== status.value.ino\n\t\t) {\n\t\t\tthrow new ScaffoldError(code, `File changed before reading at ${path}`, { path, full })\n\t\t}\n\t\tif (current.size > limit) {\n\t\t\tthrow new ScaffoldError(code, `File exceeds the artifact limit at ${path}`, {\n\t\t\t\tpath,\n\t\t\t\tfull,\n\t\t\t\tlimit,\n\t\t\t\tsize: current.size,\n\t\t\t})\n\t\t}\n\t\tconst bytes = Buffer.alloc(current.size)\n\t\tlet offset = 0\n\t\twhile (offset < bytes.byteLength) {\n\t\t\tconst length = readSync(handle, bytes, offset, bytes.byteLength - offset, offset)\n\t\t\tif (length === 0) break\n\t\t\toffset += length\n\t\t}\n\t\tconst overflow = Buffer.alloc(1)\n\t\tconst extra = readSync(handle, overflow, 0, overflow.byteLength, offset)\n\t\tconst after = fstatSync(handle)\n\t\tconst pathStatus = lstatSync(full)\n\t\tif (\n\t\t\toffset !== bytes.byteLength ||\n\t\t\textra !== 0 ||\n\t\t\tafter.dev !== current.dev ||\n\t\t\tafter.ino !== current.ino ||\n\t\t\tafter.mtimeMs !== current.mtimeMs ||\n\t\t\tafter.size !== current.size ||\n\t\t\t!pathStatus.isFile() ||\n\t\t\tpathStatus.isSymbolicLink() ||\n\t\t\tpathStatus.nlink !== 1 ||\n\t\t\tpathStatus.dev !== current.dev ||\n\t\t\tpathStatus.ino !== current.ino\n\t\t) {\n\t\t\tthrow new ScaffoldError(code, `File changed while reading at ${path}`, { path, full })\n\t\t}\n\t\treturn bytesToHex(bytes)\n\t})\n\tconst closed = attempt(() => closeSync(handle))\n\tif (!result.success) throw result.error\n\tif (!closed.success) {\n\t\tthrow new ScaffoldError(code, `Failed to close file at ${path}`, {\n\t\t\tpath,\n\t\t\tfull,\n\t\t\terror: closed.error,\n\t\t})\n\t}\n\treturn result.value\n}\n\n/**\n * Read one contained physical file as bounded UTF-8 text.\n *\n * @param root - The declared containing root.\n * @param path - The root-relative file path.\n * @param code - The coded failure for containment or reading.\n * @param boundary - The boundary name used in diagnostics.\n * @returns The exact file bytes decoded as UTF-8 text.\n */\nexport function readFileText(\n\troot: string,\n\tpath: string,\n\tcode: ScaffoldErrorCode,\n\tboundary: string,\n\tlimit = MAX_ARTIFACT_BYTES,\n): string {\n\tconst decoded = attempt(() =>\n\t\tnew TextDecoder('utf-8', { fatal: true }).decode(\n\t\t\tBuffer.from(readFileHex(root, path, code, boundary, limit), 'hex'),\n\t\t),\n\t)\n\tif (!decoded.success) {\n\t\tthrow new ScaffoldError(code, `File is not valid UTF-8 at ${path}`, {\n\t\t\tpath,\n\t\t\troot,\n\t\t\terror: decoded.error,\n\t\t})\n\t}\n\treturn decoded.value\n}\n\n/**\n * Recursively list a directory's files as root-relative paths.\n *\n * @param root - The directory to list.\n * @returns Root-relative file paths (posix-style `/` separators), code-unit\n * sorted, or `[]` when `root` is absent.\n *\n * @example\n * ```ts\n * import { listFiles } from '@orkestrel/scaffold/server'\n *\n * listFiles('./dist/host/.claude/agents') // ['scout.md', 'builder.md', …]\n * ```\n */\nexport function listFiles(root: string): readonly string[] {\n\tif (!isFilesystemPath(root)) {\n\t\tthrow new ScaffoldError('TARGET', 'Listing root is malformed or exceeds its bounds', { root })\n\t}\n\tconst rootStatus = attempt(() => lstatSync(root))\n\tif (!rootStatus.success) {\n\t\tif (isMissingPathError(rootStatus.error)) return []\n\t\tthrow new ScaffoldError('TARGET', 'Failed to inspect listing root', {\n\t\t\troot,\n\t\t\terror: rootStatus.error,\n\t\t})\n\t}\n\tif (!rootStatus.value.isDirectory() || rootStatus.value.isSymbolicLink()) {\n\t\tthrow new ScaffoldError('TARGET', 'Listing root is not a physical directory', { root })\n\t}\n\tconst files: string[] = []\n\tconst pending = [{ full: root, path: '', depth: 0 }]\n\tlet visited = 0\n\twhile (pending.length > 0) {\n\t\tconst current = pending.pop()\n\t\tif (current === undefined) break\n\t\tconst handle = opendirSync(current.full)\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst entry = handle.readSync()\n\t\t\t\tif (entry === null) break\n\t\t\t\tvisited += 1\n\t\t\t\tif (visited > MAX_HOST_ENTRIES) {\n\t\t\t\t\tthrow new ScaffoldError('TARGET', `Host traversal exceeds ${MAX_HOST_ENTRIES} entries`, {\n\t\t\t\t\t\troot,\n\t\t\t\t\t\tlimit: MAX_HOST_ENTRIES,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst path = current.path === '' ? entry.name : `${current.path}/${entry.name}`\n\t\t\t\tif (!isPortablePath(path)) {\n\t\t\t\t\tthrow new ScaffoldError('TARGET', 'Filesystem traversal found a non-portable path')\n\t\t\t\t}\n\t\t\t\tif (entry.isDirectory() && !entry.isSymbolicLink()) {\n\t\t\t\t\tconst depth = current.depth + 1\n\t\t\t\t\tif (depth > MAX_HOST_DEPTH) {\n\t\t\t\t\t\tthrow new ScaffoldError('TARGET', `Host traversal exceeds depth ${MAX_HOST_DEPTH}`, {\n\t\t\t\t\t\t\troot,\n\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\tlimit: MAX_HOST_DEPTH,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tpending.push({ full: join(current.full, entry.name), path, depth })\n\t\t\t\t} else {\n\t\t\t\t\tfiles.push(path)\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\thandle.closeSync()\n\t\t}\n\t}\n\treturn files.sort()\n}\n\n/**\n * Recursively list a directory's descendant directories.\n *\n * @param root - The directory to list.\n * @returns Root-relative POSIX directory paths in code-unit order.\n */\nexport function listDirectories(root: string): readonly string[] {\n\tif (!isFilesystemPath(root)) {\n\t\tthrow new ScaffoldError('TARGET', 'Listing root is malformed or exceeds its bounds', { root })\n\t}\n\tconst rootStatus = attempt(() => lstatSync(root))\n\tif (!rootStatus.success) {\n\t\tif (isMissingPathError(rootStatus.error)) return []\n\t\tthrow new ScaffoldError('TARGET', 'Failed to inspect listing root', {\n\t\t\troot,\n\t\t\terror: rootStatus.error,\n\t\t})\n\t}\n\tif (!rootStatus.value.isDirectory() || rootStatus.value.isSymbolicLink()) {\n\t\tthrow new ScaffoldError('TARGET', 'Listing root is not a physical directory', { root })\n\t}\n\tconst directories: string[] = []\n\tconst pending = [{ full: root, path: '', depth: 0 }]\n\tlet visited = 0\n\twhile (pending.length > 0) {\n\t\tconst current = pending.pop()\n\t\tif (current === undefined) break\n\t\tconst handle = opendirSync(current.full)\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst entry = handle.readSync()\n\t\t\t\tif (entry === null) break\n\t\t\t\tvisited += 1\n\t\t\t\tif (visited > MAX_HOST_ENTRIES) {\n\t\t\t\t\tthrow new ScaffoldError('TARGET', `Host traversal exceeds ${MAX_HOST_ENTRIES} entries`, {\n\t\t\t\t\t\troot,\n\t\t\t\t\t\tlimit: MAX_HOST_ENTRIES,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (!entry.isDirectory() || entry.isSymbolicLink()) continue\n\t\t\t\tconst path = current.path === '' ? entry.name : `${current.path}/${entry.name}`\n\t\t\t\tif (!isPortablePath(path)) {\n\t\t\t\t\tthrow new ScaffoldError('TARGET', 'Filesystem traversal found a non-portable path')\n\t\t\t\t}\n\t\t\t\tconst depth = current.depth + 1\n\t\t\t\tif (depth > MAX_HOST_DEPTH) {\n\t\t\t\t\tthrow new ScaffoldError('TARGET', `Host traversal exceeds depth ${MAX_HOST_DEPTH}`, {\n\t\t\t\t\t\troot,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tlimit: MAX_HOST_DEPTH,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tdirectories.push(path)\n\t\t\t\tpending.push({ full: join(current.full, entry.name), path, depth })\n\t\t\t}\n\t\t} finally {\n\t\t\thandle.closeSync()\n\t\t}\n\t}\n\treturn directories.sort()\n}\n\n/**\n * Map a repo-relative path to its vendored-host STAGING path, per the\n * dotfile-mapping rule `stageHost` writes into `manifest.json`.\n *\n * @param path - The repo-relative source path (e.g. `.claude/agents/reviewer.md`).\n * @returns The mapped storage path: a leading-dot TOP-LEVEL FILE maps to\n * `dotfiles/<name-without-dot>`; a leading-dot DIRECTORY segment loses its\n * dot wherever it appears; an undotted path is unchanged.\n *\n * @example\n * ```ts\n * import { storagePath } from '@orkestrel/scaffold/server'\n *\n * storagePath('.gitignore') // 'dotfiles/gitignore'\n * storagePath('.claude/agents/reviewer.md') // 'claude/agents/reviewer.md'\n * storagePath('.github/workflows/ci.yml') // 'github/workflows/ci.yml'\n * storagePath('AGENTS.md') // 'AGENTS.md'\n * ```\n */\nexport function storagePath(path: string): string {\n\tconst segments = path.split('/')\n\tif (segments.length === 1) {\n\t\tconst name = segments[0]\n\t\tif (name === undefined) return path\n\t\treturn name.startsWith('.') ? `dotfiles/${name.slice(1)}` : name\n\t}\n\treturn segments.map((segment) => (segment.startsWith('.') ? segment.slice(1) : segment)).join('/')\n}\n\n/**\n * Stage the vendored host set (byte-preserved copies + `manifest.json`) from\n * a repo root into an output directory — the BUILD-time primitive the\n * `build:host` npm script now calls directly (replacing a standalone build\n * script); `Materializer.materialize` is the RUNTIME reader of what this\n * writes (via `hostRoot` / `readHostManifest`).\n *\n * @param root - The repo root every `paths` entry resolves against.\n * @param out - The output directory to replace after staging completes.\n * @param paths - The repo-relative file/directory entries to stage; defaults\n * to the package's own vendored set (`HOST_PATHS`) — a caller passes an\n * explicit list only to stage an arbitrary/test set.\n * @remarks\n * Every source, path collision, and root/output relationship is preflighted\n * before output mutation. Files are copied into a temporary sibling; the\n * completed staging tree atomically replaces `out`, with rollback when the\n * swap fails. The manifest records both sorted file `entries` and the\n * complete sorted directory `roots` inventory so destructive consumers can\n * distinguish a declared-empty root from a truncated manifest.\n * @returns The written manifest's entries (`{ storage, destination, executable }`).\n * @throws `ScaffoldError('TARGET', …)` for an invalid/escaping source or path\n * collision, and `ScaffoldError('WRITE', …)` for staging/swap failures.\n *\n * @example\n * ```ts\n * import { stageHost } from '@orkestrel/scaffold/server'\n *\n * const entries = stageHost(process.cwd(), 'dist/host')\n * entries.length // number of files staged\n * ```\n */\nexport function stageHost(\n\troot: string,\n\tout: string,\n\tpaths: readonly string[] = HOST_PATHS,\n): readonly ManifestEntry[] {\n\tif (!isFilesystemPath(root) || !isFilesystemPath(out)) {\n\t\tthrow new ScaffoldError('TARGET', 'Host root or output is malformed or exceeds its bounds', {\n\t\t\troot,\n\t\t\tout,\n\t\t})\n\t}\n\tconst copiedPaths = parsePortablePaths(paths, MAX_HOST_ENTRIES)\n\tif (copiedPaths === undefined) {\n\t\tthrow new ScaffoldError('TARGET', 'Host source paths are malformed', {\n\t\t\troot,\n\t\t\tout,\n\t\t\tlimit: MAX_HOST_ENTRIES,\n\t\t})\n\t}\n\tconst destinations: string[] = []\n\tconst roots: string[] = []\n\tconst resolvedRoot = resolveRealPath(resolve(root))\n\tconst resolvedOut = resolveRealPath(resolve(out))\n\tif (resolvedRoot === resolvedOut || resolvedRoot.startsWith(resolvedOut + sep)) {\n\t\tthrow new ScaffoldError('TARGET', `Host output at ${out} contains the source root`, {\n\t\t\troot,\n\t\t\tout,\n\t\t})\n\t}\n\tfor (const path of copiedPaths) {\n\t\tif (!isPortablePath(path) || isSensitiveHostPath(path)) {\n\t\t\tthrow new ScaffoldError('TARGET', `Invalid host source path at ${path}`, { path, root })\n\t\t}\n\t\tconst absolute = resolvePhysicalPath(root, path, 'TARGET', 'host')\n\t\tif (!existsSync(absolute)) {\n\t\t\tthrow new ScaffoldError('TARGET', `Missing host source at ${path}`, { path, root })\n\t\t}\n\t\tconst status = attempt(() => lstatSync(absolute))\n\t\tif (!status.success) {\n\t\t\tthrow new ScaffoldError('TARGET', `Failed to inspect host source at ${path}`, {\n\t\t\t\tpath,\n\t\t\t\troot,\n\t\t\t\terror: status.error,\n\t\t\t})\n\t\t}\n\t\tif (status.value.isSymbolicLink()) {\n\t\t\tthrow new ScaffoldError('TARGET', `Host source is linked at ${path}`, { path, root })\n\t\t}\n\t\tif (status.value.isDirectory()) {\n\t\t\tconst resolvedSource = resolveRealPath(absolute)\n\t\t\tif (resolvedOut === resolvedSource || resolvedOut.startsWith(resolvedSource + sep)) {\n\t\t\t\tthrow new ScaffoldError('TARGET', `Host output at ${out} is inside source ${path}`, {\n\t\t\t\t\troot,\n\t\t\t\t\tout,\n\t\t\t\t\tpath,\n\t\t\t\t})\n\t\t\t}\n\t\t\troots.push(path)\n\t\t\tfor (const nested of listDirectories(absolute)) roots.push(`${path}/${nested}`)\n\t\t\tfor (const nested of listFiles(absolute)) destinations.push(`${path}/${nested}`)\n\t\t} else {\n\t\t\tdestinations.push(path)\n\t\t}\n\t}\n\tif (destinations.length > MAX_HOST_ENTRIES || roots.length > MAX_HOST_ENTRIES) {\n\t\tthrow new ScaffoldError('TARGET', 'Host source inventory exceeds the entry limit', {\n\t\t\troot,\n\t\t\tlimit: MAX_HOST_ENTRIES,\n\t\t})\n\t}\n\n\tconst entries: ManifestEntry[] = []\n\tconst expectations: WriteExpectation[] = []\n\tlet totalBytes = 0\n\tfor (const destination of destinations) {\n\t\tif (isSensitiveHostPath(destination)) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'TARGET',\n\t\t\t\t`Sensitive host source is not vendorable at ${destination}`,\n\t\t\t\t{\n\t\t\t\t\troot,\n\t\t\t\t\tdestination,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tconst source = resolvePhysicalPath(root, destination, 'TARGET', 'host')\n\t\tconst status = attempt(() => lstatSync(source))\n\t\tif (\n\t\t\t!status.success ||\n\t\t\t!status.value.isFile() ||\n\t\t\tstatus.value.isSymbolicLink() ||\n\t\t\tstatus.value.nlink !== 1\n\t\t) {\n\t\t\tthrow new ScaffoldError('TARGET', `Host source is not a readable file at ${destination}`, {\n\t\t\t\troot,\n\t\t\t\tdestination,\n\t\t\t\terror: status.success ? undefined : status.error,\n\t\t\t})\n\t\t}\n\t\ttotalBytes += status.value.size\n\t\tif (totalBytes > MAX_TOTAL_ARTIFACT_BYTES) {\n\t\t\tthrow new ScaffoldError('TARGET', 'Host source inventory exceeds the aggregate byte limit', {\n\t\t\t\troot,\n\t\t\t\tlimit: MAX_TOTAL_ARTIFACT_BYTES,\n\t\t\t})\n\t\t}\n\t\texpectations.push(\n\t\t\tObject.freeze({\n\t\t\t\tpath: destination,\n\t\t\t\tshape: 'file',\n\t\t\t\tdevice: status.value.dev,\n\t\t\t\tinode: status.value.ino,\n\t\t\t\tmodified: status.value.mtimeMs,\n\t\t\t\tsize: status.value.size,\n\t\t\t\tdigest: digestFile(source),\n\t\t\t}),\n\t\t)\n\t\tconst storage = storagePath(destination)\n\t\tconst executable = destination.endsWith('.sh')\n\t\tentries.push({ storage, destination, executable })\n\t\tconst segments = destination.split('/')\n\t\tfor (let index = 1; index < segments.length; index += 1) {\n\t\t\troots.push(segments.slice(0, index).join('/'))\n\t\t}\n\t}\n\tentries.sort((a, b) =>\n\t\ta.destination < b.destination ? -1 : a.destination > b.destination ? 1 : 0,\n\t)\n\tconst destinationConflict = findFileConflict(entries.map((entry) => entry.destination))\n\tif (destinationConflict !== undefined) {\n\t\tthrow new ScaffoldError(\n\t\t\t'TARGET',\n\t\t\t`Destination collision between \"${destinationConflict[0]}\" and \"${destinationConflict[1]}\"`,\n\t\t\t{ paths: destinationConflict },\n\t\t)\n\t}\n\tconst storageConflict = findFileConflict(entries.map((entry) => entry.storage))\n\tif (storageConflict !== undefined) {\n\t\tconst storageDestinations = entries\n\t\t\t.filter((entry) => entry.storage.toLowerCase() === storageConflict[0].toLowerCase())\n\t\t\t.map((entry) => entry.destination)\n\t\tthrow new ScaffoldError(\n\t\t\t'TARGET',\n\t\t\t`Storage collision at \"${storageConflict[0]}\" between destinations \"${storageDestinations[0] ?? ''}\" and \"${storageDestinations[1] ?? ''}\"`,\n\t\t\t{ storage: storageConflict[0], destinations: storageDestinations },\n\t\t)\n\t}\n\tconst manifestConflict = findFileConflict([\n\t\tHOST_MANIFEST_PATH,\n\t\t...entries.map((entry) => entry.storage),\n\t])\n\tif (manifestConflict !== undefined) {\n\t\tthrow new ScaffoldError(\n\t\t\t'TARGET',\n\t\t\t`Storage path \"${manifestConflict[1]}\" collides with reserved manifest.json`,\n\t\t\t{ paths: manifestConflict },\n\t\t)\n\t}\n\tconst uniqueRoots = [...new Set(roots)].sort()\n\tif (uniqueRoots.length > MAX_HOST_ENTRIES) {\n\t\tthrow new ScaffoldError('TARGET', 'Host source inventory exceeds the entry limit', {\n\t\t\troot,\n\t\t\tlimit: MAX_HOST_ENTRIES,\n\t\t})\n\t}\n\tconst rootConflict = findPathConflict(uniqueRoots)\n\tif (rootConflict !== undefined) {\n\t\tthrow new ScaffoldError(\n\t\t\t'TARGET',\n\t\t\t`Directory collision between \"${rootConflict[0]}\" and \"${rootConflict[1]}\"`,\n\t\t\t{ paths: rootConflict },\n\t\t)\n\t}\n\tconst manifest: HostManifest = {\n\t\tentries,\n\t\troots: uniqueRoots,\n\t\tdigest: digestHostManifest(entries, uniqueRoots),\n\t}\n\tconst parent = dirname(resolve(out))\n\tconst name = basename(resolve(out))\n\tconst token = randomUUID()\n\tconst staging = resolveContainedPath(parent, `.${name}.stage-${token}`, 'WRITE', 'output')\n\tconst backup = resolveContainedPath(parent, `.${name}.backup-${token}`, 'WRITE', 'output')\n\tlet stagingAnchor: WriteAnchor | undefined\n\tlet parentDirectory: WriteDirectoryResult | undefined\n\tconst staged = attempt(() => {\n\t\tparentDirectory = createWriteDirectory(parent, 'host output parent')\n\t\tvalidateWriteAnchor(parentDirectory.anchor, 'host output parent')\n\t\tmkdirSync(staging, { recursive: false })\n\t\tvalidateWriteAnchor(parentDirectory.anchor, 'host output parent')\n\t\tconst stagingStatus = lstatSync(staging)\n\t\tif (!stagingStatus.isDirectory() || stagingStatus.isSymbolicLink()) {\n\t\t\tthrow new ScaffoldError('WRITE', 'Host staging root is not a physical directory', {\n\t\t\t\tstaging,\n\t\t\t})\n\t\t}\n\t\tstagingAnchor = Object.freeze({\n\t\t\tpath: staging,\n\t\t\tdevice: stagingStatus.dev,\n\t\t\tinode: stagingStatus.ino,\n\t\t})\n\t\tfor (const entry of entries) {\n\t\t\tvalidateWriteAnchor(parentDirectory.anchor, 'host output parent')\n\t\t\tvalidateWriteAnchor(stagingAnchor, 'host staging root')\n\t\t\tconst source = resolvePhysicalPath(root, entry.destination, 'TARGET', 'host')\n\t\t\tconst expectation = expectations.find((candidate) => candidate.path === entry.destination)\n\t\t\tconst sourceStatus = lstatSync(source)\n\t\t\tconst sourceDigest = digestFile(source)\n\t\t\tif (\n\t\t\t\texpectation === undefined ||\n\t\t\t\t!sourceStatus.isFile() ||\n\t\t\t\tsourceStatus.isSymbolicLink() ||\n\t\t\t\tsourceStatus.nlink !== 1 ||\n\t\t\t\tsourceStatus.dev !== expectation.device ||\n\t\t\t\tsourceStatus.ino !== expectation.inode ||\n\t\t\t\tsourceStatus.mtimeMs !== expectation.modified ||\n\t\t\t\tsourceStatus.size !== expectation.size ||\n\t\t\t\tsourceDigest !== expectation.digest\n\t\t\t) {\n\t\t\t\tthrow new ScaffoldError('TARGET', `Host source changed at ${entry.destination}`, {\n\t\t\t\t\troot,\n\t\t\t\t\tdestination: entry.destination,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst destination = resolvePhysicalPath(staging, entry.storage, 'WRITE', 'staging')\n\t\t\tmkdirSync(dirname(destination), { recursive: true })\n\t\t\tvalidateWriteAnchor(stagingAnchor, 'host staging root')\n\t\t\tconst containedDestination = resolvePhysicalPath(staging, entry.storage, 'WRITE', 'staging')\n\t\t\tcopyFileSync(source, containedDestination, FS_CONSTANTS.COPYFILE_EXCL)\n\t\t\tconst copiedStatus = lstatSync(containedDestination)\n\t\t\tif (\n\t\t\t\t!copiedStatus.isFile() ||\n\t\t\t\tcopiedStatus.isSymbolicLink() ||\n\t\t\t\tcopiedStatus.nlink !== 1 ||\n\t\t\t\tdigestFile(containedDestination) !== expectation.digest\n\t\t\t) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Host staging copy changed at ${entry.destination}`, {\n\t\t\t\t\tstaging,\n\t\t\t\t\tdestination: entry.destination,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\twriteFileSync(join(staging, HOST_MANIFEST_PATH), `${JSON.stringify(manifest, null, '\\t')}\\n`, {\n\t\t\tencoding: 'utf8',\n\t\t\tflag: 'wx',\n\t\t})\n\t\tvalidateWriteAnchor(parentDirectory.anchor, 'host output parent')\n\t\tif (readHostManifest(staging) === undefined) {\n\t\t\tthrow new ScaffoldError('WRITE', 'Staged host manifest could not be verified', {\n\t\t\t\tstaging,\n\t\t\t})\n\t\t}\n\t})\n\tif (!staged.success) {\n\t\tconst identity = stagingAnchor\n\t\tconst cleanup =\n\t\t\tidentity === undefined\n\t\t\t\t? undefined\n\t\t\t\t: attempt(() => {\n\t\t\t\t\t\tvalidateWriteAnchor(identity, 'host staging root')\n\t\t\t\t\t\trmSync(staging, { recursive: true })\n\t\t\t\t\t})\n\t\tconst parentCleanup = attempt(() => {\n\t\t\tfor (const created of [...(parentDirectory?.created ?? [])].reverse()) {\n\t\t\t\tvalidateWriteAnchor(created, 'host output parent')\n\t\t\t\trmdirSync(created.path)\n\t\t\t}\n\t\t})\n\t\tthrow new ScaffoldError('WRITE', `Failed to stage host output at ${out}`, {\n\t\t\troot,\n\t\t\tout,\n\t\t\terror: staged.error,\n\t\t\tcleanup: cleanup?.success === false ? cleanup.error : undefined,\n\t\t\tparentCleanup: parentCleanup.success ? undefined : parentCleanup.error,\n\t\t})\n\t}\n\tif (parentDirectory === undefined) {\n\t\tthrow new ScaffoldError('WRITE', 'Host output parent was not established', { out })\n\t}\n\tvalidateWriteAnchor(parentDirectory.anchor, 'host output parent')\n\treplaceDirectory(staging, out, backup)\n\n\treturn entries\n}\n\n/**\n * Resolve the absolute host-storage path for a host-origin artifact's\n * `source`, manifest-aware.\n *\n * @param manifest - The parsed complete host manifest, or `undefined`\n * when the host carries none (raw-repo-root fallback).\n * @param source - The artifact's `source` (or `path`) to resolve.\n * @param host - The resolved host root the path is joined against.\n * @returns `join(host, source)` when `manifest` is `undefined` (no vendored\n * staging indirection); when `manifest` is present, `join(host,\n * entries[0].storage)` for the SINGLE manifest entry whose `destination`\n * equals `source`, or `undefined` when zero or more than one entry matches\n * (`source` names a directory, or the manifest is ambiguous — no single\n * storage file to point at).\n *\n * @example\n * ```ts\n * import { locateHostSource } from '@orkestrel/scaffold/server'\n *\n * locateHostSource(undefined, 'package.json', './dist/host') // './dist/host/package.json'\n * locateHostSource(\n * {\n * entries: [{ storage: 'pkg.tmpl', destination: 'package.json', executable: false }],\n * roots: [],\n * digest: '3b52f19450237ea4cfb39bc7a77b1e5094b52a8ff1fc9c02fd68b13ad088aa0f',\n * },\n * 'package.json',\n * './dist/host',\n * )\n * // './dist/host/pkg.tmpl'\n * ```\n */\nexport function locateHostSource(\n\tmanifest: HostManifest | undefined,\n\tsource: string,\n\thost: string,\n): string | undefined {\n\tif (manifest === undefined) return join(host, source)\n\tconst entries = manifest.entries.filter((entry) => entry.destination === source)\n\tif (entries.length !== 1) return undefined\n\tconst [entry] = entries\n\treturn entry === undefined ? undefined : join(host, entry.storage)\n}\n\n/**\n * Map a manifest destination from an artifact's source prefix to its target prefix.\n *\n * @param artifact - The host artifact carrying the target path and optional source.\n * @param destination - The matched manifest destination.\n * @returns The exact target-relative path for the matched manifest file.\n * @throws `ScaffoldError('INVALID', …)` when `destination` is outside the source prefix.\n */\nexport function remapArtifactPath(artifact: HostArtifact, destination: string): string {\n\tconst source = artifact.source ?? artifact.path\n\tif (destination === source) return artifact.path\n\tif (!destination.startsWith(`${source}/`)) {\n\t\tthrow new ScaffoldError('INVALID', `Manifest destination does not match ${source}`, {\n\t\t\tsource,\n\t\t\tdestination,\n\t\t})\n\t}\n\treturn `${artifact.path}/${destination.slice(source.length + 1)}`\n}\n\n/**\n * Rehydrate a `Plan`'s `host`-origin artifacts with their exact byte hex read\n * from `host` — manifest-aware, via `locateHostSource`.\n *\n * @param plan - The plan to hydrate.\n * @param host - The resolved host root to read from.\n * @returns A new `Plan` whose file-shaped `host` artifacts carry exact `hex`.\n * Directory-shaped host artifacts expand into one byte-aware artifact\n * per file, preserving their group and mapping the artifact/source prefixes.\n * `template` / `computed` artifacts pass through untouched.\n * @throws `ScaffoldError('TARGET', …)` when the host is not a readable\n * directory, a present manifest is invalid/incomplete, or a required source\n * is absent, escaping, not a file/directory as declared, or unreadable.\n *\n * @example\n * ```ts\n * import { hydratePlan } from '@orkestrel/scaffold/server'\n *\n * const hydrated = hydratePlan(plan, './dist/host')\n * ```\n */\nexport function hydratePlan(plan: Plan, host: string): Plan {\n\tif (!isFilesystemPath(host)) {\n\t\tthrow new ScaffoldError('TARGET', 'Host path is malformed or exceeds its bounds', { host })\n\t}\n\tconst owned = snapshotPlan(plan)\n\tconst status = attempt(() => lstatSync(host))\n\tif (!status.success || !status.value.isDirectory() || status.value.isSymbolicLink()) {\n\t\tthrow new ScaffoldError('TARGET', `Host root is not a readable directory at ${host}`, {\n\t\t\thost,\n\t\t\terror: status.success ? undefined : status.error,\n\t\t})\n\t}\n\tconst manifest = readHostManifest(host)\n\tconst artifacts: Artifact[] = []\n\tlet remaining = MAX_TOTAL_ARTIFACT_BYTES\n\tfor (const artifact of owned.artifacts) {\n\t\tif (artifact.origin !== 'host') remaining -= Buffer.byteLength(artifact.content, 'utf8')\n\t}\n\tfor (const artifact of owned.artifacts) {\n\t\tif (artifact.origin !== 'host') {\n\t\t\tartifacts.push(artifact)\n\t\t\tcontinue\n\t\t}\n\t\tconst source = artifact.source ?? artifact.path\n\t\tif (!isPortablePath(source) || isSensitiveHostPath(source)) {\n\t\t\tthrow new ScaffoldError('TARGET', `Unsafe host artifact source at ${source}`, {\n\t\t\t\thost,\n\t\t\t\tsource,\n\t\t\t})\n\t\t}\n\t\tconst full = locateHostSource(manifest, source, host)\n\t\tconst relative = full === undefined ? undefined : relativeOf(host, full).split(sep).join('/')\n\t\tif (relative !== undefined) {\n\t\t\tconst contained = resolvePhysicalPath(host, relative, 'TARGET', 'host')\n\t\t\tif (existsSync(contained)) {\n\t\t\t\tconst exact = attempt(() => lstatSync(contained))\n\t\t\t\tif (!exact.success) {\n\t\t\t\t\tthrow new ScaffoldError('TARGET', `Failed to inspect host artifact source at ${source}`, {\n\t\t\t\t\t\thost,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\terror: exact.error,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (exact.value.isFile() && !exact.value.isSymbolicLink() && exact.value.nlink === 1) {\n\t\t\t\t\tconst hex = readFileHex(\n\t\t\t\t\t\thost,\n\t\t\t\t\t\trelative,\n\t\t\t\t\t\t'TARGET',\n\t\t\t\t\t\t'host',\n\t\t\t\t\t\tMath.min(MAX_ARTIFACT_BYTES, remaining),\n\t\t\t\t\t)\n\t\t\t\t\tremaining -= hex.length / 2\n\t\t\t\t\tartifacts.push({\n\t\t\t\t\t\t...artifact,\n\t\t\t\t\t\thex,\n\t\t\t\t\t})\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (manifest !== undefined) {\n\t\t\t\t\tthrow new ScaffoldError('TARGET', `Host artifact source is not a file at ${source}`, {\n\t\t\t\t\t\thost,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (manifest !== undefined) {\n\t\t\t\tthrow new ScaffoldError('TARGET', `Host artifact source is missing at ${source}`, {\n\t\t\t\t\thost,\n\t\t\t\t\tsource,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tif (manifest !== undefined) {\n\t\t\tconst entries = manifest.entries.filter((entry) => entry.destination.startsWith(`${source}/`))\n\t\t\tif (artifacts.length + entries.length > MAX_COLLECTION_ITEMS) {\n\t\t\t\tthrow new ScaffoldError('TARGET', 'Hydrated plan exceeds the artifact count limit', {\n\t\t\t\t\thost,\n\t\t\t\t\tlimit: MAX_COLLECTION_ITEMS,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (entries.length === 0) {\n\t\t\t\tif (source.startsWith('guides/src/') && source.endsWith('.md')) {\n\t\t\t\t\t// The absent `hex` is the structural presence-ownership mark. Strip\n\t\t\t\t\t// caller-carried bytes so a manifest-confirmed guide-pointer degrade\n\t\t\t\t\t// can never masquerade as vendored content canon.\n\t\t\t\t\tconst { hex: _hex, ...presenceOwned } = artifact\n\t\t\t\t\tartifacts.push(presenceOwned)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tthrow new ScaffoldError('TARGET', `Host manifest does not declare ${source}`, {\n\t\t\t\t\thost,\n\t\t\t\t\tsource,\n\t\t\t\t})\n\t\t\t}\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (isSensitiveHostPath(entry.destination)) {\n\t\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t\t'TARGET',\n\t\t\t\t\t\t`Sensitive host artifact source at ${entry.destination}`,\n\t\t\t\t\t\t{ host, source: entry.destination },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst nestedPath = entry.destination.slice(source.length + 1)\n\t\t\t\tconst hex = readFileHex(\n\t\t\t\t\thost,\n\t\t\t\t\tentry.storage,\n\t\t\t\t\t'TARGET',\n\t\t\t\t\t'host',\n\t\t\t\t\tMath.min(MAX_ARTIFACT_BYTES, remaining),\n\t\t\t\t)\n\t\t\t\tremaining -= hex.length / 2\n\t\t\t\tartifacts.push({\n\t\t\t\t\t...artifact,\n\t\t\t\t\tpath: `${artifact.path}/${nestedPath}`,\n\t\t\t\t\tsource: entry.destination,\n\t\t\t\t\thex,\n\t\t\t\t})\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tconst directory = resolvePhysicalPath(host, source, 'TARGET', 'host')\n\t\tif (!existsSync(directory)) {\n\t\t\tthrow new ScaffoldError('TARGET', `Host artifact source is missing at ${source}`, {\n\t\t\t\thost,\n\t\t\t\tsource,\n\t\t\t})\n\t\t}\n\t\tconst directoryStatus = attempt(() => lstatSync(directory))\n\t\tif (\n\t\t\t!directoryStatus.success ||\n\t\t\t!directoryStatus.value.isDirectory() ||\n\t\t\tdirectoryStatus.value.isSymbolicLink()\n\t\t) {\n\t\t\tthrow new ScaffoldError('TARGET', `Host artifact source is not a directory at ${source}`, {\n\t\t\t\thost,\n\t\t\t\tsource,\n\t\t\t\terror: directoryStatus.success ? undefined : directoryStatus.error,\n\t\t\t})\n\t\t}\n\t\tconst relatives = listFiles(directory)\n\t\tif (artifacts.length + relatives.length > MAX_COLLECTION_ITEMS) {\n\t\t\tthrow new ScaffoldError('TARGET', 'Hydrated plan exceeds the artifact count limit', {\n\t\t\t\thost,\n\t\t\t\tlimit: MAX_COLLECTION_ITEMS,\n\t\t\t})\n\t\t}\n\t\tif (relatives.length === 0) {\n\t\t\tartifacts.push(artifact)\n\t\t\tcontinue\n\t\t}\n\t\tfor (const nestedPath of relatives) {\n\t\t\tconst nestedSource = `${source}/${nestedPath}`\n\t\t\tif (isSensitiveHostPath(nestedSource)) {\n\t\t\t\tthrow new ScaffoldError('TARGET', `Sensitive host artifact source at ${nestedSource}`, {\n\t\t\t\t\thost,\n\t\t\t\t\tsource: nestedSource,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst hex = readFileHex(\n\t\t\t\thost,\n\t\t\t\tnestedSource,\n\t\t\t\t'TARGET',\n\t\t\t\t'host',\n\t\t\t\tMath.min(MAX_ARTIFACT_BYTES, remaining),\n\t\t\t)\n\t\t\tremaining -= hex.length / 2\n\t\t\tartifacts.push({\n\t\t\t\t...artifact,\n\t\t\t\tpath: `${artifact.path}/${nestedPath}`,\n\t\t\t\tsource: nestedSource,\n\t\t\t\thex,\n\t\t\t})\n\t\t}\n\t}\n\tconst conflict = findFileConflict(artifacts.map((artifact) => artifact.path))\n\tif (conflict !== undefined) {\n\t\tthrow new ScaffoldError(\n\t\t\t'INVALID',\n\t\t\t`Hydrated artifact collision between \"${conflict[0]}\" and \"${conflict[1]}\"`,\n\t\t\t{ paths: conflict },\n\t\t)\n\t}\n\tconst hydrated = { ...owned, artifacts }\n\tif (!isPlan(hydrated)) {\n\t\tthrow new ScaffoldError('INVALID', 'Hydrated plan violates the bounded Plan contract')\n\t}\n\treturn hydrated\n}\n\n/**\n * The vendored set of destination-relative paths under `directory` (one of\n * `PRUNE_DIRECTORIES`) that `pruneTargets` must NOT report — read from the\n * manifest's `destination`s when `host` has one, else listed straight off\n * `host/<directory>`.\n *\n * @param host - The vendored host root to establish the allowlist from.\n * @param directory - The prune directory (one of `PRUNE_DIRECTORIES`) to scope the allowlist to.\n * @remarks\n * FAIL CLOSED: before returning any allowlist (even an empty one), the\n * vendored source must be POSITIVELY established, or a caller would treat an\n * unresolved host as \"vendors nothing\" and report every file under\n * `target/<directory>` as unexpected. A missing `host` root, or (no\n * `manifest.json` AND no `host/<directory>`), is a coded `TARGET` failure —\n * the distinction this guards is missing-host vs genuinely-empty-vendor: a\n * `host` that EXISTS and vendors zero files in `directory` (an existing empty\n * dir, or a manifest with zero entries for it) remains a valid empty allowlist.\n * @returns The allowed destination-relative paths under `directory`.\n * @throws `ScaffoldError('TARGET', …)` when `host` does not exist, or when\n * `host` has no `manifest.json` and no `host/<directory>` either.\n *\n * @example\n * ```ts\n * import { vendoredPruneSet } from '@orkestrel/scaffold/server'\n *\n * vendoredPruneSet('./dist/host', '.claude/agents') // Set { '.claude/agents/reviewer.md', … }\n * ```\n */\nexport function vendoredPruneSet(host: string, directory: string): ReadonlySet<string> {\n\tif (!existsSync(host)) {\n\t\tthrow new ScaffoldError(\n\t\t\t'TARGET',\n\t\t\t`Cannot establish vendored source for prune: host root not found at ${host}`,\n\t\t\t{ host, directory },\n\t\t)\n\t}\n\tconst manifest = readHostManifest(host)\n\tif (manifest !== undefined) {\n\t\tif (!manifest.roots.includes(directory)) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'TARGET',\n\t\t\t\t`Cannot establish vendored source for prune: manifest does not declare ${directory}`,\n\t\t\t\t{ host, directory },\n\t\t\t)\n\t\t}\n\t\treturn new Set(\n\t\t\tmanifest.entries\n\t\t\t\t.filter((entry) => entry.destination.startsWith(`${directory}/`))\n\t\t\t\t.map((entry) => entry.destination),\n\t\t)\n\t}\n\tconst hostDirectory = resolvePhysicalPath(host, directory, 'TARGET', 'host')\n\tif (!existsSync(hostDirectory)) {\n\t\tthrow new ScaffoldError(\n\t\t\t'TARGET',\n\t\t\t`Cannot establish vendored source for prune: no manifest.json and no host directory at ${hostDirectory}`,\n\t\t\t{ host, directory },\n\t\t)\n\t}\n\tconst hostStatus = attempt(() => lstatSync(hostDirectory))\n\tif (!hostStatus.success || !hostStatus.value.isDirectory() || hostStatus.value.isSymbolicLink()) {\n\t\tthrow new ScaffoldError(\n\t\t\t'TARGET',\n\t\t\t`Cannot establish vendored source for prune: host directory is not physical at ${hostDirectory}`,\n\t\t\t{ host, directory, ...(hostStatus.success ? {} : { error: hostStatus.error }) },\n\t\t)\n\t}\n\treturn new Set(listFiles(hostDirectory).map((relative) => `${directory}/${relative}`))\n}\n\n/**\n * List the repo-relative POSIX paths under `target`'s prune directories\n * (`.claude/agents`, `.codex/agents`, `scripts`) that the vendored `host`\n * allowlist does NOT declare — THE single source of truth for prune drift, consumed by both\n * `Materializer.prune` (which deletes exactly these paths) and the bin's\n * audit/preview UX (which now shows them honestly instead of a\n * structurally-always-zero `audit.foreign`).\n *\n * @param target - The target directory to scan for unexpected files.\n * @param host - The vendored host root the allowlist is derived from.\n * @returns The unexpected relative paths (e.g. `.claude/agents/rogue.md`); `[]`\n * when a prune directory is absent under `target`, or when none of its\n * files are unexpected. Pure read — never deletes anything.\n * @throws `ScaffoldError('TARGET', …)` when `host` cannot positively\n * establish a vendored allowlist for a prune directory that DOES exist\n * under `target` (see `vendoredPruneSet`'s fail-closed remarks).\n *\n * @example\n * ```ts\n * import { pruneTargets } from '@orkestrel/scaffold/server'\n *\n * pruneTargets('./packages/router', hostRoot()) // ['.claude/agents/rogue.md']\n * ```\n */\nexport function pruneTargets(target: string, host: string): readonly string[] {\n\tif (!isFilesystemPath(target) || !isFilesystemPath(host)) {\n\t\tthrow new ScaffoldError('TARGET', 'Prune root is malformed or exceeds its bounds', {\n\t\t\ttarget,\n\t\t\thost,\n\t\t})\n\t}\n\tconst paths: string[] = []\n\tfor (const directory of PRUNE_DIRECTORIES) {\n\t\tconst root = resolvePhysicalPath(target, directory, 'TARGET', 'target')\n\t\tif (!existsSync(root)) continue\n\t\tconst status = attempt(() => lstatSync(root))\n\t\tif (!status.success || !status.value.isDirectory() || status.value.isSymbolicLink()) {\n\t\t\tthrow new ScaffoldError('TARGET', `Prune root is not a physical directory at ${root}`, {\n\t\t\t\ttarget,\n\t\t\t\tdirectory,\n\t\t\t\t...(status.success ? {} : { error: status.error }),\n\t\t\t})\n\t\t}\n\t\tconst allowed = vendoredPruneSet(host, directory)\n\t\tfor (const relative of listFiles(root)) {\n\t\t\tconst path = `${directory}/${relative}`\n\t\t\tif (!allowed.has(path)) paths.push(path)\n\t\t}\n\t}\n\treturn paths\n}\n\n/** Consume one aggregate fleet-catalog traversal slot. */\nexport function consumeCatalogAllowance(allowance: CatalogAllowance, root: string): void {\n\tconst consumed = attempt(() => {\n\t\tif (!isCatalogAllowance(allowance)) throw new Error('allowance must be one Float64 cell')\n\t\tconst remaining = allowance[0]\n\t\tif (\n\t\t\tremaining === undefined ||\n\t\t\t!Number.isSafeInteger(remaining) ||\n\t\t\tremaining < 1 ||\n\t\t\tremaining > MAX_HOST_ENTRIES\n\t\t) {\n\t\t\tthrow new Error('allowance is outside its bounds')\n\t\t}\n\t\tconst next = remaining - 1\n\t\tallowance[0] = next\n\t\tif (allowance[0] !== next) throw new Error('allowance decrement was not retained')\n\t})\n\tif (!consumed.success) {\n\t\tthrow new ScaffoldError('TARGET', 'Fleet catalog exceeds its aggregate entry limit', {\n\t\t\troot,\n\t\t\tlimit: MAX_HOST_ENTRIES,\n\t\t\terror: consumed.error,\n\t\t})\n\t}\n}\n\n/**\n * List a fleet root's `@orkestrel/*` package directories.\n *\n * @param root - The fleet root directory to scan.\n * @returns Absolute, code-unit-sorted paths of `root`'s immediate child\n * directories whose `package.json` parses and whose `name` starts with\n * `@orkestrel/`. A child with an unreadable or unparsable `package.json`,\n * or a non-`@orkestrel` name, is skipped silently — it simply is not a\n * fleet member.\n * @throws `ScaffoldError('TARGET', …)` when a child directory name contains\n * terminal controls and therefore cannot be safely inspected or reported.\n *\n * @example\n * ```ts\n * import { discoverPackages } from '@orkestrel/scaffold/server'\n *\n * discoverPackages('./packages') // ['/abs/packages/router', '/abs/packages/budget']\n * ```\n */\nexport function discoverPackages(\n\troot: string,\n\tallowance: CatalogAllowance = new Float64Array([MAX_HOST_ENTRIES]),\n): readonly string[] {\n\tif (!isCatalogAllowance(allowance)) {\n\t\tthrow new ScaffoldError('TARGET', 'Fleet catalog allowance is malformed', {\n\t\t\troot,\n\t\t\tlimit: MAX_HOST_ENTRIES,\n\t\t})\n\t}\n\tif (!isFilesystemPath(root)) {\n\t\tthrow new ScaffoldError('TARGET', 'Fleet root is malformed or exceeds its bounds', { root })\n\t}\n\tconst rootStatus = attempt(() => lstatSync(root))\n\tif (!rootStatus.success || !rootStatus.value.isDirectory() || rootStatus.value.isSymbolicLink()) {\n\t\tthrow new ScaffoldError('TARGET', `Fleet root is not a physical directory at ${root}`, {\n\t\t\troot,\n\t\t\t...(rootStatus.success ? {} : { error: rootStatus.error }),\n\t\t})\n\t}\n\tconst packages: string[] = []\n\tconst handle = opendirSync(root)\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst entry = handle.readSync()\n\t\t\tif (entry === null) break\n\t\t\tconsumeCatalogAllowance(allowance, root)\n\t\t\tif (!entry.isDirectory()) continue\n\t\t\tif (!isTerminalText(entry.name)) {\n\t\t\t\tthrow new ScaffoldError('TARGET', 'Fleet discovery found a non-portable directory')\n\t\t\t}\n\t\t\tconst directory = join(root, entry.name)\n\t\t\tconst text = attempt(() =>\n\t\t\t\treadFileText(directory, 'package.json', 'TARGET', 'package', MAX_MANIFEST_BYTES),\n\t\t\t)\n\t\t\tif (!text.success) continue\n\t\t\tconst parsed = parseJSON(text.value)\n\t\t\tif (!isRecord(parsed)) continue\n\t\t\tconst name = ownDataValue(parsed, 'name')\n\t\t\tif (typeof name !== 'string' || !DEPENDENCY_NAME_PATTERN.test(name)) continue\n\t\t\tif (!isPortablePath(entry.name)) {\n\t\t\t\tthrow new ScaffoldError('TARGET', 'Fleet discovery found a non-portable directory')\n\t\t\t}\n\t\t\tpackages.push(directory)\n\t\t}\n\t} finally {\n\t\thandle.closeSync()\n\t}\n\treturn packages.sort()\n}\n\n/**\n * Extract the first paragraph from the first blockquote in a Markdown guide.\n *\n * @param text - The guide Markdown to traverse.\n * @returns A normalized one-line description, or `undefined` when parsing\n * fails, no blockquote paragraph exists, or the paragraph is empty.\n *\n * @example\n * ```ts\n * import { guideToDescription } from '@orkestrel/scaffold/server'\n *\n * guideToDescription('> A concise package description.\\n>\\n> More detail.')\n * // 'A concise package description.'\n * ```\n */\nexport function guideToDescription(text: string): string | undefined {\n\tif (text.length > MAX_GUIDE_BYTES || contentByteLength(text) > MAX_GUIDE_BYTES) {\n\t\treturn undefined\n\t}\n\tconst parsed = attempt(() => parseDocument(text))\n\tif (!parsed.success) return undefined\n\tlet quote: BlockquoteNode | undefined\n\tfor (const node of walkNodes(parsed.value)) {\n\t\tif (isBlockquoteNode(node)) {\n\t\t\tquote = node\n\t\t\tbreak\n\t\t}\n\t}\n\tif (quote === undefined) return undefined\n\tconst paragraph = quote.children.find((child) => isParagraphNode(child))\n\tif (paragraph === undefined) return undefined\n\tconst description = flattenText(paragraph).replace(/\\s+/g, ' ').trim()\n\treturn description.length > 0 && isCatalogDescription(description) ? description : undefined\n}\n\n/**\n * Build the fleet package catalog — one `CatalogEntry` per `@orkestrel/*`\n * package discovered under each root, its description drawn from its own\n * guide's FIRST blockquote.\n *\n * @param roots - The fleet root directories to scan (each walked via `discoverPackages`).\n * @remarks\n * Per discovered package directory: `name` / `version` come from its own\n * `package.json`; `description` is the first paragraph of the guide's opening\n * blockquote — the flattened text of the FIRST `ParagraphNode` among the\n * FIRST `BlockquoteNode` found's (depth-first, pre-order, via `walkNodes`)\n * TOP-LEVEL children in its `guides/src/<short>.md` (`<short>` = `name` with\n * the `@orkestrel/` prefix stripped), parsed with `@orkestrel/markdown`'s\n * `parseDocument` — a multi-paragraph blockquote overview yields only its\n * FIRST paragraph, never the whole quote glued together; embedded newlines\n * collapse to single spaces, and surrounding whitespace trims. A\n * missing/unreadable guide, a guide carrying no blockquote, or a blockquote\n * with no top-level paragraph child, yields `description: ''`, never a\n * thrown error. Entries merge across `roots` (a later root's entry for a\n * repeated `name` wins), then code-unit sort by `name`. An unreadable ROOT\n * itself is NOT wrapped here — whatever `discoverPackages` throws for it\n * propagates as-is; the bin layer is responsible for coding that failure\n * `TARGET`.\n * @returns The merged, sorted `CatalogEntry[]`.\n *\n * @example\n * ```ts\n * import { catalogPackages } from '@orkestrel/scaffold/server'\n *\n * catalogPackages(['/repos']) // [{ name: '@orkestrel/contract', version: '0.0.5', description: '…' }, …]\n * ```\n */\nexport function catalogPackages(\n\troots: readonly string[],\n\tlimit = MAX_HOST_ENTRIES,\n): readonly CatalogEntry[] {\n\tconst requested = parseFilesystemPaths(roots, MAX_HOST_ENTRIES)\n\tif (\n\t\trequested === undefined ||\n\t\t!Number.isSafeInteger(limit) ||\n\t\tlimit < 1 ||\n\t\tlimit > MAX_HOST_ENTRIES\n\t) {\n\t\tthrow new ScaffoldError('TARGET', 'Catalog roots are malformed', {\n\t\t\tlimit: MAX_HOST_ENTRIES,\n\t\t})\n\t}\n\tconst merged = new Map<string, CatalogEntry>()\n\tconst allowance = new Float64Array([limit])\n\tfor (const root of requested) {\n\t\tconsumeCatalogAllowance(allowance, root)\n\t\tfor (const directory of discoverPackages(root, allowance)) {\n\t\t\tconst text = attempt(() =>\n\t\t\t\treadFileText(directory, 'package.json', 'TARGET', 'package', MAX_MANIFEST_BYTES),\n\t\t\t)\n\t\t\tif (!text.success) continue\n\t\t\tconst parsed = parseJSON(text.value)\n\t\t\tif (!isRecord(parsed)) continue\n\t\t\tconst name = ownDataValue(parsed, 'name')\n\t\t\tif (typeof name !== 'string' || !DEPENDENCY_NAME_PATTERN.test(name)) continue\n\t\t\tconst version = ownDataValue(parsed, 'version')\n\t\t\tif (typeof version !== 'string' || !VERSION_PATTERN.test(version)) continue\n\t\t\tconst short = packageShortName(name)\n\t\t\tlet description = ''\n\t\t\tconst guide = attempt(() =>\n\t\t\t\treadFileText(directory, `guides/src/${short}.md`, 'TARGET', 'package', MAX_GUIDE_BYTES),\n\t\t\t)\n\t\t\tif (guide.success) description = guideToDescription(guide.value) ?? ''\n\t\t\tmerged.set(name, { name, version, description })\n\t\t}\n\t}\n\treturn [...merged.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n}\n","import type {\n\tHostManifest,\n\tMaterializeResult,\n\tMaterializerEventMap,\n\tMaterializerInterface,\n\tMaterializerOptions,\n\tWritePrecondition,\n} from './types.js'\nimport type { Audit, ContentArtifact, HostArtifact, Plan } from '@src/core'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport {\n\tchmodSync,\n\tconstants as FS_CONSTANTS,\n\tcopyFileSync,\n\texistsSync,\n\tlstatSync,\n\tmkdirSync,\n\trenameSync,\n\twriteFileSync,\n} from 'node:fs'\nimport { dirname } from 'node:path'\nimport { attempt } from '@orkestrel/contract'\nimport { Emitter } from '@orkestrel/emitter'\nimport {\n\tdiffPlan,\n\tfindFileConflict,\n\thasOnlyDataProperties,\n\thasValidAuditBytes,\n\thasValidSnapshotBytes,\n\tparsePlan,\n\tScaffoldError,\n\tvalidatePlan,\n} from '@src/core'\nimport {\n\thostRoot,\n\thydratePlan,\n\tisVacant,\n\tpruneTargets,\n\treadTarget,\n\treadHostManifest,\n\tremapArtifactPath,\n\tcommitWriteTransaction,\n\tdigestFile,\n\tdigestHex,\n\tdigestText,\n\tdiscardWriteTransaction,\n\tguideStub,\n\tresolvePhysicalPath,\n\trestoreFiles,\n\tvalidateWriteDirectories,\n\tvalidateWriteTarget,\n} from './helpers.js'\nimport { WriteTransaction } from './WriteTransaction.js'\nimport { isFilesystemPath, isPortablePath, isReservedTargetPath } from './validators.js'\nimport { parseMaterializerOptions } from './parsers.js'\n\n/**\n * The materialization entity (server) — the only impure environment in the\n * package, writing a `Plan` to `node:fs` behind an explicit call.\n *\n * @remarks\n * `materialize` is green-field: it refuses any target `isVacant` rejects\n * (`ScaffoldError('TARGET', …)`), then byte-copies each `host` artifact from\n * the `host` root and writes each `template` / `computed` artifact's rendered\n * `content`, failing fast on any write error (`ScaffoldError('WRITE', …)`).\n * `repair` is into-existing: it skips the vacancy check and writes `missing`\n * artifacts an `Audit` names. `stale` artifacts are report-only unless its\n * `replace` switch is true, because byte replacement discards local changes.\n * Hydrated directory-shaped host entries are expanded into\n * file-shaped artifacts, so canonical skills and agent configuration are\n * audited and repaired file by file. `prune` deletes stale files under\n * `target/.claude/agents/`, `target/.codex/agents/`, and `target/scripts/`\n * that the vendored `host` does not name. After `destroy()`\n * every method throws `DESTROYED`; teardown is idempotent, emitter last.\n * Before the vacancy check or any write, `materialize` and `repair` require a\n * structural `isPlan` match and a valid `validatePlan` result. Contextual\n * overrides that are missing from the artifact set, host-owned, or target\n * `package.json` therefore fail closed instead of being silently ignored.\n *\n * @remarks\n * `host`-origin copies are MANIFEST-AWARE: when the resolved `host` root\n * carries a `manifest.json` (this package's own vendored `dist/host`), each\n * artifact's `source` (a destination-relative path) is looked up in the\n * manifest to find its un-dotted STORAGE path plus an `executable` bit\n * (applied via `chmodSync` after the copy) — the vendored-package shape,\n * where storage names avoid leading dots npm would otherwise mangle. When\n * `host` carries no `manifest.json` (a caller-supplied raw repo root, e.g. a\n * sibling checkout or a test fixture), `source` maps to `host` 1:1, exactly\n * as before.\n *\n * @remarks\n * A manifest-present `source` with ZERO matching entries degrades to a stub\n * ONLY when that `source` is a dependency-guide pointer — one that starts\n * with `guides/src/` and ends with `.md` (the `guides/src/<dep>.md` pointer\n * `Compiler` emits for any dependency outside this package's vendored set).\n * That is the ONLY zero-match case that is legitimate: every `HOST_PATHS`\n * source is always staged by `stageHost`, so a non-guide zero-match means a\n * corrupted or truncated `manifest.json`, not an intentionally-unvendored\n * artifact. For a guide pointer, a short stub file is written at the\n * destination and reported exactly like a successful copy. The READ path\n * leaves that intentional pointer without canonical bytes, so `diffPlan`\n * treats it as presence-owned rather than inventing a byte match.\n * For every OTHER zero-match, the\n * fail-closed `ScaffoldError('TARGET', …)` is thrown — degrading an\n * unscoped zero-match would otherwise let a corrupted manifest silently stub\n * an unrecoverable artifact (e.g. `AGENTS.md` — `pull` only ever fetches\n * dependency guides) or write a FILE named `.claude` over what should be a\n * directory artifact. The raw-root fallback (`manifest === undefined`, a\n * caller-supplied `--from`) keeps its own throw regardless: an EXPLICITLY\n * named source failing to resolve is a different, caller-error failure\n * class, not a \"not vendored\" degrade.\n *\n * @remarks\n * Defense in depth at the filesystem trust boundary: EVERY resolved\n * destination (`materialize` and `repair`, both origins) is asserted to stay\n * within `resolve(target)` before any write, and every `host`-origin copy\n * source is asserted to stay within `resolve(host)` before any read — a\n * traversal segment (`../`) in an artifact's `path` or `source` cannot escape\n * either root, even if a gate upstream (e.g. an ungated `Plan` built by hand)\n * let it through. A destination violation throws `ScaffoldError('WRITE', …)`;\n * a source violation throws `ScaffoldError('TARGET', …)`.\n *\n * @remarks\n * The containment check is REAL-PATH aware, not merely lexical: both the\n * root (`target` / `host`) and the candidate destination/source are resolved\n * through `realpathSync` on their DEEPEST EXISTING ancestor before the prefix\n * comparison, so a symlinked subdirectory planted inside an otherwise\n * legitimate root cannot smuggle a write (or read) outside it — `repair`,\n * which has no `isVacant` gate, is covered exactly like `materialize`. A path\n * segment that does not yet exist on disk (the still-to-be-created file/dir\n * a write is about to create) is rejoined onto the resolved existing\n * ancestor rather than realpath'd itself.\n *\n * @example\n * ```ts\n * import { blueprint, blueprintToPlan } from '@orkestrel/scaffold'\n * import { createMaterializer } from '@orkestrel/scaffold/server'\n *\n * const plan = blueprintToPlan(blueprint('budget', { src: ['core'] }))\n * const materializer = createMaterializer()\n * materializer.materialize(plan, './packages/budget-new')\n * materializer.destroy()\n * ```\n */\nexport class Materializer implements MaterializerInterface {\n\treadonly #emitter: Emitter<MaterializerEventMap>\n\treadonly #host: string\n\t#manifestLoaded = false\n\t#manifestValue: HostManifest | undefined\n\t#destroyed = false\n\n\tconstructor(options?: MaterializerOptions) {\n\t\tconst parsed = parseMaterializerOptions(options)\n\t\tthis.#emitter = new Emitter<MaterializerEventMap>({\n\t\t\t...(parsed.on === undefined ? {} : { on: parsed.on }),\n\t\t\t...(parsed.error === undefined ? {} : { error: parsed.error }),\n\t\t})\n\t\t// The host IS this package's own vendored data unless `options.host`\n\t\t// overrides it — see `hostRoot`'s doc-comment for the resolution law.\n\t\tthis.#host = parsed.host ?? hostRoot()\n\t}\n\n\tget emitter(): EmitterInterface<MaterializerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tmaterialize(plan: Plan, target: string): MaterializeResult {\n\t\tthis.#ensureAlive()\n\t\tconst prepared = this.#prepare(plan, target)\n\t\tif (!isVacant(target)) {\n\t\t\tthrow new ScaffoldError('TARGET', 'materialize requires a vacant target', { target })\n\t\t}\n\t\tconst { written, copied } = this.#apply(prepared, target)\n\t\tconst result: MaterializeResult = { target, written, copied, skipped: [], removed: [] }\n\t\tthis.#emitter.emit('done', result)\n\t\treturn result\n\t}\n\n\trepair(plan: Plan, audit: Audit, target: string, replace = false): MaterializeResult {\n\t\tthis.#ensureAlive()\n\t\tconst context = this.#prepare(plan, target, plan, false)\n\t\tif (!hasOnlyDataProperties(audit) || !hasValidAuditBytes(audit)) {\n\t\t\tthrow new ScaffoldError('INVALID', 'repair requires a bounded audit snapshot')\n\t\t}\n\t\tconst preview = attempt(() => structuredClone(audit))\n\t\tif (!preview.success || !Array.isArray(preview.value.findings)) {\n\t\t\tthrow new ScaffoldError('INVALID', 'repair requires a structurally valid audit', {\n\t\t\t\t...(preview.success ? {} : { error: preview.error }),\n\t\t\t})\n\t\t}\n\t\tconst selectedPaths = new Set(\n\t\t\tpreview.value.findings\n\t\t\t\t.filter(\n\t\t\t\t\t(finding) =>\n\t\t\t\t\t\tfinding.drift === 'missing' || (replace === true && finding.drift === 'stale'),\n\t\t\t\t)\n\t\t\t\t.map((finding) => finding.path),\n\t\t)\n\t\tconst selected = {\n\t\t\t...context,\n\t\t\tartifacts: context.artifacts.filter((artifact) => selectedPaths.has(artifact.path)),\n\t\t}\n\t\tconst prepared = this.#prepare(selected, target, context)\n\t\tconst preparedByPath = new Map(prepared.artifacts.map((artifact) => [artifact.path, artifact]))\n\t\tconst comparison = {\n\t\t\t...context,\n\t\t\tartifacts: context.artifacts.map((artifact) => preparedByPath.get(artifact.path) ?? artifact),\n\t\t}\n\t\tconst current = diffPlan(\n\t\t\tcomparison,\n\t\t\treadTarget(\n\t\t\t\ttarget,\n\t\t\t\tcomparison.artifacts.map((artifact) => artifact.path),\n\t\t\t),\n\t\t)\n\t\tif (JSON.stringify(current.findings) !== JSON.stringify(preview.value.findings)) {\n\t\t\tthrow new ScaffoldError('TARGET', 'Repair target changed after its audit preview', {\n\t\t\t\ttarget,\n\t\t\t})\n\t\t}\n\t\tconst preconditions: WritePrecondition[] = prepared.artifacts.map((artifact) => {\n\t\t\tconst finding = preview.value.findings.find((candidate) => candidate.path === artifact.path)\n\t\t\tif (finding?.drift === 'missing') return { path: artifact.path, shape: 'absent' }\n\t\t\tif (finding?.drift === 'stale' && finding.observed !== undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tpath: artifact.path,\n\t\t\t\t\tshape: 'file',\n\t\t\t\t\tdigest: digestHex(finding.observed),\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new ScaffoldError('INVALID', `Repair precondition is missing at ${artifact.path}`, {\n\t\t\t\tpath: artifact.path,\n\t\t\t})\n\t\t})\n\t\tconst skipped: string[] = []\n\t\tfor (const artifact of context.artifacts) {\n\t\t\tif (!selectedPaths.has(artifact.path)) {\n\t\t\t\tskipped.push(artifact.path)\n\t\t\t}\n\t\t}\n\t\tconst { written, copied } = this.#apply(prepared, target, preconditions)\n\t\tconst result: MaterializeResult = { target, written, copied, skipped, removed: [] }\n\t\tthis.#emitter.emit('done', result)\n\t\treturn result\n\t}\n\n\t// The unexpected-file scan itself lives in `pruneTargets` (server/helpers.js)\n\t// — the single source of truth both this deletion and the bin's audit/preview\n\t// UX read from; `prune` only deletes exactly what it reports.\n\tprune(target: string, expected: Readonly<Record<string, string>>): MaterializeResult {\n\t\tthis.#ensureAlive()\n\t\tif (!isFilesystemPath(target)) {\n\t\t\tthrow new ScaffoldError('TARGET', 'Prune target is malformed or exceeds its bounds', {\n\t\t\t\ttarget,\n\t\t\t})\n\t\t}\n\t\tconst paths = pruneTargets(target, this.#host)\n\t\tif (!hasOnlyDataProperties(expected) || !hasValidSnapshotBytes(expected)) {\n\t\t\tthrow new ScaffoldError('TARGET', 'Prune preview is malformed or unbounded', { target })\n\t\t}\n\t\tconst preview = attempt(() => structuredClone(expected))\n\t\tconst expectedPaths = preview.success ? Object.keys(preview.value).sort() : []\n\t\tif (\n\t\t\t!preview.success ||\n\t\t\tJSON.stringify(expectedPaths) !== JSON.stringify([...paths].sort()) ||\n\t\t\tJSON.stringify(readTarget(target, paths)) !== JSON.stringify(preview.value)\n\t\t) {\n\t\t\tthrow new ScaffoldError('TARGET', 'Prune targets changed after their preview', {\n\t\t\t\ttarget,\n\t\t\t\t...(preview.success ? {} : { error: preview.error }),\n\t\t\t})\n\t\t}\n\t\tif (paths.length === 0) {\n\t\t\tconst result: MaterializeResult = {\n\t\t\t\ttarget,\n\t\t\t\twritten: [],\n\t\t\t\tcopied: [],\n\t\t\t\tskipped: [],\n\t\t\t\tremoved: [],\n\t\t\t}\n\t\t\tthis.#emitter.emit('done', result)\n\t\t\treturn result\n\t\t}\n\t\tconst transaction = WriteTransaction.create(target, [])\n\t\tconst files = paths.map((path) => {\n\t\t\tresolvePhysicalPath(target, path, 'WRITE', 'target')\n\t\t\treturn { path }\n\t\t})\n\t\tconst moved: typeof files = []\n\t\tconst staged = attempt(() => {\n\t\t\tfor (const file of files) {\n\t\t\t\tvalidateWriteTarget(transaction, undefined)\n\t\t\t\tconst source = resolvePhysicalPath(target, file.path, 'WRITE', 'target')\n\t\t\t\tconst sourceStatus = lstatSync(source)\n\t\t\t\tif (!sourceStatus.isFile() || sourceStatus.isSymbolicLink() || sourceStatus.nlink !== 1) {\n\t\t\t\t\tthrow new ScaffoldError('WRITE', `Prune target is not a physical file at ${file.path}`, {\n\t\t\t\t\t\tpath: file.path,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst sourceDigest = digestFile(source)\n\t\t\t\tconst expectedHex = preview.value[file.path]\n\t\t\t\tif (expectedHex === undefined || sourceDigest !== digestHex(expectedHex)) {\n\t\t\t\t\tthrow new ScaffoldError('WRITE', `Prune target changed at ${file.path}`, {\n\t\t\t\t\t\tpath: file.path,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst destination = resolvePhysicalPath(\n\t\t\t\t\ttransaction.backup,\n\t\t\t\t\tfile.path,\n\t\t\t\t\t'WRITE',\n\t\t\t\t\t'quarantine',\n\t\t\t\t)\n\t\t\t\tmkdirSync(dirname(destination), { recursive: true })\n\t\t\t\tvalidateWriteTarget(transaction, undefined)\n\t\t\t\tconst containedDestination = resolvePhysicalPath(\n\t\t\t\t\ttransaction.backup,\n\t\t\t\t\tfile.path,\n\t\t\t\t\t'WRITE',\n\t\t\t\t\t'quarantine',\n\t\t\t\t)\n\t\t\t\trenameSync(source, containedDestination)\n\t\t\t\tmoved.push(file)\n\t\t\t\tconst capturedStatus = lstatSync(containedDestination)\n\t\t\t\tconst capturedDigest = digestFile(containedDestination)\n\t\t\t\tif (\n\t\t\t\t\t!capturedStatus.isFile() ||\n\t\t\t\t\tcapturedStatus.isSymbolicLink() ||\n\t\t\t\t\tcapturedStatus.nlink !== 1 ||\n\t\t\t\t\tcapturedStatus.dev !== sourceStatus.dev ||\n\t\t\t\t\tcapturedStatus.ino !== sourceStatus.ino ||\n\t\t\t\t\tcapturedStatus.mtimeMs !== sourceStatus.mtimeMs ||\n\t\t\t\t\tcapturedStatus.size !== sourceStatus.size ||\n\t\t\t\t\tcapturedDigest !== sourceDigest\n\t\t\t\t) {\n\t\t\t\t\tthrow new ScaffoldError('WRITE', `Prune target changed at ${file.path}`, {\n\t\t\t\t\t\tpath: file.path,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\tif (!staged.success) {\n\t\t\tconst recovery = attempt(() =>\n\t\t\t\trestoreFiles(\n\t\t\t\t\ttransaction,\n\t\t\t\t\tmoved.map((file) => file.path),\n\t\t\t\t),\n\t\t\t)\n\t\t\tconst cleanup = recovery.success\n\t\t\t\t? attempt(() => discardWriteTransaction(transaction))\n\t\t\t\t: undefined\n\t\t\tthrow new ScaffoldError('WRITE', 'Failed to stage prune targets', {\n\t\t\t\ttarget,\n\t\t\t\terror: staged.error,\n\t\t\t\tquarantine: transaction.backup,\n\t\t\t\tcommitted: false,\n\t\t\t\trecovery: recovery.success ? undefined : recovery.error,\n\t\t\t\tcleanup: cleanup?.success === false ? cleanup.error : undefined,\n\t\t\t})\n\t\t}\n\t\tconst removed = files.map((file) => file.path)\n\t\tconst cleared = attempt(() => discardWriteTransaction(transaction))\n\t\tif (!cleared.success) {\n\t\t\tthrow new ScaffoldError('WRITE', 'Prune committed with cleanup residue', {\n\t\t\t\ttarget,\n\t\t\t\terror: cleared.error,\n\t\t\t\tquarantine: transaction.backup,\n\t\t\t\tcommitted: true,\n\t\t\t\tremoved,\n\t\t\t})\n\t\t}\n\t\tfor (const path of removed) this.#emitter.emit('remove', path)\n\t\tconst result: MaterializeResult = { target, written: [], copied: [], skipped: [], removed }\n\t\tthis.#emitter.emit('done', result)\n\t\treturn result\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t#apply(\n\t\tplan: Plan,\n\t\ttarget: string,\n\t\tpreconditions?: readonly WritePrecondition[],\n\t): Pick<MaterializeResult, 'written' | 'copied'> {\n\t\tif (plan.artifacts.length === 0) return { written: [], copied: [] }\n\t\tconst paths = plan.artifacts.map((artifact) => artifact.path)\n\t\tconst transaction = WriteTransaction.create(target, paths, preconditions)\n\t\tconst staged = attempt(() => {\n\t\t\tfor (const artifact of plan.artifacts) {\n\t\t\t\tvalidateWriteDirectories(transaction)\n\t\t\t\tif (artifact.origin === 'host') this.#copy(artifact, transaction)\n\t\t\t\telse this.#write(artifact, transaction)\n\t\t\t}\n\t\t})\n\t\tif (!staged.success) {\n\t\t\tconst cleanup = attempt(() => discardWriteTransaction(transaction))\n\t\t\tthis.#emitter.emit('error', staged.error)\n\t\t\tthrow new ScaffoldError('WRITE', 'Failed to stage materialization', {\n\t\t\t\ttarget,\n\t\t\t\terror: staged.error,\n\t\t\t\tcleanup: cleanup.success ? undefined : cleanup.error,\n\t\t\t})\n\t\t}\n\t\tconst committed = attempt(() => commitWriteTransaction(transaction, paths))\n\t\tif (!committed.success) {\n\t\t\tthis.#emitter.emit('error', committed.error)\n\t\t\tthrow committed.error\n\t\t}\n\t\tconst written = plan.artifacts\n\t\t\t.filter((artifact) => artifact.origin !== 'host')\n\t\t\t.map((artifact) => artifact.path)\n\t\tconst copied = plan.artifacts\n\t\t\t.filter((artifact) => artifact.origin === 'host')\n\t\t\t.map((artifact) => artifact.path)\n\t\tfor (const path of written) this.#emitter.emit('write', path)\n\t\tfor (const path of copied) this.#emitter.emit('copy', path)\n\t\treturn { written, copied }\n\t}\n\n\t#copy(artifact: HostArtifact, transaction: WriteTransaction): void {\n\t\tconst source = artifact.source ?? artifact.path\n\t\tconst manifest = this.#manifest()\n\t\tconst entries =\n\t\t\tmanifest?.entries.filter(\n\t\t\t\t(entry) => entry.destination === source || entry.destination.startsWith(`${source}/`),\n\t\t\t) ?? []\n\t\tif (manifest !== undefined && entries.length === 0) {\n\t\t\tif (!source.startsWith('guides/src/') || !source.endsWith('.md')) {\n\t\t\t\t// Not a dependency-guide pointer — every HOST_PATHS source is\n\t\t\t\t// always staged by `stageHost`, so a non-guide zero-match means a\n\t\t\t\t// corrupted or truncated manifest, not a legitimate degrade (see\n\t\t\t\t// the class doc comment). Fail closed.\n\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t'TARGET',\n\t\t\t\t\t`Manifest entry for \"${source}\" is missing — the vendored manifest may be corrupted or truncated`,\n\t\t\t\t\t{ target: transaction.stage, source },\n\t\t\t\t)\n\t\t\t}\n\t\t\t// A dependency-guide pointer — degrade to a stub instead of throwing.\n\t\t\t// The read path treats it as presence-owned while canonical bytes are\n\t\t\t// unavailable (see the class doc comment).\n\t\t\tconst to = resolvePhysicalPath(transaction.stage, artifact.path, 'WRITE', 'staging')\n\t\t\ttry {\n\t\t\t\tmkdirSync(dirname(to), { recursive: true })\n\t\t\t\tvalidateWriteDirectories(transaction)\n\t\t\t\tconst destination = resolvePhysicalPath(\n\t\t\t\t\ttransaction.stage,\n\t\t\t\t\tartifact.path,\n\t\t\t\t\t'WRITE',\n\t\t\t\t\t'staging',\n\t\t\t\t)\n\t\t\t\tconst content = guideStub(source)\n\t\t\t\twriteFileSync(destination, content, { encoding: 'utf8', flag: 'wx' })\n\t\t\t\tconst status = lstatSync(destination)\n\t\t\t\tif (\n\t\t\t\t\t!status.isFile() ||\n\t\t\t\t\tstatus.isSymbolicLink() ||\n\t\t\t\t\tstatus.nlink !== 1 ||\n\t\t\t\t\tdigestFile(destination) !== digestText(content)\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(`staged guide pointer changed at ${artifact.path}`)\n\t\t\t\t}\n\t\t\t\tvalidateWriteDirectories(transaction)\n\t\t\t} catch (error) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Failed to write host artifact stub at ${artifact.path}`, {\n\t\t\t\t\tpath: artifact.path,\n\t\t\t\t\terror,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif (manifest === undefined && artifact.hex === undefined) {\n\t\t\tconst directory = resolvePhysicalPath(this.#host, source, 'TARGET', 'host')\n\t\t\tconst status = lstatSync(directory)\n\t\t\tif (!status.isDirectory() || status.isSymbolicLink()) {\n\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t'TARGET',\n\t\t\t\t\t`Host artifact is not a physical directory at ${source}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tsource,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst destination = resolvePhysicalPath(transaction.stage, artifact.path, 'WRITE', 'staging')\n\t\t\tmkdirSync(destination, { recursive: true })\n\t\t\tvalidateWriteDirectories(transaction)\n\t\t\tconst staged = lstatSync(destination)\n\t\t\tif (!staged.isDirectory() || staged.isSymbolicLink()) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Staged host directory changed at ${artifact.path}`, {\n\t\t\t\t\tpath: artifact.path,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tconst entry = entries[0]\n\t\tconst sourcePath = entry === undefined ? source : entry.storage\n\t\tconst destinationPath =\n\t\t\tentry === undefined ? artifact.path : remapArtifactPath(artifact, entry.destination)\n\t\tconst expected = artifact.hex\n\t\tif (expected === undefined) {\n\t\t\tthrow new ScaffoldError('TARGET', `Host artifact has no byte snapshot at ${source}`, {\n\t\t\t\tsource,\n\t\t\t})\n\t\t}\n\t\tconst from = resolvePhysicalPath(this.#host, sourcePath, 'TARGET', 'host')\n\t\tconst sourceStatus = lstatSync(from)\n\t\tif (\n\t\t\t!sourceStatus.isFile() ||\n\t\t\tsourceStatus.isSymbolicLink() ||\n\t\t\tsourceStatus.nlink !== 1 ||\n\t\t\tdigestFile(from) !== digestHex(expected)\n\t\t) {\n\t\t\tthrow new ScaffoldError('TARGET', `Host artifact changed at ${source}`, { source })\n\t\t}\n\t\tconst to = resolvePhysicalPath(transaction.stage, destinationPath, 'WRITE', 'staging')\n\t\ttry {\n\t\t\tmkdirSync(dirname(to), { recursive: true })\n\t\t\tvalidateWriteDirectories(transaction)\n\t\t\tconst destination = resolvePhysicalPath(\n\t\t\t\ttransaction.stage,\n\t\t\t\tdestinationPath,\n\t\t\t\t'WRITE',\n\t\t\t\t'staging',\n\t\t\t)\n\t\t\tcopyFileSync(from, destination, FS_CONSTANTS.COPYFILE_EXCL)\n\t\t\tif (entry?.executable === true) chmodSync(destination, 0o755)\n\t\t\tconst copied = lstatSync(destination)\n\t\t\tif (\n\t\t\t\t!copied.isFile() ||\n\t\t\t\tcopied.isSymbolicLink() ||\n\t\t\t\tcopied.nlink !== 1 ||\n\t\t\t\tdigestFile(destination) !== digestHex(expected)\n\t\t\t) {\n\t\t\t\tthrow new Error(`staged host artifact changed at ${artifact.path}`)\n\t\t\t}\n\t\t\tvalidateWriteDirectories(transaction)\n\t\t} catch (error) {\n\t\t\tthrow new ScaffoldError('WRITE', `Failed to copy host artifact at ${artifact.path}`, {\n\t\t\t\tpath: artifact.path,\n\t\t\t\terror,\n\t\t\t})\n\t\t}\n\t}\n\n\t// Lazily load + cache `host`'s `manifest.json` (once per instance) —\n\t// `undefined` means `host` has no manifest and callers fall back to the\n\t// 1:1 raw-root mapping.\n\t#prepare(plan: Plan, target: string, context: Plan = plan, hydrate = true): Plan {\n\t\tif (!isFilesystemPath(target)) {\n\t\t\tthrow new ScaffoldError('TARGET', 'Materializer target is malformed or exceeds its bounds', {\n\t\t\t\ttarget,\n\t\t\t})\n\t\t}\n\t\tif (!hasOnlyDataProperties(plan)) {\n\t\t\tthrow new ScaffoldError('INVALID', 'Materializer requires a data-only Plan')\n\t\t}\n\t\tconst snapshot = attempt(() => structuredClone(plan))\n\t\tconst parsed = snapshot.success ? parsePlan(snapshot.value) : undefined\n\t\tif (parsed === undefined) {\n\t\t\tthrow new ScaffoldError('INVALID', 'Materializer requires a valid Plan', {\n\t\t\t\t...(snapshot.success ? {} : { error: snapshot.error }),\n\t\t\t})\n\t\t}\n\t\tconst contextSnapshot =\n\t\t\tcontext === plan\n\t\t\t\t? snapshot\n\t\t\t\t: hasOnlyDataProperties(context)\n\t\t\t\t\t? attempt(() => structuredClone(context))\n\t\t\t\t\t: undefined\n\t\tconst parsedContext =\n\t\t\tcontext === plan\n\t\t\t\t? parsed\n\t\t\t\t: contextSnapshot?.success === true\n\t\t\t\t\t? parsePlan(contextSnapshot.value)\n\t\t\t\t\t: undefined\n\t\tif (parsedContext === undefined) {\n\t\t\tthrow new ScaffoldError('INVALID', 'Materializer requires a valid contextual Plan', {\n\t\t\t\t...(contextSnapshot?.success === false ? { error: contextSnapshot.error } : {}),\n\t\t\t})\n\t\t}\n\t\tconst validation = validatePlan(parsedContext)\n\t\tif (!validation.valid) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'INVALID',\n\t\t\t\t'Materializer requires a semantically and contextually valid Plan',\n\t\t\t\t{ questions: validation.questions },\n\t\t\t)\n\t\t}\n\t\tfor (const artifact of parsed.artifacts) {\n\t\t\tif (!isPortablePath(artifact.path)) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Invalid artifact path at ${artifact.path}`, {\n\t\t\t\t\tpath: artifact.path,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (isReservedTargetPath(artifact.path)) {\n\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t'WRITE',\n\t\t\t\t\t`Artifact path targets reserved repository metadata at ${artifact.path}`,\n\t\t\t\t\t{ path: artifact.path },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (artifact.source !== undefined && !isPortablePath(artifact.source)) {\n\t\t\t\tthrow new ScaffoldError('TARGET', `Invalid artifact source at ${artifact.source}`, {\n\t\t\t\t\tsource: artifact.source,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tconst hosted = parsed.artifacts.some((artifact) => artifact.origin === 'host')\n\t\tconst prepared = hydrate && hosted ? hydratePlan(parsed, this.#host) : parsed\n\t\tconst conflict = findFileConflict(prepared.artifacts.map((artifact) => artifact.path))\n\t\tif (conflict !== undefined) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'INVALID',\n\t\t\t\t`Plan artifact collision between \"${conflict[0]}\" and \"${conflict[1]}\"`,\n\t\t\t\t{ paths: conflict },\n\t\t\t)\n\t\t}\n\t\tif (!hydrate) return prepared\n\t\tconst manifest = hosted ? this.#manifest() : undefined\n\t\tfor (const artifact of prepared.artifacts) {\n\t\t\tconst destination = resolvePhysicalPath(target, artifact.path, 'WRITE', 'target')\n\t\t\tif (!existsSync(destination)) continue\n\t\t\tconst destinationStatus = attempt(() => lstatSync(destination))\n\t\t\tif (!destinationStatus.success) {\n\t\t\t\tthrow new ScaffoldError('TARGET', `Failed to inspect artifact target at ${artifact.path}`, {\n\t\t\t\t\tpath: artifact.path,\n\t\t\t\t\terror: destinationStatus.error,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (\n\t\t\t\tdestinationStatus.value.isSymbolicLink() ||\n\t\t\t\t(destinationStatus.value.isFile() && destinationStatus.value.nlink !== 1)\n\t\t\t) {\n\t\t\t\tthrow new ScaffoldError('TARGET', `Artifact target is linked at ${artifact.path}`, {\n\t\t\t\t\tpath: artifact.path,\n\t\t\t\t})\n\t\t\t}\n\t\t\tlet directory = false\n\t\t\tif (artifact.origin === 'host' && manifest === undefined && artifact.hex === undefined) {\n\t\t\t\tconst source = artifact.source ?? artifact.path\n\t\t\t\tconst sourcePath = resolvePhysicalPath(this.#host, source, 'TARGET', 'host')\n\t\t\t\tconst sourceStatus = attempt(() => lstatSync(sourcePath))\n\t\t\t\tif (!sourceStatus.success) {\n\t\t\t\t\tthrow new ScaffoldError('TARGET', `Failed to inspect host artifact at ${source}`, {\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\terror: sourceStatus.error,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tdirectory = sourceStatus.value.isDirectory() && !sourceStatus.value.isSymbolicLink()\n\t\t\t}\n\t\t\tif (destinationStatus.value.isDirectory() !== directory) {\n\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t'TARGET',\n\t\t\t\t\t`Artifact target has an incompatible shape at ${artifact.path}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: artifact.path,\n\t\t\t\t\t\tdirectory,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\treturn prepared\n\t}\n\n\t#manifest(): HostManifest | undefined {\n\t\tif (!this.#manifestLoaded) {\n\t\t\tthis.#manifestValue = readHostManifest(this.#host)\n\t\t\tthis.#manifestLoaded = true\n\t\t}\n\t\treturn this.#manifestValue\n\t}\n\n\t#write(artifact: ContentArtifact, transaction: WriteTransaction): void {\n\t\tconst to = resolvePhysicalPath(transaction.stage, artifact.path, 'WRITE', 'staging')\n\t\ttry {\n\t\t\tmkdirSync(dirname(to), { recursive: true })\n\t\t\tvalidateWriteDirectories(transaction)\n\t\t\tconst destination = resolvePhysicalPath(transaction.stage, artifact.path, 'WRITE', 'staging')\n\t\t\twriteFileSync(destination, artifact.content, { encoding: 'utf8', flag: 'wx' })\n\t\t\tconst status = lstatSync(destination)\n\t\t\tif (\n\t\t\t\t!status.isFile() ||\n\t\t\t\tstatus.isSymbolicLink() ||\n\t\t\t\tstatus.nlink !== 1 ||\n\t\t\t\tdigestFile(destination) !== digestText(artifact.content)\n\t\t\t) {\n\t\t\t\tthrow new Error(`staged artifact changed at ${artifact.path}`)\n\t\t\t}\n\t\t\tvalidateWriteDirectories(transaction)\n\t\t} catch (error) {\n\t\t\tthrow new ScaffoldError('WRITE', `Failed to write artifact at ${artifact.path}`, {\n\t\t\t\tpath: artifact.path,\n\t\t\t\terror,\n\t\t\t})\n\t\t}\n\t}\n\n\t#ensureAlive(): void {\n\t\tif (this.#destroyed) throw new ScaffoldError('DESTROYED', 'Materializer has been destroyed')\n\t}\n}\n","import type {\n\tSyncAllowance,\n\tSyncEventMap,\n\tSyncInterface,\n\tSyncOptions,\n\tVersionLookup,\n\tWritePrecondition,\n} from './types.js'\nimport type {\n\tCatalogEntry,\n\tDependency,\n\tFreshness,\n\tGuideSync,\n\tSyncReport,\n\tVersionSync,\n} from '@src/core'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport { lstatSync, mkdirSync, writeFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport { attempt, isRecord, parseJSON } from '@orkestrel/contract'\nimport { Emitter } from '@orkestrel/emitter'\nimport {\n\tisSyncReport,\n\thasOnlyDataProperties,\n\tmanifestToDependencies,\n\tmanifestToName,\n\townDataValue,\n\tparseSyncReport,\n\trangeToFreshness,\n\tScaffoldError,\n\tDEPENDENCY_NAME_PATTERN,\n\tMAX_ARTIFACT_BYTES,\n\tSYNC_BASELINE_PATTERN,\n\tVERSION_PATTERN,\n} from '@src/core'\nimport {\n\tcommitWriteTransaction,\n\tdigestFile,\n\tdigestText,\n\tdiscardWriteTransaction,\n\tguideToDescription,\n\tpackageShortName,\n\treadGuideReferences,\n\treadManifest,\n\tresolvePhysicalPath,\n\tresolveGuideWrites,\n\tsyncReportOf,\n\tvalidateWriteDirectories,\n} from './helpers.js'\nimport {\n\tparseSyncCurrent,\n\tparseSyncDependencies,\n\tparseSyncNames,\n\tparseSyncOptions,\n} from './parsers.js'\nimport { isCatalogDescription, isFilesystemPath, isMissingPathError } from './validators.js'\nimport { WriteTransaction } from './WriteTransaction.js'\nimport {\n\tDEFAULT_SYNC_BUDGET,\n\tDEFAULT_SYNC_CONCURRENCY,\n\tDEFAULT_SYNC_ITEMS,\n\tDEFAULT_SYNC_LIMIT,\n\tDEFAULT_SYNC_TIMEOUT,\n} from './constants.js'\n\n/**\n * The upstream-synchronization entity (server) — the impure FETCH sibling of\n * `Materializer`, Promise-based and network-only.\n *\n * @remarks\n * Every method reads upstream over HTTPS with a 10-second per-request\n * `AbortSignal.timeout` and bounded `concurrency` (default 6, never an\n * unbounded `Promise.all`). The default COLLECT posture captures each\n * dependency's `freshness` (`404` → `missing`, transport / other non-2xx →\n * `failed`) into the result; `strict` mode instead throws\n * `ScaffoldError('FETCH', …)` naming the failing URL. `guides`'s optional\n * `current` parameter is a caller-supplied local-mirror content map keyed by\n * dependency NAME (the `diffPlan` caller-supplied-reference pattern): WITH the\n * map, a fetched guide byte-equal to its entry verdicts `current`, anything\n * differing or absent from the map verdicts `behind`; WITHOUT the map, every\n * successful fetch verdicts `behind` (no reference means it needs syncing).\n * `pull` builds that map itself from the TARGET's declared dependency mirrors;\n * `mirror` builds it from the registry's exact organization package list,\n * excluding the target's own guide and issuing no registry version reads. Both\n * verdicts are target-relative; `write` commits only the\n * `behind` guides (never `current`, `missing`, or `failed`, which carries no\n * trustworthy content) under the same realpath-anchored containment law\n * `Materializer` enforces. After `destroy()` every method throws `DESTROYED`;\n * teardown is idempotent, emitter last.\n *\n * @example\n * ```ts\n * import { createSync } from '@orkestrel/scaffold/server'\n *\n * const sync = createSync()\n * const report = await sync.pull('.')\n * if (report.failed === 0) await sync.write(report, '.')\n * sync.destroy()\n * ```\n */\nexport class Sync implements SyncInterface {\n\treadonly #emitter: Emitter<SyncEventMap>\n\treadonly #guidesBase: string\n\treadonly #branch: string\n\treadonly #guidesTimeout: number\n\treadonly #registryBase: string\n\treadonly #registryTimeout: number\n\treadonly #concurrency: number\n\treadonly #retries: number\n\treadonly #strict: boolean\n\treadonly #limit: number\n\treadonly #items: number\n\treadonly #budget: number\n\treadonly #controller = new AbortController()\n\t#destroyed = false\n\n\tconstructor(options?: SyncOptions) {\n\t\tconst parsed = parseSyncOptions(options)\n\t\tthis.#emitter = new Emitter<SyncEventMap>({\n\t\t\t...(parsed.on === undefined ? {} : { on: parsed.on }),\n\t\t\t...(parsed.error === undefined ? {} : { error: parsed.error }),\n\t\t})\n\t\tthis.#guidesBase = parsed.guides?.base ?? 'https://raw.githubusercontent.com'\n\t\tthis.#branch = parsed.guides?.branch ?? 'main'\n\t\tthis.#guidesTimeout = parsed.guides?.timeout ?? DEFAULT_SYNC_TIMEOUT\n\t\tthis.#registryBase = parsed.registry?.base ?? 'https://registry.npmjs.org'\n\t\tthis.#registryTimeout = parsed.registry?.timeout ?? DEFAULT_SYNC_TIMEOUT\n\t\tthis.#concurrency = parsed.concurrency ?? DEFAULT_SYNC_CONCURRENCY\n\t\tthis.#retries = parsed.retries ?? 0\n\t\tthis.#strict = parsed.strict ?? false\n\t\tthis.#limit = parsed.limit ?? DEFAULT_SYNC_LIMIT\n\t\tthis.#items = parsed.items ?? DEFAULT_SYNC_ITEMS\n\t\tthis.#budget = parsed.budget ?? DEFAULT_SYNC_BUDGET\n\t}\n\n\tget emitter(): EmitterInterface<SyncEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tasync lookup(names: readonly string[]): Promise<readonly VersionLookup[]> {\n\t\tthis.#ensureAlive()\n\t\treturn this.#lookup(names, Float64Array.of(this.#budget))\n\t}\n\n\tasync guides(\n\t\tdeps: readonly Dependency[],\n\t\tcurrent?: Readonly<Record<string, string>>,\n\t): Promise<readonly GuideSync[]> {\n\t\tthis.#ensureAlive()\n\t\tconst parsed = parseSyncDependencies(deps, false)\n\t\treturn this.#guides(\n\t\t\tparsed.map((dependency) => dependency.name),\n\t\t\tcurrent,\n\t\t\tFloat64Array.of(this.#budget),\n\t\t)\n\t}\n\n\tasync versions(deps: readonly Dependency[]): Promise<readonly VersionSync[]> {\n\t\tthis.#ensureAlive()\n\t\treturn this.#versions(deps, Float64Array.of(this.#budget))\n\t}\n\n\t#guides(\n\t\tnames: readonly string[],\n\t\tcurrent: Readonly<Record<string, string>> | undefined,\n\t\tallowance: SyncAllowance,\n\t): Promise<readonly GuideSync[]> {\n\t\tconst parsed = parseSyncNames(names)\n\t\tif (parsed.length > this.#items) {\n\t\t\tthrow new ScaffoldError('INVALID', 'Sync dependency count exceeds its item limit', {\n\t\t\t\titems: parsed.length,\n\t\t\t\tlimit: this.#items,\n\t\t\t})\n\t\t}\n\t\tconst reference = parseSyncCurrent(current, parsed, this.#budget)\n\t\treturn Sync.#runPool(parsed, this.#concurrency, async (name) => {\n\t\t\tconst short = packageShortName(name)\n\t\t\tconst url = this.#guideUrl(short)\n\t\t\tconst outcome = await Sync.#fetchText(\n\t\t\t\turl,\n\t\t\t\tthis.#guidesTimeout,\n\t\t\t\tthis.#retries,\n\t\t\t\tthis.#limit,\n\t\t\t\tallowance,\n\t\t\t\tthis.#controller.signal,\n\t\t\t)\n\t\t\tconst guide = Sync.#toGuideSync(name, short, outcome, reference)\n\t\t\tif (outcome.kind === 'failed') this.#emitter.emit('error', outcome.error)\n\t\t\tthis.#emitter.emit('guide', name)\n\t\t\tif (this.#strict && (guide.freshness === 'missing' || guide.freshness === 'failed')) {\n\t\t\t\tthrow new ScaffoldError('FETCH', `Failed to fetch guide at ${url}`, {\n\t\t\t\t\turl,\n\t\t\t\t\tname,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn guide\n\t\t})\n\t}\n\n\tasync #versions(\n\t\tdeps: readonly Dependency[],\n\t\tallowance: SyncAllowance,\n\t): Promise<readonly VersionSync[]> {\n\t\tconst parsed = parseSyncDependencies(deps, true)\n\t\tconst lookups = await this.#lookup(\n\t\t\tparsed.map((dependency) => dependency.name),\n\t\t\tallowance,\n\t\t)\n\t\tconst versions: VersionSync[] = []\n\t\tfor (let index = 0; index < parsed.length; index += 1) {\n\t\t\tconst dep = parsed[index]\n\t\t\tconst lookup = lookups[index]\n\t\t\tif (dep === undefined || lookup === undefined) {\n\t\t\t\tthrow new ScaffoldError('INVALID', 'Sync version lookup result is incomplete')\n\t\t\t}\n\t\t\tversions.push(Sync.#toVersionSync(dep, lookup))\n\t\t}\n\t\treturn Object.freeze(versions)\n\t}\n\n\t#lookup(names: readonly string[], allowance: SyncAllowance): Promise<readonly VersionLookup[]> {\n\t\tconst parsed = parseSyncNames(names)\n\t\tif (parsed.length > this.#items) {\n\t\t\tthrow new ScaffoldError('INVALID', 'Sync dependency count exceeds its item limit', {\n\t\t\t\titems: parsed.length,\n\t\t\t\tlimit: this.#items,\n\t\t\t})\n\t\t}\n\t\treturn Sync.#runPool(parsed, this.#concurrency, async (name) => {\n\t\t\tconst url = this.#registryUrl(name)\n\t\t\tconst outcome = await Sync.#fetchText(\n\t\t\t\turl,\n\t\t\t\tthis.#registryTimeout,\n\t\t\t\tthis.#retries,\n\t\t\t\tthis.#limit,\n\t\t\t\tallowance,\n\t\t\t\tthis.#controller.signal,\n\t\t\t)\n\t\t\tconst version = Sync.#toVersionLookup(name, outcome)\n\t\t\tif (outcome.kind === 'failed') this.#emitter.emit('error', outcome.error)\n\t\t\tthis.#emitter.emit('version', name)\n\t\t\tif (this.#strict && (version.freshness === 'missing' || version.freshness === 'failed')) {\n\t\t\t\tthrow new ScaffoldError('FETCH', `Failed to fetch registry version at ${url}`, {\n\t\t\t\t\turl,\n\t\t\t\t\tname,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn version\n\t\t})\n\t}\n\n\t/**\n\t * The fleet package catalog, sourced from the npm registry — the\n\t * AUTHORITATIVE enumeration (never a caller-supplied root).\n\t *\n\t * @returns One {@link CatalogEntry} per `@orkestrel/*` package the registry\n\t * lists, code-unit sorted by `name`.\n\t * @remarks\n\t * Three fetches build each entry: (1) the org's exact package-list\n\t * (`-/org/orkestrel/package`) enumerates every published name — an\n\t * unreachable or malformed response throws a coded `ScaffoldError('FETCH')`\n\t * UNCONDITIONALLY (never gated by `strict`), since without it there is no\n\t * catalog to build; (2) each name's own registry packument supplies\n\t * `version` (`dist-tags.latest`) and a registry-path `description`\n\t * fallback — a failed/malformed packument keeps the entry (degraded:\n\t * `version: ''`) rather than dropping it, since the org list already\n\t * proved the package exists; (3) each name's own guide\n\t * (`guides/src/<short>.md`, same canonical URL as `guides()`, fetched\n\t * unauthenticated — every fleet repo is public) supplies the PREFERRED\n\t * `description` — its first blockquote's first paragraph — falling back\n\t * to the packument description when the guide 404s, faults, or carries no\n\t * blockquote; a 404 STAYS LISTED (it is a reachability signal, not an\n\t * absence) with a note reading `guide unreachable (HTTP 404 — repo\n\t * private or guide missing?)`. Emits `package` once per entry with a\n\t * combined human-readable `note` (empty when both fetches succeeded)\n\t * alongside the existing `error` events for each degraded sub-fetch.\n\t */\n\tasync catalog(): Promise<readonly CatalogEntry[]> {\n\t\tthis.#ensureAlive()\n\t\tconst allowance: SyncAllowance = Float64Array.of(this.#budget)\n\t\tconst names = await this.#packages(allowance)\n\t\tconst entries = await Sync.#runPool(names, this.#concurrency, async (name) => {\n\t\t\tconst packumentOutcome = await Sync.#fetchText(\n\t\t\t\tthis.#registryUrl(name),\n\t\t\t\tthis.#registryTimeout,\n\t\t\t\tthis.#retries,\n\t\t\t\tthis.#limit,\n\t\t\t\tallowance,\n\t\t\t\tthis.#controller.signal,\n\t\t\t)\n\t\t\tconst packument = Sync.#toPackument(packumentOutcome)\n\t\t\tconst short = packageShortName(name)\n\t\t\tconst guideOutcome = await Sync.#fetchText(\n\t\t\t\tthis.#guideUrl(short),\n\t\t\t\tthis.#guidesTimeout,\n\t\t\t\tthis.#retries,\n\t\t\t\tthis.#limit,\n\t\t\t\tallowance,\n\t\t\t\tthis.#controller.signal,\n\t\t\t)\n\t\t\tconst guide = Sync.#toGuideDescription(guideOutcome)\n\t\t\tif (packumentOutcome.kind === 'failed') this.#emitter.emit('error', packumentOutcome.error)\n\t\t\tif (guideOutcome.kind === 'failed') this.#emitter.emit('error', guideOutcome.error)\n\t\t\tconst description = guide.description ?? packument.description\n\t\t\tconst note = Sync.#combineNote(guide.note, packument.note)\n\t\t\tthis.#emitter.emit('package', name, note)\n\t\t\treturn { name, version: packument.version, description }\n\t\t})\n\t\treturn entries\n\t}\n\n\tasync pull(target: string, dependencies?: readonly Dependency[]): Promise<SyncReport> {\n\t\tthis.#ensureAlive()\n\t\tconst manifest = readManifest(target)\n\t\tconst declared = manifestToDependencies(manifest)\n\t\tconst deps = dependencies === undefined ? declared : parseSyncDependencies(dependencies, false)\n\t\tif (\n\t\t\tdependencies !== undefined &&\n\t\t\tdeps.some(\n\t\t\t\t(dependency) =>\n\t\t\t\t\t!declared.some(\n\t\t\t\t\t\t(candidate) =>\n\t\t\t\t\t\t\tcandidate.name === dependency.name && candidate.range === dependency.range,\n\t\t\t\t\t),\n\t\t\t)\n\t\t) {\n\t\t\tthrow new ScaffoldError('INVALID', 'Sync pull selection is not declared by the target')\n\t\t}\n\t\tconst name = manifestToName(manifest)\n\t\tconst guideNames = deps\n\t\t\t.map((dependency) => dependency.name)\n\t\t\t.filter((dependency) => dependency !== name)\n\t\tconst current = readGuideReferences(target, guideNames)\n\t\tconst allowance: SyncAllowance = Float64Array.of(this.#budget)\n\t\tconst guides = await this.#guides(guideNames, current, allowance)\n\t\tconst versions = await this.#versions(deps, allowance)\n\t\tconst report = syncReportOf(target, guides, versions)\n\t\tthis.#emitter.emit('done', report)\n\t\treturn report\n\t}\n\n\tasync mirror(target: string): Promise<SyncReport> {\n\t\tthis.#ensureAlive()\n\t\tconst manifest = readManifest(target)\n\t\tconst name = manifestToName(manifest)\n\t\tconst allowance: SyncAllowance = Float64Array.of(this.#budget)\n\t\tconst names = (await this.#packages(allowance)).filter((candidate) => candidate !== name)\n\t\tconst current = readGuideReferences(target, names)\n\t\tconst guides = await this.#guides(names, current, allowance)\n\t\tconst report = syncReportOf(target, guides, [])\n\t\tthis.#emitter.emit('done', report)\n\t\treturn report\n\t}\n\n\tasync write(report: SyncReport, target: string): Promise<readonly string[]> {\n\t\tthis.#ensureAlive()\n\t\tif (!isFilesystemPath(target)) {\n\t\t\tthrow new ScaffoldError('WRITE', 'Sync write target is malformed or exceeds its bounds', {\n\t\t\t\ttarget,\n\t\t\t})\n\t\t}\n\t\tif (!hasOnlyDataProperties(report) || !isSyncReport(report)) {\n\t\t\tthrow new ScaffoldError('WRITE', 'Sync report is malformed')\n\t\t}\n\t\tconst snapshot = attempt(() => structuredClone(report))\n\t\tconst parsed = snapshot.success ? parseSyncReport(snapshot.value) : undefined\n\t\tif (parsed === undefined) {\n\t\t\tthrow new ScaffoldError('WRITE', 'Sync report is malformed', {\n\t\t\t\t...(snapshot.success ? {} : { error: snapshot.error }),\n\t\t\t})\n\t\t}\n\t\tconst destinations = resolveGuideWrites(parsed.guides, target)\n\t\tconst written = destinations.map(({ guide }) => guide.path)\n\t\tif (written.length === 0) return written\n\t\tconst preconditions: WritePrecondition[] = []\n\t\tfor (const { guide, destination } of destinations) {\n\t\t\tif (guide.baseline === undefined || !SYNC_BASELINE_PATTERN.test(guide.baseline)) {\n\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t'WRITE',\n\t\t\t\t\t`Guide baseline is missing or malformed at ${guide.path}`,\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: guide.path,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst status = attempt(() => lstatSync(destination))\n\t\t\tif (guide.baseline === 'absent') {\n\t\t\t\tif (status.success || !isMissingPathError(status.error)) {\n\t\t\t\t\tthrow new ScaffoldError('WRITE', `Guide destination changed at ${guide.path}`, {\n\t\t\t\t\t\tpath: guide.path,\n\t\t\t\t\t\t...(status.success ? {} : { error: status.error }),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tpreconditions.push({ path: guide.path, shape: 'absent' })\n\t\t\t} else if (\n\t\t\t\t!status.success ||\n\t\t\t\t!status.value.isFile() ||\n\t\t\t\tstatus.value.isSymbolicLink() ||\n\t\t\t\tstatus.value.nlink !== 1 ||\n\t\t\t\tdigestFile(destination) !== guide.baseline\n\t\t\t) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `Guide destination changed at ${guide.path}`, {\n\t\t\t\t\tpath: guide.path,\n\t\t\t\t\t...(status.success ? {} : { error: status.error }),\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tpreconditions.push({\n\t\t\t\t\tpath: guide.path,\n\t\t\t\t\tshape: 'file',\n\t\t\t\t\tdigest: guide.baseline,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tconst transaction = WriteTransaction.create(target, written, preconditions)\n\t\tconst staged = attempt(() => {\n\t\t\tfor (const { guide } of destinations) {\n\t\t\t\tif (Buffer.byteLength(guide.content, 'utf8') > MAX_ARTIFACT_BYTES) {\n\t\t\t\t\tthrow new ScaffoldError('WRITE', `Guide exceeds the artifact limit at ${guide.path}`, {\n\t\t\t\t\t\tpath: guide.path,\n\t\t\t\t\t\tlimit: MAX_ARTIFACT_BYTES,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tvalidateWriteDirectories(transaction)\n\t\t\t\tconst candidate = resolvePhysicalPath(transaction.stage, guide.path, 'WRITE', 'staging')\n\t\t\t\tmkdirSync(dirname(candidate), { recursive: true })\n\t\t\t\tvalidateWriteDirectories(transaction)\n\t\t\t\tconst destination = resolvePhysicalPath(transaction.stage, guide.path, 'WRITE', 'staging')\n\t\t\t\twriteFileSync(destination, guide.content, {\n\t\t\t\t\tencoding: 'utf8',\n\t\t\t\t\tflag: 'wx',\n\t\t\t\t})\n\t\t\t\tconst status = lstatSync(destination)\n\t\t\t\tif (\n\t\t\t\t\t!status.isFile() ||\n\t\t\t\t\tstatus.isSymbolicLink() ||\n\t\t\t\t\tstatus.nlink !== 1 ||\n\t\t\t\t\tdigestFile(destination) !== digestText(guide.content)\n\t\t\t\t) {\n\t\t\t\t\tthrow new ScaffoldError('WRITE', `Staged guide changed at ${guide.path}`, {\n\t\t\t\t\t\tpath: guide.path,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tvalidateWriteDirectories(transaction)\n\t\t\t}\n\t\t})\n\t\tif (!staged.success) {\n\t\t\tconst cleanup = attempt(() => discardWriteTransaction(transaction))\n\t\t\tthis.#emitter.emit('error', staged.error)\n\t\t\tthrow new ScaffoldError('WRITE', 'Failed to stage guide synchronization', {\n\t\t\t\ttarget,\n\t\t\t\terror: staged.error,\n\t\t\t\tcleanup: cleanup.success ? undefined : cleanup.error,\n\t\t\t})\n\t\t}\n\t\tconst committed = attempt(() => commitWriteTransaction(transaction, written))\n\t\tif (!committed.success) {\n\t\t\tthis.#emitter.emit('error', committed.error)\n\t\t\tthrow committed.error\n\t\t}\n\t\tfor (const path of written) this.#emitter.emit('write', path)\n\t\treturn written\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tthis.#controller.abort()\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// The canonical raw.githubusercontent.com form is\n\t// `/orkestrel/<short>/refs/heads/<branch>/…`. Requests use\n\t// `redirect: 'manual'`, so this direct URL never relaxes redirect policy.\n\t#guideUrl(short: string): string {\n\t\tconst branch = this.#branch\n\t\t\t.split('/')\n\t\t\t.map((segment) => encodeURIComponent(segment))\n\t\t\t.join('/')\n\t\tconst encoded = encodeURIComponent(short)\n\t\treturn `${this.#guidesBase}/orkestrel/${encoded}/refs/heads/${branch}/guides/src/${encoded}.md`\n\t}\n\n\t// npm's canonical scoped-package registry path keeps the literal `@` and\n\t// encodes only the slash (`encodeURIComponent` would also escape the `@`\n\t// into `%40`, which registries accept but which diverges from the\n\t// canonical form). A valid npm package name — `@orkestrel/*` or any other\n\t// scoped/unscoped name (`extras` may now carry either, per\n\t// `EXTRA_NAME_PATTERN`) — has at most one `/` (the single scope\n\t// boundary), so this plain first-occurrence slash replace is exhaustive\n\t// for every name `versions()` is called with, not just `@orkestrel/*`.\n\t#registryUrl(name: string): string {\n\t\treturn `${this.#registryBase}/${name.replace('/', '%2F')}`\n\t}\n\n\t// The registry's exact-membership org package list — a flat name→access\n\t// map, not a fuzzy relevance search — is `catalog()`'s authoritative\n\t// enumeration source (never `-/v1/search`, whose `scope:` qualifier does\n\t// not filter as its name implies).\n\t#orgUrl(): string {\n\t\treturn `${this.#registryBase}/-/org/orkestrel/package`\n\t}\n\n\tasync #packages(allowance: SyncAllowance): Promise<readonly string[]> {\n\t\tconst url = this.#orgUrl()\n\t\tconst outcome = await Sync.#fetchText(\n\t\t\turl,\n\t\t\tthis.#registryTimeout,\n\t\t\tthis.#retries,\n\t\t\tthis.#limit,\n\t\t\tallowance,\n\t\t\tthis.#controller.signal,\n\t\t)\n\t\tconst names = Sync.#toOrgPackages(outcome, url)\n\t\tif (names.length > this.#items) {\n\t\t\tthrow new ScaffoldError('FETCH', `Package list at ${url} exceeds the item limit`, {\n\t\t\t\turl,\n\t\t\t\titems: names.length,\n\t\t\t\tlimit: this.#items,\n\t\t\t})\n\t\t}\n\t\treturn [...names].sort((left, right) => (left < right ? -1 : left > right ? 1 : 0))\n\t}\n\n\t// Bounded-concurrency worker pool — never an unbounded `Promise.all` (§12).\n\t// `concurrency` workers pull from a shared cursor over `items`, each\n\t// running `worker` to completion before pulling the next index; results\n\t// land back at their ORIGINAL index, so the returned array preserves\n\t// input order. Fail-fast-SAFELY: the first worker error stops the cursor\n\t// from issuing further items (a `stopped` flag, checked before each pull)\n\t// and every worker is awaited via `Promise.allSettled` — so a sibling's\n\t// later rejection is always observed, never an `unhandledRejection` — then\n\t// the FIRST error is rethrown.\n\tstatic async #runPool<T, R>(\n\t\titems: readonly T[],\n\t\tconcurrency: number,\n\t\tworker: (item: T) => Promise<R>,\n\t): Promise<R[]> {\n\t\tconst results: R[] = new Array(items.length)\n\t\tconst state: {\n\t\t\tcursor: number\n\t\t\tstopped: boolean\n\t\t\tfirstError: { readonly error: unknown } | undefined\n\t\t} = { cursor: 0, stopped: false, firstError: undefined }\n\t\tconst workers = Array.from({ length: Math.min(concurrency, items.length) }, () =>\n\t\t\tSync.#drain({ items, worker, results, state }),\n\t\t)\n\t\tawait Promise.allSettled(workers)\n\t\tif (state.firstError !== undefined) throw state.firstError.error\n\t\treturn results\n\t}\n\n\t// One worker's pull-and-run loop over the shared pool `state` — extracted\n\t// from `#runPool` so no function is declared inside another (§4). `state`\n\t// carries the mutable cursor/stopped/firstError coordination shared by\n\t// every concurrent worker; `items`, `worker`, and `results` are the pool's\n\t// immutable inputs and output sink.\n\tstatic async #drain<T, R>(pool: {\n\t\treadonly items: readonly T[]\n\t\treadonly worker: (item: T) => Promise<R>\n\t\treadonly results: R[]\n\t\treadonly state: {\n\t\t\tcursor: number\n\t\t\tstopped: boolean\n\t\t\tfirstError: { readonly error: unknown } | undefined\n\t\t}\n\t}): Promise<void> {\n\t\tfor (;;) {\n\t\t\tif (pool.state.stopped) return\n\t\t\tconst index = pool.state.cursor\n\t\t\tpool.state.cursor += 1\n\t\t\tif (index >= pool.items.length) return\n\t\t\tconst item = pool.items[index]\n\t\t\tif (item === undefined) return\n\t\t\ttry {\n\t\t\t\tpool.results[index] = await pool.worker(item)\n\t\t\t} catch (error) {\n\t\t\t\tif (pool.state.firstError === undefined) pool.state.firstError = { error }\n\t\t\t\tpool.state.stopped = true\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// One HTTPS GET with a per-request `AbortSignal.timeout` and up to\n\t// `retries` additional attempts on a TRANSPORT fault (a thrown/rejected\n\t// fetch, a non-2xx non-404 response, a manual 3xx redirect, or a body\n\t// exceeding `limit` bytes) — a `404` is a definitive upstream answer\n\t// and is never retried. Every `failed` outcome carries `note`, the LAST\n\t// attempt's human-readable cause — a transport error message (with an\n\t// `ECONNREFUSED`-style cause code appended when present), an `HTTP\n\t// <status>`, the fixed redirect-blocked string, or the oversized-body\n\t// message — so a caller can tell WHY, not just THAT, the fetch failed.\n\tstatic async #fetchText(\n\t\turl: string,\n\t\ttimeout: number,\n\t\tretries: number,\n\t\tlimit: number,\n\t\tallowance: SyncAllowance,\n\t\tsignal: AbortSignal,\n\t): Promise<\n\t\t| { readonly kind: 'ok'; readonly text: string }\n\t\t| { readonly kind: 'missing' }\n\t\t| { readonly kind: 'failed'; readonly error: unknown; readonly note: string }\n\t> {\n\t\tlet lastError: unknown\n\t\tlet lastNote = ''\n\t\tfor (let retry = 0; retry <= retries; retry += 1) {\n\t\t\tif (signal.aborted) {\n\t\t\t\tthrow new ScaffoldError('DESTROYED', 'Sync has been destroyed')\n\t\t\t}\n\t\t\ttry {\n\t\t\t\t// `redirect: 'manual'` prevents a compromised or misconfigured endpoint\n\t\t\t\t// must not silently redirect cross-host; any 3xx (or the opaque\n\t\t\t\t// redirect response `redirect: 'manual'` itself resolves) is treated\n\t\t\t\t// as a distinct, named transport fault — never a bare status code.\n\t\t\t\t// Every fetch is unauthenticated (no headers) — every fleet repo is\n\t\t\t\t// public, so reachability alone is the signal.\n\t\t\t\tconst response = await fetch(url, {\n\t\t\t\t\tsignal: AbortSignal.any([signal, AbortSignal.timeout(timeout)]),\n\t\t\t\t\tredirect: 'manual',\n\t\t\t\t})\n\t\t\t\tif (response.status === 404) {\n\t\t\t\t\tawait Sync.#cancel(response)\n\t\t\t\t\treturn { kind: 'missing' }\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tresponse.type === 'opaqueredirect' ||\n\t\t\t\t\t(response.status >= 300 && response.status < 400)\n\t\t\t\t) {\n\t\t\t\t\tlastNote = 'redirected (redirect following is disabled)'\n\t\t\t\t\tlastError = new Error(`Redirect blocked for ${url}`)\n\t\t\t\t\tawait Sync.#cancel(response)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tlastNote = `HTTP ${String(response.status)}`\n\t\t\t\t\tlastError = new Error(`Unexpected HTTP status ${response.status} for ${url}`)\n\t\t\t\t\tawait Sync.#cancel(response)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconst read = await Sync.#readBounded(response, url, limit, allowance)\n\t\t\t\tif (!read.ok) {\n\t\t\t\t\tlastError = read.error\n\t\t\t\t\tlastNote = read.note\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treturn { kind: 'ok', text: read.text }\n\t\t\t} catch (error) {\n\t\t\t\tif (signal.aborted) {\n\t\t\t\t\tthrow new ScaffoldError('DESTROYED', 'Sync has been destroyed', { error })\n\t\t\t\t}\n\t\t\t\tlastError = error\n\t\t\t\tlastNote = Sync.#transportNote(error)\n\t\t\t}\n\t\t}\n\t\treturn { kind: 'failed', error: lastError, note: lastNote }\n\t}\n\n\tstatic async #cancel(response: Response): Promise<void> {\n\t\tawait response.body?.cancel()\n\t}\n\n\t// A thrown/rejected `fetch`'s message, with the underlying cause's `code`\n\t// (e.g. `ECONNREFUSED`, `ETIMEDOUT`) appended when the runtime attaches\n\t// one — Node's `fetch failed` wraps the real socket error in `.cause`.\n\tstatic #transportNote(error: unknown): string {\n\t\tif (!(error instanceof Error)) return String(error)\n\t\tconst code = Sync.#causeCode(error)\n\t\treturn code !== undefined ? `${error.message}: ${code}` : error.message\n\t}\n\n\tstatic #causeCode(error: Error): string | undefined {\n\t\tconst cause = error.cause\n\t\tif (typeof cause !== 'object' || cause === null) return undefined\n\t\tif (!('code' in cause)) return undefined\n\t\treturn typeof cause.code === 'string' ? cause.code : undefined\n\t}\n\n\t// Reads `response.body` incrementally, counting bytes, aborting past\n\t// `limit` (a declared oversized `Content-Length` short-circuits before any\n\t// read) — an overflow is reported as a transport fault, handled by the\n\t// caller exactly like any other (retry-eligible, then `failed` / strict\n\t// `FETCH`). `response.body` may be `null` (e.g. an empty reply); that\n\t// decodes to an empty string with no reader loop.\n\tstatic async #readBounded(\n\t\tresponse: Response,\n\t\turl: string,\n\t\tlimit: number,\n\t\tallowance: SyncAllowance,\n\t): Promise<\n\t\t| { readonly ok: true; readonly text: string }\n\t\t| { readonly ok: false; readonly error: unknown; readonly note: string }\n\t> {\n\t\tconst declared = response.headers.get('content-length')\n\t\tif (declared !== null) {\n\t\t\tconst declaredBytes = Number(declared)\n\t\t\tif (\n\t\t\t\tNumber.isFinite(declaredBytes) &&\n\t\t\t\t(declaredBytes > limit || declaredBytes > (allowance[0] ?? 0))\n\t\t\t) {\n\t\t\t\tawait response.body?.cancel()\n\t\t\t\tconst threshold = Math.min(limit, allowance[0] ?? 0)\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: new Error(\n\t\t\t\t\t\t`Response body for ${url} declares ${String(declaredBytes)} bytes, exceeding the ${String(threshold)}-byte allowance`,\n\t\t\t\t\t),\n\t\t\t\t\tnote: `response exceeded allowance (${String(threshold)} bytes)`,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst body = response.body\n\t\tif (body === null) return { ok: true, text: '' }\n\t\tconst reader = body.getReader()\n\t\tconst decoder = new TextDecoder('utf-8', { fatal: true })\n\t\tconst chunks: string[] = []\n\t\tlet total = 0\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst { done, value } = await reader.read()\n\t\t\t\tif (done) break\n\t\t\t\ttotal += value.byteLength\n\t\t\t\tif (total > limit || value.byteLength > (allowance[0] ?? 0)) {\n\t\t\t\t\tawait reader.cancel()\n\t\t\t\t\tconst threshold = Math.min(limit, total + (allowance[0] ?? 0) - value.byteLength)\n\t\t\t\t\tallowance[0] = Math.max(0, (allowance[0] ?? 0) - value.byteLength)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: new Error(\n\t\t\t\t\t\t\t`Response body for ${url} exceeded the ${String(threshold)}-byte allowance`,\n\t\t\t\t\t\t),\n\t\t\t\t\t\tnote: `response exceeded allowance (${String(threshold)} bytes)`,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tallowance[0] = (allowance[0] ?? 0) - value.byteLength\n\t\t\t\tchunks.push(decoder.decode(value, { stream: true }))\n\t\t\t}\n\t\t\tchunks.push(decoder.decode())\n\t\t} catch (error) {\n\t\t\tawait reader.cancel(error).catch(() => undefined)\n\t\t\tthrow error\n\t\t} finally {\n\t\t\treader.releaseLock()\n\t\t}\n\t\treturn { ok: true, text: chunks.join('') }\n\t}\n\n\tstatic #toGuideSync(\n\t\tname: string,\n\t\tshort: string,\n\t\toutcome:\n\t\t\t| { readonly kind: 'ok'; readonly text: string }\n\t\t\t| { readonly kind: 'missing' }\n\t\t\t| { readonly kind: 'failed'; readonly error: unknown; readonly note: string },\n\t\tcurrent?: Readonly<Record<string, string>>,\n\t): GuideSync {\n\t\tconst path = `guides/src/${short}.md`\n\t\tconst local = current?.[name]\n\t\tconst baseline =\n\t\t\tcurrent === undefined ? undefined : local === undefined ? 'absent' : digestText(local)\n\t\tif (outcome.kind === 'missing') {\n\t\t\treturn {\n\t\t\t\tname,\n\t\t\t\tpath,\n\t\t\t\tcontent: '',\n\t\t\t\tfreshness: 'missing',\n\t\t\t\tnote: 'HTTP 404',\n\t\t\t\t...(baseline === undefined ? {} : { baseline }),\n\t\t\t}\n\t\t}\n\t\tif (outcome.kind === 'failed') {\n\t\t\treturn {\n\t\t\t\tname,\n\t\t\t\tpath,\n\t\t\t\tcontent: '',\n\t\t\t\tfreshness: 'failed',\n\t\t\t\tnote: outcome.note,\n\t\t\t\t...(baseline === undefined ? {} : { baseline }),\n\t\t\t}\n\t\t}\n\t\tconst freshness: Freshness =\n\t\t\tcurrent !== undefined && local !== undefined && local === outcome.text ? 'current' : 'behind'\n\t\treturn {\n\t\t\tname,\n\t\t\tpath,\n\t\t\tcontent: outcome.text,\n\t\t\tfreshness,\n\t\t\t...(baseline === undefined ? {} : { baseline }),\n\t\t}\n\t}\n\n\tstatic #toVersionLookup(\n\t\tname: string,\n\t\toutcome:\n\t\t\t| { readonly kind: 'ok'; readonly text: string }\n\t\t\t| { readonly kind: 'missing' }\n\t\t\t| { readonly kind: 'failed'; readonly error: unknown; readonly note: string },\n\t): VersionLookup {\n\t\tif (outcome.kind === 'missing') {\n\t\t\treturn {\n\t\t\t\tname,\n\t\t\t\tfreshness: 'missing',\n\t\t\t\tnote: 'HTTP 404',\n\t\t\t}\n\t\t}\n\t\tif (outcome.kind === 'failed') {\n\t\t\treturn {\n\t\t\t\tname,\n\t\t\t\tfreshness: 'failed',\n\t\t\t\tnote: outcome.note,\n\t\t\t}\n\t\t}\n\t\tconst latest = Sync.#parseLatest(outcome.text)\n\t\tif (latest === undefined) {\n\t\t\treturn {\n\t\t\t\tname,\n\t\t\t\tfreshness: 'failed',\n\t\t\t\tnote: 'malformed registry response (missing dist-tags.latest)',\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tname,\n\t\t\tlatest,\n\t\t\tfreshness: 'behind',\n\t\t}\n\t}\n\n\tstatic #toVersionSync(dep: Dependency, lookup: VersionLookup): VersionSync {\n\t\tif (lookup.freshness !== 'behind') {\n\t\t\treturn {\n\t\t\t\tname: dep.name,\n\t\t\t\trange: dep.range,\n\t\t\t\tlatest: '',\n\t\t\t\tfreshness: lookup.freshness,\n\t\t\t\tnote: lookup.note,\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tname: dep.name,\n\t\t\trange: dep.range,\n\t\t\tlatest: lookup.latest,\n\t\t\tfreshness: rangeToFreshness(dep.range, lookup.latest),\n\t\t}\n\t}\n\n\t// The org package-list response is the WHOLE reason `catalog()` can claim\n\t// to be authoritative — an unreachable or malformed response means there\n\t// IS no catalog, so this throws unconditionally (never gated by\n\t// `strict`), unlike every other collect-mode FETCH outcome in this class.\n\tstatic #toOrgPackages(\n\t\toutcome:\n\t\t\t| { readonly kind: 'ok'; readonly text: string }\n\t\t\t| { readonly kind: 'missing' }\n\t\t\t| { readonly kind: 'failed'; readonly error: unknown; readonly note: string },\n\t\turl: string,\n\t): readonly string[] {\n\t\tif (outcome.kind === 'missing' || outcome.kind === 'failed') {\n\t\t\tconst note = outcome.kind === 'missing' ? 'HTTP 404' : outcome.note\n\t\t\tthrow new ScaffoldError('FETCH', `Failed to fetch the package list at ${url}`, { url, note })\n\t\t}\n\t\tconst parsed = parseJSON(outcome.text)\n\t\tif (!isRecord(parsed)) {\n\t\t\tthrow new ScaffoldError('FETCH', `Malformed package list response at ${url}`, { url })\n\t\t}\n\t\tconst names = Object.keys(parsed)\n\t\tif (names.length === 0 || names.some((name) => !DEPENDENCY_NAME_PATTERN.test(name))) {\n\t\t\tthrow new ScaffoldError('FETCH', `Malformed package list response at ${url}`, { url })\n\t\t}\n\t\treturn names\n\t}\n\n\t// A packument fetch that fails or comes back malformed keeps the entry\n\t// (the org list already proved the package exists) rather than dropping\n\t// it — degraded, never absent. The FULL packument (never the abbreviated\n\t// `Accept` form, which omits `description`) supplies both `dist-tags.latest`\n\t// and the top-level `description` — the registry-path fallback description.\n\tstatic #toPackument(\n\t\toutcome:\n\t\t\t| { readonly kind: 'ok'; readonly text: string }\n\t\t\t| { readonly kind: 'missing' }\n\t\t\t| { readonly kind: 'failed'; readonly error: unknown; readonly note: string },\n\t): { readonly version: string; readonly description: string; readonly note: string } {\n\t\tif (outcome.kind === 'missing') return { version: '', description: '', note: 'HTTP 404' }\n\t\tif (outcome.kind === 'failed') {\n\t\t\treturn { version: '', description: '', note: outcome.note }\n\t\t}\n\t\tconst parsed = parseJSON(outcome.text)\n\t\tif (parsed === undefined) {\n\t\t\treturn {\n\t\t\t\tversion: '',\n\t\t\t\tdescription: '',\n\t\t\t\tnote: 'malformed registry response (invalid JSON)',\n\t\t\t}\n\t\t}\n\t\tif (!isRecord(parsed)) {\n\t\t\treturn {\n\t\t\t\tversion: '',\n\t\t\t\tdescription: '',\n\t\t\t\tnote: 'malformed registry response (not an object)',\n\t\t\t}\n\t\t}\n\t\tconst distTags = ownDataValue(parsed, 'dist-tags')\n\t\tconst latest = ownDataValue(distTags, 'latest')\n\t\tconst version =\n\t\t\tisRecord(distTags) && typeof latest === 'string' && VERSION_PATTERN.test(latest) ? latest : ''\n\t\tconst rawDescription = ownDataValue(parsed, 'description')\n\t\tconst description = isCatalogDescription(rawDescription) ? rawDescription : ''\n\t\tconst note = version === '' ? 'malformed registry response (missing dist-tags.latest)' : ''\n\t\treturn { version, description, note }\n\t}\n\n\t// The guide-fetch counterpart of `#toPackument` — `description` is\n\t// `undefined` (never `''`) on ANY degradation (404, transport fault, no\n\t// blockquote) so `catalog()`'s caller can cleanly fall back to the\n\t// packument description with `??`. Every fleet repo is public, so a guide\n\t// 404 is a READINESS signal (repo private or guide not yet written), not\n\t// an absence — the entry STAYS LISTED with this exact note text.\n\tstatic #toGuideDescription(\n\t\toutcome:\n\t\t\t| { readonly kind: 'ok'; readonly text: string }\n\t\t\t| { readonly kind: 'missing' }\n\t\t\t| { readonly kind: 'failed'; readonly error: unknown; readonly note: string },\n\t): { readonly description: string | undefined; readonly note: string } {\n\t\tif (outcome.kind === 'missing') {\n\t\t\treturn {\n\t\t\t\tdescription: undefined,\n\t\t\t\tnote: 'guide unreachable (HTTP 404 — repo private or guide missing?)',\n\t\t\t}\n\t\t}\n\t\tif (outcome.kind === 'failed') return { description: undefined, note: outcome.note }\n\t\tconst description = guideToDescription(outcome.text)\n\t\treturn description !== undefined\n\t\t\t? { description, note: '' }\n\t\t\t: { description: undefined, note: 'guide has no blockquote description' }\n\t}\n\n\t// Combines a degraded guide/packument note into one human-readable string\n\t// for `SyncEventMap['package']`'s `note` — empty when both succeeded.\n\tstatic #combineNote(guideNote: string, packumentNote: string): string {\n\t\tconst parts: string[] = []\n\t\tif (packumentNote !== '') parts.push(`version unavailable — ${packumentNote}`)\n\t\tif (guideNote !== '') parts.push(`description from registry — ${guideNote}`)\n\t\treturn parts.join('; ')\n\t}\n\n\tstatic #parseLatest(text: string): string | undefined {\n\t\tconst parsed = parseJSON(text)\n\t\tif (!isRecord(parsed)) return undefined\n\t\tconst distTags = ownDataValue(parsed, 'dist-tags')\n\t\tif (!isRecord(distTags)) return undefined\n\t\tconst latest = ownDataValue(distTags, 'latest')\n\t\treturn typeof latest === 'string' && VERSION_PATTERN.test(latest) ? latest : undefined\n\t}\n\n\t#ensureAlive(): void {\n\t\tif (this.#destroyed) throw new ScaffoldError('DESTROYED', 'Sync has been destroyed')\n\t}\n}\n","import type {\n\tMaterializerInterface,\n\tMaterializerOptions,\n\tSyncInterface,\n\tSyncOptions,\n} from './types.js'\nimport { Materializer } from './Materializer.js'\nimport { Sync } from './Sync.js'\n\n/**\n * Create a `MaterializerInterface` (server) — the materialization entity,\n * seeded from `MaterializerOptions`.\n *\n * @param options - Optional `host` root override, emitter hooks, and error handler\n * @returns A {@link MaterializerInterface}\n *\n * @example\n * ```ts\n * import { createMaterializer } from '@orkestrel/scaffold/server'\n *\n * const materializer = createMaterializer()\n * materializer.destroy()\n * ```\n */\nexport function createMaterializer(options?: MaterializerOptions): MaterializerInterface {\n\treturn new Materializer(options)\n}\n\n/**\n * Create a `SyncInterface` (server) — the upstream-synchronization entity,\n * seeded from `SyncOptions`.\n *\n * @param options - Optional endpoint bases/branch, concurrency, retries, strict, emitter hooks, and error handler\n * @returns A {@link SyncInterface}\n *\n * @example\n * ```ts\n * import { createSync } from '@orkestrel/scaffold/server'\n *\n * const sync = createSync()\n * sync.destroy()\n * ```\n */\nexport function createSync(options?: SyncOptions): SyncInterface {\n\treturn new Sync(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAcA,IAAa,oBAAuC,OAAO,OAAO;CACjE;CACA;CACA;AACD,CAAC;;AAGD,IAAa,qBAAqB;;AAGlC,IAAa,8BACZ;;AAGD,IAAa,+BAA+B;;AAG5C,IAAa,iCAAiC;;AAG9C,IAAa,kBAAkB;;AAG/B,IAAa,mBAAmB;;AAGhC,IAAa,iBAAiB;;AAG9B,IAAa,uBAAuB;;AAGpC,IAAa,yBAAyB;;AAGtC,IAAa,gCACZ;;AAGD,IAAa,uBAAuB;;AAGpC,IAAa,2BAA2B;;AAGxC,IAAa,mBAAmB;;AAGhC,IAAa,mBAAmB;;AAGhC,IAAa,uBAAuB;;AAGpC,IAAa,iBAAiB;;AAG9B,IAAa,qBAAqB;;AAGlC,IAAa,qBAAqB;;AAGlC,IAAa,iBAAiB;;AAG9B,IAAa,sBAAsB;;AAGnC,IAAa,kBAAkB;;AAG/B,IAAa,uBAAuB;;AAGpC,IAAa,yBAAyB;;AAGtC,IAAa,uBAAuB;;AAGpC,IAAa,sBAAsB;;;;AC3EnC,SAAgB,wBAAwB;CACvC,OAAO,YAAY;EAClB,MAAM,cAAc,YAAY;GAAE,KAAK;GAAG,KAAK;EAAqB,CAAC,CAAC;EACtE,QAAQ,cAAc,YAAY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,SAAS,QAAQ,GAAG,OAAO,KAAA;EAChC,MAAM,SAAS,aAAa,UAAU,QAAQ;EAC9C,OAAO,OAAO,WAAW,YAAY,gBAAgB,KAAK,MAAM,IAAI,SAAS,KAAA;CAC9E;CAEA,eAAqB;EACpB,IAAI,KAAKR,YAAY,MAAM,IAAI,cAAc,aAAa,yBAAyB;CACpF;AACD;;;;;;;;;;;;;;;;;;ACt6BA,SAAgB,mBAAmB,SAAsD;CACxF,OAAO,IAAI,aAAa,OAAO;AAChC;;;;;;;;;;;;;;;;AAiBA,SAAgB,WAAW,SAAsC;CAChE,OAAO,IAAI,KAAK,OAAO;AACxB"}
1
+ {"version":3,"file":"index.js","names":["#target","#root","#stage","#backup","#expectations","#created","#staged","#established","#taken","#resolve","#establish","#open","#recover","#claim","#stagePath","#assertOpen","#expectation","#preflight","#promote","#take","#opening","#closing","#emitter","#host","#manifest","#entries","#error","#reconcile","#assertAlive","#accept","#derive","#empty","#hydrate","#apply","#reconfirm","#bind","#rewrite","#recatalog","#redeclare","#purge","#destroyed","#expand","#roots","#expandRaw","#remap","#deferred","#presence","#read","#hydrated","#finish","#open","#copy","#close","#cell","#span","#defaultGuide","#defaultRegistry","#defaultBranch","#defaultTimeout","#defaultConcurrency","#defaultRetries","#defaultBudget","#scope","#unreadable","#emitter","#guideBase","#guideBranch","#guideTimeout","#registryBase","#registryTimeout","#concurrency","#retries","#limit","#budget","#controller","#endpoint","#assertAlive","#accept","#gather","#release","#mirror","#packages","#entry","#destroyed","#error","#read","#registryURL","#latest","#guideURL","#request","#body","#note","#drain"],"sources":["../../../src/server/constants.ts","../../../src/server/validators.ts","../../../src/server/helpers.ts","../../../src/server/WriteTransaction.ts","../../../src/server/Materializer.ts","../../../src/server/Upstream.ts","../../../src/server/factories.ts"],"sourcesContent":["/**\n * The drive prefix a Windows host path may open with.\n *\n * @remarks\n * The one segment allowed to carry a colon. Every other segment is measured by\n * {@link INVALID_SEGMENT_CHARACTER_PATTERN}, which refuses one, so a stream name\n * such as `file.txt:stream` cannot be smuggled through a later segment.\n */\nexport const DRIVE_PATTERN = /^[A-Za-z]:$/\n\n/**\n * Visible characters no host path segment may carry.\n *\n * @remarks\n * Narrower than the core path law by exactly one character: a backslash is a\n * separator on a Windows host rather than a forbidden character, so it is\n * normalized to `/` before the segments are measured instead of refused here.\n */\nexport const INVALID_SEGMENT_CHARACTER_PATTERN = /[<>:\"|?*]/\n\n/**\n * The Windows device names that stay reserved even when an extension follows.\n *\n * @remarks\n * Refused on every host rather than only on Windows. A generated workspace is\n * checked out on all of them, so a directory this package writes on Linux must\n * still be a name Windows can hold.\n */\nexport const RESERVED_SEGMENT_PATTERN =\n\t/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9]|conin\\$|conout\\$)(?:\\..*)?$/i\n\n/**\n * The exact SHA-256 syntax a digest is stated in: sixty-four lowercase hexadecimal digits.\n *\n * @remarks\n * Fixed length, unlike the core byte encoding, because a digest is one value of\n * one algorithm rather than a variable run of bytes. Lowercase only, so two\n * spellings of one digest can never compare unequal.\n */\nexport const DIGEST_PATTERN = /^[0-9a-f]{64}$/\n\n/**\n * The Git branch syntax the guide endpoint accepts.\n *\n * @remarks\n * A branch is caller-supplied and reaches a URL path, so it is closed to\n * alphanumerics, dot, underscore, hyphen, and the separator, must open with an\n * alphanumeric, and may carry no `..` anywhere. That last refusal is what stops\n * a branch from walking out of the guide directory it addresses.\n */\nexport const BRANCH_PATTERN = /^(?!.*\\.\\.)[A-Za-z0-9][A-Za-z0-9._/-]*$/\n\n/**\n * Maximum UTF-8 bytes one host path segment may encode to.\n *\n * @remarks\n * The limit every supported filesystem shares for a single name. It is a byte\n * count rather than a character count, because that is the unit the filesystem\n * imposes it in: eighty-six three-byte characters are already past it.\n */\nexport const MAX_PATH_SEGMENT_BYTES = 255\n\n/**\n * Maximum segments one host path may carry.\n *\n * @remarks\n * Bounds the work a path decision costs before any filesystem call is made. With\n * {@link MAX_PATH_SEGMENT_BYTES} it is also the real length ceiling of an\n * accepted path, well inside the core character ceiling.\n */\nexport const MAX_PATH_DEPTH = 64\n\n/**\n * Maximum paths one target's working-tree inventory may report.\n *\n * @remarks\n * Far above the core collection ceiling, and deliberately so. A tracked or dirty\n * path list is the target repository's own fact rather than an argument a caller\n * authored, so measuring it against the ceiling that bounds a public collection\n * would read a legitimately large checkout as hostile and refuse the deletion\n * verb on it.\n */\nexport const MAX_INVENTORY_PATHS = 100_000\n\n/** Maximum characters one caller-supplied upstream endpoint may carry. */\nexport const MAX_ENDPOINT_LENGTH = 2_048\n\n/** Maximum characters one guide branch may carry. */\nexport const MAX_BRANCH_LENGTH = 255\n\n/**\n * Maximum simultaneous upstream requests.\n *\n * @remarks\n * A ceiling rather than a default: the reader picks what it opens by, and this\n * is only what a caller may raise it to.\n */\nexport const MAX_UPSTREAM_CONCURRENCY = 64\n\n/** Maximum retries one upstream request may be given after a transport fault. */\nexport const MAX_UPSTREAM_RETRIES = 5\n\n/** Maximum timeout one upstream request may be given, in milliseconds. */\nexport const MAX_UPSTREAM_TIMEOUT = 300_000\n\n/**\n * The reserved metadata name a staged vendored host writes at its own root.\n *\n * @remarks\n * The one name a vendored file may never claim, because the staged root holds\n * the manifest under it. The producer refuses a storage name equal to it and the\n * reader looks for exactly this file, so both sides read one constant rather\n * than repeating a literal that only agrees by inspection.\n */\nexport const MANIFEST_NAME = 'manifest.json'\n","import type { Guard } from '@orkestrel/contract'\nimport type { EmitterHooks } from '@orkestrel/emitter'\nimport type { CatalogEntry, Dependency, Mirror } from '@src/core'\nimport type {\n\tHostManifest,\n\tManifestEntry,\n\tMaterializerEventMap,\n\tMaterializerOptions,\n\tRepository,\n\tUpstreamEventMap,\n\tUpstreamOptions,\n} from './types.js'\nimport {\n\tandOf,\n\tarrayOf,\n\tboundsOf,\n\tholds,\n\tisArray,\n\tisBoolean,\n\tisFunction,\n\tisInteger,\n\tisString,\n\trecordOf,\n\tstringOf,\n} from '@orkestrel/contract'\nimport {\n\tcomputeBytes,\n\tCONTROL_CHARACTER_PATTERN,\n\tisCatalogEntry,\n\tisCollection,\n\tisDependency,\n\tisDependencyName,\n\tisMirror,\n\tisPath,\n\tMAX_ARTIFACT_BYTES,\n\tMAX_PATH_LENGTH,\n\tMAX_TOTAL_ARTIFACT_BYTES,\n} from '@src/core'\nimport {\n\tBRANCH_PATTERN,\n\tDIGEST_PATTERN,\n\tDRIVE_PATTERN,\n\tINVALID_SEGMENT_CHARACTER_PATTERN,\n\tMAX_BRANCH_LENGTH,\n\tMAX_ENDPOINT_LENGTH,\n\tMAX_INVENTORY_PATHS,\n\tMAX_PATH_DEPTH,\n\tMAX_PATH_SEGMENT_BYTES,\n\tMAX_UPSTREAM_CONCURRENCY,\n\tMAX_UPSTREAM_RETRIES,\n\tMAX_UPSTREAM_TIMEOUT,\n\tRESERVED_SEGMENT_PATTERN,\n} from './constants.js'\n\n/**\n * Narrow a value to a path naming a location on this host.\n *\n * @param value - The candidate host path.\n * @returns `true` for a bounded absolute or relative path whose every segment is\n * portable across the supported filesystems.\n *\n * @remarks\n * The counterpart to the core path law, not a copy of it. A target directory and\n * the vendored host root are locations on the machine rather than paths inside a\n * workspace, so a drive prefix, a UNC share, and a backslash separator are all\n * admitted here and `..` is a legitimate way to name a sibling directory.\n * Containment is still enforced, but by the core law over the artifact paths\n * written beneath the target, not by this one.\n *\n * What it does refuse is a segment no supported filesystem can hold: an empty\n * one, a reserved Windows device name, a trailing dot or space, a wildcard or\n * redirection character, a colon anywhere but the drive prefix, and a name past\n * the byte ceiling. The character ceiling is read first so an oversized string is\n * refused before it is split.\n *\n * @example\n * ```ts\n * import { isFilesystemPath } from '@orkestrel/scaffold/server'\n *\n * isFilesystemPath('C:/Users/sample/project') // true\n * isFilesystemPath('../sibling') // true\n * isFilesystemPath('project/nul') // false\n * ```\n */\nexport function isFilesystemPath(value: unknown): value is string {\n\treturn holds(() => {\n\t\tif (!isString(value) || value.length === 0 || value.length > MAX_PATH_LENGTH) return false\n\t\tif (CONTROL_CHARACTER_PATTERN.test(value)) return false\n\t\tconst normalized = value.replaceAll('\\\\', '/')\n\t\t// A UNC share and a POSIX root are prefixes rather than segments, so the\n\t\t// root comes off before the segment law applies to what remains.\n\t\tconst rooted = normalized.startsWith('//')\n\t\t\t? normalized.slice(2)\n\t\t\t: normalized.startsWith('/')\n\t\t\t\t? normalized.slice(1)\n\t\t\t\t: normalized\n\t\tconst segments = rooted.split('/')\n\t\tif (segments.length > MAX_PATH_DEPTH) return false\n\t\tfor (const [index, segment] of segments.entries()) {\n\t\t\tif (segment === '.' || segment === '..') continue\n\t\t\tif (index === 0 && DRIVE_PATTERN.test(segment)) continue\n\t\t\tif (segment.length === 0) return false\n\t\t\tif (INVALID_SEGMENT_CHARACTER_PATTERN.test(segment)) return false\n\t\t\tif (segment.endsWith('.') || segment.endsWith(' ')) return false\n\t\t\tif (computeBytes(segment) > MAX_PATH_SEGMENT_BYTES) return false\n\t\t\tif (RESERVED_SEGMENT_PATTERN.test(segment)) return false\n\t\t}\n\t\treturn true\n\t})\n}\n\n/**\n * Narrow a value to one exact SHA-256 digest.\n *\n * @remarks\n * The identity a vendored host manifest and a write precondition are both stated\n * in. Fixed at sixty-four lowercase digits, so the value either is a digest of\n * that algorithm or is refused; there is no shorter or longer accepted form.\n *\n * @example\n * ```ts\n * import { isDigest } from '@orkestrel/scaffold/server'\n *\n * isDigest('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855') // true\n * isDigest('E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855') // false\n * ```\n */\nexport const isDigest: Guard<string> = stringOf({ pattern: DIGEST_PATTERN })\n\n/**\n * Narrow a value to a working-tree inventory within the limit one target may report.\n *\n * @param value - The candidate inventory.\n * @returns `true` for an array of no more than `MAX_INVENTORY_PATHS` items.\n *\n * @remarks\n * Compose this ahead of an element guard exactly as the core collection guard is\n * composed, and for the same reason: the item count is settled before anything\n * walks the items, and a hostile `length` accessor answers `false` rather than\n * escaping as a throw. It exists beside that guard rather than reusing it\n * because the two bound different things — one bounds what a caller may hand a\n * public method, this one bounds what a checkout may contain.\n *\n * @example\n * ```ts\n * import { isInventory } from '@orkestrel/scaffold/server'\n *\n * isInventory(['AGENTS.md']) // true\n * isInventory('AGENTS.md') // false\n * ```\n */\nexport function isInventory(value: unknown): value is readonly unknown[] {\n\treturn holds(() => isArray(value) && value.length <= MAX_INVENTORY_PATHS)\n}\n\n/**\n * Narrow a value to a bounded upstream endpoint.\n *\n * @remarks\n * Length only. Which schemes and hosts an endpoint may name is the reader's law,\n * because it builds the request and can report why one was refused, where a\n * guard has only `false` to say.\n */\nexport const isEndpoint: Guard<string> = stringOf({ min: 1, max: MAX_ENDPOINT_LENGTH })\n\n/**\n * Narrow a value to a Git branch the guide endpoint accepts.\n *\n * @remarks\n * A branch reaches the guide URL's path, so the syntax is closed rather than\n * merely bounded and no `..` is admitted anywhere in it.\n *\n * @example\n * ```ts\n * import { isBranch } from '@orkestrel/scaffold/server'\n *\n * isBranch('main') // true\n * isBranch('main/../etc') // false\n * ```\n */\nexport const isBranch: Guard<string> = stringOf({\n\tmin: 1,\n\tmax: MAX_BRANCH_LENGTH,\n\tpattern: BRANCH_PATTERN,\n})\n\n/**\n * Narrow a value to a per-request timeout in milliseconds.\n *\n * @remarks\n * A whole number of milliseconds, at least one and no more than\n * {@link MAX_UPSTREAM_TIMEOUT}. Zero is refused because a request that may not\n * take any time is a request that cannot succeed.\n */\nexport const isTimeout: Guard<number> = andOf(isInteger, boundsOf(1, MAX_UPSTREAM_TIMEOUT))\n\n/**\n * Narrow a value to a bounded list of `@orkestrel` package names.\n *\n * @remarks\n * Composed from the core collection and dependency-name guards rather than\n * restated, so the scope law that keeps a derived guide mirror inside its\n * directory has exactly one home.\n *\n * @example\n * ```ts\n * import { isDependencyNames } from '@orkestrel/scaffold/server'\n *\n * isDependencyNames(['@orkestrel/router']) // true\n * isDependencyNames(['router']) // false\n * ```\n */\nexport const isDependencyNames: Guard<readonly string[]> = andOf(\n\tisCollection,\n\tarrayOf(isDependencyName),\n)\n\n/** Narrow a value to a bounded list of declared runtime dependencies. */\nexport const isDependencies: Guard<readonly Dependency[]> = andOf(\n\tisCollection,\n\tarrayOf(isDependency),\n)\n\n/** Narrow a value to a bounded list of fetched guide mirrors. */\nexport const isMirrors: Guard<readonly Mirror[]> = andOf(isCollection, arrayOf(isMirror))\n\n/** Narrow a value to a bounded list of fleet catalog rows. */\nexport const isCatalogEntries: Guard<readonly CatalogEntry[]> = andOf(\n\tisCollection,\n\tarrayOf(isCatalogEntry),\n)\n\n/**\n * Narrow a value to one {@link ManifestEntry}.\n *\n * @remarks\n * Both paths are measured by the core path law, because a vendored host's\n * storage name and the destination it maps to are each a path inside a\n * workspace. That is what stops a hand-edited manifest from mapping a vendored\n * file to a destination outside the target.\n *\n * @example\n * ```ts\n * import { isManifestEntry } from '@orkestrel/scaffold/server'\n *\n * isManifestEntry({ storage: 'AGENTS.md', destination: 'AGENTS.md', executable: false }) // true\n * ```\n */\nexport const isManifestEntry: Guard<ManifestEntry> = recordOf({\n\tstorage: isPath,\n\tdestination: isPath,\n\texecutable: isBoolean,\n})\n\n/**\n * Narrow a value to one {@link HostManifest}.\n *\n * @remarks\n * The manifest is read from a directory a caller named, so it is the least\n * trusted value the server face handles and is guarded whole: every entry, every\n * declared root, and the digest that authenticates their membership.\n */\nexport const isHostManifest: Guard<HostManifest> = recordOf({\n\tentries: andOf(isCollection, arrayOf(isManifestEntry)),\n\troots: andOf(isCollection, arrayOf(isPath)),\n\tdigest: isDigest,\n})\n\n/**\n * Narrow a value to a {@link Repository}.\n *\n * @remarks\n * Both path lists are target-relative, so both are measured by the core path\n * law: a reported path that is not one this package could have planned is not a\n * path it will delete. The inventory guard bounds the lists, because a checkout\n * is legitimately far larger than any collection a caller hands a method.\n *\n * @example\n * ```ts\n * import { isRepository } from '@orkestrel/scaffold/server'\n *\n * isRepository({ tracked: ['AGENTS.md'], dirty: [] }) // true\n * isRepository({ tracked: ['../secrets'], dirty: [] }) // false\n * ```\n */\nexport const isRepository: Guard<Repository> = recordOf({\n\ttracked: andOf(isInventory, arrayOf(isPath)),\n\tdirty: andOf(isInventory, arrayOf(isPath)),\n})\n\n/**\n * Narrow a value to the materializer's initial listener record.\n *\n * @remarks\n * Every event is optional and every declared value is a function. A key outside\n * the materializer's event map is refused, so a listener wired to a misspelled\n * event fails at construction instead of never firing.\n */\nexport const isMaterializerHooks: Guard<EmitterHooks<MaterializerEventMap>> = recordOf(\n\t{\n\t\twrite: isFunction,\n\t\tremove: isFunction,\n\t\tfinish: isFunction,\n\t\terror: isFunction,\n\t\tdestroy: isFunction,\n\t},\n\ttrue,\n)\n\n/**\n * Narrow a value to {@link MaterializerOptions}.\n *\n * @example\n * ```ts\n * import { isMaterializerOptions } from '@orkestrel/scaffold/server'\n *\n * isMaterializerOptions({}) // true\n * isMaterializerOptions({ host: 'dist/host*' }) // false\n * ```\n */\nexport const isMaterializerOptions: Guard<MaterializerOptions> = recordOf(\n\t{ host: isFilesystemPath, on: isMaterializerHooks, error: isFunction },\n\ttrue,\n)\n\n/**\n * Narrow a value to the upstream reader's initial listener record.\n *\n * @remarks\n * Closed to the reader's own four events for the same reason the materializer's\n * record is closed to its five.\n */\nexport const isUpstreamHooks: Guard<EmitterHooks<UpstreamEventMap>> = recordOf(\n\t{ release: isFunction, mirror: isFunction, error: isFunction, destroy: isFunction },\n\ttrue,\n)\n\n/**\n * Narrow a value to {@link UpstreamOptions}.\n *\n * @remarks\n * Each grouped endpoint is closed to its own leaves, so a setting written under\n * the wrong entity is refused rather than ignored. Every numeric leaf is a whole\n * number inside a ceiling: an unbounded concurrency, retry count, response\n * limit, or call budget is a way to exhaust the caller, so the ceiling is stated\n * here rather than left to the reader. The two byte ceilings are the core\n * artifact and total-artifact limits, because a fetched guide is an artifact and\n * a whole call retains no more than a whole plan.\n *\n * @example\n * ```ts\n * import { isUpstreamOptions } from '@orkestrel/scaffold/server'\n *\n * isUpstreamOptions({ guides: { branch: 'main' }, concurrency: 4 }) // true\n * isUpstreamOptions({ concurrency: 0 }) // false\n * ```\n */\nexport const isUpstreamOptions: Guard<UpstreamOptions> = recordOf(\n\t{\n\t\tguides: recordOf({ base: isEndpoint, branch: isBranch, timeout: isTimeout }, true),\n\t\tregistry: recordOf({ base: isEndpoint, timeout: isTimeout }, true),\n\t\tconcurrency: andOf(isInteger, boundsOf(1, MAX_UPSTREAM_CONCURRENCY)),\n\t\tretries: andOf(isInteger, boundsOf(0, MAX_UPSTREAM_RETRIES)),\n\t\tlimit: andOf(isInteger, boundsOf(1, MAX_ARTIFACT_BYTES)),\n\t\tbudget: andOf(isInteger, boundsOf(1, MAX_TOTAL_ARTIFACT_BYTES)),\n\t\ton: isUpstreamHooks,\n\t\terror: isFunction,\n\t},\n\ttrue,\n)\n","import type { Snapshot } from '@src/core'\nimport type {\n\tHostManifest,\n\tManifestEntry,\n\tWriteAnchor,\n\tWriteExpectation,\n\tWritePrecondition,\n} from './types.js'\nimport { createHash } from 'node:crypto'\nimport {\n\tchmodSync,\n\tcloseSync,\n\tconstants,\n\tcopyFileSync,\n\tfstatSync,\n\tlstatSync,\n\tmkdirSync,\n\topendirSync,\n\topenSync,\n\treaddirSync,\n\treadSync,\n\trealpathSync,\n\twriteFileSync,\n} from 'node:fs'\nimport { basename, dirname, join, parse, relative, resolve, sep } from 'node:path'\nimport { attempt, holds, isError, parseJSONAs } from '@orkestrel/contract'\nimport {\n\tbytesToHex,\n\tHOST_PATHS,\n\tisCollection,\n\tisPath,\n\tMAX_ARTIFACT_BYTES,\n\tMAX_COLLECTION_ITEMS,\n\tMAX_MANIFEST_BYTES,\n\tMAX_TOTAL_ARTIFACT_BYTES,\n\tScaffoldError,\n} from '@src/core'\nimport { isFilesystemPath, isHostManifest } from './validators.js'\nimport { MANIFEST_NAME, MAX_INVENTORY_PATHS, MAX_PATH_DEPTH } from './constants.js'\n\n/**\n * Test whether a caught filesystem error reports an absent path.\n *\n * @param error - The caught value.\n * @returns `true` only for an `Error` whose `code` is exactly `ENOENT`.\n *\n * @remarks\n * The one place absence is told apart from failure. Every read here answers\n * `undefined` or an empty result for a path that is not there and reports a path\n * that is there but unreadable, so the two must never be read from the same\n * caught value by eye. Total for any caught value, including a hostile one.\n *\n * @example\n * ```ts\n * import { matchesMissingPath } from '@orkestrel/scaffold/server'\n *\n * matchesMissingPath(Object.assign(new Error('gone'), { code: 'ENOENT' })) // true\n * matchesMissingPath(new Error('gone')) // false\n * ```\n */\nexport function matchesMissingPath(error: unknown): boolean {\n\treturn holds(() => isError(error) && Reflect.get(error, 'code') === 'ENOENT')\n}\n\n/**\n * Test whether a path addresses a target's own repository metadata.\n *\n * @param path - The path to classify; either separator is read.\n * @returns `true` for `.git` and for anything beneath it.\n *\n * @remarks\n * The one home of the `.git` membership rule, read from two directions. A target\n * holding nothing but this directory is still vacant, because a checkout of an\n * empty repository is where a fresh workspace legitimately starts. A path\n * beneath it is never removed and never vendored, because deleting a target's\n * history is not a repair.\n *\n * @example\n * ```ts\n * import { matchesGitPath } from '@orkestrel/scaffold/server'\n *\n * matchesGitPath('.git') // true\n * matchesGitPath('.git/config') // true\n * matchesGitPath('.gitignore') // false\n * ```\n */\nexport function matchesGitPath(path: string): boolean {\n\treturn /(?:^|\\/)\\.git(?:\\/|$)/i.test(path.replaceAll('\\\\', '/'))\n}\n\n/**\n * Test whether a target-relative path is one no verb may delete.\n *\n * @param path - The target-relative path to classify.\n * @returns `true` when the path must survive every verb this package runs.\n *\n * @remarks\n * The deletion deny-list, stated as a rule over paths rather than as a list of\n * directories. It is the inversion the contract asks for: the candidate set\n * comes from an audit's foreign findings narrowed by what git tracks, and this\n * is what that set is then measured against. Repository metadata is protected\n * because losing history is not a repair, and a target's own `src` and `app`\n * trees are protected because a workspace's source is the one thing scaffold\n * never plans and never owns, whatever an audit reports about it.\n *\n * @example\n * ```ts\n * import { matchesProtectedPath } from '@orkestrel/scaffold/server'\n *\n * matchesProtectedPath('src/core/index.ts') // true\n * matchesProtectedPath('.git/config') // true\n * matchesProtectedPath('.claude/agents/rogue.md') // false\n * ```\n */\nexport function matchesProtectedPath(path: string): boolean {\n\tconst normalized = path.replaceAll('\\\\', '/')\n\tif (matchesGitPath(normalized)) return true\n\tif (normalized === 'src' || normalized === 'app') return true\n\treturn normalized.startsWith('src/') || normalized.startsWith('app/')\n}\n\n/**\n * Test whether a path names local configuration or a credential.\n *\n * @param path - The path to classify; either separator is read.\n * @returns `true` when the path must never be copied into a vendored host.\n *\n * @remarks\n * The vendoring deny-list. A host root is staged from a real checkout, so the\n * refusal is stated over the path rather than over the file's content: a\n * credential is recognizable by where it sits and what it is called long before\n * anything reads it. Repository metadata is included through\n * {@link matchesGitPath}, so one call answers the whole question and no caller\n * has to remember to ask twice.\n *\n * @example\n * ```ts\n * import { matchesSensitivePath } from '@orkestrel/scaffold/server'\n *\n * matchesSensitivePath('.npmrc') // true\n * matchesSensitivePath('.claude/settings.local.json') // true\n * matchesSensitivePath('.claude/settings.json') // false\n * ```\n */\nexport function matchesSensitivePath(path: string): boolean {\n\tconst normalized = path.replaceAll('\\\\', '/')\n\tif (matchesGitPath(normalized)) return true\n\treturn /(?:^|\\/)(?:(?:\\.ssh|\\.aws|\\.azure|\\.docker|\\.kube|\\.gnupg|\\.env(?:\\.[^/]*)?)(?:\\/|$)|(?:\\.npmrc|\\.pypirc|\\.netrc|\\.git-credentials|settings\\.local\\.json|auth\\.json|credentials(?:\\.json)?|application_default_credentials\\.json|id_rsa|id_ed25519|kubeconfig)$|\\.config\\/(?:gh|gcloud)(?:\\/|$)|\\.local\\/share\\/keyrings(?:\\/|$)|[^/]*service-account[^/]*\\.json$|[^/]*\\.(?:jks|key|p12|pem|pfx|pkcs12)$)/i.test(\n\t\tnormalized,\n\t)\n}\n\n/**\n * Project a target-relative path to the storage name a vendored host holds it under.\n *\n * @param path - The target-relative path the file is written to.\n * @returns The storage name beneath the host root.\n *\n * @remarks\n * A staged host is a plain directory that npm packs, and npm's own ignore rules\n * would drop a leading-dot entry from the tarball. So every dot that opens a\n * segment comes off, and a dotted file at the root moves under `dotfiles/` to\n * keep it from colliding with an undotted sibling of the same name. The mapping\n * is one direction only: a staged host's manifest records the destination each\n * storage name answers for, so the reader never re-derives this.\n *\n * @example\n * ```ts\n * import { pathToStorage } from '@orkestrel/scaffold/server'\n *\n * pathToStorage('.gitignore') // 'dotfiles/gitignore'\n * pathToStorage('.claude/rules/names.md') // 'claude/rules/names.md'\n * pathToStorage('AGENTS.md') // 'AGENTS.md'\n * ```\n */\nexport function pathToStorage(path: string): string {\n\tconst segments = path.split('/')\n\tif (segments.length === 1) {\n\t\treturn path.startsWith('.') ? `dotfiles/${path.slice(1)}` : path\n\t}\n\treturn segments.map((segment) => (segment.startsWith('.') ? segment.slice(1) : segment)).join('/')\n}\n\n/**\n * Compute the SHA-256 digest of text.\n *\n * @param content - The text to digest.\n * @returns Sixty-four lowercase hexadecimal digits.\n *\n * @remarks\n * The identity the server face states, and the reason it differs from core's:\n * core settled on a folded 64-bit identity because compilation is synchronous by\n * contract and the only cryptographic digest a host-independent scope reaches is\n * asynchronous. A Node host reaches the real one synchronously, and\n * `HostManifest.digest` is documented as SHA-256, so this is what the server\n * uses everywhere a digest is claimed.\n *\n * @example\n * ```ts\n * import { computeDigest } from '@orkestrel/scaffold/server'\n *\n * computeDigest('hi\\n') // '98ea6e4f216f2fb4b69fff9b3a44842c38686ca685f3f55dc48c5d3fb1107be4'\n * ```\n */\nexport function computeDigest(content: string): string {\n\treturn createHash('sha256').update(content, 'utf8').digest('hex')\n}\n\n/**\n * Compute the digest of a vendored host's declared membership.\n *\n * @param entries - The ordered file membership declarations.\n * @param roots - The ordered directory membership declarations.\n * @returns The SHA-256 of that exact membership, in that exact order.\n *\n * @remarks\n * Independent of the manifest's own `digest` field, which is what lets a reader\n * detect a membership edit that did not update it. Order is part of the claim\n * rather than normalized away, because a staged manifest sorts its entries and\n * roots once and a reordered copy is a different file. Each entry is projected\n * to exactly the three declared fields, so a hand-added property cannot ride\n * into the digest and cannot change it either.\n *\n * @example\n * ```ts\n * import { computeManifestDigest } from '@orkestrel/scaffold/server'\n *\n * computeManifestDigest([], []) // the digest of the empty membership\n * ```\n */\nexport function computeManifestDigest(\n\tentries: readonly ManifestEntry[],\n\troots: readonly string[],\n): string {\n\treturn computeDigest(\n\t\tJSON.stringify({\n\t\t\tentries: entries.map((entry) => ({\n\t\t\t\tstorage: entry.storage,\n\t\t\t\tdestination: entry.destination,\n\t\t\t\texecutable: entry.executable,\n\t\t\t})),\n\t\t\troots: [...roots],\n\t\t}),\n\t)\n}\n\n/**\n * Test whether a path is a physical file this package will read or replace.\n *\n * @param path - The resolved host path to inspect, without following links.\n * @returns `true` only for a regular file that is neither a link nor hard-linked\n * elsewhere.\n *\n * @remarks\n * The link tests are the point. A symbolic link is a path pointing somewhere\n * else, so writing through one writes outside the target; a hard link means a\n * second name shares the same bytes, so replacing them changes a file nobody\n * asked about. Both are refused rather than followed.\n *\n * @example\n * ```ts\n * import { isPhysicalFile } from '@orkestrel/scaffold/server'\n *\n * isPhysicalFile('/tmp/project/AGENTS.md') // true for a plain file\n * ```\n */\nexport function isPhysicalFile(path: string): boolean {\n\tconst status = attempt(() => lstatSync(path))\n\treturn (\n\t\tstatus.success &&\n\t\tstatus.value.isFile() &&\n\t\t!status.value.isSymbolicLink() &&\n\t\tstatus.value.nlink === 1\n\t)\n}\n\n/**\n * Test whether a path is a physical file with exact on-disk casing.\n *\n * @param path - The host path to inspect segment by segment.\n * @returns `true` only for a physical file whose requested segments exactly\n * match the names each parent directory stores.\n *\n * @remarks\n * A direct file lookup follows the host's case-folding rules on Windows and\n * common macOS filesystems. Reading each parent directory supplies the stored\n * names, so this predicate can enforce the package's exact-case structural\n * contract on every supported host.\n *\n * @example\n * ```ts\n * import { isExactCaseFile } from '@orkestrel/scaffold/server'\n *\n * isExactCaseFile('/tmp/project/src/bin/main.ts') // true only for that exact spelling\n * ```\n */\nexport function isExactCaseFile(path: string): boolean {\n\tconst full = resolve(path)\n\tif (!isPhysicalFile(full)) return false\n\tconst root = parse(full).root\n\tconst segments = relative(root, full).split(sep)\n\tlet parent = root\n\tfor (const segment of segments) {\n\t\tconst entries = attempt(() => readdirSync(parent))\n\t\tif (entries.success) {\n\t\t\tif (!entries.value.includes(segment)) return false\n\t\t} else {\n\t\t\tconst actual = attempt(() => realpathSync.native(join(parent, segment)))\n\t\t\tif (!actual.success || basename(actual.value) !== segment) return false\n\t\t}\n\t\tparent = join(parent, segment)\n\t}\n\treturn true\n}\n\n/**\n * Test whether a path is a physical directory this package will read or write into.\n *\n * @param path - The resolved host path to inspect, without following links.\n * @returns `true` only for a directory that is not a link.\n *\n * @remarks\n * A junction and a directory symbolic link both report as directories once\n * followed, so the inspection deliberately does not follow: a redirected\n * directory is refused here rather than silently accepted as the one the caller\n * named.\n *\n * @example\n * ```ts\n * import { isPhysicalDirectory } from '@orkestrel/scaffold/server'\n *\n * isPhysicalDirectory('/tmp/project') // true for a plain directory\n * ```\n */\nexport function isPhysicalDirectory(path: string): boolean {\n\tconst status = attempt(() => lstatSync(path))\n\treturn status.success && status.value.isDirectory() && !status.value.isSymbolicLink()\n}\n\n/**\n * Compute the SHA-256 digest of one file's exact bytes.\n *\n * @param path - The resolved host path to digest.\n * @returns The digest, or `undefined` when the path is not a physical file, is\n * past the artifact ceiling, or moved while it was being read.\n *\n * @remarks\n * Read in bounded chunks rather than loaded whole, so digesting a large file\n * costs one buffer instead of its size. The file's identity and size are\n * measured before and after the read and a mismatch answers `undefined`, so a\n * digest is either of one settled file or is not produced at all.\n *\n * @example\n * ```ts\n * import { computeFileDigest } from '@orkestrel/scaffold/server'\n *\n * computeFileDigest('/tmp/project/AGENTS.md') // the file's SHA-256\n * computeFileDigest('/tmp/project/absent.md') // undefined\n * ```\n */\nexport function computeFileDigest(path: string): string | undefined {\n\tif (!isPhysicalFile(path)) return undefined\n\tconst opened = attempt(() => openSync(path, 'r'))\n\tif (!opened.success) return undefined\n\tconst handle = opened.value\n\tconst read = attempt(() => {\n\t\tconst before = fstatSync(handle)\n\t\tif (!before.isFile() || before.nlink !== 1 || before.size > MAX_ARTIFACT_BYTES) return undefined\n\t\tconst hash = createHash('sha256')\n\t\tconst buffer = Buffer.alloc(65_536)\n\t\tlet size = 0\n\t\tfor (;;) {\n\t\t\tconst length = readSync(handle, buffer, 0, buffer.byteLength, null)\n\t\t\tif (length === 0) break\n\t\t\tsize += length\n\t\t\tif (size > MAX_ARTIFACT_BYTES) return undefined\n\t\t\thash.update(buffer.subarray(0, length))\n\t\t}\n\t\tconst after = fstatSync(handle)\n\t\tif (size !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs) {\n\t\t\treturn undefined\n\t\t}\n\t\treturn hash.digest('hex')\n\t})\n\tattempt(() => closeSync(handle))\n\treturn read.success ? read.value : undefined\n}\n\n/**\n * Resolve a path through the real filesystem, keeping the part that does not exist yet.\n *\n * @param path - The absolute or relative host path to resolve.\n * @returns The path with its existing prefix resolved through every link, or\n * `undefined` when the text is not a host path, no bounded existing ancestor\n * resolves, or an ancestor cannot be read.\n *\n * @remarks\n * A containment decision has to be made about a destination that does not exist\n * yet, and a lexical answer is not enough: a link anywhere in the existing\n * prefix moves the destination somewhere the text never named. So the deepest\n * existing ancestor is resolved and the remaining segments are re-joined onto\n * it. The climb is bounded by the path-depth ceiling, so an adversarial path\n * cannot make it walk indefinitely.\n *\n * @example\n * ```ts\n * import { resolveRealPath } from '@orkestrel/scaffold/server'\n *\n * resolveRealPath('./packages/new/src') // the real path of `packages`, plus `new/src`\n * ```\n */\nexport function resolveRealPath(path: string): string | undefined {\n\tif (!isFilesystemPath(path)) return undefined\n\tlet current = resolve(path)\n\tconst pending: string[] = []\n\tfor (let depth = 0; depth <= MAX_PATH_DEPTH; depth += 1) {\n\t\tconst real = attempt(() => realpathSync(current))\n\t\tif (real.success) {\n\t\t\tlet physical = real.value\n\t\t\tfor (const segment of pending) physical = join(physical, segment)\n\t\t\treturn physical\n\t\t}\n\t\tif (!matchesMissingPath(real.error)) return undefined\n\t\tconst parent = dirname(current)\n\t\tif (parent === current) return undefined\n\t\tpending.unshift(relative(parent, current))\n\t\tcurrent = parent\n\t}\n\treturn undefined\n}\n\n/**\n * Resolve a root-relative path and refuse one that leaves its root.\n *\n * @param root - The containing host directory.\n * @param path - The portable root-relative path.\n * @returns The destination as this package will address it, or `undefined` when\n * either argument is off contract or the destination lies outside `root`.\n *\n * @remarks\n * The containment law, and the one door every read in this module goes through.\n * Both sides are resolved through the real filesystem before they are compared,\n * so a link planted inside the root cannot smuggle a destination out of it; the\n * answer is then the lexical join, so the caller operates on the path it named\n * rather than on a resolved form the target may not recognize.\n *\n * Comparison is exact text, which fails closed on a case-insensitive\n * filesystem: a root and a path spelled with different case resolve to\n * different strings there and are refused, never wrongly admitted.\n *\n * @example\n * ```ts\n * import { resolveContainedPath } from '@orkestrel/scaffold/server'\n *\n * resolveContainedPath('/tmp/project', 'guides/router.md') // '/tmp/project/guides/router.md'\n * resolveContainedPath('/tmp/project', '../secrets') // undefined\n * ```\n */\nexport function resolveContainedPath(root: string, path: string): string | undefined {\n\tif (!isFilesystemPath(root) || !isPath(path)) return undefined\n\tconst base = resolve(root)\n\tconst destination = join(base, path)\n\tconst physicalRoot = resolveRealPath(base)\n\tconst physical = resolveRealPath(destination)\n\tif (physicalRoot === undefined || physical === undefined) return undefined\n\tif (physical !== physicalRoot && !physical.startsWith(physicalRoot + sep)) return undefined\n\treturn destination\n}\n\n/**\n * Test whether a target is safe to write a fresh workspace into.\n *\n * @param target - The candidate target directory.\n * @returns `true` when the target is absent, empty, or holds nothing but its own\n * `.git` directory.\n *\n * @remarks\n * The green-field law. A checkout of an empty repository is where a new\n * workspace legitimately starts, so that one directory is admitted and nothing\n * else is; anything more means the caller is repairing a workspace rather than\n * creating one. Only the first two entries are read, so the answer costs the\n * same on an empty directory and on a full one.\n *\n * @example\n * ```ts\n * import { isVacant } from '@orkestrel/scaffold/server'\n *\n * isVacant('./packages/router-new') // true when absent, empty, or `.git` only\n * ```\n */\nexport function isVacant(target: string): boolean {\n\tif (!isFilesystemPath(target)) return false\n\tconst status = attempt(() => lstatSync(target))\n\tif (!status.success) return matchesMissingPath(status.error)\n\tif (!status.value.isDirectory() || status.value.isSymbolicLink()) return false\n\tconst opened = attempt(() => opendirSync(target))\n\tif (!opened.success) return false\n\tconst handle = opened.value\n\tconst read = attempt(() => {\n\t\tconst first = handle.readSync()\n\t\tif (first === null) return true\n\t\tif (handle.readSync() !== null) return false\n\t\treturn matchesGitPath(first.name) && first.isDirectory() && !first.isSymbolicLink()\n\t})\n\tattempt(() => handle.closeSync())\n\treturn read.success && read.value\n}\n\n/**\n * List a directory's files as sorted root-relative paths.\n *\n * @param root - The directory to inventory.\n * @returns Every descendant file as a `/`-separated root-relative path, in\n * code-unit order, and `[]` when `root` is absent.\n * @throws `ScaffoldError('INVALID', …)` when `root` is not a host path.\n * @throws `ScaffoldError('TARGET', …)` when `root` is present but is not a\n * physical directory, cannot be read, holds a name this package could not plan,\n * or carries more entries or more nesting than one inventory may report.\n *\n * @remarks\n * A whole-tree answer throws where a single-path answer returns `undefined`, and\n * the reason is that a partial inventory reads exactly like a complete one. A\n * caller comparing a target against a plan would treat a truncated listing as\n * proof that the missing files are not there.\n *\n * Absence is the one exception: nothing to inventory is a complete answer, so it\n * is the empty list. Links are listed as files rather than followed, so no\n * traversal can leave the root and no cycle can form.\n *\n * @example\n * ```ts\n * import { listFiles } from '@orkestrel/scaffold/server'\n *\n * listFiles('./dist/host') // ['AGENTS.md', 'claude/rules/names.md', …]\n * ```\n */\nexport function listFiles(root: string): readonly string[] {\n\tif (!isFilesystemPath(root)) {\n\t\tthrow new ScaffoldError('INVALID', 'Listing root is not a host path', { root })\n\t}\n\tconst status = attempt(() => lstatSync(root))\n\tif (!status.success) {\n\t\tif (matchesMissingPath(status.error)) return []\n\t\tthrow new ScaffoldError('TARGET', `Listing root cannot be inspected at ${root}`, {\n\t\t\troot,\n\t\t\terror: status.error,\n\t\t})\n\t}\n\tif (!status.value.isDirectory() || status.value.isSymbolicLink()) {\n\t\tthrow new ScaffoldError('TARGET', `Listing root is not a physical directory at ${root}`, {\n\t\t\troot,\n\t\t})\n\t}\n\tconst files: string[] = []\n\tconst pending = [{ full: root, path: '', depth: 0 }]\n\tlet visited = 0\n\twhile (pending.length > 0) {\n\t\tconst current = pending.pop()\n\t\tif (current === undefined) break\n\t\tconst opened = attempt(() => opendirSync(current.full))\n\t\tif (!opened.success) {\n\t\t\tthrow new ScaffoldError('TARGET', `Listing directory cannot be read at ${current.full}`, {\n\t\t\t\troot,\n\t\t\t\tpath: current.path,\n\t\t\t\terror: opened.error,\n\t\t\t})\n\t\t}\n\t\tconst handle = opened.value\n\t\tconst walked = attempt(() => {\n\t\t\tfor (;;) {\n\t\t\t\tconst entry = handle.readSync()\n\t\t\t\tif (entry === null) break\n\t\t\t\tvisited += 1\n\t\t\t\tif (visited > MAX_INVENTORY_PATHS) {\n\t\t\t\t\tthrow new ScaffoldError('TARGET', 'Listing exceeds the paths one inventory may report', {\n\t\t\t\t\t\troot,\n\t\t\t\t\t\tlimit: MAX_INVENTORY_PATHS,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst path = current.path === '' ? entry.name : `${current.path}/${entry.name}`\n\t\t\t\tif (!isPath(path)) {\n\t\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t\t'TARGET',\n\t\t\t\t\t\t`Listing found a path this package cannot plan at ${path}`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\troot,\n\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (!entry.isDirectory() || entry.isSymbolicLink()) {\n\t\t\t\t\tfiles.push(path)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconst depth = current.depth + 1\n\t\t\t\tif (depth >= MAX_PATH_DEPTH) {\n\t\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t\t'TARGET',\n\t\t\t\t\t\t`Listing exceeds the depth one path may carry at ${path}`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\troot,\n\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\tlimit: MAX_PATH_DEPTH,\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tpending.push({ full: join(current.full, entry.name), path, depth })\n\t\t\t}\n\t\t})\n\t\tattempt(() => handle.closeSync())\n\t\tif (!walked.success) throw walked.error\n\t}\n\treturn files.sort()\n}\n\n/**\n * List a directory's descendant directories as sorted root-relative paths.\n *\n * @param root - The directory to inventory.\n * @returns Every descendant directory as a `/`-separated root-relative path, in\n * code-unit order, and `[]` when `root` is absent.\n * @throws `ScaffoldError('INVALID', …)` when `root` is not a host path.\n * @throws `ScaffoldError('TARGET', …)` when `root` is present but is not a\n * physical directory, cannot be read, holds a name this package could not plan,\n * or carries more entries or more nesting than one inventory may report.\n *\n * @remarks\n * The sibling of {@link listFiles}, under the same bounds and the same refusals,\n * and it exists because a directory holding no file is invisible to a file walk.\n * That is the half a vendored host's `roots` declares and the half a file\n * inventory cannot check, so a stager needs both walks to state a complete\n * membership.\n *\n * `root` itself is not listed, because the answer is root-relative and the root\n * has no root-relative name. A redirected directory is not listed and is not\n * walked into, so no traversal can leave the root and no cycle can form.\n *\n * @example\n * ```ts\n * import { listDirectories } from '@orkestrel/scaffold/server'\n *\n * listDirectories('./.claude') // ['agents', 'rules', 'skills', …]\n * ```\n */\nexport function listDirectories(root: string): readonly string[] {\n\tif (!isFilesystemPath(root)) {\n\t\tthrow new ScaffoldError('INVALID', 'Listing root is not a host path', { root })\n\t}\n\tconst status = attempt(() => lstatSync(root))\n\tif (!status.success) {\n\t\tif (matchesMissingPath(status.error)) return []\n\t\tthrow new ScaffoldError('TARGET', `Listing root cannot be inspected at ${root}`, {\n\t\t\troot,\n\t\t\terror: status.error,\n\t\t})\n\t}\n\tif (!status.value.isDirectory() || status.value.isSymbolicLink()) {\n\t\tthrow new ScaffoldError('TARGET', `Listing root is not a physical directory at ${root}`, {\n\t\t\troot,\n\t\t})\n\t}\n\tconst directories: string[] = []\n\tconst pending = [{ full: root, path: '', depth: 0 }]\n\tlet visited = 0\n\twhile (pending.length > 0) {\n\t\tconst current = pending.pop()\n\t\tif (current === undefined) break\n\t\tconst opened = attempt(() => opendirSync(current.full))\n\t\tif (!opened.success) {\n\t\t\tthrow new ScaffoldError('TARGET', `Listing directory cannot be read at ${current.full}`, {\n\t\t\t\troot,\n\t\t\t\tpath: current.path,\n\t\t\t\terror: opened.error,\n\t\t\t})\n\t\t}\n\t\tconst handle = opened.value\n\t\tconst walked = attempt(() => {\n\t\t\tfor (;;) {\n\t\t\t\tconst entry = handle.readSync()\n\t\t\t\tif (entry === null) break\n\t\t\t\tvisited += 1\n\t\t\t\tif (visited > MAX_INVENTORY_PATHS) {\n\t\t\t\t\tthrow new ScaffoldError('TARGET', 'Listing exceeds the paths one inventory may report', {\n\t\t\t\t\t\troot,\n\t\t\t\t\t\tlimit: MAX_INVENTORY_PATHS,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tconst path = current.path === '' ? entry.name : `${current.path}/${entry.name}`\n\t\t\t\tif (!isPath(path)) {\n\t\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t\t'TARGET',\n\t\t\t\t\t\t`Listing found a path this package cannot plan at ${path}`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\troot,\n\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (!entry.isDirectory() || entry.isSymbolicLink()) continue\n\t\t\t\tconst depth = current.depth + 1\n\t\t\t\tif (depth >= MAX_PATH_DEPTH) {\n\t\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t\t'TARGET',\n\t\t\t\t\t\t`Listing exceeds the depth one path may carry at ${path}`,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\troot,\n\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\tlimit: MAX_PATH_DEPTH,\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tdirectories.push(path)\n\t\t\t\tpending.push({ full: join(current.full, entry.name), path, depth })\n\t\t\t}\n\t\t})\n\t\tattempt(() => handle.closeSync())\n\t\tif (!walked.success) throw walked.error\n\t}\n\treturn directories.sort()\n}\n\n/**\n * Read one contained file as its exact bytes in lowercase hexadecimal.\n *\n * @param root - The containing host directory.\n * @param path - The portable root-relative file path.\n * @param limit - The most bytes this read accepts; the artifact ceiling by default.\n * @returns The exact bytes as hexadecimal, or `undefined` when the file is\n * absent, is not a physical readable file, is past `limit`, or moved while it\n * was being read.\n * @throws `ScaffoldError('INVALID', …)` when the arguments are off contract or\n * `path` leaves `root`.\n *\n * @remarks\n * Hexadecimal rather than text, because this is what a byte comparison is stated\n * in everywhere in this package: a plan's artifact, an audit finding, and a\n * snapshot all compare as the same digits. The file's identity and size are\n * measured before and after the read, and one extra byte is requested past the\n * declared size, so a file that grew or was replaced mid-read answers\n * `undefined` rather than half of two files.\n *\n * @example\n * ```ts\n * import { readFileHex } from '@orkestrel/scaffold/server'\n *\n * readFileHex('/tmp/project', 'AGENTS.md') // '2320416765…'\n * ```\n */\nexport function readFileHex(\n\troot: string,\n\tpath: string,\n\tlimit: number = MAX_ARTIFACT_BYTES,\n): string | undefined {\n\tif (!Number.isSafeInteger(limit) || limit < 0 || limit > MAX_ARTIFACT_BYTES) {\n\t\tthrow new ScaffoldError('INVALID', `Byte limit is outside the artifact ceiling at ${path}`, {\n\t\t\troot,\n\t\t\tpath,\n\t\t\tlimit,\n\t\t})\n\t}\n\tconst full = resolveContainedPath(root, path)\n\tif (full === undefined) {\n\t\tthrow new ScaffoldError('INVALID', `Path is off contract or leaves its root at ${path}`, {\n\t\t\troot,\n\t\t\tpath,\n\t\t})\n\t}\n\tif (!isPhysicalFile(full)) return undefined\n\tconst opened = attempt(() => openSync(full, 'r'))\n\tif (!opened.success) return undefined\n\tconst handle = opened.value\n\tconst read = attempt(() => {\n\t\tconst before = fstatSync(handle)\n\t\tif (!before.isFile() || before.nlink !== 1 || before.size > limit) return undefined\n\t\tconst bytes = Buffer.alloc(before.size)\n\t\tlet offset = 0\n\t\twhile (offset < bytes.byteLength) {\n\t\t\tconst length = readSync(handle, bytes, offset, bytes.byteLength - offset, offset)\n\t\t\tif (length === 0) break\n\t\t\toffset += length\n\t\t}\n\t\tconst overflow = readSync(handle, Buffer.alloc(1), 0, 1, offset)\n\t\tconst after = fstatSync(handle)\n\t\tif (\n\t\t\toffset !== bytes.byteLength ||\n\t\t\toverflow !== 0 ||\n\t\t\tafter.size !== before.size ||\n\t\t\tafter.mtimeMs !== before.mtimeMs\n\t\t) {\n\t\t\treturn undefined\n\t\t}\n\t\treturn bytesToHex(bytes)\n\t})\n\tattempt(() => closeSync(handle))\n\treturn read.success ? read.value : undefined\n}\n\n/**\n * Read one contained file as bounded UTF-8 text.\n *\n * @param root - The containing host directory.\n * @param path - The portable root-relative file path.\n * @param limit - The most bytes this read accepts; the artifact ceiling by default.\n * @returns The decoded text, or `undefined` when {@link readFileHex} answers\n * nothing or the bytes are not valid UTF-8.\n * @throws `ScaffoldError('INVALID', …)` when the arguments are off contract or\n * `path` leaves `root`.\n *\n * @remarks\n * Decoding is strict, so a file carrying an invalid sequence answers `undefined`\n * rather than text carrying replacement characters. That matters because the\n * text is parsed next: a manifest silently repaired into valid JSON by lossy\n * decoding would be trusted.\n *\n * @example\n * ```ts\n * import { readFileText } from '@orkestrel/scaffold/server'\n *\n * readFileText('/tmp/project', 'package.json') // '{ \"name\": \"@orkestrel/router\", … }'\n * ```\n */\nexport function readFileText(\n\troot: string,\n\tpath: string,\n\tlimit: number = MAX_ARTIFACT_BYTES,\n): string | undefined {\n\tconst hex = readFileHex(root, path, limit)\n\tif (hex === undefined) return undefined\n\tconst decoded = attempt(() =>\n\t\tnew TextDecoder('utf-8', { fatal: true }).decode(Buffer.from(hex, 'hex')),\n\t)\n\treturn decoded.success ? decoded.value : undefined\n}\n\n/**\n * Read a target's current bytes at the paths a plan claims.\n *\n * @param target - The target directory to read.\n * @param paths - The plan-relative paths to probe.\n * @returns One entry per path that is there: a file maps to its exact bytes as\n * hexadecimal and a directory maps to `''`, which records presence with no bytes\n * to compare. An absent path is omitted.\n * @throws `ScaffoldError('INVALID', …)` when `target` is not a host path or\n * `paths` is not a bounded list of plannable paths.\n * @throws `ScaffoldError('TARGET', …)` when a path that is there cannot be read,\n * or when the whole read would retain more bytes than one plan may.\n *\n * @remarks\n * The one door from a real directory into the vocabulary an audit compares in.\n * Absence is omission rather than an empty value, because core reads a missing\n * key as a missing destination and an empty string as a present directory; the\n * two are different verdicts. A path that is there but unreadable throws instead\n * of being omitted, because omission would report it as missing and a repair\n * would then overwrite whatever is actually sitting there.\n *\n * @example\n * ```ts\n * import { readSnapshot } from '@orkestrel/scaffold/server'\n *\n * readSnapshot('./packages/router', ['package.json', 'guides'])\n * // { 'package.json': '7b226e…', guides: '' }\n * ```\n */\nexport function readSnapshot(target: string, paths: readonly string[]): Snapshot {\n\tif (!isFilesystemPath(target)) {\n\t\tthrow new ScaffoldError('INVALID', 'Snapshot target is not a host path', { target })\n\t}\n\tif (!isCollection(paths) || !paths.every((path) => isPath(path))) {\n\t\tthrow new ScaffoldError('INVALID', 'Snapshot paths are not a bounded list of plannable paths', {\n\t\t\ttarget,\n\t\t\tlimit: MAX_COLLECTION_ITEMS,\n\t\t})\n\t}\n\tlet remaining = MAX_TOTAL_ARTIFACT_BYTES\n\tconst snapshot: Record<string, string> = {}\n\tfor (const path of paths) {\n\t\tconst full = resolveContainedPath(target, path)\n\t\tif (full === undefined) {\n\t\t\tthrow new ScaffoldError('INVALID', `Snapshot path leaves its target at ${path}`, {\n\t\t\t\ttarget,\n\t\t\t\tpath,\n\t\t\t})\n\t\t}\n\t\tconst status = attempt(() => lstatSync(full))\n\t\tif (!status.success) {\n\t\t\tif (matchesMissingPath(status.error)) continue\n\t\t\tthrow new ScaffoldError('TARGET', `Snapshot path cannot be inspected at ${path}`, {\n\t\t\t\ttarget,\n\t\t\t\tpath,\n\t\t\t\terror: status.error,\n\t\t\t})\n\t\t}\n\t\tif (isPhysicalDirectory(full)) {\n\t\t\tsnapshot[path] = ''\n\t\t\tcontinue\n\t\t}\n\t\tconst hex = readFileHex(target, path, Math.min(MAX_ARTIFACT_BYTES, remaining))\n\t\tif (hex === undefined) {\n\t\t\tthrow new ScaffoldError('TARGET', `Snapshot path is not a readable file at ${path}`, {\n\t\t\t\ttarget,\n\t\t\t\tpath,\n\t\t\t\tlimit: MAX_TOTAL_ARTIFACT_BYTES,\n\t\t\t})\n\t\t}\n\t\tremaining -= hex.length / 2\n\t\tsnapshot[path] = hex\n\t}\n\treturn snapshot\n}\n\n/**\n * Read a vendored host's manifest, when it carries one.\n *\n * @param host - The vendored host root to read.\n * @returns The manifest, or `undefined` when the host carries none.\n * @throws `ScaffoldError('INVALID', …)` when `host` is not a host path.\n * @throws `ScaffoldError('TARGET', …)` when the manifest is there but cannot be\n * read, is not the declared shape, or does not match its own membership.\n *\n * @remarks\n * The two failures are held apart deliberately. A host with no manifest is a\n * raw checkout, and a caller reads it by mapping each path one to one. A host\n * with a manifest that does not verify is a staged host that has been edited,\n * and answering `undefined` there would degrade it to that same one-to-one\n * mapping — which is how an edited manifest would get a caller to read files it\n * never declared. So absence answers and corruption throws.\n *\n * Verification here is the manifest's own self-consistency: the digest against\n * the exact membership beside it. Whether that membership matches the files\n * actually stored is a separate question, and it belongs to the reader that\n * walks the host.\n *\n * @example\n * ```ts\n * import { readHostManifest } from '@orkestrel/scaffold/server'\n *\n * readHostManifest('./dist/host') // the manifest, or undefined for a raw root\n * ```\n */\nexport function readHostManifest(host: string): HostManifest | undefined {\n\tif (!isFilesystemPath(host)) {\n\t\tthrow new ScaffoldError('INVALID', 'Host root is not a host path', { host })\n\t}\n\t// The reserved metadata name a staged host writes at its own root.\n\tconst name = MANIFEST_NAME\n\tconst full = resolveContainedPath(host, name)\n\tif (full === undefined) {\n\t\tthrow new ScaffoldError('INVALID', `Host manifest leaves its root at ${host}`, { host })\n\t}\n\tconst status = attempt(() => lstatSync(full))\n\tif (!status.success) {\n\t\tif (matchesMissingPath(status.error)) return undefined\n\t\tthrow new ScaffoldError('TARGET', `Host manifest cannot be inspected at ${full}`, {\n\t\t\thost,\n\t\t\terror: status.error,\n\t\t})\n\t}\n\tconst text = readFileText(host, name, MAX_MANIFEST_BYTES)\n\tif (text === undefined) {\n\t\tthrow new ScaffoldError('TARGET', `Host manifest is not readable text at ${full}`, { host })\n\t}\n\tconst manifest = parseJSONAs(text, isHostManifest)\n\tif (manifest === undefined) {\n\t\tthrow new ScaffoldError('TARGET', `Host manifest is malformed at ${full}`, { host })\n\t}\n\tif (manifest.digest !== computeManifestDigest(manifest.entries, manifest.roots)) {\n\t\tthrow new ScaffoldError('TARGET', `Host manifest membership is corrupted at ${full}`, { host })\n\t}\n\treturn manifest\n}\n\n/**\n * Derive one vendored-host manifest entry from a file in a checkout.\n *\n * @param destination - The target-relative path the file is written to.\n * @param source - The resolved host path the bytes are read from.\n * @returns The entry, or `undefined` when `source` is not a physical file this\n * package will vendor or carries more bytes than one artifact may.\n *\n * @remarks\n * The one place the three declared fields are decided together, because they are\n * three readings of one file: {@link pathToStorage} decides where it is stored,\n * the destination is the path it answers for, and the executable bit is read\n * from the source's own mode.\n *\n * That mode is the honest limit of this reading. A Windows host reports no\n * executable bit at all, so a host staged there declares every entry\n * non-executable and a consumer receives scripts without it. Staging on a POSIX\n * host is what carries the bit through.\n *\n * @example\n * ```ts\n * import { readManifestEntry } from '@orkestrel/scaffold/server'\n *\n * readManifestEntry('.gitignore', '/tmp/checkout/.gitignore')\n * // { storage: 'dotfiles/gitignore', destination: '.gitignore', executable: false }\n * ```\n */\nexport function readManifestEntry(destination: string, source: string): ManifestEntry | undefined {\n\tif (!isPhysicalFile(source)) return undefined\n\tconst status = attempt(() => lstatSync(source))\n\tif (!status.success || status.value.size > MAX_ARTIFACT_BYTES) return undefined\n\treturn {\n\t\tstorage: pathToStorage(destination),\n\t\tdestination,\n\t\texecutable: (status.value.mode & 0o111) !== 0,\n\t}\n}\n\n/**\n * Stage a vendored host root from a real checkout.\n *\n * @param checkout - The checkout the vendored paths are read from.\n * @param host - The vendored host root to fill; it must be absent or empty.\n * @returns One entry per staged file, sorted by storage name.\n * @throws `ScaffoldError('INVALID', …)` when either argument is not a host path\n * or a vendored path leaves the checkout or the host root.\n * @throws `ScaffoldError('TARGET', …)` when the checkout is not a directory, the\n * host root is not vacant, the checkout does not carry every vendored path, two\n * vendored files claim one storage name, a vendored file is not a plain file\n * within the artifact ceiling, or the staged manifest does not read back.\n * @throws `ScaffoldError('WRITE', …)` when a staged file or the manifest cannot\n * be written.\n *\n * @remarks\n * This is the producer half of the vendored host, and it is not the mutation\n * contract `MaterializerInterface` states. That contract owns **target**\n * writes: it materializes a compiled plan into a consumer's workspace, binds\n * every destination to what the caller observed, and rolls a failed commit back.\n * This reads this package's own checkout at build time and fills its own build\n * output. Different direction, different lifetime, no consumer target involved,\n * so the two do not overlap and neither one belongs inside the other.\n *\n * Staging is plain rather than transactional for the same reason. A\n * `WriteTransaction` exists to hold a directory that already holds work\n * still; a build output holds nothing, is deleted whole before every build, and\n * has no concurrent reader. What replaces it is refusing early and ordering the\n * writes: the whole membership is derived before anything is created, so a\n * checkout this refuses leaves no host root at all, and `manifest.json` is\n * written last, so a stage that failed part way through leaves a root every\n * reader treats as a raw checkout and fails loudly on.\n *\n * A missing vendored path is refused rather than staged around. A partial root\n * is not detectably partial: it fails later, in a consumer's terminal, on\n * whichever path the plan reached first. Refusing here fails the build that\n * produced it, where the maintainer can act, and it names every missing path at\n * once. A directory is the same case — declaring an absent directory as an empty\n * root would create an empty directory in every generated workspace.\n *\n * The vendoring deny-list applies to what the walk discovers beneath a vendored\n * directory, where a maintainer's local credential can legitimately sit, and\n * such a path is skipped. A path `HOST_PATHS` names itself is curated data\n * rather than discovery, so it is staged or the stage is refused.\n *\n * @example\n * ```ts\n * import { stageHost } from '@orkestrel/scaffold/server'\n *\n * stageHost(process.cwd(), 'dist/host').length // the files staged\n * ```\n */\nexport function stageHost(checkout: string, host: string): readonly ManifestEntry[] {\n\tif (!isFilesystemPath(checkout)) {\n\t\tthrow new ScaffoldError('INVALID', 'Staging checkout is not a host path', { checkout })\n\t}\n\tif (!isFilesystemPath(host)) {\n\t\tthrow new ScaffoldError('INVALID', 'Staging host root is not a host path', { host })\n\t}\n\tconst source = resolve(checkout)\n\tif (!isPhysicalDirectory(source)) {\n\t\tthrow new ScaffoldError('TARGET', `Staging checkout is not a physical directory at ${source}`, {\n\t\t\tcheckout: source,\n\t\t})\n\t}\n\tif (!isVacant(host)) {\n\t\tthrow new ScaffoldError('TARGET', `Staging host root is not vacant at ${host}`, { host })\n\t}\n\tconst vendored: string[] = []\n\tconst roots: string[] = []\n\tconst missing: string[] = []\n\tfor (const path of HOST_PATHS) {\n\t\tconst full = resolveContainedPath(source, path)\n\t\tif (full === undefined) {\n\t\t\tthrow new ScaffoldError('INVALID', `Vendored path leaves its checkout at ${path}`, {\n\t\t\t\tcheckout: source,\n\t\t\t\tpath,\n\t\t\t})\n\t\t}\n\t\tif (isPhysicalFile(full)) {\n\t\t\tvendored.push(path)\n\t\t\tcontinue\n\t\t}\n\t\tif (!isPhysicalDirectory(full)) {\n\t\t\tmissing.push(path)\n\t\t\tcontinue\n\t\t}\n\t\troots.push(path)\n\t\tfor (const nested of listDirectories(full)) {\n\t\t\tconst rooted = `${path}/${nested}`\n\t\t\tif (!matchesSensitivePath(rooted)) roots.push(rooted)\n\t\t}\n\t\tfor (const name of listFiles(full)) {\n\t\t\tconst destination = `${path}/${name}`\n\t\t\tif (!matchesSensitivePath(destination)) vendored.push(destination)\n\t\t}\n\t}\n\tif (missing.length > 0) {\n\t\tthrow new ScaffoldError('TARGET', 'The checkout does not carry every vendored path', {\n\t\t\tcheckout: source,\n\t\t\tmissing,\n\t\t})\n\t}\n\t// Seeded with the reserved metadata name a staged host writes at its own root,\n\t// the same literal `readHostManifest` reads back, so a vendored file claiming it\n\t// is refused rather than silently replaced by the manifest.\n\tconst stored = new Set<string>([MANIFEST_NAME])\n\tconst entries: ManifestEntry[] = []\n\tfor (const destination of vendored) {\n\t\tconst full = resolveContainedPath(source, destination)\n\t\tif (full === undefined) {\n\t\t\tthrow new ScaffoldError('INVALID', `Vendored path leaves its checkout at ${destination}`, {\n\t\t\t\tcheckout: source,\n\t\t\t\tpath: destination,\n\t\t\t})\n\t\t}\n\t\tconst entry = readManifestEntry(destination, full)\n\t\tif (entry === undefined) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'TARGET',\n\t\t\t\t`Vendored path is not a plain file within the artifact ceiling at ${destination}`,\n\t\t\t\t{ checkout: source, path: destination, limit: MAX_ARTIFACT_BYTES },\n\t\t\t)\n\t\t}\n\t\tif (stored.has(entry.storage)) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'TARGET',\n\t\t\t\t`Two vendored paths claim the storage name ${entry.storage}`,\n\t\t\t\t{ checkout: source, path: destination, storage: entry.storage },\n\t\t\t)\n\t\t}\n\t\tstored.add(entry.storage)\n\t\tentries.push(entry)\n\t}\n\tentries.sort((first, second) => (first.storage < second.storage ? -1 : 1))\n\troots.sort()\n\tconst root = resolve(host)\n\tconst established = attempt(() => mkdirSync(root, { recursive: true }))\n\tif (!established.success || !isPhysicalDirectory(root)) {\n\t\tthrow new ScaffoldError('WRITE', `Staging host root could not be established at ${root}`, {\n\t\t\thost: root,\n\t\t\t...(established.success ? {} : { error: established.error }),\n\t\t})\n\t}\n\tfor (const entry of entries) {\n\t\tconst origin = resolveContainedPath(source, entry.destination)\n\t\tconst destination = resolveContainedPath(root, entry.storage)\n\t\tif (origin === undefined || destination === undefined) {\n\t\t\tthrow new ScaffoldError('INVALID', `Vendored path leaves its root at ${entry.destination}`, {\n\t\t\t\tcheckout: source,\n\t\t\t\thost: root,\n\t\t\t\tpath: entry.destination,\n\t\t\t\tstorage: entry.storage,\n\t\t\t})\n\t\t}\n\t\tconst copied = attempt(() => {\n\t\t\tmkdirSync(dirname(destination), { recursive: true })\n\t\t\tcopyFileSync(origin, destination, constants.COPYFILE_EXCL)\n\t\t\tif (entry.executable) chmodSync(destination, 0o755)\n\t\t})\n\t\tif (!copied.success) {\n\t\t\tthrow new ScaffoldError('WRITE', `Vendored file could not be staged at ${entry.storage}`, {\n\t\t\t\thost: root,\n\t\t\t\tstorage: entry.storage,\n\t\t\t\terror: copied.error,\n\t\t\t})\n\t\t}\n\t}\n\tconst manifest: HostManifest = {\n\t\tentries,\n\t\troots,\n\t\tdigest: computeManifestDigest(entries, roots),\n\t}\n\tconst metadata = resolveContainedPath(root, MANIFEST_NAME)\n\tif (metadata === undefined) {\n\t\tthrow new ScaffoldError('INVALID', `Host manifest leaves its root at ${root}`, { host: root })\n\t}\n\tconst published = attempt(() =>\n\t\twriteFileSync(metadata, `${JSON.stringify(manifest, null, '\\t')}\\n`, {\n\t\t\tencoding: 'utf8',\n\t\t\tflag: 'wx',\n\t\t}),\n\t)\n\tif (!published.success) {\n\t\tthrow new ScaffoldError('WRITE', `Host manifest could not be staged at ${metadata}`, {\n\t\t\thost: root,\n\t\t\terror: published.error,\n\t\t})\n\t}\n\tconst verified = readHostManifest(root)\n\tif (verified === undefined || verified.digest !== manifest.digest) {\n\t\tthrow new ScaffoldError('TARGET', `The staged host manifest does not read back at ${root}`, {\n\t\t\thost: root,\n\t\t})\n\t}\n\treturn entries\n}\n\n/**\n * Capture one directory's physical identity.\n *\n * @param path - The resolved directory path to capture.\n * @returns The anchor, or `undefined` when the path is not a physical directory.\n *\n * @remarks\n * Device and inode rather than the path, because the path is the thing that can\n * be swapped underneath a write. An anchor captured before a mutation and\n * checked again after it is what proves the directory written into is the\n * directory that was inspected.\n *\n * @example\n * ```ts\n * import { readAnchor } from '@orkestrel/scaffold/server'\n *\n * readAnchor('/tmp/project') // { path: '/tmp/project', device: 1, inode: 2 }\n * ```\n */\nexport function readAnchor(path: string): WriteAnchor | undefined {\n\tconst status = attempt(() => lstatSync(path))\n\tif (!status.success || !status.value.isDirectory() || status.value.isSymbolicLink()) {\n\t\treturn undefined\n\t}\n\treturn { path, device: status.value.dev, inode: status.value.ino }\n}\n\n/**\n * Test whether a captured directory is still the same directory.\n *\n * @param anchor - The identity captured earlier.\n * @returns `true` when the path still holds a physical directory of that exact\n * device and inode.\n *\n * @remarks\n * The check a write repeats between steps. A directory replaced by another\n * directory of the same name answers `false` here, which is the case a path\n * comparison alone cannot see.\n *\n * @example\n * ```ts\n * import { matchesAnchor, readAnchor } from '@orkestrel/scaffold/server'\n *\n * const anchor = readAnchor('/tmp/project')\n * anchor !== undefined && matchesAnchor(anchor) // true while it is untouched\n * ```\n */\nexport function matchesAnchor(anchor: WriteAnchor): boolean {\n\tconst current = readAnchor(anchor.path)\n\treturn current !== undefined && current.device === anchor.device && current.inode === anchor.inode\n}\n\n/**\n * Capture what one destination holds before a write.\n *\n * @param path - The resolved destination path to capture.\n * @returns The expectation, or `undefined` when the destination is a link or a\n * shape this package will not write over.\n *\n * @remarks\n * Absence is a captured state rather than a failure, because most writes expect\n * exactly that. Each shape carries only the facts it supplies: a directory\n * carries its identity, a file carries its identity, size, and bytes, and an\n * absent destination carries nothing at all. A file past the artifact ceiling\n * carries no digest and is bound by its identity, size, and modification time\n * alone, which is the strongest honest claim about bytes nobody read.\n *\n * @example\n * ```ts\n * import { readExpectation } from '@orkestrel/scaffold/server'\n *\n * readExpectation('/tmp/project/absent.md') // { path: …, shape: 'absent' }\n * ```\n */\nexport function readExpectation(path: string): WriteExpectation | undefined {\n\tconst status = attempt(() => lstatSync(path))\n\tif (!status.success) {\n\t\treturn matchesMissingPath(status.error) ? { path, shape: 'absent' } : undefined\n\t}\n\tconst stats = status.value\n\tif (stats.isSymbolicLink()) return undefined\n\tif (stats.isDirectory()) {\n\t\treturn {\n\t\t\tpath,\n\t\t\tshape: 'directory',\n\t\t\tdevice: stats.dev,\n\t\t\tinode: stats.ino,\n\t\t\tmodified: stats.mtimeMs,\n\t\t}\n\t}\n\tif (!stats.isFile() || stats.nlink !== 1) return undefined\n\tconst digest = computeFileDigest(path)\n\treturn {\n\t\tpath,\n\t\tshape: 'file',\n\t\tdevice: stats.dev,\n\t\tinode: stats.ino,\n\t\tmodified: stats.mtimeMs,\n\t\tsize: stats.size,\n\t\t...(digest === undefined ? {} : { digest }),\n\t}\n}\n\n/**\n * Test whether a destination still holds what was captured of it.\n *\n * @param expectation - The state captured earlier.\n * @returns `true` when re-reading the destination now produces that same state.\n *\n * @remarks\n * Compared field for field against a fresh {@link readExpectation}, so an\n * expectation recorded without a digest matches only a destination that still\n * has no digest to give. That is what keeps the comparison honest in both\n * directions: nothing is treated as satisfied because it was never measured.\n *\n * @example\n * ```ts\n * import { matchesExpectation, readExpectation } from '@orkestrel/scaffold/server'\n *\n * const expectation = readExpectation('/tmp/project/AGENTS.md')\n * expectation !== undefined && matchesExpectation(expectation) // true while untouched\n * ```\n */\nexport function matchesExpectation(expectation: WriteExpectation): boolean {\n\tconst current = readExpectation(expectation.path)\n\tif (current === undefined) return false\n\treturn (\n\t\tcurrent.shape === expectation.shape &&\n\t\tcurrent.device === expectation.device &&\n\t\tcurrent.inode === expectation.inode &&\n\t\tcurrent.modified === expectation.modified &&\n\t\tcurrent.size === expectation.size &&\n\t\tcurrent.digest === expectation.digest\n\t)\n}\n\n/**\n * Test whether a destination still matches the narrower state a caller observed.\n *\n * @param precondition - The caller-observed state the write is held to.\n * @returns `true` when the destination is absent as stated, or holds a physical\n * file whose bytes digest to the stated value.\n *\n * @remarks\n * Narrower than {@link matchesExpectation} on purpose. A caller observed bytes,\n * not inodes and timestamps, so binding a write to a device identity it never\n * saw would refuse writes that are perfectly safe — a file rewritten to\n * identical bytes by an editor is still the file the caller read. A precondition\n * that states no digest claims presence only.\n *\n * @example\n * ```ts\n * import { matchesPrecondition } from '@orkestrel/scaffold/server'\n *\n * matchesPrecondition({ path: '/tmp/project/new.md', shape: 'absent' }) // true while absent\n * ```\n */\nexport function matchesPrecondition(precondition: WritePrecondition): boolean {\n\tconst status = attempt(() => lstatSync(precondition.path))\n\tif (!status.success) {\n\t\treturn precondition.shape === 'absent' && matchesMissingPath(status.error)\n\t}\n\tif (precondition.shape !== 'file' || !isPhysicalFile(precondition.path)) return false\n\tif (precondition.digest === undefined) return true\n\treturn computeFileDigest(precondition.path) === precondition.digest\n}\n","import type {\n\tWriteAnchor,\n\tWriteDirectoryResult,\n\tWriteExpectation,\n\tWritePrecondition,\n} from './types.js'\nimport { randomUUID } from 'node:crypto'\nimport {\n\tchmodSync,\n\tconstants,\n\tcopyFileSync,\n\tlinkSync,\n\tmkdirSync,\n\trenameSync,\n\trmdirSync,\n\trmSync,\n\twriteFileSync,\n} from 'node:fs'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport { attempt } from '@orkestrel/contract'\nimport { isCollection, isPath, ScaffoldError } from '@src/core'\nimport {\n\tcomputeDigest,\n\tcomputeFileDigest,\n\tisPhysicalFile,\n\tmatchesAnchor,\n\tmatchesExpectation,\n\tmatchesMissingPath,\n\tmatchesPrecondition,\n\treadAnchor,\n\treadExpectation,\n\tresolveContainedPath,\n} from './helpers.js'\nimport { isFilesystemPath } from './validators.js'\nimport { MAX_PATH_DEPTH } from './constants.js'\n\n/**\n * One staged, reversible mutation of one target directory.\n *\n * @remarks\n * The transaction owns a private root beside the target — a sibling directory on\n * the same volume, so every promotion is a rename rather than a copy. Staging\n * writes go into that root and nothing else, so a call that fails while staging\n * has not touched the target at all. Commit is the only step that mutates the\n * target, and it is the only step that can need rolling back.\n *\n * Two bindings hold a destination still. A **precondition** is what the caller\n * observed earlier and is checked once, at construction, so a target that moved\n * between the caller's read and this transaction fails before anything is\n * created. An **expectation** is captured here, at construction, and re-checked\n * at commit, so a target that moves while the write is being staged fails before\n * anything is promoted.\n *\n * What this provides, exactly:\n *\n * - **Across destinations, staged-then-swapped with rollback on a caught\n * failure.** A failure part way through commit restores every destination it\n * already promoted, restores every file it already took, and removes every\n * directory it created, then reports what recovery could not undo. This is\n * measured: a promotion is driven to fail after an earlier one landed, and the\n * earlier destination is read back.\n * - **No partly written destination.** Every file is written whole into the\n * private root and digested there before commit, so a destination never\n * receives bytes that were still being produced.\n * - **No crash atomicity across destinations.** A process killed between two\n * promotions leaves the target holding some new files and some old ones, and\n * leaves the private root behind. Nothing here is a journal, and the private\n * root's name is the only record a later run could read.\n *\n * A destination is preserved by hard link and then replaced by a single\n * `rename`, rather than moved aside and replaced, so the path continues to name\n * the old file right up to the swap. That is a property of `rename` on the host,\n * not one this package's tests measure: telling it apart from move-then-replace\n * needs a reader observing the destination inside the swap, and no test here\n * does that. Read the claim as the mechanism it describes, not as a proven\n * guarantee about a concurrent reader.\n *\n * A path names a file this transaction writes, takes, or establishes as a\n * directory; every path is target-relative and is measured by the portable-path\n * law. An expectation and a precondition both name the resolved destination\n * instead, because that is the path each is re-read at.\n *\n * @example\n * ```ts\n * import { WriteTransaction } from '@orkestrel/scaffold/server'\n *\n * const transaction = new WriteTransaction('./packages/router', ['AGENTS.md'])\n * try {\n * \ttransaction.write('AGENTS.md', '# Agents\\n')\n * \ttransaction.commit() // ['AGENTS.md']\n * } finally {\n * \ttransaction.discard()\n * }\n * ```\n */\nexport class WriteTransaction {\n\treadonly #target: string\n\treadonly #root: string\n\treadonly #stage: string\n\treadonly #backup: string\n\treadonly #expectations: ReadonlyMap<string, WriteExpectation>\n\treadonly #created: WriteAnchor[] = []\n\treadonly #staged: string[] = []\n\treadonly #established: string[] = []\n\treadonly #taken: string[] = []\n\t#open = true\n\n\t/**\n\t * Open a transaction over one target directory.\n\t *\n\t * @param target - The directory every path is written beneath.\n\t * @param paths - Every target-relative path this transaction may touch.\n\t * @param preconditions - The caller-observed destination states the whole\n\t * transaction is held to, each naming a resolved destination of `paths`.\n\t * @throws {@link ScaffoldError} coded `INVALID` when an argument is off\n\t * contract, `TARGET` when a destination is a shape this package will not write\n\t * over or no longer matches its precondition, and `WRITE` when the private\n\t * root cannot be established.\n\t *\n\t * @remarks\n\t * Nothing is created until every destination has been inspected and every\n\t * precondition has held, so a refused transaction leaves no residue at all.\n\t * The private root is created last and carries a random name, so two\n\t * transactions over one target never collide.\n\t */\n\tconstructor(\n\t\ttarget: string,\n\t\tpaths: readonly string[],\n\t\tpreconditions?: readonly WritePrecondition[],\n\t) {\n\t\tif (!isFilesystemPath(target)) {\n\t\t\tthrow new ScaffoldError('INVALID', 'The write target is not a host path.', { target })\n\t\t}\n\t\tif (!isCollection(paths) || !paths.every((path) => isPath(path))) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'INVALID',\n\t\t\t\t'The write paths are not a bounded list of plannable paths.',\n\t\t\t\t{\n\t\t\t\t\ttarget,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tif (new Set(paths).size !== paths.length) {\n\t\t\tthrow new ScaffoldError('INVALID', 'The write paths repeat a destination.', { target, paths })\n\t\t}\n\t\tthis.#target = resolve(target)\n\t\tconst expectations = new Map<string, WriteExpectation>()\n\t\tfor (const path of paths) {\n\t\t\tconst destination = this.#resolve(this.#target, path)\n\t\t\tconst expectation = readExpectation(destination)\n\t\t\tif (expectation === undefined) {\n\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t'TARGET',\n\t\t\t\t\t`The destination at ${path} is a shape this package will not write over.`,\n\t\t\t\t\t{ target: this.#target, path },\n\t\t\t\t)\n\t\t\t}\n\t\t\texpectations.set(path, expectation)\n\t\t}\n\t\tthis.#expectations = expectations\n\t\tconst destinations = new Set([...expectations.values()].map((expectation) => expectation.path))\n\t\tfor (const precondition of preconditions ?? []) {\n\t\t\tif (!destinations.has(precondition.path)) {\n\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`The precondition at ${precondition.path} names no destination of this transaction.`,\n\t\t\t\t\t{ target: this.#target, path: precondition.path },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (!matchesPrecondition(precondition)) {\n\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t'TARGET',\n\t\t\t\t\t`The destination at ${precondition.path} no longer holds what the caller observed.`,\n\t\t\t\t\t{ target: this.#target, path: precondition.path },\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tconst parent = dirname(this.#target)\n\t\tthis.#root = join(parent, `.${basename(this.#target)}.write-${randomUUID()}`)\n\t\tthis.#stage = join(this.#root, 'stage')\n\t\tthis.#backup = join(this.#root, 'backup')\n\t\tconst opened = attempt(() => {\n\t\t\tthis.#created.push(...this.#establish(parent).created)\n\t\t\tfor (const directory of [this.#root, this.#stage, this.#backup]) {\n\t\t\t\tmkdirSync(directory, { mode: 0o700 })\n\t\t\t\tif (readAnchor(directory) === undefined) {\n\t\t\t\t\tthrow new ScaffoldError('WRITE', 'The private write root is not a physical directory.', {\n\t\t\t\t\t\ttarget: this.#target,\n\t\t\t\t\t\troot: this.#root,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\tif (!opened.success) {\n\t\t\tthis.#open = false\n\t\t\tthis.#recover([], [])\n\t\t\tthrow new ScaffoldError('WRITE', 'The private write root could not be established.', {\n\t\t\t\ttarget: this.#target,\n\t\t\t\troot: this.#root,\n\t\t\t\terror: opened.error,\n\t\t\t})\n\t\t}\n\t}\n\n\t/** The resolved directory every path is written beneath. */\n\tget target(): string {\n\t\treturn this.#target\n\t}\n\n\t/** What each destination held when the transaction opened, in path order. */\n\tget expectations(): readonly WriteExpectation[] {\n\t\treturn [...this.#expectations.values()]\n\t}\n\n\t/** Whether the transaction can still be committed or discarded. */\n\tget open(): boolean {\n\t\treturn this.#open\n\t}\n\n\t/**\n\t * Stage one text file.\n\t *\n\t * @param path - The target-relative path to write.\n\t * @param content - The exact UTF-8 text the destination should hold.\n\t * @returns Nothing.\n\t * @throws {@link ScaffoldError} coded `INVALID` when the path is not one this\n\t * transaction opened or is already staged, `TARGET` when the destination holds\n\t * a directory, and `WRITE` when the staged file cannot be written or does not\n\t * carry the bytes it was given.\n\t *\n\t * @remarks\n\t * The staged file is read back and digested against the text it was given, so\n\t * a partial or interrupted write is refused here rather than promoted later.\n\t */\n\twrite(path: string, content: string): void {\n\t\tconst expectation = this.#claim(path)\n\t\tif (expectation.shape === 'directory') {\n\t\t\tthrow new ScaffoldError('TARGET', `The destination at ${path} holds a directory.`, { path })\n\t\t}\n\t\tconst staged = this.#stagePath(path)\n\t\tconst written = attempt(() => {\n\t\t\twriteFileSync(staged, content, { encoding: 'utf8', flag: 'wx' })\n\t\t})\n\t\tif (!written.success) {\n\t\t\tthrow new ScaffoldError('WRITE', `The staged file at ${path} could not be written.`, {\n\t\t\t\tpath,\n\t\t\t\terror: written.error,\n\t\t\t})\n\t\t}\n\t\tif (computeFileDigest(staged) !== computeDigest(content)) {\n\t\t\tthrow new ScaffoldError('WRITE', `The staged file at ${path} does not carry its content.`, {\n\t\t\t\tpath,\n\t\t\t})\n\t\t}\n\t\tthis.#staged.push(path)\n\t}\n\n\t/**\n\t * Stage one byte-for-byte copy of a file that already exists on this host.\n\t *\n\t * @param path - The target-relative path to write.\n\t * @param source - The resolved absolute path to copy the bytes from.\n\t * @param executable - Whether the destination should carry the executable bit.\n\t * @returns Nothing.\n\t * @throws {@link ScaffoldError} coded `INVALID` when the path is not one this\n\t * transaction opened or is already staged, `TARGET` when the destination holds\n\t * a directory or the source is not a physical file, and `WRITE` when the copy\n\t * cannot be made or does not digest to the source's bytes.\n\t *\n\t * @remarks\n\t * The source is digested before the copy and the copy is digested after it, so\n\t * a source that changed mid-copy is refused instead of staged.\n\t */\n\tcopy(path: string, source: string, executable: boolean): void {\n\t\tconst expectation = this.#claim(path)\n\t\tif (expectation.shape === 'directory') {\n\t\t\tthrow new ScaffoldError('TARGET', `The destination at ${path} holds a directory.`, { path })\n\t\t}\n\t\tconst digest = isPhysicalFile(source) ? computeFileDigest(source) : undefined\n\t\tif (digest === undefined) {\n\t\t\tthrow new ScaffoldError('TARGET', `The copy source for ${path} is not a readable file.`, {\n\t\t\t\tpath,\n\t\t\t\tsource,\n\t\t\t})\n\t\t}\n\t\tconst staged = this.#stagePath(path)\n\t\tconst copied = attempt(() => {\n\t\t\tcopyFileSync(source, staged, constants.COPYFILE_EXCL)\n\t\t\tif (executable) chmodSync(staged, 0o755)\n\t\t})\n\t\tif (!copied.success) {\n\t\t\tthrow new ScaffoldError('WRITE', `The staged copy at ${path} could not be made.`, {\n\t\t\t\tpath,\n\t\t\t\tsource,\n\t\t\t\terror: copied.error,\n\t\t\t})\n\t\t}\n\t\tif (computeFileDigest(staged) !== digest) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'WRITE',\n\t\t\t\t`The staged copy at ${path} does not carry the source bytes.`,\n\t\t\t\t{\n\t\t\t\t\tpath,\n\t\t\t\t\tsource,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tthis.#staged.push(path)\n\t}\n\n\t/**\n\t * Establish one directory inside the target, one segment at a time.\n\t *\n\t * @param path - The target-relative directory to establish.\n\t * @returns The directory's identity and every segment this call created.\n\t * @throws {@link ScaffoldError} coded `INVALID` when the path is not one this\n\t * transaction opened, `TARGET` when the destination holds a file, and `WRITE`\n\t * when a segment cannot be created or changed while it was being created.\n\t *\n\t * @remarks\n\t * A directory is created immediately rather than staged, because creating one\n\t * destroys nothing: rollback removes exactly the segments this call created,\n\t * innermost first, and leaves every segment that was already there. Each\n\t * created segment is captured by device and inode, so a segment swapped\n\t * underneath the transaction is detected rather than written into.\n\t */\n\tdirectory(path: string): WriteDirectoryResult {\n\t\tthis.#assertOpen()\n\t\tconst expectation = this.#expectation(path)\n\t\tif (expectation.shape === 'file') {\n\t\t\tthrow new ScaffoldError('TARGET', `The destination at ${path} holds a file.`, { path })\n\t\t}\n\t\tconst result = this.#establish(this.#resolve(this.#target, path))\n\t\tthis.#created.push(...result.created)\n\t\tif (result.created.length > 0 && !this.#established.includes(path)) this.#established.push(path)\n\t\treturn result\n\t}\n\n\t/**\n\t * Mark one file for deletion at commit.\n\t *\n\t * @param path - The target-relative file to delete.\n\t * @returns Nothing.\n\t * @throws {@link ScaffoldError} coded `INVALID` when the path is not one this\n\t * transaction opened or is already claimed, and `TARGET` when the destination\n\t * does not hold a file.\n\t *\n\t * @remarks\n\t * Nothing moves here. Commit renames the file into the private backup rather\n\t * than unlinking it, so a later failure in the same commit puts it back.\n\t */\n\tremove(path: string): void {\n\t\tconst expectation = this.#claim(path)\n\t\tif (expectation.shape !== 'file') {\n\t\t\tthrow new ScaffoldError('TARGET', `The destination at ${path} holds no file to remove.`, {\n\t\t\t\tpath,\n\t\t\t})\n\t\t}\n\t\tthis.#taken.push(path)\n\t}\n\n\t/**\n\t * Promote every staged file and take every marked file, or roll the whole call back.\n\t *\n\t * @returns Every target-relative path whose destination changed: the files\n\t * promoted, then the directories established, then the files taken.\n\t * @throws {@link ScaffoldError} coded `WRITE` when the transaction is closed,\n\t * when a destination moved since the transaction opened, or when the commit\n\t * failed; a failure reports what rollback could not undo in its context.\n\t *\n\t * @remarks\n\t * Every destination and every directory this transaction created is re-checked\n\t * before anything moves, so the common failure moves nothing at all. That\n\t * check runs inside the same rollback as the promotions, because a transaction\n\t * that refuses before it starts still has a private root and created\n\t * directories to clear. The transaction is closed either way: a committed one\n\t * has nothing left to undo and a failed one has already been rolled back.\n\t */\n\tcommit(): readonly string[] {\n\t\tthis.#assertOpen()\n\t\tconst promoted: string[] = []\n\t\tconst taken: string[] = []\n\t\tconst applied = attempt(() => {\n\t\t\tthis.#preflight()\n\t\t\tfor (const path of this.#staged) {\n\t\t\t\tthis.#promote(path)\n\t\t\t\tpromoted.push(path)\n\t\t\t}\n\t\t\tfor (const path of this.#taken) {\n\t\t\t\tthis.#take(path)\n\t\t\t\ttaken.push(path)\n\t\t\t}\n\t\t})\n\t\tthis.#open = false\n\t\tif (!applied.success) {\n\t\t\tconst residue = this.#recover(promoted, taken)\n\t\t\tthrow new ScaffoldError('WRITE', 'The commit failed and was rolled back.', {\n\t\t\t\ttarget: this.#target,\n\t\t\t\troot: this.#root,\n\t\t\t\terror: applied.error,\n\t\t\t\tcommitted: false,\n\t\t\t\tresidue,\n\t\t\t})\n\t\t}\n\t\tconst cleared = attempt(() => rmSync(this.#root, { recursive: true, force: true }))\n\t\tif (!cleared.success) {\n\t\t\tthrow new ScaffoldError('WRITE', 'The commit completed but left private residue.', {\n\t\t\t\ttarget: this.#target,\n\t\t\t\troot: this.#root,\n\t\t\t\terror: cleared.error,\n\t\t\t\tcommitted: true,\n\t\t\t})\n\t\t}\n\t\treturn [...this.#staged, ...this.#established, ...this.#taken]\n\t}\n\n\t/**\n\t * Abandon the transaction and remove everything it created.\n\t *\n\t * @returns Nothing.\n\t * @throws {@link ScaffoldError} coded `WRITE` when residue could not be\n\t * removed, naming the private root that still holds it.\n\t *\n\t * @remarks\n\t * Idempotent, and a no-op on a transaction that already committed or already\n\t * failed, so a caller can put it in a `finally` beside the work it guards.\n\t */\n\tdiscard(): void {\n\t\tif (!this.#open) return\n\t\tthis.#open = false\n\t\tconst residue = this.#recover([], [])\n\t\tif (residue.length > 0) {\n\t\t\tthrow new ScaffoldError('WRITE', 'The discarded transaction left residue.', {\n\t\t\t\ttarget: this.#target,\n\t\t\t\troot: this.#root,\n\t\t\t\tresidue,\n\t\t\t})\n\t\t}\n\t}\n\n\t// Resolve a root-relative path and refuse one whose existing ancestors are not\n\t// all physical directories. Containment alone is a read-time law: a link\n\t// planted between the root and the destination stays inside the root, so it\n\t// passes containment while still moving the write somewhere the caller never\n\t// named.\n\t#resolve(root: string, path: string): string {\n\t\tconst destination = resolveContainedPath(root, path)\n\t\tif (destination === undefined) {\n\t\t\tthrow new ScaffoldError('INVALID', `The path ${path} is off contract or leaves its root.`, {\n\t\t\t\troot,\n\t\t\t\tpath,\n\t\t\t})\n\t\t}\n\t\tconst base = resolve(root)\n\t\tlet ancestor = dirname(destination)\n\t\tfor (let depth = 0; depth <= MAX_PATH_DEPTH; depth += 1) {\n\t\t\tconst state = readExpectation(ancestor)\n\t\t\tif (state === undefined || state.shape === 'file') {\n\t\t\t\tthrow new ScaffoldError('WRITE', `The path ${path} passes through a link or a file.`, {\n\t\t\t\t\troot,\n\t\t\t\t\tpath,\n\t\t\t\t\tancestor,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (ancestor === base) return destination\n\t\t\tconst parent = dirname(ancestor)\n\t\t\tif (parent === ancestor) break\n\t\t\tancestor = parent\n\t\t}\n\t\tthrow new ScaffoldError('INVALID', `The path ${path} does not resolve beneath its root.`, {\n\t\t\troot,\n\t\t\tpath,\n\t\t})\n\t}\n\n\t// Create one absolute directory path segment by segment, revalidating the\n\t// deepest established segment before and after each `mkdir`, so a segment\n\t// swapped between two steps is caught rather than written into.\n\t#establish(path: string): WriteDirectoryResult {\n\t\tconst destination = resolve(path)\n\t\tconst missing: string[] = []\n\t\tlet current = destination\n\t\tlet anchor = readAnchor(current)\n\t\tfor (let depth = 0; anchor === undefined && depth <= MAX_PATH_DEPTH; depth += 1) {\n\t\t\tconst state = readExpectation(current)\n\t\t\tif (state === undefined || state.shape !== 'absent') {\n\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t'WRITE',\n\t\t\t\t\t`The directory at ${current} is not a physical directory.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: destination,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tmissing.push(current)\n\t\t\tconst parent = dirname(current)\n\t\t\tif (parent === current) {\n\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t'WRITE',\n\t\t\t\t\t`The directory at ${destination} has no existing ancestor.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: destination,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tcurrent = parent\n\t\t\tanchor = readAnchor(current)\n\t\t}\n\t\tif (anchor === undefined) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'WRITE',\n\t\t\t\t`The directory at ${destination} is nested past the ceiling.`,\n\t\t\t\t{\n\t\t\t\t\tpath: destination,\n\t\t\t\t\tlimit: MAX_PATH_DEPTH,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tconst created: WriteAnchor[] = []\n\t\tfor (const segment of [...missing].reverse()) {\n\t\t\tif (!matchesAnchor(anchor)) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `The directory at ${anchor.path} changed while writing.`, {\n\t\t\t\t\tpath: destination,\n\t\t\t\t\tancestor: anchor.path,\n\t\t\t\t})\n\t\t\t}\n\t\t\tmkdirSync(segment)\n\t\t\tconst established = readAnchor(segment)\n\t\t\tif (established === undefined) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `The directory at ${segment} changed while writing.`, {\n\t\t\t\t\tpath: destination,\n\t\t\t\t})\n\t\t\t}\n\t\t\tanchor = established\n\t\t\tcreated.push(established)\n\t\t}\n\t\treturn { anchor, created }\n\t}\n\n\t// Every destination and every created directory, re-read once before the first\n\t// promotion. A failure here has moved nothing, so the caller still holds the\n\t// target exactly as it found it.\n\t#preflight(): void {\n\t\tfor (const anchor of this.#created) {\n\t\t\tif (!matchesAnchor(anchor)) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `The directory at ${anchor.path} changed while writing.`, {\n\t\t\t\t\ttarget: this.#target,\n\t\t\t\t\tpath: anchor.path,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tfor (const path of [...this.#staged, ...this.#taken]) {\n\t\t\tconst expectation = this.#expectation(path)\n\t\t\tif (!matchesExpectation(expectation)) {\n\t\t\t\tthrow new ScaffoldError('WRITE', `The destination at ${path} moved while writing.`, {\n\t\t\t\t\ttarget: this.#target,\n\t\t\t\t\tpath,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tfor (const path of this.#staged) {\n\t\t\tif (!isPhysicalFile(this.#resolve(this.#stage, path))) {\n\t\t\t\tthrow new ScaffoldError(\n\t\t\t\t\t'WRITE',\n\t\t\t\t\t`The staged file at ${path} is no longer a physical file.`,\n\t\t\t\t\t{\n\t\t\t\t\t\ttarget: this.#target,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Preserve the destination's bytes under a second name, then replace the\n\t// directory entry in one rename. The destination names the whole old file\n\t// until that rename lands and the whole new file after it.\n\t#promote(path: string): void {\n\t\tconst expectation = this.#expectation(path)\n\t\tif (!matchesExpectation(expectation)) {\n\t\t\tthrow new ScaffoldError('WRITE', `The destination at ${path} moved while writing.`, { path })\n\t\t}\n\t\tconst staged = this.#resolve(this.#stage, path)\n\t\tif (expectation.shape === 'absent') {\n\t\t\tthis.#created.push(...this.#establish(dirname(expectation.path)).created)\n\t\t} else {\n\t\t\tconst backup = this.#resolve(this.#backup, path)\n\t\t\tmkdirSync(dirname(backup), { recursive: true })\n\t\t\tlinkSync(expectation.path, backup)\n\t\t}\n\t\trenameSync(staged, expectation.path)\n\t}\n\n\t// Move the file out of the target rather than unlinking it, so a later failure\n\t// in the same commit can put the exact bytes back.\n\t#take(path: string): void {\n\t\tconst expectation = this.#expectation(path)\n\t\tif (!matchesExpectation(expectation)) {\n\t\t\tthrow new ScaffoldError('WRITE', `The destination at ${path} moved while writing.`, { path })\n\t\t}\n\t\tconst backup = this.#resolve(this.#backup, path)\n\t\tmkdirSync(dirname(backup), { recursive: true })\n\t\trenameSync(expectation.path, backup)\n\t}\n\n\t// Undo everything this transaction did, newest first, and report what it could\n\t// not undo instead of throwing over the failure that started the rollback.\n\t#recover(promoted: readonly string[], taken: readonly string[]): readonly unknown[] {\n\t\tconst residue: unknown[] = []\n\t\tfor (const path of [...taken].reverse()) {\n\t\t\tconst restored = attempt(() =>\n\t\t\t\trenameSync(this.#resolve(this.#backup, path), this.#expectation(path).path),\n\t\t\t)\n\t\t\tif (!restored.success) residue.push(restored.error)\n\t\t}\n\t\tfor (const path of [...promoted].reverse()) {\n\t\t\tconst expectation = this.#expectation(path)\n\t\t\tconst restored = attempt(() => {\n\t\t\t\tif (expectation.shape === 'absent') {\n\t\t\t\t\trmSync(expectation.path, { force: true })\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\trenameSync(this.#resolve(this.#backup, path), expectation.path)\n\t\t\t})\n\t\t\tif (!restored.success) residue.push(restored.error)\n\t\t}\n\t\t// The private root holds every preserved copy, so it survives whenever a\n\t\t// restore failed: deleting it there would destroy the only remaining bytes.\n\t\tif (residue.length === 0) {\n\t\t\tconst cleared = attempt(() => rmSync(this.#root, { recursive: true, force: true }))\n\t\t\tif (!cleared.success) residue.push(cleared.error)\n\t\t}\n\t\tfor (const anchor of [...this.#created].reverse()) {\n\t\t\tconst removed = attempt(() => rmdirSync(anchor.path))\n\t\t\tif (!removed.success && !matchesMissingPath(removed.error)) residue.push(removed.error)\n\t\t}\n\t\treturn residue\n\t}\n\n\t// Establish the staged file's parents inside the private root and hand back the\n\t// path to write at. Nothing here reaches the target.\n\t#stagePath(path: string): string {\n\t\tconst staged = this.#resolve(this.#stage, path)\n\t\tmkdirSync(dirname(staged), { recursive: true })\n\t\treturn staged\n\t}\n\n\t// One path may be written, copied, or removed exactly once, and only while the\n\t// transaction is open.\n\t#claim(path: string): WriteExpectation {\n\t\tthis.#assertOpen()\n\t\tconst expectation = this.#expectation(path)\n\t\tif (this.#staged.includes(path) || this.#taken.includes(path)) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'INVALID',\n\t\t\t\t`The path ${path} is already claimed by this transaction.`,\n\t\t\t\t{\n\t\t\t\t\tpath,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn expectation\n\t}\n\n\t#expectation(path: string): WriteExpectation {\n\t\tconst expectation = this.#expectations.get(path)\n\t\tif (expectation === undefined) {\n\t\t\tthrow new ScaffoldError('INVALID', `The path ${path} is not one this transaction opened.`, {\n\t\t\t\tpath,\n\t\t\t})\n\t\t}\n\t\treturn expectation\n\t}\n\n\t#assertOpen(): void {\n\t\tif (!this.#open) {\n\t\t\tthrow new ScaffoldError('WRITE', 'This write transaction is closed.', {\n\t\t\t\ttarget: this.#target,\n\t\t\t})\n\t\t}\n\t}\n}\n","import type { Guard, Result } from '@orkestrel/contract'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tArtifact,\n\tAudit,\n\tCatalogEntry,\n\tDependency,\n\tDrift,\n\tFinding,\n\tHostArtifact,\n\tHydratedArtifact,\n\tMirror,\n\tPlan,\n\tScaffoldErrorCode,\n} from '@src/core'\nimport type {\n\tHostManifest,\n\tManifestEntry,\n\tMaterializeResult,\n\tMaterializerEventMap,\n\tMaterializerInterface,\n\tMaterializerOptions,\n\tRepository,\n\tWritePrecondition,\n} from './types.js'\nimport { dirname, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { attempt } from '@orkestrel/contract'\nimport { Emitter } from '@orkestrel/emitter'\nimport {\n\tCATALOG_AGENT_PATH,\n\tcloneValue,\n\tcomputeBytes,\n\tcontentToHex,\n\tinferGroup,\n\tisAudit,\n\tisPlan,\n\tMAX_ARTIFACT_BYTES,\n\tMAX_MANIFEST_BYTES,\n\tMAX_TOTAL_ARTIFACT_BYTES,\n\tplanToFindings,\n\tScaffoldError,\n} from '@src/core'\nimport {\n\tcomputeFileDigest,\n\tisPhysicalDirectory,\n\tisPhysicalFile,\n\tisVacant,\n\tlistFiles,\n\tmatchesProtectedPath,\n\treadFileHex,\n\treadFileText,\n\treadHostManifest,\n\treadSnapshot,\n\tresolveContainedPath,\n} from './helpers.js'\nimport {\n\tisCatalogEntries,\n\tisDependencies,\n\tisFilesystemPath,\n\tisMaterializerOptions,\n\tisMirrors,\n\tisRepository,\n} from './validators.js'\nimport { WriteTransaction } from './WriteTransaction.js'\n\n/**\n * The mutation spine: read the vendored host, re-derive the target, stage, swap.\n *\n * @remarks\n * Every verb runs the same three steps. It snapshots each caller-supplied value\n * and guards the snapshot, so a property backed by an accessor never reaches a\n * decision. It re-derives what it is about to touch and compares that against\n * the observation the caller handed in, refusing the whole call when anything\n * moved. Only then does it open a {@link WriteTransaction}, which stages every\n * byte in a private sibling directory and swaps them into place.\n *\n * The vendored host is read once, at construction, and cross-checked once. Its\n * manifest authenticates its own membership, which is all a checksum sitting\n * beside the data can do; matching that membership against the files actually\n * stored is this class's job. The comparison is exact text and therefore exact\n * case, so a manifest naming `agents.md` for a stored `AGENTS.md` is refused on\n * a case-insensitive filesystem rather than silently resolved.\n *\n * What a mutation guarantees is exactly what {@link WriteTransaction}\n * guarantees, and no more: a caught failure part way through a commit rolls the\n * whole commit back, no destination ever receives half-written bytes, and a\n * process killed mid-commit leaves a mixed target. This is not a journal and\n * does not claim to be one.\n *\n * Every error is emitted on `error` immediately before it is thrown, so an\n * observer sees a refusal even where the caller catches it.\n *\n * @example\n * ```ts\n * import type { Plan } from '@orkestrel/scaffold'\n * import { Materializer } from '@orkestrel/scaffold/server'\n *\n * declare const plan: Plan\n *\n * const materializer = new Materializer({ host: './dist/host' })\n * materializer.materialize(plan, './packages/router')\n * materializer.destroy()\n * ```\n */\nexport class Materializer implements MaterializerInterface {\n\t// The marker pair bounding the package table inside the catalog agent file.\n\t// It sits here rather than in `constants.ts` because that file is frozen; the\n\t// artifact that renders the file must read the same pair, so the pair belongs\n\t// in core as soon as both consumers exist.\n\tstatic readonly #opening = '<!-- orkestrel:catalog -->'\n\tstatic readonly #closing = '<!-- /orkestrel:catalog -->'\n\n\treadonly #emitter: Emitter<MaterializerEventMap>\n\treadonly #host: string\n\treadonly #manifest: HostManifest | undefined\n\treadonly #entries: ReadonlyMap<string, ManifestEntry>\n\t#destroyed = false\n\n\t/**\n\t * Construct a materializer over one vendored host root.\n\t *\n\t * @param options - The vendored host root, the initial listeners, and the\n\t * listener-error handler.\n\t * @throws {@link ScaffoldError} coded `INVALID` when `options` is present but\n\t * is not an option bag this materializer accepts, and `TARGET` when the host\n\t * carries a manifest that cannot be read or does not match what it stores.\n\t *\n\t * @remarks\n\t * `host` defaults to this package's own vendored root, resolved from this\n\t * module's own location so it never depends on the caller's working\n\t * directory. A host carrying no manifest is read as a raw checkout and every\n\t * artifact maps onto it one to one.\n\t *\n\t * The host is read here rather than on first use, so a broken vendored root\n\t * fails at construction where the caller can still act on it, and so nothing\n\t * has to carry a second flag recording whether the read has happened yet.\n\t */\n\tconstructor(options?: MaterializerOptions) {\n\t\tif (options !== undefined && !isMaterializerOptions(options)) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'INVALID',\n\t\t\t\t'The options argument is not the exact shape this materializer accepts.',\n\t\t\t\t{ field: 'options' },\n\t\t\t)\n\t\t}\n\t\tthis.#emitter = new Emitter<MaterializerEventMap>({\n\t\t\t...(options?.on === undefined ? {} : { on: options.on }),\n\t\t\t...(options?.error === undefined ? {} : { error: options.error }),\n\t\t})\n\t\tthis.#host = options?.host ?? resolve(dirname(fileURLToPath(import.meta.url)), '../../host')\n\t\tconst read = attempt(() => readHostManifest(this.#host))\n\t\tif (!read.success) {\n\t\t\tthrow this.#error('TARGET', 'The vendored host carries a manifest that cannot be read.', {\n\t\t\t\thost: this.#host,\n\t\t\t\terror: read.error,\n\t\t\t})\n\t\t}\n\t\tthis.#manifest = read.value\n\t\tthis.#entries = new Map<string, ManifestEntry>(\n\t\t\t(read.value?.entries ?? []).map((entry) => [entry.destination, entry]),\n\t\t)\n\t\tif (read.value !== undefined) this.#reconcile(read.value)\n\t}\n\n\t/** The materializer's observation channel. */\n\tget emitter(): EmitterInterface<MaterializerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\t/**\n\t * Compare a plan with a target through the vendored host that will repair it.\n\t *\n\t * @param plan - The compiled plan to compare.\n\t * @param target - The directory to inspect.\n\t * @returns One finding per hydrated planned path, plus foreign files beneath owned host roots.\n\t * @throws {@link ScaffoldError} coded `INVALID` when an argument is not the\n\t * exact shape, `TARGET` when the host or target cannot be read within its\n\t * bounds, and `DESTROYED` after teardown.\n\t *\n\t * @remarks\n\t * Host directories expand before the target is read, so this method and\n\t * {@link repair} compare the same paths with the same ownership. Foreign\n\t * candidates are files beneath those expanded roots only; a root file never\n\t * becomes a deletion candidate merely because its group is selected.\n\t */\n\taudit(plan: Plan, target: string): Audit {\n\t\tthis.#assertAlive()\n\t\tconst accepted = this.#accept(plan, isPlan, 'plan')\n\t\tconst directory = this.#accept(target, isFilesystemPath, 'target')\n\t\treturn this.#derive(accepted, directory)\n\t}\n\n\t/**\n\t * Write a plan into a vacant target.\n\t *\n\t * @param plan - The compiled plan to write.\n\t * @param target - The directory to write into; it must hold nothing the plan would collide with.\n\t * @returns The paths written and skipped.\n\t * @throws {@link ScaffoldError} coded `INVALID` when an argument is not the\n\t * exact shape, `TARGET` when the target is not vacant or the host does not\n\t * carry a planned artifact, `WRITE` when the write cannot be staged or\n\t * committed, and `DESTROYED` after teardown.\n\t *\n\t * @remarks\n\t * The plan's own bytes are not trusted: every host-origin artifact is re-read\n\t * from the vendored root, so what lands is what this package ships rather than\n\t * what a caller-built plan claimed it ships. A vendored directory expands into\n\t * one artifact per file beneath it, and a vendored directory holding no file\n\t * at all is created as an empty directory.\n\t */\n\tmaterialize(plan: Plan, target: string): MaterializeResult {\n\t\tthis.#assertAlive()\n\t\tconst accepted = this.#accept(plan, isPlan, 'plan')\n\t\tconst directory = this.#accept(target, isFilesystemPath, 'target')\n\t\tif (!isVacant(directory)) {\n\t\t\tthrow this.#error('TARGET', `The target at ${directory} is not vacant.`, {\n\t\t\t\ttarget: directory,\n\t\t\t})\n\t\t}\n\t\tconst empty = this.#empty(accepted)\n\t\tconst hydrated = this.#hydrate(accepted)\n\t\treturn this.#apply(directory, hydrated.artifacts, empty, [], [])\n\t}\n\n\t/**\n\t * Write a plan into an existing target, guided by an audit of it.\n\t *\n\t * @param plan - The compiled plan to write.\n\t * @param audit - The preview returned by this materializer's `audit` method.\n\t * @param target - The directory to write into.\n\t * @returns The paths written and skipped, each decided by its artifact's ownership.\n\t * @throws {@link ScaffoldError} coded `INVALID` when an argument is not the\n\t * exact shape, `TARGET` when the target moved since its audit, `WRITE` when\n\t * the write cannot be staged or committed, and `DESTROYED` after teardown.\n\t *\n\t * @remarks\n\t * The audit is a preview, not an instruction. The plan is hydrated and\n\t * compared against the target again here, and the verdicts that produces must\n\t * match the ones the audit carried for every path the plan owns; anything else\n\t * means the target moved, and the whole call is refused. A missing destination\n\t * is restored whatever its ownership; a stale one is replaced only where the\n\t * artifact claims its bytes, which is what leaves a presence-owned file a\n\t * consumer has edited exactly as it is.\n\t */\n\trepair(plan: Plan, audit: Audit, target: string): MaterializeResult {\n\t\tthis.#assertAlive()\n\t\tconst accepted = this.#accept(plan, isPlan, 'plan')\n\t\tconst preview = this.#accept(audit, isAudit, 'audit')\n\t\tconst directory = this.#accept(target, isFilesystemPath, 'target')\n\t\tconst hydrated = this.#hydrate(accepted)\n\t\tconst derived = this.#derive(accepted, directory, hydrated)\n\t\tthis.#reconfirm(derived.findings, preview.findings, directory)\n\t\tconst drifted = new Map<string, Drift>(\n\t\t\tderived.findings.map((finding) => [finding.path, finding.drift]),\n\t\t)\n\t\tconst writes: Artifact[] = []\n\t\tconst skipped: string[] = []\n\t\tconst preconditions: WritePrecondition[] = []\n\t\tfor (const artifact of hydrated.artifacts) {\n\t\t\tconst drift = drifted.get(artifact.path)\n\t\t\tif (drift !== 'missing' && drift !== 'stale') {\n\t\t\t\tskipped.push(artifact.path)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpreconditions.push(this.#bind(directory, artifact.path, drift === 'missing'))\n\t\t\twrites.push(artifact)\n\t\t}\n\t\treturn this.#apply(directory, writes, [], skipped, preconditions)\n\t}\n\n\t/**\n\t * Write fetched dependency guides to their local mirrors.\n\t *\n\t * @param mirrors - The fetched guides; each carries the local bytes its write is held to.\n\t * @param target - The directory to write into.\n\t * @returns The mirror paths written and skipped; a mirror already current is skipped.\n\t * @throws {@link ScaffoldError} coded `INVALID` when an argument is not the\n\t * exact shape, `TARGET` when a mirror moved since it was fetched, `WRITE` when\n\t * the write cannot be staged or committed, and `DESTROYED` after teardown.\n\t *\n\t * @remarks\n\t * A verdict carrying no bytes carries a cause instead, so it is skipped rather\n\t * than written: one unreachable package never costs the caller the rest of the\n\t * fetch, and it never empties a mirror it could not replace.\n\t */\n\tmirror(mirrors: readonly Mirror[], target: string): MaterializeResult {\n\t\tthis.#assertAlive()\n\t\tconst accepted = this.#accept(mirrors, isMirrors, 'mirrors')\n\t\tconst directory = this.#accept(target, isFilesystemPath, 'target')\n\t\tconst writes: Artifact[] = []\n\t\tconst skipped: string[] = []\n\t\tconst preconditions: WritePrecondition[] = []\n\t\tfor (const fetched of accepted) {\n\t\t\tif (fetched.lookup !== 'found' || fetched.observed === contentToHex(fetched.content)) {\n\t\t\t\tskipped.push(fetched.path)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst current = readFileHex(directory, fetched.path)\n\t\t\tif (current !== fetched.observed) {\n\t\t\t\tthrow this.#error('TARGET', `The mirror at ${fetched.path} moved since it was fetched.`, {\n\t\t\t\t\ttarget: directory,\n\t\t\t\t\tpath: fetched.path,\n\t\t\t\t})\n\t\t\t}\n\t\t\tpreconditions.push(this.#bind(directory, fetched.path, current === undefined))\n\t\t\twrites.push({\n\t\t\t\tpath: fetched.path,\n\t\t\t\tgroup: inferGroup(fetched.path),\n\t\t\t\townership: 'content',\n\t\t\t\torigin: 'computed',\n\t\t\t\tcontent: fetched.content,\n\t\t\t})\n\t\t}\n\t\treturn this.#apply(directory, writes, [], skipped, preconditions)\n\t}\n\n\t/**\n\t * Rewrite the marker-bounded package table in the target's catalog agent file.\n\t *\n\t * @param entries - The published packages the table should list.\n\t * @param target - The directory to write into.\n\t * @returns The catalog path, written when the region's bytes moved and skipped otherwise.\n\t * @throws {@link ScaffoldError} coded `INVALID` when an argument is not the\n\t * exact shape, `TARGET` when the file is unreadable or carries no marked\n\t * region, `WRITE` when the write cannot be staged or committed, and\n\t * `DESTROYED` after teardown.\n\t *\n\t * @remarks\n\t * Only the text between the two markers is replaced, so every word a consumer\n\t * wrote around the table survives the call. A row whose lookup produced no\n\t * version prints the cause it carries instead, because dropping the row would\n\t * hide a package the organization publishes behind one failed request.\n\t */\n\tcatalog(entries: readonly CatalogEntry[], target: string): MaterializeResult {\n\t\tthis.#assertAlive()\n\t\tconst accepted = this.#accept(entries, isCatalogEntries, 'entries')\n\t\tconst directory = this.#accept(target, isFilesystemPath, 'target')\n\t\treturn this.#rewrite(\n\t\t\tdirectory,\n\t\t\tCATALOG_AGENT_PATH,\n\t\t\tMAX_ARTIFACT_BYTES,\n\t\t\tthis.#recatalog(accepted),\n\t\t)\n\t}\n\n\t/**\n\t * Rewrite the `@orkestrel/*` range set in the target's manifest.\n\t *\n\t * @param dependencies - The names and ranges the manifest should declare.\n\t * @param target - The directory to write into.\n\t * @returns The manifest path, written when a declared range moved and skipped otherwise.\n\t * @throws {@link ScaffoldError} coded `INVALID` when an argument is not the\n\t * exact shape or names a package the manifest does not declare, `TARGET` when\n\t * the manifest is unreadable, `WRITE` when the write cannot be staged or\n\t * committed, and `DESTROYED` after teardown.\n\t *\n\t * @remarks\n\t * No other part of the manifest is read back out or rewritten, so a consumer's\n\t * own description, keywords, scripts, and formatting survive the call. Only a\n\t * range already declared is rewritten: inserting a package would mean\n\t * re-serializing the whole manifest, which is exactly the edit this verb\n\t * promises not to make, so an undeclared name is refused by name instead.\n\t */\n\tdeclare(dependencies: readonly Dependency[], target: string): MaterializeResult {\n\t\tthis.#assertAlive()\n\t\tconst accepted = this.#accept(dependencies, isDependencies, 'dependencies')\n\t\tconst directory = this.#accept(target, isFilesystemPath, 'target')\n\t\treturn this.#rewrite(directory, 'package.json', MAX_MANIFEST_BYTES, this.#redeclare(accepted))\n\t}\n\n\t/**\n\t * Delete the files the plan does not own.\n\t *\n\t * @param audit - The preview returned by this materializer's `audit` method; its foreign findings are the candidate set.\n\t * @param repository - The target's git state; only a tracked path is ever deleted.\n\t * @param target - The directory to delete from.\n\t * @returns The paths removed.\n\t * @throws {@link ScaffoldError} coded `INVALID` when an argument is not the\n\t * exact shape, `TARGET` when the tree carries uncommitted changes or a\n\t * candidate moved since its audit, `WRITE` when the deletion cannot be staged\n\t * or committed, and `DESTROYED` after teardown.\n\t *\n\t * @remarks\n\t * The candidate set is re-derived and compared against the audit before\n\t * anything moves, and every file is quarantined and re-verified rather than\n\t * unlinked, so a failure part way through restores what it already took. The\n\t * package's own source and application trees are never candidates, whatever\n\t * the audit reports, and neither is anything git does not track: git is the\n\t * recovery mechanism, so a path it cannot restore is not one this verb takes.\n\t * A tree carrying uncommitted work is refused whole for the same reason.\n\t */\n\tremove(audit: Audit, repository: Repository, target: string): MaterializeResult {\n\t\tthis.#assertAlive()\n\t\tconst preview = this.#accept(audit, isAudit, 'audit')\n\t\tconst state = this.#accept(repository, isRepository, 'repository')\n\t\tconst directory = this.#accept(target, isFilesystemPath, 'target')\n\t\tif (state.dirty.length > 0) {\n\t\t\tthrow this.#error('TARGET', `The target at ${directory} carries uncommitted changes.`, {\n\t\t\t\ttarget: directory,\n\t\t\t\tdirty: state.dirty.length,\n\t\t\t})\n\t\t}\n\t\tconst tracked = new Set(state.tracked)\n\t\tconst observed = new Map<string, string | undefined>()\n\t\tconst removals: string[] = []\n\t\tconst skipped: string[] = []\n\t\tfor (const finding of preview.findings) {\n\t\t\tif (finding.drift !== 'foreign') continue\n\t\t\tif (!tracked.has(finding.path) || matchesProtectedPath(finding.path)) {\n\t\t\t\tskipped.push(finding.path)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tobserved.set(finding.path, finding.observed)\n\t\t\tremovals.push(finding.path)\n\t\t}\n\t\tconst current = readSnapshot(directory, removals)\n\t\tconst preconditions: WritePrecondition[] = []\n\t\tfor (const path of removals) {\n\t\t\tif (current[path] !== observed.get(path)) {\n\t\t\t\tthrow this.#error('TARGET', `The path ${path} moved since its audit.`, {\n\t\t\t\t\ttarget: directory,\n\t\t\t\t\tpath,\n\t\t\t\t})\n\t\t\t}\n\t\t\tpreconditions.push(this.#bind(directory, path, false))\n\t\t}\n\t\treturn this.#purge(directory, removals, skipped, preconditions)\n\t}\n\n\t/**\n\t * Tear the materializer down. Every later call throws, and teardown is idempotent.\n\t *\n\t * @returns Nothing.\n\t *\n\t * @example\n\t * ```ts\n\t * import { Materializer } from '@orkestrel/scaffold/server'\n\t *\n\t * const materializer = new Materializer()\n\t * materializer.destroy()\n\t * materializer.emitter.destroyed // true\n\t * ```\n\t */\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// The claim a manifest cannot make about itself: that what it declares is what\n\t// the host actually stores, one to one and spelled the same way. Compared as\n\t// exact text against a real directory walk, so a case-folded name on a\n\t// case-insensitive filesystem is a refusal rather than a silent resolution.\n\t#reconcile(manifest: HostManifest): void {\n\t\tconst walked = attempt(() => listFiles(this.#host))\n\t\tif (!walked.success) {\n\t\t\tthrow this.#error('TARGET', 'The vendored host cannot be inventoried.', {\n\t\t\t\thost: this.#host,\n\t\t\t\terror: walked.error,\n\t\t\t})\n\t\t}\n\t\tconst declared = [...manifest.entries.map((entry) => entry.storage), 'manifest.json'].sort()\n\t\tconst stored = walked.value\n\t\tif (\n\t\t\tstored.length !== declared.length ||\n\t\t\tstored.some((name, index) => name !== declared[index])\n\t\t) {\n\t\t\tthrow this.#error('TARGET', 'The vendored host does not store what its manifest declares.', {\n\t\t\t\thost: this.#host,\n\t\t\t\tstored: stored.length,\n\t\t\t\tdeclared: declared.length,\n\t\t\t})\n\t\t}\n\t\tif (this.#entries.size !== manifest.entries.length) {\n\t\t\tthrow this.#error('TARGET', 'The vendored host manifest maps two files to one destination.', {\n\t\t\t\thost: this.#host,\n\t\t\t})\n\t\t}\n\t}\n\n\t// Replace every host-origin artifact with what the vendored root actually\n\t// holds. A directory becomes one artifact per file beneath it; the destinations\n\t// another verb owns the bytes of stay presence-owned, because a byte claim this\n\t// verb cannot keep is one the audit beside it would immediately fail.\n\t#hydrate(plan: Plan): Plan {\n\t\tconst artifacts: Artifact[] = []\n\t\tlet remaining = MAX_TOTAL_ARTIFACT_BYTES\n\t\tfor (const artifact of plan.artifacts) {\n\t\t\tif (artifact.origin !== 'host') {\n\t\t\t\tremaining -= computeBytes(artifact.content)\n\t\t\t\tartifacts.push(artifact)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst expanded = this.#expand(artifact, remaining)\n\t\t\tfor (const one of expanded) remaining -= (one.hex?.length ?? 0) / 2\n\t\t\tartifacts.push(...expanded)\n\t\t}\n\t\tif (remaining < 0) {\n\t\t\tthrow this.#error('TARGET', 'The hydrated plan retains more bytes than one plan may.', {\n\t\t\t\thost: this.#host,\n\t\t\t\tlimit: MAX_TOTAL_ARTIFACT_BYTES,\n\t\t\t})\n\t\t}\n\t\treturn { blueprint: plan.blueprint, groups: plan.groups, artifacts }\n\t}\n\n\t// Hydrate once, extend the target snapshot only beneath vendored directories\n\t// this plan expands, then run the core comparison over that one population.\n\t// Repair may supply the hydrated plan it already needs for writes, while the\n\t// public audit lets this method own the hydration itself.\n\t#derive(plan: Plan, target: string, hydrated = this.#hydrate(plan)): Audit {\n\t\tconst paths = new Set(hydrated.artifacts.map((artifact) => artifact.path))\n\t\tfor (const root of this.#roots(plan)) {\n\t\t\tconst directory = resolveContainedPath(target, root)\n\t\t\tif (directory === undefined) {\n\t\t\t\tthrow this.#error('TARGET', `The owned root at ${root} leaves its target.`, {\n\t\t\t\t\ttarget,\n\t\t\t\t\tpath: root,\n\t\t\t\t})\n\t\t\t}\n\t\t\tfor (const name of listFiles(directory)) paths.add(`${root}/${name}`)\n\t\t}\n\t\treturn {\n\t\t\tfindings: planToFindings(hydrated, readSnapshot(target, [...paths])),\n\t\t\tquestions: [],\n\t\t}\n\t}\n\n\t// The target roots scaffold owns completely are exactly the host directories\n\t// this plan expands. A manifest states the directory shape; a raw host is\n\t// inspected directly. Files and host roots outside the plan never enter the set.\n\t#roots(plan: Plan): readonly string[] {\n\t\tconst roots = new Set<string>()\n\t\tfor (const artifact of plan.artifacts) {\n\t\t\tif (artifact.origin !== 'host') continue\n\t\t\tconst source = artifact.source ?? artifact.path\n\t\t\tif (this.#manifest?.roots.includes(source) === true) {\n\t\t\t\troots.add(artifact.path)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (this.#manifest !== undefined) continue\n\t\t\tconst directory = resolveContainedPath(this.#host, source)\n\t\t\tif (directory !== undefined && isPhysicalDirectory(directory)) roots.add(artifact.path)\n\t\t}\n\t\treturn [...roots]\n\t}\n\n\t// One host artifact against the vendored root, through the manifest when the\n\t// root carries one and one to one when it does not.\n\t#expand(artifact: HostArtifact | HydratedArtifact, remaining: number): readonly Artifact[] {\n\t\tconst manifest = this.#manifest\n\t\tconst source = artifact.source ?? artifact.path\n\t\tif (manifest === undefined) return this.#expandRaw(artifact, source, remaining)\n\t\tconst matched = manifest.entries.filter(\n\t\t\t(entry) => entry.destination === source || entry.destination.startsWith(`${source}/`),\n\t\t)\n\t\tconst rooted = manifest.roots.some((root) => root === source || root.startsWith(`${source}/`))\n\t\tif (matched.length === 0 && !rooted) {\n\t\t\tthrow this.#error('TARGET', `The vendored host does not carry ${source}.`, {\n\t\t\t\thost: this.#host,\n\t\t\t\tsource,\n\t\t\t})\n\t\t}\n\t\tconst expanded: Artifact[] = []\n\t\tlet budget = remaining\n\t\tfor (const entry of matched) {\n\t\t\tconst path = this.#remap(artifact, entry.destination)\n\t\t\tif (this.#deferred(path)) {\n\t\t\t\texpanded.push(this.#presence(artifact, path, entry.destination))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst hex = this.#read(entry.storage, budget)\n\t\t\tbudget -= hex.length / 2\n\t\t\texpanded.push(this.#hydrated(artifact, path, entry.destination, hex))\n\t\t}\n\t\treturn expanded\n\t}\n\n\t// A host root with no manifest is a plain checkout, so a destination maps onto\n\t// it under the name it is written to and a directory is walked directly.\n\t#expandRaw(\n\t\tartifact: HostArtifact | HydratedArtifact,\n\t\tsource: string,\n\t\tremaining: number,\n\t): readonly Artifact[] {\n\t\tconst full = resolveContainedPath(this.#host, source)\n\t\tif (full === undefined) {\n\t\t\tthrow this.#error('TARGET', `The host source at ${source} leaves its root.`, {\n\t\t\t\thost: this.#host,\n\t\t\t\tsource,\n\t\t\t})\n\t\t}\n\t\tif (isPhysicalFile(full)) {\n\t\t\treturn [\n\t\t\t\tthis.#deferred(artifact.path)\n\t\t\t\t\t? this.#presence(artifact, artifact.path, source)\n\t\t\t\t\t: this.#hydrated(artifact, artifact.path, source, this.#read(source, remaining)),\n\t\t\t]\n\t\t}\n\t\tif (!isPhysicalDirectory(full)) {\n\t\t\tthrow this.#error('TARGET', `The host source at ${source} is not a readable file.`, {\n\t\t\t\thost: this.#host,\n\t\t\t\tsource,\n\t\t\t})\n\t\t}\n\t\tconst expanded: Artifact[] = []\n\t\tlet budget = remaining\n\t\tfor (const name of listFiles(full)) {\n\t\t\tconst path = `${artifact.path}/${name}`\n\t\t\tconst destination = `${source}/${name}`\n\t\t\tif (this.#deferred(path)) {\n\t\t\t\texpanded.push(this.#presence(artifact, path, destination))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst hex = this.#read(destination, budget)\n\t\t\tbudget -= hex.length / 2\n\t\t\texpanded.push(this.#hydrated(artifact, path, destination, hex))\n\t\t}\n\t\treturn expanded\n\t}\n\n\t// The vendored directories holding no file at all. They are the one thing a\n\t// file inventory cannot report, which is why the manifest declares them, and a\n\t// plan covering their parent covers them.\n\t#empty(plan: Plan): readonly string[] {\n\t\tconst manifest = this.#manifest\n\t\tif (manifest === undefined) return []\n\t\tconst directories = new Set<string>()\n\t\tfor (const artifact of plan.artifacts) {\n\t\t\tif (artifact.origin !== 'host') continue\n\t\t\tconst source = artifact.source ?? artifact.path\n\t\t\tfor (const root of manifest.roots) {\n\t\t\t\tif (root !== source && !root.startsWith(`${source}/`)) continue\n\t\t\t\tconst filled = manifest.entries.some(\n\t\t\t\t\t(entry) => entry.destination === root || entry.destination.startsWith(`${root}/`),\n\t\t\t\t)\n\t\t\t\tif (!filled) directories.add(this.#remap(artifact, root))\n\t\t\t}\n\t\t}\n\t\treturn [...directories].sort()\n\t}\n\n\t// Move one manifest destination from the artifact's source prefix onto its\n\t// target prefix, so a vendored directory expands under the path the plan wrote\n\t// rather than under the name the host stores it as.\n\t#remap(artifact: HostArtifact | HydratedArtifact, destination: string): string {\n\t\tconst source = artifact.source ?? artifact.path\n\t\tif (destination === source) return artifact.path\n\t\tif (!destination.startsWith(`${source}/`)) {\n\t\t\tthrow this.#error('TARGET', `The vendored destination ${destination} is outside ${source}.`, {\n\t\t\t\thost: this.#host,\n\t\t\t\tsource,\n\t\t\t\tdestination,\n\t\t\t})\n\t\t}\n\t\treturn `${artifact.path}/${destination.slice(source.length + 1)}`\n\t}\n\n\t// The destinations whose bytes belong to another verb: the catalog agent file,\n\t// whose marked region `catalog` owns, and every guide mirror, which `mirror`\n\t// refetches. Hydrating them would claim a byte comparison the verb that owns\n\t// them is about to break.\n\t#deferred(path: string): boolean {\n\t\treturn path === CATALOG_AGENT_PATH || (path.startsWith('guides/') && path.endsWith('.md'))\n\t}\n\n\t#presence(\n\t\tartifact: HostArtifact | HydratedArtifact,\n\t\tpath: string,\n\t\tdestination: string,\n\t): HostArtifact {\n\t\treturn {\n\t\t\tpath,\n\t\t\tgroup: artifact.group,\n\t\t\townership: 'presence',\n\t\t\torigin: 'host',\n\t\t\tsource: destination,\n\t\t\t...(artifact.environment === undefined ? {} : { environment: artifact.environment }),\n\t\t}\n\t}\n\n\t#hydrated(\n\t\tartifact: HostArtifact | HydratedArtifact,\n\t\tpath: string,\n\t\tdestination: string,\n\t\thex: string,\n\t): HydratedArtifact {\n\t\treturn {\n\t\t\tpath,\n\t\t\tgroup: artifact.group,\n\t\t\townership: 'content',\n\t\t\torigin: 'host',\n\t\t\tsource: destination,\n\t\t\t...(artifact.environment === undefined ? {} : { environment: artifact.environment }),\n\t\t\thex,\n\t\t}\n\t}\n\n\t#read(storage: string, budget: number): string {\n\t\tconst hex = readFileHex(this.#host, storage, Math.max(0, Math.min(MAX_ARTIFACT_BYTES, budget)))\n\t\tif (hex === undefined) {\n\t\t\tthrow this.#error('TARGET', `The vendored host cannot be read at ${storage}.`, {\n\t\t\t\thost: this.#host,\n\t\t\t\tstorage,\n\t\t\t})\n\t\t}\n\t\treturn hex\n\t}\n\n\t// The audit is a preview of the same comparison this call just made, so the two\n\t// must agree on every path the plan owns. A wider audit may also carry foreign\n\t// paths, which belong to the deletion verb and say nothing here.\n\t#reconfirm(derived: readonly Finding[], preview: readonly Finding[], target: string): void {\n\t\tconst previewed = new Map<string, Finding>(preview.map((finding) => [finding.path, finding]))\n\t\tfor (const finding of derived) {\n\t\t\tif (finding.drift === 'foreign') continue\n\t\t\tconst other = previewed.get(finding.path)\n\t\t\tif (other === undefined) {\n\t\t\t\tthrow this.#error('TARGET', `The path ${finding.path} is not covered by its audit.`, {\n\t\t\t\t\ttarget,\n\t\t\t\t\tpath: finding.path,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (other.drift === finding.drift && other.observed === finding.observed) continue\n\t\t\tthrow this.#error('TARGET', `The path ${finding.path} moved since its audit.`, {\n\t\t\t\ttarget,\n\t\t\t\tpath: finding.path,\n\t\t\t})\n\t\t}\n\t}\n\n\t// Bind one destination to what this call just observed at it. The digest is\n\t// taken now rather than derived from the observation, because a digest over\n\t// bytes nobody re-read would only restate what the comparison already proved.\n\t#bind(target: string, path: string, absent: boolean): WritePrecondition {\n\t\tconst destination = resolveContainedPath(target, path)\n\t\tif (destination === undefined) {\n\t\t\tthrow this.#error('INVALID', `The path ${path} is off contract or leaves its target.`, {\n\t\t\t\ttarget,\n\t\t\t\tpath,\n\t\t\t})\n\t\t}\n\t\tif (absent) return { path: destination, shape: 'absent' }\n\t\tconst digest = computeFileDigest(destination)\n\t\tif (digest === undefined) {\n\t\t\tthrow this.#error('TARGET', `The path ${path} moved while it was being bound.`, {\n\t\t\t\ttarget,\n\t\t\t\tpath,\n\t\t\t})\n\t\t}\n\t\treturn { path: destination, shape: 'file', digest }\n\t}\n\n\t// Read one whole text file, hand it to the rewrite that owns it, and write it\n\t// back only when its bytes actually moved.\n\t#rewrite(\n\t\ttarget: string,\n\t\tpath: string,\n\t\tlimit: number,\n\t\trewrite: (text: string) => string,\n\t): MaterializeResult {\n\t\tconst text = readFileText(target, path, limit)\n\t\tif (text === undefined) {\n\t\t\tthrow this.#error('TARGET', `The file at ${path} is not readable text.`, { target, path })\n\t\t}\n\t\tconst content = rewrite(text)\n\t\tif (content === text) {\n\t\t\treturn this.#finish({ target, written: [], skipped: [path], removed: [] })\n\t\t}\n\t\treturn this.#apply(\n\t\t\ttarget,\n\t\t\t[{ path, group: inferGroup(path), ownership: 'content', origin: 'computed', content }],\n\t\t\t[],\n\t\t\t[],\n\t\t\t[this.#bind(target, path, false)],\n\t\t)\n\t}\n\n\t// Stage every write in one transaction and swap them in together, so a target\n\t// either receives the whole set or is left as it was found.\n\t#apply(\n\t\ttarget: string,\n\t\twrites: readonly Artifact[],\n\t\tdirectories: readonly string[],\n\t\tskipped: readonly string[],\n\t\tpreconditions: readonly WritePrecondition[],\n\t): MaterializeResult {\n\t\tconst paths = [...writes.map((artifact) => artifact.path), ...directories]\n\t\tif (paths.length === 0) return this.#finish({ target, written: [], skipped, removed: [] })\n\t\tconst transaction = this.#open(target, paths, preconditions)\n\t\tconst staged = attempt(() => {\n\t\t\tfor (const artifact of writes) {\n\t\t\t\tif (artifact.origin === 'host') this.#copy(transaction, artifact)\n\t\t\t\telse transaction.write(artifact.path, artifact.content)\n\t\t\t}\n\t\t\tfor (const path of directories) transaction.directory(path)\n\t\t})\n\t\tconst written = this.#close(transaction, staged, target)\n\t\tfor (const path of written) this.#emitter.emit('write', path)\n\t\treturn this.#finish({ target, written, skipped, removed: [] })\n\t}\n\n\t// Quarantine every candidate in one transaction. A deletion that fails part way\n\t// through puts back what it already took.\n\t#purge(\n\t\ttarget: string,\n\t\tremovals: readonly string[],\n\t\tskipped: readonly string[],\n\t\tpreconditions: readonly WritePrecondition[],\n\t): MaterializeResult {\n\t\tif (removals.length === 0) return this.#finish({ target, written: [], skipped, removed: [] })\n\t\tconst transaction = this.#open(target, removals, preconditions)\n\t\tconst staged = attempt(() => {\n\t\t\tfor (const path of removals) transaction.remove(path)\n\t\t})\n\t\tconst removed = this.#close(transaction, staged, target)\n\t\tfor (const path of removed) this.#emitter.emit('remove', path)\n\t\treturn this.#finish({ target, written: [], skipped, removed })\n\t}\n\n\t#open(\n\t\ttarget: string,\n\t\tpaths: readonly string[],\n\t\tpreconditions: readonly WritePrecondition[],\n\t): WriteTransaction {\n\t\tconst opened = attempt(() => new WriteTransaction(target, paths, preconditions))\n\t\tif (opened.success) return opened.value\n\t\tthis.#emitter.emit('error', opened.error)\n\t\tthrow opened.error\n\t}\n\n\t// Commit a staged transaction, or discard it and republish whichever failure\n\t// the caller has to act on. The transaction's own coded reason survives, so a\n\t// destination that moved is still told apart from a write that could not land.\n\t#close(transaction: WriteTransaction, staged: Result<void>, target: string): readonly string[] {\n\t\tif (!staged.success) {\n\t\t\tconst cleared = attempt(() => transaction.discard())\n\t\t\tif (!cleared.success) {\n\t\t\t\tthrow this.#error('WRITE', `The write into ${target} could not be staged or cleared.`, {\n\t\t\t\t\ttarget,\n\t\t\t\t\terror: staged.error,\n\t\t\t\t\tcleanup: cleared.error,\n\t\t\t\t})\n\t\t\t}\n\t\t\tthis.#emitter.emit('error', staged.error)\n\t\t\tthrow staged.error\n\t\t}\n\t\tconst committed = attempt(() => transaction.commit())\n\t\tif (committed.success) return committed.value\n\t\tthis.#emitter.emit('error', committed.error)\n\t\tthrow committed.error\n\t}\n\n\t// Stage one vendored file, under the storage name the manifest holds it as and\n\t// with the executable bit that manifest records.\n\t#copy(transaction: WriteTransaction, artifact: HostArtifact | HydratedArtifact): void {\n\t\tconst destination = artifact.source ?? artifact.path\n\t\tconst entry = this.#entries.get(destination)\n\t\tconst storage = entry === undefined ? destination : entry.storage\n\t\tconst source = resolveContainedPath(this.#host, storage)\n\t\tif (source === undefined) {\n\t\t\tthrow this.#error('TARGET', `The vendored source at ${storage} leaves its root.`, {\n\t\t\t\thost: this.#host,\n\t\t\t\tstorage,\n\t\t\t})\n\t\t}\n\t\ttransaction.copy(artifact.path, source, entry?.executable === true)\n\t}\n\n\t// The catalog table, rendered between the markers that bound it.\n\t#recatalog(entries: readonly CatalogEntry[]): (text: string) => string {\n\t\tconst rows = entries.map(\n\t\t\t(entry) =>\n\t\t\t\t`| \\`${entry.name}\\` | ${entry.lookup === 'found' ? `\\`${entry.version}\\`` : this.#cell(entry.note)} |`,\n\t\t)\n\t\tconst table = ['| Package | Version |', '| --- | --- |', ...rows].join('\\n')\n\t\treturn (text: string) => {\n\t\t\tconst opening = text.indexOf(Materializer.#opening)\n\t\t\tconst closing = text.indexOf(Materializer.#closing, opening + Materializer.#opening.length)\n\t\t\tif (opening < 0 || closing < 0) {\n\t\t\t\tthrow this.#error('TARGET', 'The catalog agent file carries no marked region.', {\n\t\t\t\t\tpath: CATALOG_AGENT_PATH,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn `${text.slice(0, opening + Materializer.#opening.length)}\\n${table}\\n${text.slice(closing)}`\n\t\t}\n\t}\n\n\t// One note, flattened into something a table row can hold.\n\t#cell(note: string): string {\n\t\treturn note.replaceAll('|', '\\\\|').replaceAll(/\\s+/gu, ' ').trim()\n\t}\n\n\t// Every declared range replaced in place. The manifest's text is edited rather\n\t// than re-serialized, so nothing but the ranges moves.\n\t#redeclare(dependencies: readonly Dependency[]): (text: string) => string {\n\t\treturn (text: string) => {\n\t\t\tlet manifest = text\n\t\t\tfor (const dependency of dependencies) {\n\t\t\t\tconst key = JSON.stringify(dependency.name)\n\t\t\t\tconst range = JSON.stringify(dependency.range)\n\t\t\t\tlet index = manifest.indexOf(key)\n\t\t\t\tlet declared = false\n\t\t\t\twhile (index >= 0) {\n\t\t\t\t\tconst span = this.#span(manifest, index + key.length)\n\t\t\t\t\tif (span === undefined) {\n\t\t\t\t\t\tindex = manifest.indexOf(key, index + key.length)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tmanifest = manifest.slice(0, span[0]) + range + manifest.slice(span[1])\n\t\t\t\t\tdeclared = true\n\t\t\t\t\tindex = manifest.indexOf(key, span[0] + range.length)\n\t\t\t\t}\n\t\t\t\tif (!declared) {\n\t\t\t\t\tthrow this.#error(\n\t\t\t\t\t\t'INVALID',\n\t\t\t\t\t\t`The manifest does not declare ${dependency.name}, so its range cannot be rewritten.`,\n\t\t\t\t\t\t{ name: dependency.name },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn manifest\n\t\t}\n\t}\n\n\t// The quoted value a key introduces, as the half-open span it occupies, or\n\t// nothing when the text is a value rather than a key.\n\t#span(text: string, from: number): readonly [number, number] | undefined {\n\t\tlet index = from\n\t\twhile (index < text.length && /\\s/u.test(text.charAt(index))) index += 1\n\t\tif (text.charAt(index) !== ':') return undefined\n\t\tindex += 1\n\t\twhile (index < text.length && /\\s/u.test(text.charAt(index))) index += 1\n\t\tif (text.charAt(index) !== '\"') return undefined\n\t\tconst start = index\n\t\tindex += 1\n\t\twhile (index < text.length) {\n\t\t\tif (text.charAt(index) === '\\\\') {\n\t\t\t\tindex += 2\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (text.charAt(index) === '\"') return [start, index + 1]\n\t\t\tindex += 1\n\t\t}\n\t\treturn undefined\n\t}\n\n\t// Publish the outcome on the observation channel, then hand it back.\n\t#finish(result: MaterializeResult): MaterializeResult {\n\t\tthis.#emitter.emit('finish', result)\n\t\treturn result\n\t}\n\n\t// Snapshot the caller's value, then guard the snapshot. The snapshot is what\n\t// closes the guard/use race: a property backed by an accessor never reaches the\n\t// guard, so what the guard measured is what every later read returns.\n\t#accept<T>(value: unknown, guard: Guard<T>, field: string): T {\n\t\tconst snapshot = cloneValue(value)\n\t\tif (guard(snapshot)) return snapshot\n\t\tthrow this.#error(\n\t\t\t'INVALID',\n\t\t\t`The ${field} argument is not the exact shape this materializer accepts.`,\n\t\t\t{ field },\n\t\t)\n\t}\n\n\t#assertAlive(): void {\n\t\tif (this.#destroyed) throw this.#error('DESTROYED', 'This materializer has been destroyed.')\n\t}\n\n\t// Publish the failure on the observation channel, then hand it back to be\n\t// thrown at the site that decided it.\n\t#error(code: ScaffoldErrorCode, message: string, context?: unknown): ScaffoldError {\n\t\tconst error = new ScaffoldError(code, message, context)\n\t\tthis.#emitter.emit('error', error)\n\t\treturn error\n\t}\n}\n","import type { Guard } from '@orkestrel/contract'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tCatalogEntry,\n\tDependency,\n\tLookup,\n\tMirror,\n\tRelease,\n\tScaffoldErrorCode,\n\tSnapshot,\n} from '@src/core'\nimport type { UpstreamEventMap, UpstreamInterface, UpstreamOptions } from './types.js'\nimport { isError, isRecord, isString, parseJSON, parseStringField } from '@orkestrel/contract'\nimport { Emitter } from '@orkestrel/emitter'\nimport {\n\tcloneValue,\n\tCONTROL_CHARACTER_PATTERN,\n\tisCollection,\n\tisDependencyName,\n\tisSnapshot,\n\tMAX_ARTIFACT_BYTES,\n\tMAX_RANGE_LENGTH,\n\tnameToGuide,\n\tScaffoldError,\n} from '@src/core'\nimport { isDependencies, isDependencyNames, isUpstreamOptions } from './validators.js'\n\n/**\n * The reading spine: one bounded, unauthenticated, redirect-free request per answer.\n *\n * @remarks\n * This is the package's only network reader, and it never writes. Every call\n * opens one byte allowance and spends it across every read the call makes, so a\n * caller is bounded twice over: `limit` refuses one oversized answer and\n * `budget` refuses many small ones. The two are separate exhaustion routes and\n * neither bound covers the other.\n *\n * A per-package failure never escapes as a throw. It is projected into the\n * verdict that package's row already carries — `missing` for an upstream `404`,\n * which is a definite answer, and `failed` for a transport fault, which is no\n * answer at all — so one unreachable package never costs the caller the rest of\n * the answer. The organization package list is the one exception: without it\n * there is no fleet to report, so an unreachable or malformed list is a coded\n * `FETCH` failure.\n *\n * Requests are unauthenticated because every fleet repository is public, and\n * they follow no redirect, so a misconfigured or hostile endpoint cannot move a\n * read to another host. Each one is bounded by its endpoint's timeout and by the\n * reader's own abort signal, so {@link Upstream.destroy} cancels what is in\n * flight instead of waiting for it.\n *\n * The allowance is threaded through the private reads as a mutable\n * `{ remaining: number }` carrier rather than held on the instance, because\n * concurrent calls each own their own budget and must not spend each other's.\n *\n * @example\n * ```ts\n * import { Upstream } from '@orkestrel/scaffold/server'\n *\n * const upstream = new Upstream({ registry: { timeout: 5_000 } })\n * const releases = await upstream.lookup([{ name: '@orkestrel/emitter', range: '^0.0.5' }])\n * upstream.destroy()\n * ```\n */\nexport class Upstream implements UpstreamInterface {\n\t// The defaults a request is built with, and the two fixed strings the fleet's\n\t// own addresses are assembled from. They sit here rather than in\n\t// `constants.ts` because that file is frozen, and each is read by exactly one\n\t// line of this class: a default is the entity's law applied when it builds a\n\t// request, so it belongs beside the law rather than in shared data.\n\tstatic readonly #defaultGuide = 'https://raw.githubusercontent.com'\n\tstatic readonly #defaultRegistry = 'https://registry.npmjs.org'\n\tstatic readonly #defaultBranch = 'main'\n\tstatic readonly #defaultTimeout = 10_000\n\tstatic readonly #defaultConcurrency = 6\n\tstatic readonly #defaultRetries = 0\n\tstatic readonly #defaultBudget = 16_777_216\n\tstatic readonly #scope = 'orkestrel'\n\tstatic readonly #unreadable = 'the answer carries no readable latest version'\n\n\treadonly #emitter: Emitter<UpstreamEventMap>\n\treadonly #guideBase: string\n\treadonly #guideBranch: string\n\treadonly #guideTimeout: number\n\treadonly #registryBase: string\n\treadonly #registryTimeout: number\n\treadonly #concurrency: number\n\treadonly #retries: number\n\treadonly #limit: number\n\treadonly #budget: number\n\treadonly #controller = new AbortController()\n\t#destroyed = false\n\n\t/**\n\t * Construct a reader over one guide host and one registry.\n\t *\n\t * @param options - The two endpoints, the request bounds, the initial\n\t * listeners, and the listener-error handler.\n\t * @throws {@link ScaffoldError} coded `INVALID` when `options` is present but\n\t * is not an option bag this reader accepts, or when either endpoint names a\n\t * scheme, host, or form this reader will not request.\n\t *\n\t * @remarks\n\t * `isEndpoint` bounds an endpoint's length and nothing else, so the scheme and\n\t * host law is settled here, where a refusal can say which endpoint was refused\n\t * and why. An endpoint must be HTTPS, or HTTP to a loopback host — the one\n\t * place an unencrypted request has no network between the two ends. That\n\t * refuses `file:`, `data:`, and plain HTTP to a real host, and it is what\n\t * keeps a fixture reachable without weakening transport security anywhere a\n\t * real request goes. An endpoint carrying credentials, a query, or a fragment\n\t * is refused too: this reader authenticates nothing and appends its own path.\n\t */\n\tconstructor(options?: UpstreamOptions) {\n\t\tif (options !== undefined && !isUpstreamOptions(options)) {\n\t\t\tthrow new ScaffoldError(\n\t\t\t\t'INVALID',\n\t\t\t\t'The options argument is not the exact shape this upstream reader accepts.',\n\t\t\t\t{ field: 'options' },\n\t\t\t)\n\t\t}\n\t\tthis.#emitter = new Emitter<UpstreamEventMap>({\n\t\t\t...(options?.on === undefined ? {} : { on: options.on }),\n\t\t\t...(options?.error === undefined ? {} : { error: options.error }),\n\t\t})\n\t\tthis.#guideBase = this.#endpoint(options?.guides?.base ?? Upstream.#defaultGuide, 'guides')\n\t\tthis.#guideBranch = options?.guides?.branch ?? Upstream.#defaultBranch\n\t\tthis.#guideTimeout = options?.guides?.timeout ?? Upstream.#defaultTimeout\n\t\tthis.#registryBase = this.#endpoint(\n\t\t\toptions?.registry?.base ?? Upstream.#defaultRegistry,\n\t\t\t'registry',\n\t\t)\n\t\tthis.#registryTimeout = options?.registry?.timeout ?? Upstream.#defaultTimeout\n\t\tthis.#concurrency = options?.concurrency ?? Upstream.#defaultConcurrency\n\t\tthis.#retries = options?.retries ?? Upstream.#defaultRetries\n\t\tthis.#limit = options?.limit ?? MAX_ARTIFACT_BYTES\n\t\tthis.#budget = options?.budget ?? Upstream.#defaultBudget\n\t}\n\n\t/** The upstream reader's observation channel. */\n\tget emitter(): EmitterInterface<UpstreamEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\t/**\n\t * Look up the registry's latest release for each declared dependency.\n\t *\n\t * @param dependencies - The declared dependencies to look up.\n\t * @returns One release verdict per dependency, in input order.\n\t * @throws {@link ScaffoldError} coded `INVALID` when `dependencies` is not a\n\t * bounded list of declared dependencies, and `DESTROYED` when the reader is\n\t * torn down before or during the call.\n\t *\n\t * @remarks\n\t * Whether the declared range already admits the reported version is not\n\t * decided here and is not stored on the verdict: it is a function of the\n\t * `range` and `latest` sitting beside each other, and one centralized helper\n\t * answers it for every caller.\n\t *\n\t * @example\n\t * ```ts\n\t * import { Upstream } from '@orkestrel/scaffold/server'\n\t *\n\t * const upstream = new Upstream()\n\t * await upstream.lookup([{ name: '@orkestrel/router', range: '^0.0.8' }])\n\t * upstream.destroy()\n\t * ```\n\t */\n\tasync lookup(dependencies: readonly Dependency[]): Promise<readonly Release[]> {\n\t\tthis.#assertAlive()\n\t\tconst accepted = this.#accept(dependencies, isDependencies, 'dependencies')\n\t\tconst allowance = { remaining: this.#budget }\n\t\treturn this.#gather(accepted, (dependency) => this.#release(dependency, allowance))\n\t}\n\n\t/**\n\t * Fetch each named package's guide, beside the local mirror it answers for.\n\t *\n\t * @param names - The packages to fetch: the target's declared set, or the whole organization.\n\t * @param current - The target's local mirrors as exact bytes, keyed by mirror path.\n\t * @returns One mirror verdict per name, in input order.\n\t * @throws {@link ScaffoldError} coded `INVALID` when `names` is not a bounded\n\t * list of fleet package names or `current` is not a snapshot, and `DESTROYED`\n\t * when the reader is torn down before or during the call.\n\t *\n\t * @remarks\n\t * The mirror path is derived from the package name by the same helper the plan\n\t * derives it with, and the fetched URL ends in that exact path, so a verdict\n\t * always answers for the file it names. `observed` is carried through from\n\t * `current` whatever the lookup produced, because it is the precondition the\n\t * later write is held to and a failed fetch does not change what the target\n\t * currently holds.\n\t *\n\t * @example\n\t * ```ts\n\t * import { Upstream } from '@orkestrel/scaffold/server'\n\t *\n\t * const upstream = new Upstream()\n\t * await upstream.fetch(['@orkestrel/router'], { 'guides/router.md': '2320526f75746572' })\n\t * upstream.destroy()\n\t * ```\n\t */\n\tasync fetch(names: readonly string[], current: Snapshot): Promise<readonly Mirror[]> {\n\t\tthis.#assertAlive()\n\t\tconst accepted = this.#accept(names, isDependencyNames, 'names')\n\t\tconst observed = this.#accept(current, isSnapshot, 'current')\n\t\tconst allowance = { remaining: this.#budget }\n\t\treturn this.#gather(accepted, (name) => this.#mirror(name, observed, allowance))\n\t}\n\n\t/**\n\t * Catalog the published fleet from the registry's organization package list.\n\t *\n\t * @returns One row per published package, sorted by name.\n\t * @throws {@link ScaffoldError} coded `FETCH` when the organization package\n\t * list is unreachable, malformed, empty, or larger than one bounded\n\t * collection, and `DESTROYED` when the reader is torn down before or during\n\t * the call.\n\t *\n\t * @remarks\n\t * The organization list is the exact membership the registry publishes, not a\n\t * relevance search, and it is the whole reason this answer can claim to be the\n\t * fleet. So it fails hard where a per-package lookup fails soft: an empty or\n\t * unreadable list would otherwise be written into a target's catalog table as\n\t * a fleet with no packages in it. A package whose own version lookup then\n\t * fails still keeps its row, carrying the cause instead of a version, because\n\t * the list already proved the package is published.\n\t *\n\t * @example\n\t * ```ts\n\t * import { Upstream } from '@orkestrel/scaffold/server'\n\t *\n\t * const upstream = new Upstream()\n\t * const entries = await upstream.catalog()\n\t * upstream.destroy()\n\t * ```\n\t */\n\tasync catalog(): Promise<readonly CatalogEntry[]> {\n\t\tthis.#assertAlive()\n\t\tconst allowance = { remaining: this.#budget }\n\t\tconst names = await this.#packages(allowance)\n\t\treturn this.#gather(names, (name) => this.#entry(name, allowance))\n\t}\n\n\t/**\n\t * Tear the reader down, aborting every request in flight. Teardown is idempotent.\n\t *\n\t * @returns Nothing.\n\t *\n\t * @remarks\n\t * A call still in flight rejects with a `DESTROYED` error rather than\n\t * resolving to a partial answer, because half a fleet reads exactly like a\n\t * whole one.\n\t *\n\t * @example\n\t * ```ts\n\t * import { Upstream } from '@orkestrel/scaffold/server'\n\t *\n\t * const upstream = new Upstream()\n\t * upstream.destroy()\n\t * upstream.emitter.destroyed // true\n\t * ```\n\t */\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\tthis.#controller.abort()\n\t\tthis.#emitter.emit('destroy')\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// The scheme and host law `isEndpoint` deliberately leaves to this entity. A\n\t// guard has only `false` to say; this can name the endpoint and the reason.\n\t#endpoint(base: string, field: string): string {\n\t\tconst parsed = URL.parse(base)\n\t\tif (parsed === null) {\n\t\t\tthrow this.#error('INVALID', `The ${field} endpoint is not a URL.`, { field, base })\n\t\t}\n\t\tconst loopback =\n\t\t\tparsed.hostname === '127.0.0.1' ||\n\t\t\tparsed.hostname === 'localhost' ||\n\t\t\tparsed.hostname === '[::1]'\n\t\tif (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && loopback)) {\n\t\t\tthrow this.#error(\n\t\t\t\t'INVALID',\n\t\t\t\t`The ${field} endpoint at ${base} is not HTTPS and is not a loopback host.`,\n\t\t\t\t{ field, base },\n\t\t\t)\n\t\t}\n\t\tif (\n\t\t\tparsed.username !== '' ||\n\t\t\tparsed.password !== '' ||\n\t\t\tparsed.search !== '' ||\n\t\t\tparsed.hash !== ''\n\t\t) {\n\t\t\tthrow this.#error(\n\t\t\t\t'INVALID',\n\t\t\t\t`The ${field} endpoint at ${base} carries credentials, a query, or a fragment.`,\n\t\t\t\t{ field, base },\n\t\t\t)\n\t\t}\n\t\treturn parsed.href.replace(/\\/+$/u, '')\n\t}\n\n\t// One dependency, read and projected into the verdict its row carries. A\n\t// found answer that states no readable version is a failed lookup rather than\n\t// a found one carrying nothing, because an empty version is not an answer.\n\tasync #release(dependency: Dependency, allowance: { remaining: number }): Promise<Release> {\n\t\tconst outcome = await this.#read(\n\t\t\tthis.#registryURL(dependency.name),\n\t\t\tthis.#registryTimeout,\n\t\t\tallowance,\n\t\t)\n\t\tconst latest = outcome.lookup === 'found' ? this.#latest(outcome.content) : undefined\n\t\tconst release: Release =\n\t\t\tlatest === undefined\n\t\t\t\t? {\n\t\t\t\t\t\tname: dependency.name,\n\t\t\t\t\t\trange: dependency.range,\n\t\t\t\t\t\tlookup: outcome.lookup === 'missing' ? 'missing' : 'failed',\n\t\t\t\t\t\tnote: outcome.lookup === 'found' ? Upstream.#unreadable : outcome.note,\n\t\t\t\t\t}\n\t\t\t\t: { name: dependency.name, range: dependency.range, lookup: 'found', latest }\n\t\tthis.#emitter.emit('release', release)\n\t\treturn release\n\t}\n\n\t// One guide, read and projected beside the local bytes it answers for.\n\tasync #mirror(\n\t\tname: string,\n\t\tcurrent: Snapshot,\n\t\tallowance: { remaining: number },\n\t): Promise<Mirror> {\n\t\tconst path = nameToGuide(name)\n\t\tconst outcome = await this.#read(this.#guideURL(name), this.#guideTimeout, allowance)\n\t\tconst observed = current[path]\n\t\tconst mirror: Mirror =\n\t\t\toutcome.lookup === 'found'\n\t\t\t\t? {\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tlookup: 'found',\n\t\t\t\t\t\tcontent: outcome.content,\n\t\t\t\t\t\t...(observed === undefined ? {} : { observed }),\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tpath,\n\t\t\t\t\t\tlookup: outcome.lookup,\n\t\t\t\t\t\tnote: outcome.note,\n\t\t\t\t\t\t...(observed === undefined ? {} : { observed }),\n\t\t\t\t\t}\n\t\tthis.#emitter.emit('mirror', mirror)\n\t\treturn mirror\n\t}\n\n\t// One catalog row. It publishes nothing on the observation channel: the\n\t// channel carries the two verdicts the writer binds to, and a catalog row is\n\t// neither, so the whole sorted list is the answer instead.\n\tasync #entry(name: string, allowance: { remaining: number }): Promise<CatalogEntry> {\n\t\tconst outcome = await this.#read(this.#registryURL(name), this.#registryTimeout, allowance)\n\t\tconst version = outcome.lookup === 'found' ? this.#latest(outcome.content) : undefined\n\t\tif (version !== undefined) return { name, lookup: 'found', version }\n\t\treturn {\n\t\t\tname,\n\t\t\tlookup: outcome.lookup === 'missing' ? 'missing' : 'failed',\n\t\t\tnote: outcome.lookup === 'found' ? Upstream.#unreadable : outcome.note,\n\t\t}\n\t}\n\n\t// The registry's exact organization membership, which is a flat name-to-access\n\t// map rather than a search. Every refusal here is coded rather than collected,\n\t// because a caller that received an empty or partial fleet could not tell it\n\t// from a fleet that shrank.\n\tasync #packages(allowance: { remaining: number }): Promise<readonly string[]> {\n\t\tconst url = `${this.#registryBase}/-/org/${Upstream.#scope}/package`\n\t\tconst outcome = await this.#read(url, this.#registryTimeout, allowance)\n\t\tif (outcome.lookup !== 'found') {\n\t\t\tthrow this.#error('FETCH', `The organization package list at ${url} produced no answer.`, {\n\t\t\t\turl,\n\t\t\t\tnote: outcome.note,\n\t\t\t})\n\t\t}\n\t\tconst parsed = parseJSON(outcome.content)\n\t\tif (!isRecord(parsed)) {\n\t\t\tthrow this.#error('FETCH', `The organization package list at ${url} is not a record.`, {\n\t\t\t\turl,\n\t\t\t})\n\t\t}\n\t\tconst names = Object.keys(parsed)\n\t\tif (\n\t\t\tnames.length === 0 ||\n\t\t\t!isCollection(names) ||\n\t\t\t!names.every((name) => isDependencyName(name))\n\t\t) {\n\t\t\tthrow this.#error(\n\t\t\t\t'FETCH',\n\t\t\t\t`The organization package list at ${url} does not name a bounded fleet.`,\n\t\t\t\t{ url, count: names.length },\n\t\t\t)\n\t\t}\n\t\treturn [...names].sort()\n\t}\n\n\t// The latest version the registry states, or nothing. The full packument is\n\t// read rather than the abbreviated form, because only the full one carries\n\t// `dist-tags`. The version is bounded and control-free before it is admitted,\n\t// so an upstream answer cannot smuggle text into a verdict a caller prints.\n\t#latest(content: string): string | undefined {\n\t\tconst parsed = parseJSON(content)\n\t\tif (!isRecord(parsed)) return undefined\n\t\tconst latest = parseStringField(parsed, ['dist-tags', 'latest'])\n\t\tif (latest === undefined || latest.length === 0 || latest.length > MAX_RANGE_LENGTH) {\n\t\t\treturn undefined\n\t\t}\n\t\treturn CONTROL_CHARACTER_PATTERN.test(latest) ? undefined : latest\n\t}\n\n\t// The canonical scoped-package registry path keeps the literal `@` and encodes\n\t// the scope boundary, which is the exact form registries publish. Everything\n\t// is encoded first and only `@` is restored, so the encoding is total rather\n\t// than a list of characters someone remembered: a declared dependency name is\n\t// bounded and non-empty but is otherwise the caller's text, and a name\n\t// carrying a separator, a dot segment, a query, or a fragment must address one\n\t// package rather than walking out of the endpoint's own path.\n\t#registryURL(name: string): string {\n\t\treturn `${this.#registryBase}/${encodeURIComponent(name).replaceAll('%40', '@')}`\n\t}\n\n\t// The canonical raw-content path is `/<scope>/<repository>/refs/heads/<branch>/<path>`.\n\t// The tail is the same mirror path the verdict carries, derived by the same\n\t// helper, so the file fetched and the file answered for cannot drift apart; it\n\t// is left unencoded because that helper's one separator is a real path\n\t// separator here. The branch and the repository are each a single segment and\n\t// each is encoded whole, because both reach the URL and only one of them is\n\t// closed by a guard.\n\t#guideURL(name: string): string {\n\t\tconst branch = this.#guideBranch\n\t\t\t.split('/')\n\t\t\t.map((segment) => encodeURIComponent(segment))\n\t\t\t.join('/')\n\t\tconst repository = encodeURIComponent(name.slice(name.lastIndexOf('/') + 1))\n\t\treturn `${this.#guideBase}/${Upstream.#scope}/${repository}/refs/heads/${branch}/${nameToGuide(name)}`\n\t}\n\n\t// One read, plus the retries a transport fault is given. A `404` is a definite\n\t// answer and is never retried; an exhausted allowance short-circuits the next\n\t// attempt rather than spending a request to be refused again. The fault is\n\t// published here, at the one place that knows the cause, which is what lets\n\t// every projection downstream stay a plain value.\n\tasync #read(\n\t\turl: string,\n\t\ttimeout: number,\n\t\tallowance: { remaining: number },\n\t): Promise<{ readonly lookup: Lookup; readonly content: string; readonly note: string }> {\n\t\tlet note = ''\n\t\tfor (let attempt = 0; attempt <= this.#retries; attempt += 1) {\n\t\t\tthis.#assertAlive()\n\t\t\tconst outcome = await this.#request(url, timeout, allowance)\n\t\t\tif (outcome.lookup !== 'failed') return outcome\n\t\t\tnote = outcome.note\n\t\t}\n\t\tthis.#error('FETCH', `The upstream read at ${url} produced no answer.`, { url, note })\n\t\treturn { lookup: 'failed', content: '', note }\n\t}\n\n\t// One request: unauthenticated, redirect-free, and bounded by both the\n\t// endpoint's timeout and this reader's own abort signal. Teardown is the only\n\t// outcome that escapes as a throw, because a cancelled call has no verdict.\n\tasync #request(\n\t\turl: string,\n\t\ttimeout: number,\n\t\tallowance: { remaining: number },\n\t): Promise<{ readonly lookup: Lookup; readonly content: string; readonly note: string }> {\n\t\tif (allowance.remaining <= 0) {\n\t\t\treturn {\n\t\t\t\tlookup: 'failed',\n\t\t\t\tcontent: '',\n\t\t\t\tnote: `the call spent its ${String(this.#budget)}-byte allowance`,\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconst response = await fetch(url, {\n\t\t\t\tsignal: AbortSignal.any([this.#controller.signal, AbortSignal.timeout(timeout)]),\n\t\t\t\tredirect: 'manual',\n\t\t\t})\n\t\t\tif (response.status === 404) {\n\t\t\t\tawait response.body?.cancel()\n\t\t\t\treturn { lookup: 'missing', content: '', note: 'HTTP 404' }\n\t\t\t}\n\t\t\tif (response.status >= 300 && response.status < 400) {\n\t\t\t\tawait response.body?.cancel()\n\t\t\t\treturn {\n\t\t\t\t\tlookup: 'failed',\n\t\t\t\t\tcontent: '',\n\t\t\t\t\tnote: `HTTP ${String(response.status)}, and a redirect is never followed`,\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!response.ok) {\n\t\t\t\tawait response.body?.cancel()\n\t\t\t\treturn { lookup: 'failed', content: '', note: `HTTP ${String(response.status)}` }\n\t\t\t}\n\t\t\treturn await this.#body(response, allowance)\n\t\t} catch (error) {\n\t\t\tthis.#assertAlive()\n\t\t\treturn { lookup: 'failed', content: '', note: this.#note(error) }\n\t\t}\n\t}\n\n\t// The body, read against both bounds at once. A declared length past either\n\t// one is refused before a byte is read; the stream is then counted chunk by\n\t// chunk against the response limit and against what the whole call has left,\n\t// so one oversized answer and many small ones are refused by different tests.\n\t// Every byte taken off the wire is spent whatever the verdict, because bytes\n\t// a failed read consumed are bytes the caller no longer has.\n\tasync #body(\n\t\tresponse: Response,\n\t\tallowance: { remaining: number },\n\t): Promise<{ readonly lookup: Lookup; readonly content: string; readonly note: string }> {\n\t\tconst declared = response.headers.get('content-length')\n\t\tconst stated = declared === null ? undefined : Number(declared)\n\t\tif (\n\t\t\tstated !== undefined &&\n\t\t\tNumber.isFinite(stated) &&\n\t\t\t(stated > this.#limit || stated > allowance.remaining)\n\t\t) {\n\t\t\tawait response.body?.cancel()\n\t\t\treturn {\n\t\t\t\tlookup: 'failed',\n\t\t\t\tcontent: '',\n\t\t\t\tnote: `the response declares ${String(stated)} bytes, past the ${String(Math.min(this.#limit, allowance.remaining))}-byte allowance`,\n\t\t\t}\n\t\t}\n\t\tconst body = response.body\n\t\tif (body === null) return { lookup: 'found', content: '', note: '' }\n\t\tconst reader = body.getReader()\n\t\tconst decoder = new TextDecoder('utf-8', { fatal: true })\n\t\tconst chunks: string[] = []\n\t\tlet total = 0\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst chunk = await reader.read()\n\t\t\t\tif (chunk.done) break\n\t\t\t\ttotal += chunk.value.byteLength\n\t\t\t\tallowance.remaining -= chunk.value.byteLength\n\t\t\t\tif (total > this.#limit) {\n\t\t\t\t\tawait reader.cancel()\n\t\t\t\t\treturn {\n\t\t\t\t\t\tlookup: 'failed',\n\t\t\t\t\t\tcontent: '',\n\t\t\t\t\t\tnote: `the response passed the ${String(this.#limit)}-byte response limit`,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (allowance.remaining < 0) {\n\t\t\t\t\tawait reader.cancel()\n\t\t\t\t\treturn {\n\t\t\t\t\t\tlookup: 'failed',\n\t\t\t\t\t\tcontent: '',\n\t\t\t\t\t\tnote: `the call spent its ${String(this.#budget)}-byte allowance`,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tchunks.push(decoder.decode(chunk.value, { stream: true }))\n\t\t\t}\n\t\t\tchunks.push(decoder.decode())\n\t\t} catch (error) {\n\t\t\tawait reader.cancel().catch(() => undefined)\n\t\t\tthrow error\n\t\t} finally {\n\t\t\treader.releaseLock()\n\t\t}\n\t\treturn { lookup: 'found', content: chunks.join(''), note: '' }\n\t}\n\n\t// A caught transport fault, flattened into one line a caller can print. Node\n\t// wraps the real socket failure in `cause`, so its code is appended where the\n\t// runtime attached one — the difference between a refused connection and a\n\t// name that does not resolve is the part worth reading.\n\t#note(error: unknown): string {\n\t\tif (!isError(error)) return 'the request failed for an unreported reason'\n\t\tconst cause = error.cause\n\t\tconst code = isRecord(cause) && isString(cause.code) ? cause.code : undefined\n\t\tconst message = `${error.name}: ${error.message}`\n\t\treturn code === undefined ? message : `${message} (${code})`\n\t}\n\n\t// A bounded worker pool, never an unbounded parallel start. Results land at\n\t// their original index, so the answer is in input order however the reads\n\t// interleaved. Every worker is awaited whatever it did, so a sibling's later\n\t// rejection is observed rather than escaping as an unhandled one, and the\n\t// first failure is the one rethrown.\n\tasync #gather<T, R>(items: readonly T[], run: (item: T) => Promise<R>): Promise<readonly R[]> {\n\t\tconst results: R[] = []\n\t\tconst state: { cursor: number; failure: { readonly error: unknown } | undefined } = {\n\t\t\tcursor: 0,\n\t\t\tfailure: undefined,\n\t\t}\n\t\tconst workers = Array.from({ length: Math.min(this.#concurrency, items.length) }, () =>\n\t\t\tthis.#drain(items, run, results, state),\n\t\t)\n\t\tawait Promise.allSettled(workers)\n\t\tif (state.failure !== undefined) throw state.failure.error\n\t\treturn results\n\t}\n\n\t// One worker's pull-and-run loop over the shared cursor.\n\tasync #drain<T, R>(\n\t\titems: readonly T[],\n\t\trun: (item: T) => Promise<R>,\n\t\tresults: R[],\n\t\tstate: { cursor: number; failure: { readonly error: unknown } | undefined },\n\t): Promise<void> {\n\t\tfor (;;) {\n\t\t\tif (state.failure !== undefined) return\n\t\t\tconst index = state.cursor\n\t\t\tstate.cursor += 1\n\t\t\tif (index >= items.length) return\n\t\t\tconst item = items[index]\n\t\t\tif (item === undefined) return\n\t\t\ttry {\n\t\t\t\tresults[index] = await run(item)\n\t\t\t} catch (error) {\n\t\t\t\tstate.failure ??= { error }\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// Snapshot the caller's value, then guard the snapshot, so a property backed\n\t// by an accessor never reaches a decision this reader later depends on.\n\t#accept<T>(value: unknown, guard: Guard<T>, field: string): T {\n\t\tconst snapshot = cloneValue(value)\n\t\tif (guard(snapshot)) return snapshot\n\t\tthrow this.#error(\n\t\t\t'INVALID',\n\t\t\t`The ${field} argument is not the exact shape this upstream reader accepts.`,\n\t\t\t{ field },\n\t\t)\n\t}\n\n\t#assertAlive(): void {\n\t\tif (this.#destroyed) throw this.#error('DESTROYED', 'This upstream reader has been destroyed.')\n\t}\n\n\t// Publish the failure on the observation channel, then hand it back to be\n\t// thrown at the site that decided it, or discarded where the failure is\n\t// collected into a verdict instead.\n\t#error(code: ScaffoldErrorCode, message: string, context?: unknown): ScaffoldError {\n\t\tconst error = new ScaffoldError(code, message, context)\n\t\tthis.#emitter.emit('error', error)\n\t\treturn error\n\t}\n}\n","import type {\n\tMaterializerInterface,\n\tMaterializerOptions,\n\tUpstreamInterface,\n\tUpstreamOptions,\n} from './types.js'\nimport { Materializer } from './Materializer.js'\nimport { Upstream } from './Upstream.js'\n\n/**\n * Construct a {@link Materializer}.\n *\n * @param options - The vendored host root, the initial listeners, and the listener-error handler.\n * @returns The materializer, typed as the contract consumers program against.\n * @throws {@link ScaffoldError} coded `INVALID` when `options` is present but is\n * not an option bag the materializer accepts, and `TARGET` when the host carries\n * a manifest that cannot be read or does not match what it stores.\n *\n * @example\n * ```ts\n * import { createMaterializer } from '@orkestrel/scaffold/server'\n *\n * const materializer = createMaterializer({ host: './dist/host' })\n * materializer.destroy()\n * ```\n */\nexport function createMaterializer(options?: MaterializerOptions): MaterializerInterface {\n\treturn new Materializer(options)\n}\n\n/**\n * Construct an {@link Upstream}.\n *\n * @param options - The two endpoints, the request bounds, the initial listeners,\n * and the listener-error handler.\n * @returns The reader, typed as the contract consumers program against.\n * @throws {@link ScaffoldError} coded `INVALID` when `options` is present but is\n * not an option bag the reader accepts, or when either endpoint names a scheme,\n * host, or form the reader will not request.\n *\n * @example\n * ```ts\n * import { createUpstream } from '@orkestrel/scaffold/server'\n *\n * const upstream = createUpstream({ guides: { branch: 'main' } })\n * upstream.destroy()\n * ```\n */\nexport function createUpstream(options?: UpstreamOptions): UpstreamInterface {\n\treturn new Upstream(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAQA,IAAa,gBAAgB;;;;;;;;;AAU7B,IAAa,oCAAoC;;;;;;;;;AAUjD,IAAa,2BACZ;;;;;;;;;AAUD,IAAa,iBAAiB;;;;;;;;;;AAW9B,IAAa,iBAAiB;;;;;;;;;AAU9B,IAAa,yBAAyB;;;;;;;;;AAUtC,IAAa,iBAAiB;;;;;;;;;;;AAY9B,IAAa,sBAAsB;;AAGnC,IAAa,sBAAsB;;AAGnC,IAAa,oBAAoB;;;;;;;;AASjC,IAAa,2BAA2B;;AAGxC,IAAa,uBAAuB;;AAGpC,IAAa,uBAAuB;;;;;;;;;;AAWpC,IAAa,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC9B7B,SAAgB,iBAAiB,OAAiC;CACjE,OAAO,YAAY;EAClB,IAAI,CAAC,SAAS,KAAK,KAAK,MAAM,WAAW,KAAK,MAAM,SAAS,iBAAiB,OAAO;EACrF,IAAI,0BAA0B,KAAK,KAAK,GAAG,OAAO;EAClD,MAAM,aAAa,MAAM,WAAW,MAAM,GAAG;EAQ7C,MAAM,YALS,WAAW,WAAW,IAAI,IACtC,WAAW,MAAM,CAAC,IAClB,WAAW,WAAW,GAAG,IACxB,WAAW,MAAM,CAAC,IAClB,WAAA,CACoB,MAAM,GAAG;EACjC,IAAI,SAAS,SAAA,IAAyB,OAAO;EAC7C,KAAK,MAAM,CAAC,OAAO,YAAY,SAAS,QAAQ,GAAG;GAClD,IAAI,YAAY,OAAO,YAAY,MAAM;GACzC,IAAI,UAAU,KAAK,cAAc,KAAK,OAAO,GAAG;GAChD,IAAI,QAAQ,WAAW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