@orkestrel/scaffold 0.0.38 → 0.0.39
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.
- package/dist/host/agents/orchestration.md +17 -3
- package/dist/host/claude/agents/orkestrel.md +37 -33
- package/dist/src/core/index.cjs +9 -9
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.js +9 -9
- package/dist/src/core/index.js.map +1 -1
- package/dist/src/server/index.cjs +32 -10
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.js +32 -10
- package/dist/src/server/index.js.map +1 -1
- package/package.json +8 -8
|
@@ -1 +1 @@
|
|
|
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","#presence","#deferred","#read","#hydrated","#finish","#open","#copy","#close","#cell","#span","#defaultGuide","#defaultRegistry","#defaultBranch","#defaultTimeout","#defaultConcurrency","#defaultRetries","#defaultBudget","#scope","#unreadable","#packument","#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","#edges","#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 * The two spellings of an empty segment are answered differently. A trailing\n * separator terminates a directory rather than opening a segment, and every\n * supported filesystem and every Node path API reads `project/` and `project` as\n * one location, so it is admitted. A doubled separator is a genuine empty\n * segment, so `project//src` is refused. Nothing normalizes the argument first —\n * every server entry point guards the caller's text and resolves it afterwards —\n * so a directory taken from a shell completion arrives carrying the separator the\n * shell appended and names the directory it appears to name.\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/') // true\n * isFilesystemPath('project//src') // false\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\t// A trailing separator terminates a directory rather than opening a segment,\n\t\t// and every supported filesystem and every Node path API reads the two\n\t\t// spellings as one location. A doubled separator is a genuine empty segment\n\t\t// and stays refused below.\n\t\tconst segments = (rooted.endsWith('/') ? rooted.slice(0, -1) : 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\treadlinkSync,\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\tEXECUTABLE_PATHS,\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 * Test whether a vendored path is one a target receives executable.\n *\n * @param path - The target-relative path to classify; either separator is read.\n * @returns `true` when the path is declared in {@link EXECUTABLE_PATHS}.\n *\n * @remarks\n * The declaration is the whole answer, and deliberately so. Reading the staging\n * host's mode instead makes the manifest depend on where the package was built:\n * Windows carries no executable bit, so a host staged there declares every entry\n * non-executable and every target it later fills receives hooks at `0644`. One\n * checkout stages one manifest on every host because this predicate never\n * consults the filesystem.\n *\n * @example\n * ```ts\n * import { matchesExecutablePath } from '@orkestrel/scaffold/server'\n *\n * matchesExecutablePath('scripts/codex.sh') // true\n * matchesExecutablePath('scripts\\\\deps.sh') // true\n * matchesExecutablePath('AGENTS.md') // false\n * ```\n */\nexport function matchesExecutablePath(path: string): boolean {\n\treturn EXECUTABLE_PATHS.includes(path.replaceAll('\\\\', '/'))\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 lexical resolution of `path`, with its existing prefix then\n * resolved through every link, or `undefined` when the text is not a host path,\n * no bounded existing ancestor resolves, a link target cannot be read, a link\n * target carries a `..` segment, 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 * The caller's own text is collapsed first, which is what `resolve` does with a\n * `..` the caller wrote: it cancels the segment before it as text, before any\n * link in that segment is read. So `<root>/hop/..` answers `<root>` even where\n * `hop` links elsewhere, rather than the directory holding what `hop` points at.\n * The collapse only ever shortens the caller's path, so nothing reaches outside\n * it by this; the answer is that lexical location resolved through links, not\n * the physical location the links lead to. {@link resolveContainedPath} passes\n * its `root` through here, so a root written with a parent segment is contained\n * against its collapsed spelling.\n *\n * `realpath` answers `ENOENT` both for a name that is not there and for a link\n * whose target is not there. The name is therefore inspected without following\n * it: a dangling link redirects the walk to its target, while a genuinely absent\n * name is retained as one segment of the unresolved suffix. A dangling link\n * target containing a `..` segment is refused. Resolving that target as one\n * lexical string could discard a preceding link before the filesystem gives\n * `..` its physical meaning.\n *\n * That target is split on both separators on every host, which is the reading\n * `isPath` already gives a planned path. A POSIX filename legally containing a\n * backslash is therefore refused with it: `weird\\..\\name` is one name to the\n * host and three segments here. The package keeps one separator law rather than\n * a host-dependent second one, and this is the conservative side of it.\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 status = attempt(() => lstatSync(current))\n\t\tif (status.success) {\n\t\t\tif (!status.value.isSymbolicLink()) return undefined\n\t\t\tconst target = attempt(() => readlinkSync(current))\n\t\t\tif (!target.success) return undefined\n\t\t\tif (target.value.split(/[\\\\/]/u).includes('..')) return undefined\n\t\t\tcurrent = resolve(dirname(current), target.value)\n\t\t\tcontinue\n\t\t}\n\t\tif (!matchesMissingPath(status.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 * A dangling link is followed only when its raw target contains no parent\n * traversal. The answer is then the lexical join of `root` and `path` — an\n * absolute path under `root`, not a root-relative one — so the caller operates\n * on the path it named rather than on a resolved form the target may not\n * recognize. A `root` written with a parent segment is collapsed by that\n * resolution before anything is read, so containment is measured against the\n * directory the caller's text names.\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 * The answer describes the namespace this call read. The contract excludes a\n * concurrent rename or link swap during the call or before the caller finishes\n * using the returned path. This helper returns a string, not a filesystem\n * handle, so it cannot bind its containment check to a later operation. A caller\n * that admits hostile concurrent namespace mutation needs a handle-bound\n * operation instead.\n *\n * @example\n * ```ts\n * import { resolveContainedPath } from '@orkestrel/scaffold/server'\n *\n * resolveContainedPath('/tmp/project', 'guides/router.md')?.endsWith('router.md') // true\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.md', 'LICENSE', …]\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 path: {@link pathToStorage} decides where it is stored,\n * the destination is the path it answers for, and {@link matchesExecutablePath}\n * decides whether a target receives it executable.\n *\n * The bit is read from that declaration rather than from the source's mode, so\n * the entry does not depend on where the package was staged. A Windows host\n * reports no executable bit at all, and reading the mode there declared every\n * entry non-executable and shipped consumers hooks they could not run.\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: matchesExecutablePath(destination),\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 proves the directory written into sits where the\n * inspected one sat, not that it is the one 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 * This binds location rather than history. `true` means the path still resolves\n * to the same physical directory on the same device, so the next write lands\n * where the last one did. A path now holding nothing, a file, or a symlink\n * answers `false`; a directory swapped in by `rename` also answers `false`\n * because the replacement carries its own inode. A directory deleted and made\n * again under the same name can receive the old inode back and answers `true`,\n * which nothing here detects.\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 * - **Containment, not continuity, of the directories it creates.** Every\n * ancestor is re-read between `mkdir` calls and again before the first\n * promotion, so an ancestor that became a file, a symlink, a directory\n * elsewhere, or nothing is refused. An ancestor deleted and recreated under\n * the same name can receive its old inode back and is indistinguishable here\n * from one that never moved.\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: Array<string | 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.#establish(parent)\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\tchmodSync(staged, executable ? 0o755 : 0o644)\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 established = attempt(() => this.#establish(this.#resolve(this.#target, path)))\n\t\tif (!established.success) {\n\t\t\tthrow new ScaffoldError('WRITE', `The directory at ${path} could not be established.`, {\n\t\t\t\tpath,\n\t\t\t\terror: established.error,\n\t\t\t})\n\t\t}\n\t\tconst result = established.value\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, promoted)\n\t\t\t}\n\t\t\tfor (const path of this.#taken) {\n\t\t\t\tthis.#take(path, taken)\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\tthis.#created.push(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\tthis.#created[this.#created.length - 1] = 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 (typeof anchor === 'string') {\n\t\t\t\tthrow new ScaffoldError('WRITE', `The directory at ${anchor} changed while writing.`, {\n\t\t\t\t\ttarget: this.#target,\n\t\t\t\t\tpath: anchor,\n\t\t\t\t})\n\t\t\t}\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, promoted: 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.#establish(dirname(expectation.path))\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\tpromoted.push(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, taken: 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\ttaken.push(path)\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 created of [...this.#created].reverse()) {\n\t\t\tconst path = typeof created === 'string' ? created : created.path\n\t\t\tconst removed = attempt(() => rmdirSync(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\tcatalogToLayers,\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\tmatchesDriftReachability,\n\tplanToFindings,\n\tScaffoldError,\n\tWORKSPACE_OWNED_PATHS,\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. The audit is checked\n\t * for agreement rather than for plausibility, so a verdict the comparison could\n\t * not have produced — a birth-owned path reported stale, which the `Finding`\n\t * shape admits — disagrees with the derived one and is refused. A missing\n\t * destination is restored whatever its ownership; a stale one is replaced only\n\t * where the artifact claims its bytes, which is what leaves a presence-owned\n\t * file a 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 (WORKSPACE_OWNED_PATHS.includes(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\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\tif (WORKSPACE_OWNED_PATHS.includes(artifact.path)) {\n\t\t\t\treturn [this.#presence(artifact, artifact.path, source)]\n\t\t\t}\n\t\t\tif (this.#deferred(artifact.path)) {\n\t\t\t\treturn [this.#presence(artifact, artifact.path, source)]\n\t\t\t}\n\t\t\treturn [this.#hydrated(artifact, artifact.path, source, this.#read(source, remaining))]\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 (WORKSPACE_OWNED_PATHS.includes(path)) {\n\t\t\t\texpanded.push(this.#presence(artifact, path, destination))\n\t\t\t\tcontinue\n\t\t\t}\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\tif (!matchesDriftReachability(finding.ownership, other)) {\n\t\t\t\tthrow this.#error(\n\t\t\t\t\t'TARGET',\n\t\t\t\t\t`The path ${finding.path} carries an audit verdict this plan could not produce.`,\n\t\t\t\t\t{ target, path: finding.path, ownership: finding.ownership, drift: other.drift },\n\t\t\t\t)\n\t\t\t}\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\t// The layer is computed from the edges in the same call that writes them, so\n\t\t// the two cannot disagree. A name absent from every layer sits in a cycle and\n\t\t// carries no layer cell rather than a guessed one.\n\t\tconst layers = catalogToLayers(entries)\n\t\tconst placed = new Map<string, number>()\n\t\tfor (const [index, layer] of layers.entries()) for (const name of layer) placed.set(name, index)\n\t\tconst rows = entries.map((entry) => {\n\t\t\tif (entry.lookup !== 'found') {\n\t\t\t\treturn `| \\`${entry.name}\\` | ${this.#cell(entry.note)} | | |`\n\t\t\t}\n\t\t\tconst layer = placed.get(entry.name)\n\t\t\tconst edges = entry.dependencies\n\t\t\t\t.map((dependency) => `\\`${dependency.name}\\` \\`${dependency.range}\\``)\n\t\t\t\t.join(', ')\n\t\t\treturn `| \\`${entry.name}\\` | \\`${entry.version}\\` | ${layer === undefined ? '' : `L${String(layer)}`} | ${edges} |`\n\t\t})\n\t\tconst table = [\n\t\t\t'| Package | Version | Layer | Runtime dependencies |',\n\t\t\t'| --- | --- | --- | --- |',\n\t\t\t...rows,\n\t\t].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_COLLECTION_ITEMS,\n\tMAX_DEPENDENCY_NAME_LENGTH,\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\t// The media type that selects the registry's abbreviated packument. It sits\n\t// with the request defaults because it is part of how this class asks for a\n\t// version, and it is asked for at exactly the two reads that want one.\n\tstatic readonly #packument = 'application/vnd.npm.install-v1+json'\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\tUpstream.#packument,\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(\n\t\t\tthis.#registryURL(name),\n\t\t\tthis.#registryTimeout,\n\t\t\tallowance,\n\t\t\tUpstream.#packument,\n\t\t)\n\t\tconst version = outcome.lookup === 'found' ? this.#latest(outcome.content) : undefined\n\t\tif (version !== undefined) {\n\t\t\treturn { name, lookup: 'found', version, dependencies: this.#edges(outcome.content, version) }\n\t\t}\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 runtime edges the published version declares, read from the same\n\t// abbreviated packument the version came from rather than from a second\n\t// request. Development edges are deliberately not read: they reach no\n\t// consumer, so they constrain nothing a publish order decides. A packument\n\t// that carries no readable edges answers none rather than failing the row,\n\t// because a package with no dependencies and a package whose manifest could\n\t// not be read both publish first, and the version is what the row promises.\n\t#edges(content: string, version: string): readonly Dependency[] {\n\t\tconst parsed = parseJSON(content)\n\t\tif (!isRecord(parsed)) return []\n\t\tconst versions = parsed.versions\n\t\tif (!isRecord(versions)) return []\n\t\tconst manifest = versions[version]\n\t\tif (!isRecord(manifest)) return []\n\t\tconst declared = manifest.dependencies\n\t\tif (!isRecord(declared)) return []\n\t\tconst edges: Dependency[] = []\n\t\tfor (const [name, range] of Object.entries(declared)) {\n\t\t\tif (edges.length >= MAX_COLLECTION_ITEMS) break\n\t\t\tif (typeof range !== 'string' || range.length === 0 || range.length > MAX_RANGE_LENGTH) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (CONTROL_CHARACTER_PATTERN.test(name) || CONTROL_CHARACTER_PATTERN.test(range)) continue\n\t\t\tif (name.length === 0 || name.length > MAX_DEPENDENCY_NAME_LENGTH) continue\n\t\t\tedges.push({ name, range })\n\t\t}\n\t\treturn edges\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 version is bounded\n\t// and control-free before it is admitted, so an upstream answer cannot smuggle\n\t// 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\t//\n\t// `accept` is stated only where an endpoint publishes more than one form of\n\t// the same answer, which is the packument alone. Every other read takes what\n\t// the endpoint serves, so no request declares a media type it has no reason to.\n\tasync #read(\n\t\turl: string,\n\t\ttimeout: number,\n\t\tallowance: { remaining: number },\n\t\taccept?: string,\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, accept)\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\taccept?: string,\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\t...(accept === undefined ? {} : { headers: { accept } }),\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. The stream is 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 decoded byte is spent whatever the verdict, because bytes a failed\n\t// read consumed are bytes the caller no longer has. `content-length` cannot\n\t// refuse early: it counts wire octets, while both bounds count decoded bytes,\n\t// and content encoding may make either count larger than the other.\n\t//\n\t// A status carrying no representation reaches this method too, because `ok`\n\t// covers the whole 2xx range. It is a verdict rather than an empty answer: a\n\t// zero-byte file arrives as a `200` with an empty stream and still reads as\n\t// found.\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 body = response.body\n\t\tif (body === null) {\n\t\t\treturn {\n\t\t\t\tlookup: 'failed',\n\t\t\t\tcontent: '',\n\t\t\t\tnote: `HTTP ${String(response.status)}, and the answer carries no body`,\n\t\t\t}\n\t\t}\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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACnB7B,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;EAG7C,MAAM,SAAS,WAAW,WAAW,IAAI,IACtC,WAAW,MAAM,CAAC,IAClB,WAAW,WAAW,GAAG,IACxB,WAAW,M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I,MAAM,QAAQ,GAAG,OAAO;EAC5B,MAAM,KAAKT,OACV,WACA,OAAO,MAAM,iEACb,EAAE,MAAM,CACT;CACD;CAEA,eAAqB;EACpB,IAAI,KAAKD,YAAY,MAAM,KAAKC,OAAO,aAAa,0CAA0C;CAC/F;CAKA,OAAO,MAAyB,SAAiB,SAAkC;EAClF,MAAM,QAAQ,IAAI,cAAc,MAAM,SAAS,OAAO;EACtD,KAAKpB,SAAS,KAAK,SAAS,KAAK;EACjC,OAAO;CACR;AACD;;;;;;;;;;;;;;;;;;;;AC/pBA,SAAgB,mBAAmB,SAAsD;CACxF,OAAO,IAAI,aAAa,OAAO;AAChC;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,eAAe,SAA8C;CAC5E,OAAO,IAAI,SAAS,OAAO;AAC5B"}
|
|
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","#presence","#deferred","#read","#hydrated","#finish","#open","#copy","#close","#cell","#span","#defaultGuide","#defaultRegistry","#defaultBranch","#defaultTimeout","#defaultConcurrency","#defaultRetries","#defaultBudget","#scope","#unreadable","#packument","#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","#edges","#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 * The two spellings of an empty segment are answered differently. A trailing\n * separator terminates a directory rather than opening a segment, and every\n * supported filesystem and every Node path API reads `project/` and `project` as\n * one location, so it is admitted. A doubled separator is a genuine empty\n * segment, so `project//src` is refused. Nothing normalizes the argument first —\n * every server entry point guards the caller's text and resolves it afterwards —\n * so a directory taken from a shell completion arrives carrying the separator the\n * shell appended and names the directory it appears to name.\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/') // true\n * isFilesystemPath('project//src') // false\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\t// A trailing separator terminates a directory rather than opening a segment,\n\t\t// and every supported filesystem and every Node path API reads the two\n\t\t// spellings as one location. A doubled separator is a genuine empty segment\n\t\t// and stays refused below.\n\t\tconst segments = (rooted.endsWith('/') ? rooted.slice(0, -1) : 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\treadlinkSync,\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\tEXECUTABLE_PATHS,\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 * Test whether a vendored path is one a target receives executable.\n *\n * @param path - The target-relative path to classify; either separator is read.\n * @returns `true` when the path is declared in {@link EXECUTABLE_PATHS}.\n *\n * @remarks\n * The declaration is the whole answer, and deliberately so. Reading the staging\n * host's mode instead makes the manifest depend on where the package was built:\n * Windows carries no executable bit, so a host staged there declares every entry\n * non-executable and every target it later fills receives hooks at `0644`. One\n * checkout stages one manifest on every host because this predicate never\n * consults the filesystem.\n *\n * @example\n * ```ts\n * import { matchesExecutablePath } from '@orkestrel/scaffold/server'\n *\n * matchesExecutablePath('scripts/codex.sh') // true\n * matchesExecutablePath('scripts\\\\deps.sh') // true\n * matchesExecutablePath('AGENTS.md') // false\n * ```\n */\nexport function matchesExecutablePath(path: string): boolean {\n\treturn EXECUTABLE_PATHS.includes(path.replaceAll('\\\\', '/'))\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 lexical resolution of `path`, with its existing prefix then\n * resolved through every link, or `undefined` when the text is not a host path,\n * no bounded existing ancestor resolves, a link target cannot be read, a link\n * target carries a `..` segment, 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 * The caller's own text is collapsed first, which is what `resolve` does with a\n * `..` the caller wrote: it cancels the segment before it as text, before any\n * link in that segment is read. So `<root>/hop/..` answers `<root>` even where\n * `hop` links elsewhere, rather than the directory holding what `hop` points at.\n * The collapse only ever shortens the caller's path, so nothing reaches outside\n * it by this; the answer is that lexical location resolved through links, not\n * the physical location the links lead to. {@link resolveContainedPath} passes\n * its `root` through here, so a root written with a parent segment is contained\n * against its collapsed spelling.\n *\n * `realpath` answers `ENOENT` both for a name that is not there and for a link\n * whose target is not there. The name is therefore inspected without following\n * it: a dangling link redirects the walk to its target, while a genuinely absent\n * name is retained as one segment of the unresolved suffix. A dangling link\n * target containing a `..` segment is refused. Resolving that target as one\n * lexical string could discard a preceding link before the filesystem gives\n * `..` its physical meaning.\n *\n * That target is split on both separators on every host, which is the reading\n * `isPath` already gives a planned path. A POSIX filename legally containing a\n * backslash is therefore refused with it: `weird\\..\\name` is one name to the\n * host and three segments here. The package keeps one separator law rather than\n * a host-dependent second one, and this is the conservative side of it.\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 status = attempt(() => lstatSync(current))\n\t\tif (status.success) {\n\t\t\tif (!status.value.isSymbolicLink()) return undefined\n\t\t\tconst target = attempt(() => readlinkSync(current))\n\t\t\tif (!target.success) return undefined\n\t\t\tif (target.value.split(/[\\\\/]/u).includes('..')) return undefined\n\t\t\tcurrent = resolve(dirname(current), target.value)\n\t\t\tcontinue\n\t\t}\n\t\tif (!matchesMissingPath(status.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 * A dangling link is followed only when its raw target contains no parent\n * traversal. The answer is then the lexical join of `root` and `path` — an\n * absolute path under `root`, not a root-relative one — so the caller operates\n * on the path it named rather than on a resolved form the target may not\n * recognize. A `root` written with a parent segment is collapsed by that\n * resolution before anything is read, so containment is measured against the\n * directory the caller's text names.\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 * The answer describes the namespace this call read. The contract excludes a\n * concurrent rename or link swap during the call or before the caller finishes\n * using the returned path. This helper returns a string, not a filesystem\n * handle, so it cannot bind its containment check to a later operation. A caller\n * that admits hostile concurrent namespace mutation needs a handle-bound\n * operation instead.\n *\n * @example\n * ```ts\n * import { resolveContainedPath } from '@orkestrel/scaffold/server'\n *\n * resolveContainedPath('/tmp/project', 'guides/router.md')?.endsWith('router.md') // true\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.md', 'LICENSE', …]\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 path: {@link pathToStorage} decides where it is stored,\n * the destination is the path it answers for, and {@link matchesExecutablePath}\n * decides whether a target receives it executable.\n *\n * The bit is read from that declaration rather than from the source's mode, so\n * the entry does not depend on where the package was staged. A Windows host\n * reports no executable bit at all, and reading the mode there declared every\n * entry non-executable and shipped consumers hooks they could not run.\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: matchesExecutablePath(destination),\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 proves the directory written into sits where the\n * inspected one sat, not that it is the one 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 * This binds location rather than history. `true` means the path still resolves\n * to the same physical directory on the same device, so the next write lands\n * where the last one did. A path now holding nothing, a file, or a symlink\n * answers `false`; a directory swapped in by `rename` also answers `false`\n * because the replacement carries its own inode. A directory deleted and made\n * again under the same name can receive the old inode back and answers `true`,\n * which nothing here detects.\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 * - **Containment, not continuity, of the directories it creates.** Every\n * ancestor is re-read between `mkdir` calls and again before the first\n * promotion, so an ancestor that became a file, a symlink, a directory\n * elsewhere, or nothing is refused. An ancestor deleted and recreated under\n * the same name can receive its old inode back and is indistinguishable here\n * from one that never moved.\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: Array<string | 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.#establish(parent)\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\tchmodSync(staged, executable ? 0o755 : 0o644)\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 established = attempt(() => this.#establish(this.#resolve(this.#target, path)))\n\t\tif (!established.success) {\n\t\t\tthrow new ScaffoldError('WRITE', `The directory at ${path} could not be established.`, {\n\t\t\t\tpath,\n\t\t\t\terror: established.error,\n\t\t\t})\n\t\t}\n\t\tconst result = established.value\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, promoted)\n\t\t\t}\n\t\t\tfor (const path of this.#taken) {\n\t\t\t\tthis.#take(path, taken)\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\tthis.#created.push(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\tthis.#created[this.#created.length - 1] = 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 (typeof anchor === 'string') {\n\t\t\t\tthrow new ScaffoldError('WRITE', `The directory at ${anchor} changed while writing.`, {\n\t\t\t\t\ttarget: this.#target,\n\t\t\t\t\tpath: anchor,\n\t\t\t\t})\n\t\t\t}\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, promoted: 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.#establish(dirname(expectation.path))\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\tpromoted.push(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, taken: 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\ttaken.push(path)\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 created of [...this.#created].reverse()) {\n\t\t\tconst path = typeof created === 'string' ? created : created.path\n\t\t\tconst removed = attempt(() => rmdirSync(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\tcatalogToLayers,\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\tmatchesDriftReachability,\n\tplanToFindings,\n\tScaffoldError,\n\tWORKSPACE_OWNED_PATHS,\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. The audit is checked\n\t * for agreement rather than for plausibility, so a verdict the comparison could\n\t * not have produced — a birth-owned path reported stale, which the `Finding`\n\t * shape admits — disagrees with the derived one and is refused. A missing\n\t * destination is restored whatever its ownership; a stale one is replaced only\n\t * where the artifact claims its bytes, which is what leaves a presence-owned\n\t * file a 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 (WORKSPACE_OWNED_PATHS.includes(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\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\tif (WORKSPACE_OWNED_PATHS.includes(artifact.path)) {\n\t\t\t\treturn [this.#presence(artifact, artifact.path, source)]\n\t\t\t}\n\t\t\tif (this.#deferred(artifact.path)) {\n\t\t\t\treturn [this.#presence(artifact, artifact.path, source)]\n\t\t\t}\n\t\t\treturn [this.#hydrated(artifact, artifact.path, source, this.#read(source, remaining))]\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 (WORKSPACE_OWNED_PATHS.includes(path)) {\n\t\t\t\texpanded.push(this.#presence(artifact, path, destination))\n\t\t\t\tcontinue\n\t\t\t}\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\tif (!matchesDriftReachability(finding.ownership, other)) {\n\t\t\t\tthrow this.#error(\n\t\t\t\t\t'TARGET',\n\t\t\t\t\t`The path ${finding.path} carries an audit verdict this plan could not produce.`,\n\t\t\t\t\t{ target, path: finding.path, ownership: finding.ownership, drift: other.drift },\n\t\t\t\t)\n\t\t\t}\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\t// The layer is computed from the edges in the same call that writes them, so\n\t\t// the two cannot disagree. A name absent from every layer sits in a cycle and\n\t\t// carries no layer cell rather than a guessed one.\n\t\tconst layers = catalogToLayers(entries)\n\t\tconst placed = new Map<string, number>()\n\t\tfor (const [index, layer] of layers.entries()) for (const name of layer) placed.set(name, index)\n\t\tconst rows: string[][] = entries.map((entry) => {\n\t\t\tif (entry.lookup !== 'found') {\n\t\t\t\treturn [`\\`${entry.name}\\``, this.#cell(entry.note), '', '']\n\t\t\t}\n\t\t\tconst layer = placed.get(entry.name)\n\t\t\tconst edges = entry.dependencies\n\t\t\t\t.map((dependency) => `\\`${dependency.name}\\` \\`${dependency.range}\\``)\n\t\t\t\t.join(', ')\n\t\t\treturn [\n\t\t\t\t`\\`${entry.name}\\``,\n\t\t\t\t`\\`${entry.version}\\``,\n\t\t\t\tlayer === undefined ? '' : `L${String(layer)}`,\n\t\t\t\tedges,\n\t\t\t]\n\t\t})\n\t\tconst headers = ['Package', 'Version', 'Layer', 'Runtime dependencies']\n\t\tconst widths = headers.map((header, column) => {\n\t\t\tlet width = Math.max(3, header.length)\n\t\t\tfor (const row of rows) width = Math.max(width, row[column]?.length ?? 0)\n\t\t\treturn width\n\t\t})\n\t\tconst table = [headers, widths.map((width) => '-'.repeat(width)), ...rows]\n\t\t\t.map(\n\t\t\t\t(row) =>\n\t\t\t\t\t`| ${row.map((cell, column) => cell.padEnd(widths[column] ?? cell.length)).join(' | ')} |`,\n\t\t\t)\n\t\t\t.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\\n${table}\\n\\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_COLLECTION_ITEMS,\n\tMAX_DEPENDENCY_NAME_LENGTH,\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\t// The media type that selects the registry's abbreviated packument. It sits\n\t// with the request defaults because it is part of how this class asks for a\n\t// version, and it is asked for at exactly the two reads that want one.\n\tstatic readonly #packument = 'application/vnd.npm.install-v1+json'\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\tUpstream.#packument,\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(\n\t\t\tthis.#registryURL(name),\n\t\t\tthis.#registryTimeout,\n\t\t\tallowance,\n\t\t\tUpstream.#packument,\n\t\t)\n\t\tconst version = outcome.lookup === 'found' ? this.#latest(outcome.content) : undefined\n\t\tif (version !== undefined) {\n\t\t\treturn { name, lookup: 'found', version, dependencies: this.#edges(outcome.content, version) }\n\t\t}\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 runtime edges the published version declares, read from the same\n\t// abbreviated packument the version came from rather than from a second\n\t// request. Development edges are deliberately not read: they reach no\n\t// consumer, so they constrain nothing a publish order decides. A packument\n\t// that carries no readable edges answers none rather than failing the row,\n\t// because a package with no dependencies and a package whose manifest could\n\t// not be read both publish first, and the version is what the row promises.\n\t#edges(content: string, version: string): readonly Dependency[] {\n\t\tconst parsed = parseJSON(content)\n\t\tif (!isRecord(parsed)) return []\n\t\tconst versions = parsed.versions\n\t\tif (!isRecord(versions)) return []\n\t\tconst manifest = versions[version]\n\t\tif (!isRecord(manifest)) return []\n\t\tconst declared = manifest.dependencies\n\t\tif (!isRecord(declared)) return []\n\t\tconst edges: Dependency[] = []\n\t\tfor (const [name, range] of Object.entries(declared)) {\n\t\t\tif (edges.length >= MAX_COLLECTION_ITEMS) break\n\t\t\tif (typeof range !== 'string' || range.length === 0 || range.length > MAX_RANGE_LENGTH) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (CONTROL_CHARACTER_PATTERN.test(name) || CONTROL_CHARACTER_PATTERN.test(range)) continue\n\t\t\tif (name.length === 0 || name.length > MAX_DEPENDENCY_NAME_LENGTH) continue\n\t\t\tedges.push({ name, range })\n\t\t}\n\t\treturn edges\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 version is bounded\n\t// and control-free before it is admitted, so an upstream answer cannot smuggle\n\t// 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\t//\n\t// `accept` is stated only where an endpoint publishes more than one form of\n\t// the same answer, which is the packument alone. Every other read takes what\n\t// the endpoint serves, so no request declares a media type it has no reason to.\n\tasync #read(\n\t\turl: string,\n\t\ttimeout: number,\n\t\tallowance: { remaining: number },\n\t\taccept?: string,\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, accept)\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\taccept?: string,\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\t...(accept === undefined ? {} : { headers: { accept } }),\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. The stream is 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 decoded byte is spent whatever the verdict, because bytes a failed\n\t// read consumed are bytes the caller no longer has. `content-length` cannot\n\t// refuse early: it counts wire octets, while both bounds count decoded bytes,\n\t// and content encoding may make either count larger than the other.\n\t//\n\t// A status carrying no representation reaches this method too, because `ok`\n\t// covers the whole 2xx range. It is a verdict rather than an empty answer: a\n\t// zero-byte file arrives as a `200` with an empty stream and still reads as\n\t// found.\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 body = response.body\n\t\tif (body === null) {\n\t\t\treturn {\n\t\t\t\tlookup: 'failed',\n\t\t\t\tcontent: '',\n\t\t\t\tnote: `HTTP ${String(response.status)}, and the answer carries no body`,\n\t\t\t}\n\t\t}\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;;;;;;;;;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