@brucewaynedecoy/make-docs 2.0.4 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/{backup-CM7RL2Q7.js → backup-2OT4A6LR.js} +4 -4
  2. package/dist/{chunk-GERMRLJ2.js → chunk-46MGH32G.js} +6 -4
  3. package/dist/chunk-46MGH32G.js.map +1 -0
  4. package/dist/{chunk-LV3CBXZB.js → chunk-CCYP5NU2.js} +3 -3
  5. package/dist/{chunk-OR5ZVGLG.js → chunk-CLSOY7NV.js} +151 -5
  6. package/dist/chunk-CLSOY7NV.js.map +1 -0
  7. package/dist/{chunk-ADVNSMA7.js → chunk-CMNKQM7L.js} +3 -3
  8. package/dist/{chunk-YVSASZMT.js → chunk-HXWD2EUD.js} +19 -14
  9. package/dist/chunk-HXWD2EUD.js.map +1 -0
  10. package/dist/{chunk-65QWMODG.js → chunk-I4FADOUK.js} +3 -3
  11. package/dist/{chunk-65QWMODG.js.map → chunk-I4FADOUK.js.map} +1 -1
  12. package/dist/{chunk-M7DMFIKU.js → chunk-ISSMVKIA.js} +224 -20
  13. package/dist/chunk-ISSMVKIA.js.map +1 -0
  14. package/dist/{chunk-J5QDGRZ7.js → chunk-UNR4CYVX.js} +116 -37
  15. package/dist/chunk-UNR4CYVX.js.map +1 -0
  16. package/dist/{chunk-7R2PPKTB.js → chunk-VMKG3H4B.js} +2 -2
  17. package/dist/{chunk-52FTNVXS.js → chunk-XDSWX4Y4.js} +8906 -2899
  18. package/dist/chunk-XDSWX4Y4.js.map +1 -0
  19. package/dist/index.js +210 -86
  20. package/dist/index.js.map +1 -1
  21. package/dist/registry-PC5GKAKM.js +50 -0
  22. package/dist/registry-PC5GKAKM.js.map +1 -0
  23. package/dist/{self-36ULRIJ6.js → self-WYVXO23B.js} +10 -10
  24. package/dist/server-BQOG6FTA.js +1113 -0
  25. package/dist/server-BQOG6FTA.js.map +1 -0
  26. package/dist/{setup-system-JI36YJ6D.js → setup-system-KN7FTTLT.js} +263 -40
  27. package/dist/setup-system-KN7FTTLT.js.map +1 -0
  28. package/dist/{skills-command-IGDVLNKY.js → skills-command-KEW7MOEW.js} +17 -7
  29. package/dist/skills-command-KEW7MOEW.js.map +1 -0
  30. package/dist/{uninstall-VBGMQQLA.js → uninstall-45XF4CHD.js} +9 -9
  31. package/dist/virtual_make-docs-first-party-skills-ECJESFL2.js +11 -0
  32. package/dist/virtual_make-docs-first-party-skills-ECJESFL2.js.map +1 -0
  33. package/package.json +5 -5
  34. package/skill-registry.json +24 -8
  35. package/skill-registry.schema.json +2 -1
  36. package/template/.make-docs/system/contracts/system-resource-contract.md +16 -0
  37. package/template/.make-docs/system-resources.catalog.json +415 -0
  38. package/template/.make-docs/system-resources.schema.json +25 -0
  39. package/dist/chunk-52FTNVXS.js.map +0 -1
  40. package/dist/chunk-GERMRLJ2.js.map +0 -1
  41. package/dist/chunk-J5QDGRZ7.js.map +0 -1
  42. package/dist/chunk-M7DMFIKU.js.map +0 -1
  43. package/dist/chunk-OR5ZVGLG.js.map +0 -1
  44. package/dist/chunk-YVSASZMT.js.map +0 -1
  45. package/dist/server-H754TA4Q.js +0 -512
  46. package/dist/server-H754TA4Q.js.map +0 -1
  47. package/dist/setup-system-JI36YJ6D.js.map +0 -1
  48. package/dist/skills-command-IGDVLNKY.js.map +0 -1
  49. package/dist/virtual_make-docs-first-party-skills-H3FC47C2.js +0 -11
  50. package/dist/virtual_make-docs-first-party-skills-H3FC47C2.js.map +0 -1
  51. /package/dist/{backup-CM7RL2Q7.js.map → backup-2OT4A6LR.js.map} +0 -0
  52. /package/dist/{chunk-LV3CBXZB.js.map → chunk-CCYP5NU2.js.map} +0 -0
  53. /package/dist/{chunk-ADVNSMA7.js.map → chunk-CMNKQM7L.js.map} +0 -0
  54. /package/dist/{chunk-7R2PPKTB.js.map → chunk-VMKG3H4B.js.map} +0 -0
  55. /package/dist/{self-36ULRIJ6.js.map → self-WYVXO23B.js.map} +0 -0
  56. /package/dist/{uninstall-VBGMQQLA.js.map → uninstall-45XF4CHD.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/platform.ts","../src/store/paths.ts","../src/store/installation-state.ts","../../../node_modules/yaml/browser/dist/nodes/identity.js","../../../node_modules/yaml/browser/dist/visit.js","../../../node_modules/yaml/browser/dist/doc/directives.js","../../../node_modules/yaml/browser/dist/doc/anchors.js","../../../node_modules/yaml/browser/dist/doc/applyReviver.js","../../../node_modules/yaml/browser/dist/nodes/toJS.js","../../../node_modules/yaml/browser/dist/nodes/Node.js","../../../node_modules/yaml/browser/dist/nodes/Alias.js","../../../node_modules/yaml/browser/dist/nodes/Scalar.js","../../../node_modules/yaml/browser/dist/doc/createNode.js","../../../node_modules/yaml/browser/dist/nodes/Collection.js","../../../node_modules/yaml/browser/dist/stringify/stringifyComment.js","../../../node_modules/yaml/browser/dist/stringify/foldFlowLines.js","../../../node_modules/yaml/browser/dist/stringify/stringifyString.js","../../../node_modules/yaml/browser/dist/stringify/stringify.js","../../../node_modules/yaml/browser/dist/stringify/stringifyPair.js","../../../node_modules/yaml/browser/dist/log.js","../../../node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js","../../../node_modules/yaml/browser/dist/nodes/addPairToJSMap.js","../../../node_modules/yaml/browser/dist/nodes/Pair.js","../../../node_modules/yaml/browser/dist/stringify/stringifyCollection.js","../../../node_modules/yaml/browser/dist/nodes/YAMLMap.js","../../../node_modules/yaml/browser/dist/schema/common/map.js","../../../node_modules/yaml/browser/dist/nodes/YAMLSeq.js","../../../node_modules/yaml/browser/dist/schema/common/seq.js","../../../node_modules/yaml/browser/dist/schema/common/string.js","../../../node_modules/yaml/browser/dist/schema/common/null.js","../../../node_modules/yaml/browser/dist/schema/core/bool.js","../../../node_modules/yaml/browser/dist/stringify/stringifyNumber.js","../../../node_modules/yaml/browser/dist/schema/core/float.js","../../../node_modules/yaml/browser/dist/schema/core/int.js","../../../node_modules/yaml/browser/dist/schema/core/schema.js","../../../node_modules/yaml/browser/dist/schema/json/schema.js","../../../node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js","../../../node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js","../../../node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js","../../../node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js","../../../node_modules/yaml/browser/dist/schema/yaml-1.1/float.js","../../../node_modules/yaml/browser/dist/schema/yaml-1.1/int.js","../../../node_modules/yaml/browser/dist/schema/yaml-1.1/set.js","../../../node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js","../../../node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js","../../../node_modules/yaml/browser/dist/schema/tags.js","../../../node_modules/yaml/browser/dist/schema/Schema.js","../../../node_modules/yaml/browser/dist/stringify/stringifyDocument.js","../../../node_modules/yaml/browser/dist/doc/Document.js","../../../node_modules/yaml/browser/dist/errors.js","../../../node_modules/yaml/browser/dist/compose/resolve-props.js","../../../node_modules/yaml/browser/dist/compose/util-contains-newline.js","../../../node_modules/yaml/browser/dist/compose/util-flow-indent-check.js","../../../node_modules/yaml/browser/dist/compose/util-map-includes.js","../../../node_modules/yaml/browser/dist/compose/resolve-block-map.js","../../../node_modules/yaml/browser/dist/compose/resolve-block-seq.js","../../../node_modules/yaml/browser/dist/compose/resolve-end.js","../../../node_modules/yaml/browser/dist/compose/resolve-flow-collection.js","../../../node_modules/yaml/browser/dist/compose/compose-collection.js","../../../node_modules/yaml/browser/dist/compose/resolve-block-scalar.js","../../../node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js","../../../node_modules/yaml/browser/dist/compose/compose-scalar.js","../../../node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js","../../../node_modules/yaml/browser/dist/compose/compose-node.js","../../../node_modules/yaml/browser/dist/compose/compose-doc.js","../../../node_modules/yaml/browser/dist/compose/composer.js","../../../node_modules/yaml/browser/dist/parse/cst-visit.js","../../../node_modules/yaml/browser/dist/parse/cst.js","../../../node_modules/yaml/browser/dist/parse/lexer.js","../../../node_modules/yaml/browser/dist/parse/line-counter.js","../../../node_modules/yaml/browser/dist/parse/parser.js","../../../node_modules/yaml/browser/dist/public-api.js","../src/store/lease-recovery.ts","../src/store/database.ts","../src/store/global-asset-lock.ts","../src/manifest.ts","../src/agentic-skill-roles.ts","../src/types.ts","../src/managed-block.ts","../src/utils.ts","../src/profile.ts","../src/router-paths.ts","../src/system-assets.ts","../src/tool-directory.ts","../src/skill-paths.ts","../src/skill-registry.ts","../src/skill-catalog.ts","../src/skill-resolver.ts","../src/rules.ts","../src/catalog.ts"],"sourcesContent":["import {\n closeSync,\n constants,\n fchmodSync,\n fstatSync,\n fsyncSync,\n lstatSync,\n openSync,\n readdirSync,\n realpathSync,\n renameSync,\n statfsSync,\n type Stats,\n} from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nexport type CorePlatform = \"win32\" | \"darwin\" | \"linux\";\nexport type ProcessLiveness = \"alive\" | \"dead\" | \"unknown\";\nexport type GuardedFileKind = \"file\" | \"directory\";\n\nexport interface FileMutationGuard {\n strategy: \"object-number\" | \"metadata\";\n kind: GuardedFileKind;\n device?: number;\n inode?: number;\n size: number;\n mode: number;\n birthtimeMs: number;\n ctimeMs: number;\n}\n\nexport interface PlatformPath {\n displayPath: string;\n canonicalPath: string;\n comparisonKey: string;\n}\n\nexport interface PlatformService {\n readonly kind: CorePlatform;\n readonly hostname: string;\n readonly caseSensitiveComparison: boolean;\n readonly canMutateOpenPaths: boolean;\n userHome(options?: { homeDir?: string }): string;\n userDataRoot(options?: { env?: NodeJS.ProcessEnv; homeDir?: string }): string;\n describePath(input: string): PlatformPath;\n comparisonKey(input: string): string;\n samePath(left: string, right: string): boolean;\n isPathInside(root: string, candidate: string): boolean;\n assertPathInside(root: string, candidate: string): void;\n acceptsExecutableMode(mode: number): boolean;\n matchesFileMode(actual: number, expected: number): boolean;\n applyPrivateMode(fd: number, mode: number): void;\n findExecutable(executableName: string, executablePath?: string): string | null;\n processLiveness(pid: number, ownerHostname?: string): ProcessLiveness;\n captureFileGuard(stats: Stats, kind?: GuardedFileKind): FileMutationGuard;\n matchesFileGuard(stats: Stats, guard: FileMutationGuard): boolean;\n matchesFileIdentity(stats: Stats, guard: FileMutationGuard): boolean;\n sameFileObject(left: Stats, right: Stats, kind?: GuardedFileKind): boolean;\n atomicReplace(source: string, target: string): void;\n syncDirectory(directory: string): void;\n availableBytes(input: string): bigint;\n}\n\nexport class PlatformOperationError extends Error {\n constructor(\n readonly code:\n | \"unsupported-platform\"\n | \"unsafe-path\"\n | \"path-unavailable\"\n | \"atomic-replace-failed\"\n | \"directory-sync-failed\",\n message: string,\n readonly cause?: unknown,\n ) {\n super(message);\n this.name = \"PlatformOperationError\";\n }\n}\n\nfunction corePlatform(value: NodeJS.Platform): CorePlatform {\n if (value === \"win32\" || value === \"darwin\" || value === \"linux\") return value;\n throw new PlatformOperationError(\n \"unsupported-platform\",\n `Make Docs core file operations do not support ${value}. No files changed.`,\n );\n}\n\nfunction pathApi(kind: CorePlatform): typeof path.win32 | typeof path.posix {\n return kind === \"win32\" ? path.win32 : path.posix;\n}\n\n/** Pure path syntax normalization used by fixtures for every supported platform. */\nexport function normalizePathSyntax(\n input: string,\n kind: CorePlatform,\n cwd = kind === \"win32\" ? \"C:\\\\\" : \"/\",\n): string {\n if (!input.trim()) {\n throw new PlatformOperationError(\"unsafe-path\", \"A path cannot be empty.\");\n }\n const api = pathApi(kind);\n const normalized = api.isAbsolute(input) ? api.normalize(input) : api.resolve(cwd, input);\n const root = api.parse(normalized).root;\n return normalized.length > root.length ? normalized.replace(/[\\\\/]+$/, \"\") : normalized;\n}\n\n/** Pure comparison-key logic. Native path discovery is kept separate. */\nexport function comparisonKeyForPath(input: string, kind: CorePlatform, cwd?: string): string {\n const normalized = normalizePathSyntax(input, kind, cwd);\n return kind === \"win32\" ? normalized.replaceAll(\"/\", \"\\\\\").toLocaleLowerCase(\"en-US\") : normalized;\n}\n\nfunction canonicalNativePath(input: string, kind: CorePlatform): string {\n if (kind !== \"win32\" && (/^[A-Za-z]:[\\\\/]/.test(input) || input.startsWith(\"\\\\\\\\\"))) {\n throw new PlatformOperationError(\n \"unsafe-path\",\n \"A Windows drive or UNC path cannot identify local state on this host.\",\n );\n }\n let current = path.resolve(input);\n const missing: string[] = [];\n while (!lstatSync(current, { throwIfNoEntry: false })) {\n const parent = path.dirname(current);\n if (parent === current) {\n throw new PlatformOperationError(\"path-unavailable\", `The path cannot be resolved: ${input}`);\n }\n missing.unshift(path.basename(current));\n current = parent;\n }\n try {\n return path.join(realpathSync.native(current), ...missing);\n } catch (error) {\n throw new PlatformOperationError(\n \"path-unavailable\",\n `The path contains an unresolved link: ${current}`,\n error,\n );\n }\n}\n\nconst volumeCaseSensitivity = new Map<string, boolean>();\n\nfunction volumeUsesCaseSensitiveNames(input: string, kind: CorePlatform): boolean {\n if (kind === \"win32\") return false;\n if (kind === \"linux\") return true;\n let current = lstatSync(input, { throwIfNoEntry: false })?.isDirectory() ? input : path.dirname(input);\n const visited: string[] = [];\n const remember = (value: boolean): boolean => {\n for (const directory of visited) volumeCaseSensitivity.set(`${kind}:${directory}`, value);\n return value;\n };\n while (true) {\n const cached = volumeCaseSensitivity.get(`${kind}:${current}`);\n if (cached !== undefined) return remember(cached);\n visited.push(current);\n try {\n for (const name of readdirSync(current)) {\n const index = name.search(/[A-Za-z]/);\n if (index < 0) continue;\n const character = name[index];\n const changed = character === character.toLocaleLowerCase(\"en-US\")\n ? character.toLocaleUpperCase(\"en-US\")\n : character.toLocaleLowerCase(\"en-US\");\n const alternateName = `${name.slice(0, index)}${changed}${name.slice(index + 1)}`;\n if (alternateName === name) continue;\n const original = path.join(current, name);\n const alternate = path.join(current, alternateName);\n if (!lstatSync(alternate, { throwIfNoEntry: false })) return remember(true);\n return remember(realpathSync.native(original) !== realpathSync.native(alternate));\n }\n } catch {\n // Try an accessible parent. If none can prove the volume rule, preserve case.\n }\n const parent = path.dirname(current);\n if (parent === current) return remember(true);\n current = parent;\n }\n}\n\nfunction fileKind(stats: Stats): GuardedFileKind | null {\n if (stats.isFile()) return \"file\";\n if (stats.isDirectory()) return \"directory\";\n return null;\n}\n\nfunction hasObjectNumbers(stats: Stats): boolean {\n return Number.isSafeInteger(stats.dev) && Number.isSafeInteger(stats.ino) &&\n (stats.dev !== 0 || stats.ino !== 0);\n}\n\nexport function createPlatformService(\n platformValue: NodeJS.Platform = process.platform,\n hostname = os.hostname(),\n): PlatformService {\n const kind = corePlatform(platformValue);\n const nativeKind = corePlatform(process.platform);\n const caseSensitiveComparison = kind === \"win32\"\n ? false\n : kind === \"linux\"\n ? true\n : kind === nativeKind\n ? volumeUsesCaseSensitiveNames(canonicalNativePath(process.cwd(), kind), kind)\n : true;\n\n const describePath = (input: string): PlatformPath => {\n const canonicalPath = canonicalNativePath(input, kind);\n const caseSensitive = volumeUsesCaseSensitiveNames(canonicalPath, kind);\n return {\n displayPath: path.resolve(input),\n canonicalPath,\n comparisonKey: caseSensitive\n ? normalizePathSyntax(canonicalPath, kind, process.cwd())\n : normalizePathSyntax(canonicalPath, kind, process.cwd()).toLocaleLowerCase(\"en-US\"),\n };\n };\n\n const captureFileGuard = (stats: Stats, expected?: GuardedFileKind): FileMutationGuard => {\n const kindValue = fileKind(stats);\n if (!kindValue || (expected && kindValue !== expected)) {\n throw new PlatformOperationError(\"unsafe-path\", \"The guarded path has an unsupported file type.\");\n }\n return {\n strategy: hasObjectNumbers(stats) ? \"object-number\" : \"metadata\",\n kind: kindValue,\n ...(hasObjectNumbers(stats) ? { device: stats.dev, inode: stats.ino } : {}),\n size: stats.size,\n mode: stats.mode,\n birthtimeMs: stats.birthtimeMs,\n ctimeMs: stats.ctimeMs,\n };\n };\n\n const matchesFileGuard = (stats: Stats, guard: FileMutationGuard): boolean => {\n const currentKind = fileKind(stats);\n if (currentKind !== guard.kind) return false;\n if (guard.strategy === \"object-number\") {\n return stats.dev === guard.device && stats.ino === guard.inode;\n }\n const stableBirth = guard.birthtimeMs > 0 && stats.birthtimeMs > 0;\n return stats.mode === guard.mode && stats.size === guard.size &&\n (stableBirth\n ? stats.birthtimeMs === guard.birthtimeMs\n : stats.ctimeMs === guard.ctimeMs);\n };\n\n const matchesFileIdentity = (stats: Stats, guard: FileMutationGuard): boolean => {\n const currentKind = fileKind(stats);\n if (currentKind !== guard.kind) return false;\n if (guard.strategy === \"object-number\") {\n return stats.dev === guard.device && stats.ino === guard.inode;\n }\n const stableBirth = guard.birthtimeMs > 0 && stats.birthtimeMs > 0;\n return stableBirth\n ? stats.birthtimeMs === guard.birthtimeMs\n : stats.mode === guard.mode && stats.size === guard.size && stats.ctimeMs === guard.ctimeMs;\n };\n\n const service: PlatformService = {\n kind,\n hostname,\n caseSensitiveComparison,\n canMutateOpenPaths: kind !== \"win32\",\n userHome(options = {}) {\n return options.homeDir ?? os.homedir();\n },\n userDataRoot(options = {}) {\n const env = options.env ?? process.env;\n const homeDir = service.userHome({ homeDir: options.homeDir });\n if (kind === \"win32\") {\n return env.LOCALAPPDATA?.trim() || env.APPDATA?.trim() || homeDir;\n }\n return homeDir;\n },\n describePath,\n comparisonKey(input) {\n return describePath(input).comparisonKey;\n },\n samePath(left, right) {\n return service.comparisonKey(left) === service.comparisonKey(right);\n },\n isPathInside(root, candidate) {\n const rootPath = describePath(root);\n const candidatePath = describePath(candidate);\n const api = pathApi(kind);\n const relative = api.relative(rootPath.canonicalPath, candidatePath.canonicalPath);\n return relative === \"\" ||\n (!relative.startsWith(`..${api.sep}`) && relative !== \"..\" && !api.isAbsolute(relative));\n },\n assertPathInside(root, candidate) {\n if (service.isPathInside(root, candidate)) return;\n throw new PlatformOperationError(\n \"unsafe-path\",\n `The path escapes its approved root: ${path.resolve(candidate)}`,\n );\n },\n acceptsExecutableMode(mode) {\n return kind === \"win32\" || (mode & 0o111) !== 0;\n },\n matchesFileMode(actual, expected) {\n return kind === \"win32\" || (actual & 0o777) === (expected & 0o777);\n },\n applyPrivateMode(fd, mode) {\n if (kind !== \"win32\") fchmodSync(fd, mode);\n },\n findExecutable(executableName, executablePath = process.env.PATH ?? \"\") {\n const api = pathApi(kind);\n const pathEntries = executablePath.split(api.delimiter).filter(Boolean);\n const suffixes = kind === \"win32\"\n ? (process.env.PATHEXT ?? \".COM;.EXE;.BAT;.CMD\").split(\";\").filter(Boolean)\n : [\"\"];\n const names = kind === \"win32\" && !path.win32.extname(executableName)\n ? [executableName, ...suffixes.map(suffix => `${executableName}${suffix.toLocaleLowerCase(\"en-US\")}`)]\n : [executableName];\n for (const entry of pathEntries) {\n for (const name of [...new Set(names)]) {\n const candidate = api.join(entry, name);\n try {\n const stat = lstatSync(candidate);\n if (stat.isFile() && service.acceptsExecutableMode(stat.mode)) return candidate;\n } catch {\n // A PATH entry that cannot be read cannot prove an executable.\n }\n }\n }\n return null;\n },\n processLiveness(pid, ownerHostname = hostname) {\n if (!Number.isSafeInteger(pid) || pid <= 0 || ownerHostname !== hostname) return \"unknown\";\n try {\n process.kill(pid, 0);\n return \"alive\";\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"ESRCH\" ? \"dead\" : \"unknown\";\n }\n },\n captureFileGuard,\n matchesFileGuard,\n matchesFileIdentity,\n sameFileObject(left, right, expected) {\n return matchesFileIdentity(right, captureFileGuard(left, expected));\n },\n atomicReplace(source, target) {\n try {\n renameSync(source, target);\n } catch (error) {\n throw new PlatformOperationError(\n \"atomic-replace-failed\",\n `Atomic replacement failed. The reviewed target was preserved: ${target}`,\n error,\n );\n }\n service.syncDirectory(path.dirname(target));\n },\n syncDirectory(directory) {\n if (kind === \"win32\") return;\n let fd: number | null = null;\n try {\n const directoryFlag = typeof constants.O_DIRECTORY === \"number\" ? constants.O_DIRECTORY : 0;\n fd = openSync(directory, constants.O_RDONLY | directoryFlag);\n const stat = fstatSync(fd);\n if (!stat.isDirectory()) {\n throw new PlatformOperationError(\"unsafe-path\", `The sync target is not a directory: ${directory}`);\n }\n fsyncSync(fd);\n } catch (error) {\n if (error instanceof PlatformOperationError) throw error;\n throw new PlatformOperationError(\n \"directory-sync-failed\",\n `The replacement completed, but its directory sync failed: ${directory}`,\n error,\n );\n } finally {\n if (fd !== null) closeSync(fd);\n }\n },\n availableBytes(input) {\n try {\n const stats = statfsSync(input, { bigint: true });\n return stats.bavail * stats.bsize;\n } catch (error) {\n throw new PlatformOperationError(\n \"path-unavailable\",\n `Available storage space cannot be verified for: ${path.resolve(input)}`,\n error,\n );\n }\n },\n };\n return Object.freeze(service);\n}\n\nexport const platform = createPlatformService();\n","import path from \"node:path\";\nimport { platform } from \"../platform\";\n\n/**\n * Environment variable that overrides the global store root. Tests and\n * sandboxed environments set this so the store never touches the real\n * `~/.make-docs/` directory.\n */\nexport const STORE_ROOT_ENV_VAR = \"MAKE_DOCS_HOME\";\n\n/** Directory name of the global store under the user's home directory. */\nexport const STORE_DIR_NAME = \".make-docs\";\n\n/** Global configuration file (machine-level and tool-level settings). */\nexport const GLOBAL_CONFIG_FILE = \"config.json\";\n\n/** Global manifest file (tool-level state). */\nexport const GLOBAL_MANIFEST_FILE = \"manifest.json\";\n\n/** SQLite database file (operational data). */\nexport const STORE_DATABASE_FILE = \"store.db\";\n\nexport interface ResolveStoreRootOptions {\n /** Explicit store root; wins over the environment and the home directory. */\n storeRoot?: string;\n /** Environment to consult for {@link STORE_ROOT_ENV_VAR}. Defaults to `process.env`. */\n env?: NodeJS.ProcessEnv;\n /** Home directory used for the default `~/.make-docs` location. */\n homeDir?: string;\n}\n\n/**\n * Resolves the global store root. Precedence: explicit option, then the\n * `MAKE_DOCS_HOME` environment variable, then `~/.make-docs`.\n */\nexport function resolveStoreRoot(options: ResolveStoreRootOptions = {}): string {\n if (options.storeRoot) {\n return platform.describePath(options.storeRoot).displayPath;\n }\n const env = options.env ?? process.env;\n const envRoot = env[STORE_ROOT_ENV_VAR];\n if (envRoot && envRoot.trim() !== \"\") {\n return platform.describePath(envRoot).displayPath;\n }\n return path.join(platform.userDataRoot({ env, homeDir: options.homeDir }), STORE_DIR_NAME);\n}\n\nexport function getGlobalConfigPath(storeRoot: string): string {\n return path.join(storeRoot, GLOBAL_CONFIG_FILE);\n}\n\nexport function getGlobalManifestPath(storeRoot: string): string {\n return path.join(storeRoot, GLOBAL_MANIFEST_FILE);\n}\n\nexport function getStoreDatabasePath(storeRoot: string): string {\n return path.join(storeRoot, STORE_DATABASE_FILE);\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport { existsSync, lstatSync, mkdirSync, readFileSync, writeFileSync, openSync, closeSync, fsyncSync, unlinkSync, readdirSync, rmdirSync, symlinkSync, readlinkSync, chmodSync, fstatSync } from 'node:fs';\nimport path from 'node:path';\nimport { parseDocument } from 'yaml';\nimport { recoverDeadStoreLeases } from './lease-recovery';\nimport { acquireGlobalAssetLock, assertGlobalAssetLockActive, releaseGlobalAssetLock, type GlobalAssetLock } from './global-asset-lock';\nimport { acquireStoreAccess, applyStoreMigrations, classifyStoreCheckpoint9State, CURRENT_STORE_SCHEMA_VERSION, formatStoreIssue, isSqliteContention, makeStoreIssue, openStoreSqliteConnection, STORE_BUSY_TIMEOUT_MS, STORE_OWNER_WAIT_MS, StoreUnavailableError, tryCreateExclusiveStoreLease, waitForStoreAccessToDrain, waitForStoreRetry, type StoreDatabase, type StoreIssue } from './database';\nimport { resolveStoreRoot, getStoreDatabasePath } from './paths';\nimport { validateAndMigrateManifest } from '../manifest';\nimport type { InstallManifest, ManifestFileEntry } from '../types';\nimport { getCanonicalSkillDirectory, getHarnessSkillDirectory } from '../skill-paths';\nimport { platform, PlatformOperationError, type FileMutationGuard } from '../platform';\nexport class InstallationStateError extends Error {\n constructor(readonly code: 'store-unavailable' | 'writer-active' | 'ownership-unverified' | 'recovery-required' | 'snapshot-drift', message: string, readonly issue?: StoreIssue) { super(message); this.name = 'InstallationStateError'; }\n}\nexport interface InstallationLock {\n projectRoot: string;\n storeRoot: string;\n token: string;\n lockPath: string;\n}\ninterface HeldLock extends InstallationLock {\n depth: number;\n releaseAccess: () => void;\n globalLock?: GlobalAssetLock;\n}\ninterface Checkout {\n checkout_id: string;\n project_id: string;\n root_path: string;\n root_path_key: string | null;\n verified_at: string | null;\n verification_json: string | null;\n}\n\ninterface CheckoutVerificationEvidence {\n schemaVersion: 1;\n projectId: string;\n configDigest: string | null;\n ledgerDigest: string | null;\n managedContentDigest: string | null;\n}\ninterface Operation {\n operation_id: string;\n checkout_id: string;\n operation: string;\n status: string;\n before_ledger: string | null;\n after_ledger: string | null;\n plan_complete: number;\n}\n\nexport type CompletedRemovalHandoffReview =\n | { status: 'none' }\n | {\n status: 'ready';\n operationId: string;\n projectId: string;\n checkoutId: string;\n beforeManifest: InstallManifest;\n backupRoot: string;\n removedPaths: string[];\n preservedPaths: string[];\n }\n | {\n status: 'blocked';\n operationId: string;\n projectId: string;\n checkoutId: string;\n blockers: string[];\n nextAction: string;\n };\nexport interface InstallationFileState {\n kind: 'missing' | 'file' | 'directory' | 'symlink';\n digest?: string;\n payload?: string;\n mode?: number;\n target?: string;\n /** Detached plans keep recovery bytes in the Store, never in a local plan. */\n contentBase64?: string;\n}\ntype FileState = InstallationFileState;\ninterface Step {\n ordinal: number;\n relative_path: string;\n before_json: string;\n after_json: string;\n applied: number;\n}\nexport type PlannedFileState = {\n kind: 'missing';\n} | {\n kind: 'directory';\n} | {\n kind: 'file';\n content: string | Uint8Array;\n mode?: number;\n} | {\n kind: 'symlink';\n target: string;\n};\nconst held = new Map<string, HeldLock>();\nlet reviewedStoreBridgeDepth = 0;\nconst active = new Map<string, {\n id: string;\n storeRoot: string;\n projectId: string;\n depth: number;\n}>();\nconst sha = (bytes: string | Uint8Array) => createHash('sha256').update(bytes).digest('hex');\nconst now = () => new Date().toISOString();\n\nfunction isRetiredSkillPath(root: string, relative: string): boolean {\n const absolute = path.resolve(root, relative);\n return [root, platform.userHome()].some(base => inside(path.join(base, '.make-docs/agentics'), absolute));\n}\n\n/** New children are absent while their exact reviewed former exposure is still a link. */\nfunction underSavedBeforeLink(root: string, relative: string, changes: DetachedInstallationPlan['changes']): boolean {\n const absolute = path.resolve(root, relative);\n return changes.some(change => {\n const ancestor = path.resolve(root, change.path);\n return absolute !== ancestor && inside(ancestor, absolute) && change.before.kind === 'symlink'\n && changes.some(final => final.path === change.path && final.after.kind === 'directory')\n && matches(root, change.path, change.before);\n });\n}\n\nexport interface DetachedInstallationPlan {\n schemaVersion: 1;\n reviewDigest: string;\n mode: 'cli' | 'manual';\n metadata: unknown;\n changes: Array<{ path: string; before: InstallationFileState; after: InstallationFileState }>;\n afterLedger?: InstallManifest | null;\n /** Only setup.skills.adopt may opt into the bounded Skill path policy. */\n skillScope?: { roots: string[]; symlinkTargets: Record<string, string>; beforeSymlinkTargets?: Record<string, string>; bootstrapPaths?: string[]; backupRoots?: string[] };\n copyFallbacks?: Record<string, {\n changes: Array<{path: string; before: InstallationFileState; after: InstallationFileState}>;\n ledgerEntry: ManifestFileEntry;\n }>;\n /** Written only by the executor after a proved no-effect symlink failure. */\n selectedCopyFallbacks?: string[];\n}\nexport interface InstallationPathClaim {\n checkoutId: string;\n projectId: string;\n rootPath: string;\n path: string;\n kind: 'ownership' | 'pending';\n operationId?: string;\n}\n/** Read current ownership and pending intent without creating a Store or binding. */\nexport function readInstallationPathClaims(projectRoot: string, roots: string[], storeRoot?: string): InstallationPathClaim[] {\n const root = canonicalInstallationPath(projectRoot);\n if (!hasInstallationSchema(root, storeRoot)) return [];\n const requested = roots.map(p => { const absolute = path.resolve(root, p); return path.join(canonicalInstallationPath(path.dirname(absolute)), path.basename(absolute)); });\n return withInstallationDatabase(root, db => {\n const claims: InstallationPathClaim[] = [];\n const append = (row: Checkout, p: string, kind: InstallationPathClaim['kind'], operationId?: string) => {\n const resolved = path.resolve(row.root_path, p);\n const absolute = path.join(canonicalInstallationPath(path.dirname(resolved)), path.basename(resolved));\n if (requested.some(r => inside(r, absolute) || inside(absolute, r))) claims.push({checkoutId: row.checkout_id, projectId: row.project_id, rootPath: row.root_path, path: absolute, kind, ...(operationId ? {operationId} : {})});\n };\n for (const row of db.prepare('SELECT * FROM installation_checkouts').all() as unknown as Checkout[]) {\n const ledger = db.prepare('SELECT manifest_json FROM installation_ledgers WHERE checkout_id=?').get(row.checkout_id) as {manifest_json: string} | undefined;\n if (ledger) for (const p of Object.keys((JSON.parse(ledger.manifest_json) as InstallManifest).files)) append(row, p, 'ownership');\n for (const op of db.prepare(\"SELECT * FROM installation_operations WHERE checkout_id=? AND status='pending'\").all(row.checkout_id) as unknown as Operation[]) {\n for (const step of db.prepare('SELECT relative_path FROM installation_steps WHERE operation_id=?').all(op.operation_id) as {relative_path: string}[]) append(row, step.relative_path, 'pending', op.operation_id);\n const intendedLedger = op.after_ledger ? JSON.parse(op.after_ledger) as InstallManifest | null : null;\n if (intendedLedger) for (const p of Object.keys(intendedLedger.files)) append(row, p, 'pending', op.operation_id);\n }\n }\n return [...new Map(claims.map(c => [canonicalJson(c), c])).values()].sort((a, b) => canonicalJson(a).localeCompare(canonicalJson(b)));\n }, {storeRoot, readOnly: true});\n}\nfunction assertNoOtherPendingPathClaims(root: string, paths: string[], storeRoot?: string): void {\n if (!paths.length) return;\n // Ordinary writers need pending reservations only. Do not parse every committed ledger per file.\n const conflict = withInstallationDatabase(root, db => {\n const pending = db.prepare(\"SELECT o.operation_id,o.after_ledger,c.root_path FROM installation_operations o JOIN installation_checkouts c ON c.checkout_id=o.checkout_id WHERE o.status='pending' AND c.root_path<>?\").all(root) as {operation_id: string; after_ledger: string | null; root_path: string}[];\n if (!pending.length) return undefined;\n const canonicalPath = (base: string, p: string) => { const absolute = path.resolve(base, p); return path.join(canonicalInstallationPath(path.dirname(absolute)), path.basename(absolute)); };\n const requested = paths.map(p => canonicalPath(root, p));\n for (const op of pending) {\n const planned = db.prepare('SELECT relative_path FROM installation_steps WHERE operation_id=?').all(op.operation_id) as {relative_path: string}[];\n const intendedLedger = op.after_ledger ? JSON.parse(op.after_ledger) as InstallManifest | null : null;\n const reserved = [...planned.map(step => step.relative_path), ...Object.keys(intendedLedger?.files ?? {})];\n for (const p of reserved) {\n const absolute = canonicalPath(op.root_path, p);\n if (requested.some(r => inside(r, absolute) || inside(absolute, r))) return {operationId: op.operation_id, rootPath: op.root_path, path: absolute};\n }\n }\n return undefined;\n }, {storeRoot, readOnly: true});\n if (conflict) fail('recovery-required', `Pending operation ${conflict.operationId} in ${conflict.rootPath} reserves ${conflict.path}. Recover that operation before overlapping managed writes.`);\n}\ninterface DetachedOperationHooks {\n validate(root: string, metadata: unknown, phase: 'before' | 'after' | 'progress', temporaryFiles?: Record<string, FileState>): string[];\n beforeRetiredCleanup?(root: string, metadata: unknown): string[];\n nextAction(root: string, operationId: string, mode: 'cli' | 'manual'): string;\n}\nconst detachedHooks = new Map<string, DetachedOperationHooks>();\n/** Domain checks extend the same journal and recovery executor used by setup. */\nexport function registerDetachedInstallationOperation(operation: string, hooks: DetachedOperationHooks): void {\n if (detachedHooks.has(operation)) throw new Error(`Duplicate detached operation: ${operation}`);\n detachedHooks.set(operation, hooks);\n}\nfunction detachedSnapshot(db: StoreDatabase, op: Operation): DetachedInstallationPlan | null {\n const record = db.prepare(\"SELECT record_json FROM installation_migration_records WHERE checkout_id=? AND kind='snapshot' AND record_id=?\").get(op.checkout_id, `detached:${op.operation_id}`) as {record_json: string} | undefined;\n if (!record) {\n if (detachedHooks.has(op.operation) || op.operation.startsWith('project.layout')) fail('recovery-required', 'The saved layout plan is missing. Preserve the files and restore its Store evidence.');\n return null;\n }\n const envelope = JSON.parse(record.record_json) as { digest: string; plan: DetachedInstallationPlan };\n if (!envelope.plan || sha(canonicalJson(envelope.plan)) !== envelope.digest || envelope.plan.schemaVersion !== 1 || !['cli', 'manual'].includes(envelope.plan.mode) || !Array.isArray(envelope.plan.changes)) fail('snapshot-drift', 'The saved operation plan is invalid or changed.');\n if (envelope.plan.afterLedger !== undefined && canonicalJson(envelope.plan.afterLedger) !== canonicalJson(op.after_ledger ? JSON.parse(op.after_ledger) : null)) fail('snapshot-drift', 'The saved plan and final ownership ledger disagree.');\n const steps = db.prepare('SELECT * FROM installation_steps WHERE operation_id=? ORDER BY ordinal').all(op.operation_id) as unknown as Step[];\n if (steps.length !== envelope.plan.changes.length || steps.some((step, index) => step.relative_path !== envelope.plan.changes[index].path || canonicalJson(JSON.parse(step.before_json)) !== canonicalJson(envelope.plan.changes[index].before) || canonicalJson(JSON.parse(step.after_json)) !== canonicalJson(envelope.plan.changes[index].after))) fail('snapshot-drift', 'The saved plan and file journal disagree.');\n if (!detachedHooks.has(op.operation)) fail('recovery-required', `This CLI cannot validate the saved ${op.operation} operation.`);\n return envelope.plan;\n}\nfunction validateDetached(root: string, op: Operation, plan: DetachedInstallationPlan | null, phase: 'before' | 'after' | 'progress', temporaryFiles?: Record<string, FileState>): string[] {\n return plan ? detachedHooks.get(op.operation)!.validate(root, plan.metadata, phase, temporaryFiles) : [];\n}\nfunction assertDetachedPaths(root: string, plan: DetachedInstallationPlan, checkBefore = true, operation?: string, hypotheticalFallback = false): void {\n if ([...Object.keys(plan.afterLedger?.files ?? {}), ...(plan.afterLedger?.skillFiles ?? [])].some(p => isRetiredSkillPath(root, p))) fail('recovery-required', 'The saved final ownership uses retired .make-docs/agentics paths. Use a current reviewed Skill layout cutover.');\n if ((plan.skillScope || plan.copyFallbacks) && operation !== 'setup.skills.adopt') fail('ownership-unverified', 'Skill path policy is only valid for reviewed Skill adoption.');\n if (operation === 'setup.skills.adopt' && !plan.skillScope) fail('ownership-unverified', 'Adoption requires its complete selected Skill roots.');\n const selected = plan.afterLedger?.selections;\n const permittedDirectories = [path.join(root,'.agents/skills'),path.join(root,'.claude/skills'),path.join(root,'.codex/skills'),path.join(root,'.make-docs/agentics/skills'),path.join(platform.userHome(),'.agents/skills'),path.join(platform.userHome(),'.claude/skills'),path.join(platform.userHome(),'.codex/skills'),path.join(platform.userHome(),'.make-docs/agentics/skills'),getHarnessSkillDirectory('codex','global'),getHarnessSkillDirectory('claude-code','global')].map(p=>path.resolve(p));\n const canonicalDirectory = selected ? path.resolve(selected.skillScope === 'project' ? root : platform.userHome(),getCanonicalSkillDirectory(selected)) : '';\n const skillRoots = plan.skillScope?.roots.map(p => {\n const absolute = path.resolve(root, p);\n if (!permittedDirectories.includes(path.dirname(absolute)) || !/^[a-z0-9][a-z0-9-]*$/.test(path.basename(absolute))) fail('ownership-unverified', `Invalid selected Skill root: ${p}`);\n if (!plan.afterLedger?.selections.selectedSkills.includes(path.basename(absolute))) fail('ownership-unverified', 'Skill root is not in the selected set.');\n assertSafeFilePath(root, p);\n return absolute;\n }) ?? [];\n const bootstrap = (plan.skillScope?.bootstrapPaths ?? []).map(p => {\n const router = plan.afterLedger?.routerOwnership?.routers[p];\n if (path.isAbsolute(p) || !router || router.relativePath !== p || router.routerClass !== 'bootstrap' || !plan.afterLedger?.files[p] || !/^(?:(?:docs(?:\\/(?:designs|plans|prd|work))?|\\.make-docs(?:\\/system(?:\\/(?:contracts|references|prompts|templates))?)?)\\/)?(?:AGENTS|CLAUDE)\\.md$/.test(p)) fail('ownership-unverified', `Unproved bootstrap router: ${p}`);\n return path.resolve(root, p);\n });\n const backups = (plan.skillScope?.backupRoots ?? []).map(p => {\n if (!/^\\.make-docs\\/backup\\/skill-adoption-[a-f0-9]{12}$/.test(p) || (checkBefore && inspect(root, p).kind !== 'missing')) fail('ownership-unverified', 'Adoption backup must use its reviewed, initially absent root.');\n return path.resolve(root, p);\n });\n const checkSkillPath = (change: DetachedInstallationPlan['changes'][number]) => {\n const absolute = path.resolve(root, change.path);\n const identity = change.path === '.make-docs/config.yaml';\n const backup = backups.some(p => inside(p, absolute));\n if (!backup && isRetiredSkillPath(root,change.path) && change.after.kind !== 'missing') fail('recovery-required','This saved plan would recreate retired .make-docs/agentics paths. Preserve its evidence; use a current reviewed Skill layout cutover.');\n const parentOnly = [...skillRoots, ...bootstrap, ...backups, path.join(root, '.make-docs/config.yaml')].some(p => inside(absolute, p)) && change.before.kind !== 'file' && change.after.kind !== 'file' && change.before.kind !== 'symlink' && change.after.kind !== 'symlink';\n if (absolute === root || absolute === platform.userHome() || (!identity && !parentOnly && !backup && !bootstrap.includes(absolute) && !skillRoots.some(p => inside(p, absolute)))) fail('ownership-unverified', `Path is outside the reviewed Skill roots: ${change.path}`);\n if (backup && (change.before.kind !== 'missing' || !['file', 'directory'].includes(change.after.kind))) fail('ownership-unverified', 'Adoption backups cannot replace existing content.');\n if (backup && change.after.kind === 'file' && !plan.changes.some(c => c.before.kind === 'file' && c.before.digest === change.after.digest && c.before.contentBase64 === change.after.contentBase64)) fail('ownership-unverified', 'Backup bytes do not match reviewed existing content.');\n if (identity && change.after.kind === 'file') {\n const config = parseDocument(Buffer.from(change.after.contentBase64 ?? '', 'base64').toString('utf8')).toJS() as {projectId?: string} | null;\n if (!config || config.projectId !== plan.afterLedger?.projectId) fail('ownership-unverified', 'The prepared config and final ledger identities disagree.');\n }\n };\n const prior = new Map<string, FileState>();\n const lastSteps = new Map<string, Step>();\n plan.changes.forEach((change, index) => lastSteps.set(change.path, {ordinal: index + 1, relative_path: change.path, before_json: JSON.stringify(change.before), after_json: JSON.stringify(change.after), applied: 0}));\n for (const change of plan.changes) {\n if (!change.path || change.path === '.' || (!plan.skillScope && path.isAbsolute(change.path)) || change.path.includes('\\\\') || change.path.split('/').slice(path.isAbsolute(change.path) ? 1 : 0).some(part => !part || part === '.' || part === '..')) fail('ownership-unverified', 'A saved operation path cannot escape its reviewed scope.');\n if (plan.skillScope) checkSkillPath(change);\n // A later, verified parent link subsumes removed children. Never walk that link to inspect the old tree.\n const removedUnderRecordedAncestor = !checkBefore && change.after.kind === 'missing' && subsumedByAncestor(root, lastSteps.get(change.path)!, lastSteps);\n const absentUnderOldLink = change.before.kind === 'missing' && underSavedBeforeLink(root,change.path,plan.changes);\n if (!hypotheticalFallback && !removedUnderRecordedAncestor && !absentUnderOldLink) assertSafeFilePath(root, change.path);\n for (const [index,state] of [change.before, change.after].entries()) {\n if (!['missing', 'directory', 'file', 'symlink'].includes(state.kind) || state.payload !== undefined) fail('ownership-unverified', 'Unsupported detached file state.');\n if (state.kind === 'file' && (typeof state.contentBase64 !== 'string' || sha(Buffer.from(state.contentBase64, 'base64')) !== state.digest || !Number.isInteger(state.mode) || state.mode! < 0 || state.mode! > 0o777)) fail('snapshot-drift', `Saved file bytes or mode are invalid: ${change.path}`);\n if (state.kind === 'symlink') {\n const target = index === 0 ? plan.skillScope?.beforeSymlinkTargets?.[change.path] ?? plan.skillScope?.symlinkTargets[change.path] : plan.skillScope?.symlinkTargets[change.path];\n const destination = target ? path.resolve(path.dirname(path.resolve(root,change.path)),target) : '';\n if (!target || state.target !== target || destination === path.resolve(root,change.path) || !skillRoots.includes(destination) || (index === 1 && path.dirname(destination) !== canonicalDirectory)) fail('ownership-unverified', 'Only the exact reviewed native Skill link target is allowed.');\n }\n }\n const preceding = prior.get(change.path);\n if (preceding && canonicalJson(preceding) !== canonicalJson(change.before)) fail('snapshot-drift', `Non-contiguous file plan: ${change.path}`);\n if (checkBefore && !preceding && !absentUnderOldLink && !matches(root, change.path, change.before)) fail('snapshot-drift', `Input changed before preparation: ${change.path}`);\n prior.set(change.path, change.after);\n }\n for (const [exposure, fallback] of Object.entries(plan.copyFallbacks ?? {})) {\n const trigger = plan.changes.find(c => c.path === exposure && c.after.kind === 'symlink');\n const selected = plan.selectedCopyFallbacks?.includes(exposure);\n if ((!selected && (!trigger || trigger.before.kind !== 'missing')) || !fallback.changes.length || fallback.changes.some(c => !inside(path.resolve(root, exposure), path.resolve(root, c.path)) || c.before.kind !== 'missing' || !['file', 'directory'].includes(c.after.kind)) || fallback.ledgerEntry.skillExposure?.mode !== 'copy-mirror') fail('ownership-unverified', 'Invalid predeclared native copy fallback.');\n if (selected && canonicalJson(plan.afterLedger?.files[exposure]) !== canonicalJson(fallback.ledgerEntry)) fail('snapshot-drift', 'Selected copy fallback and ledger disagree.');\n assertDetachedPaths(root, {...plan, changes: fallback.changes, copyFallbacks: undefined}, false, operation, true);\n }\n}\n/** Persist a sealed plan without creating config, project backup files, or changing content. */\nexport function prepareDetachedInstallationOperation(projectRoot: string, operation: string, build: () => DetachedInstallationPlan, storeRoot?: string) {\n const root = canonicalInstallationPath(projectRoot);\n if (!lstatSync(root, {throwIfNoEntry: false})?.isDirectory()) fail('ownership-unverified', 'Layout preparation requires an existing project directory.');\n const hooks = detachedHooks.get(operation);\n if (!hooks) fail('recovery-required', 'No validator is registered for this operation.');\n const lock = acquireInstallationLock(root, storeRoot);\n try {\n if (operation === 'setup.skills.adopt') held.get(root)!.globalLock = acquireGlobalAssetLock(root);\n const plan = build();\n if (plan.selectedCopyFallbacks?.length) fail('ownership-unverified', 'A new adoption cannot claim an executor-selected fallback.');\n const issues = hooks.validate(root, plan.metadata, 'before');\n if (issues.length) fail('snapshot-drift', issues.join('\\n'));\n assertDetachedPaths(root, plan, true, operation);\n assertNoOtherPendingPathClaims(root, [...plan.changes.map(c => c.path), ...Object.keys(plan.afterLedger?.files ?? {})], lock.storeRoot);\n const id = randomUUID();\n withInstallationDatabase(root, db => transaction(db, () => {\n const row = bindCheckout(db, root, operation === 'setup.skills.adopt' ? plan.afterLedger?.projectId : undefined);\n const pending = db.prepare(\"SELECT operation_id FROM installation_operations WHERE checkout_id=? AND status='pending'\").get(row.checkout_id) as {operation_id: string} | undefined;\n if (pending) fail('recovery-required', `Operation ${pending.operation_id} is pending. Inspect project state status.`);\n const ledger = (db.prepare('SELECT manifest_json FROM installation_ledgers WHERE checkout_id=?').get(row.checkout_id) as {manifest_json: string} | undefined)?.manifest_json ?? null;\n const afterLedger = plan.afterLedger === undefined ? ledger : plan.afterLedger === null ? null : JSON.stringify(plan.afterLedger);\n if (afterLedger) {\n const validated = validateAndMigrateManifest(JSON.parse(afterLedger), 'Prepared layout installation ledger');\n if (validated.projectId !== row.project_id) fail('ownership-unverified', 'The prepared ledger belongs to another project.');\n }\n db.prepare(\"INSERT INTO installation_operations (operation_id,checkout_id,operation,status,before_ledger,after_ledger,created_at,finished_at,plan_complete) VALUES (?,?,?,'pending',?,?,?,NULL,1)\").run(id, row.checkout_id, operation, ledger, afterLedger, now());\n for (const [index, change] of plan.changes.entries()) db.prepare('INSERT INTO installation_steps VALUES (?,?,?,?,?,0)').run(id, index + 1, change.path, JSON.stringify(change.before), JSON.stringify(change.after));\n db.prepare(\"INSERT INTO installation_migration_records VALUES (?,'snapshot',?,?)\").run(row.checkout_id, `detached:${id}`, JSON.stringify({digest: sha(canonicalJson(plan)), plan}));\n if (operation === 'setup.skills.adopt') db.prepare(\"INSERT INTO installation_migration_records VALUES (?,'snapshot',?,?)\").run(row.checkout_id, `detached-original:${id}`, JSON.stringify({digest: sha(canonicalJson(plan)), plan}));\n }), {storeRoot: lock.storeRoot});\n // Read the committed receipt back before giving a mover instructions.\n withInstallationDatabase(root, db => {\n const op = db.prepare('SELECT * FROM installation_operations WHERE operation_id=?').get(id) as unknown as Operation;\n if (!op || !detachedSnapshot(db, op)) fail('recovery-required', 'The prepared operation could not be read back.');\n }, {storeRoot: lock.storeRoot, readOnly: true});\n assertInstallationLockActive(lock);\n return {schemaVersion: 1 as const, operationId: id, status: 'pending' as const, mode: plan.mode, reviewDigest: plan.reviewDigest, nextAction: hooks.nextAction(root, id, plan.mode)};\n } finally { releaseInstallationLock(lock); }\n}\nexport function readDetachedInstallationOperation(projectRoot: string, operationId: string, operation: string, storeRoot?: string) {\n const root = canonicalInstallationPath(projectRoot);\n return withInstallationDatabase(root, db => {\n const row = checkout(db, root);\n if (!row) fail('ownership-unverified', 'No checkout binding for this operation.');\n assertCheckoutIdentity(row, root);\n const op = db.prepare('SELECT * FROM installation_operations WHERE operation_id=? AND checkout_id=?').get(operationId, row.checkout_id) as unknown as Operation | undefined;\n if (!op || op.operation !== operation) fail('ownership-unverified', 'This operation does not belong to the requested layout and checkout.');\n const plan = detachedSnapshot(db, op);\n if (!plan) fail('recovery-required', 'The complete saved operation plan is absent.');\n return {status: op.status, plan};\n }, {storeRoot, readOnly: true});\n}\nfunction fail(code: ConstructorParameters<typeof InstallationStateError>[0], message: string, issue?: StoreIssue): never { throw new InstallationStateError(code, message, issue); }\n/** Resolve absent leaves without trusting a symlink spelling of an external path. */\nexport function canonicalInstallationPath(input: string): string {\n try {\n return platform.describePath(input).canonicalPath;\n }\n catch (error) {\n const message = error instanceof PlatformOperationError ? error.message : `The path cannot be resolved: ${input}`;\n return fail('store-unavailable', message);\n }\n}\nfunction inside(root: string, candidate: string): boolean { const rel = path.relative(root, candidate); return rel === '' || (!rel.startsWith(`..${path.sep}`) && rel !== '..' && !path.isAbsolute(rel)); }\nexport function validateInstallationStoreRoot(projectRoot: string, storeRoot = resolveStoreRoot()): string {\n const project = canonicalInstallationPath(projectRoot);\n const store = canonicalInstallationPath(storeRoot);\n if (inside(project, store)) {\n const issue = makeStoreIssue('unsafe-path', store, 'validate Store root', new Error('The Make Docs Store must be outside the project.'));\n fail('store-unavailable', formatStoreIssue(issue), issue);\n }\n for (const suffix of ['store.db', 'store.db-wal', 'store.db-shm', 'store-access.lock', 'removal.lock', 'installation-bootstrap.lock', 'installation-lease-recovery.lock']) {\n const child = path.join(store, suffix);\n try {\n if (lstatSync(child, { throwIfNoEntry: false })?.isSymbolicLink()) {\n const issue = makeStoreIssue('unsafe-path', child, 'validate Store path', new Error('Symbolic links are not allowed for Store state.'));\n fail('store-unavailable', formatStoreIssue(issue), issue);\n }\n }\n catch (error) {\n if (error instanceof InstallationStateError)\n throw error;\n const issue = makeStoreIssue('io-error', child, 'validate Store path', error);\n fail('store-unavailable', formatStoreIssue(issue), issue);\n }\n if (!inside(store, path.resolve(child))) {\n const issue = makeStoreIssue('unsafe-path', child, 'validate Store path', new Error('A derived Store path escapes the Store.'));\n fail('store-unavailable', formatStoreIssue(issue), issue);\n }\n }\n return store;\n}\nfunction acquireStorePreparationLease(storeRoot: string, lockPath: string, token: string): import('node:fs').Stats {\n const started = Date.now();\n const deadline = started + STORE_OWNER_WAIT_MS;\n let attempts = 0;\n while (true) {\n try {\n const result = tryCreateExclusiveStoreLease(lockPath, { token, pid: process.pid, hostname: platform.hostname, startedAt: new Date().toISOString() });\n if (result.created)\n return result.stat;\n throw Object.assign(new Error('The Store preparation lock exists.'), { code: 'EEXIST' });\n }\n catch (error) {\n if (error instanceof StoreUnavailableError)\n throw error;\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {\n const issue = makeStoreIssue('io-error', lockPath, 'create Store preparation lock', error, { attempts: attempts + 1, waitedMs: Date.now() - started });\n return fail('store-unavailable', formatStoreIssue(issue), issue);\n }\n if (Date.now() >= deadline) {\n const issue: StoreIssue = { code: 'contention-timeout', path: lockPath, operation: 'wait for Store preparation', retryable: true, attempts: attempts + 1, waitedMs: Date.now() - started, cause: 'The Store preparation owner is still active.' };\n return fail('writer-active', formatStoreIssue(issue), issue);\n }\n const release = acquireStoreAccess(storeRoot, false, Math.max(0, deadline - Date.now()));\n release();\n attempts++;\n }\n }\n}\nfunction isDead(pid: number, host: string): boolean {\n return platform.processLiveness(pid, host) === 'dead';\n}\nfunction transaction<T>(db: StoreDatabase, fn: () => T): T { db.exec('BEGIN IMMEDIATE'); try {\n const result = fn();\n db.exec('COMMIT');\n return result;\n}\ncatch (e) {\n try {\n db.exec('ROLLBACK');\n }\n catch { }\n throw e;\n} }\nfunction prepareStore(projectRoot: string, storeRoot: string): void {\n validateInstallationStoreRoot(projectRoot, storeRoot);\n try {\n mkdirSync(storeRoot, { recursive: true, mode: 0o700 });\n }\n catch (error) {\n const issue = makeStoreIssue('io-error', storeRoot, 'create Store directory', error);\n fail('store-unavailable', formatStoreIssue(issue), issue);\n }\n let release: () => void;\n try {\n release = acquireStoreAccess(storeRoot);\n }\n catch (error) {\n if (error instanceof StoreUnavailableError && error.issue.code === 'owner-unverified' && path.basename(error.issue.path) === 'installation-bootstrap.lock') {\n recoverDeadStoreLeases(storeRoot);\n release = acquireStoreAccess(storeRoot);\n }\n else {\n throw error;\n }\n }\n try {\n const current = classifyStoreCheckpoint9State(storeRoot);\n if (current.state === 'supported-current')\n return;\n if (current.state === 'supported-legacy' && reviewedStoreBridgeDepth === 0)\n fail('store-unavailable', `The Store uses supported legacy schema ${current.schemaVersion}. Run make-docs setup to review and apply the compatibility bridge. No project files changed.`);\n if (current.state !== 'supported-legacy' && current.state !== 'absent') {\n const issue = ('issue' in current ? current.issue : undefined) ?? {\n code: current.state === 'corrupt' ? 'corrupt' as const : current.state === 'newer-unknown' ? 'schema-newer' as const : 'schema-unknown' as const,\n path: current.databasePath,\n operation: 'prepare',\n retryable: false,\n attempts: 1,\n waitedMs: 0,\n cause: current.reason,\n };\n fail('store-unavailable', formatStoreIssue(issue), issue);\n }\n }\n finally {\n release();\n }\n const lockPath = path.join(storeRoot, 'installation-bootstrap.lock');\n const token = randomUUID();\n const lockStat = acquireStorePreparationLease(storeRoot, lockPath, token);\n const lockGuard = platform.captureFileGuard(lockStat, 'file');\n try {\n validateInstallationStoreRoot(projectRoot, storeRoot);\n const beforeDrain = classifyStoreCheckpoint9State(storeRoot);\n if (beforeDrain.state === 'supported-current')\n return;\n if (beforeDrain.state !== 'absent' && beforeDrain.state !== 'supported-legacy') {\n const issue = ('issue' in beforeDrain ? beforeDrain.issue : undefined) ?? makeStoreIssue(\n beforeDrain.state === 'corrupt' ? 'corrupt' : beforeDrain.state === 'newer-unknown' ? 'schema-newer' : 'schema-unknown',\n beforeDrain.databasePath,\n 'prepare Store',\n new Error(beforeDrain.reason),\n );\n fail('store-unavailable', formatStoreIssue(issue), issue);\n }\n waitForStoreAccessToDrain(storeRoot);\n const c = classifyStoreCheckpoint9State(storeRoot);\n if (!['absent', 'supported-current', 'supported-legacy'].includes(c.state)) {\n const issue = ('issue' in c ? c.issue : undefined) ?? makeStoreIssue(\n c.state === 'corrupt' ? 'corrupt' : c.state === 'newer-unknown' ? 'schema-newer' : 'schema-unknown',\n c.databasePath,\n 'prepare Store',\n new Error(\"reason\" in c ? String(c.reason) : `Store state is ${c.state}.`),\n );\n fail('store-unavailable', formatStoreIssue(issue), issue);\n }\n const db = openStoreSqliteConnection(getStoreDatabasePath(storeRoot), {}, 'prepare');\n try {\n // Check prior registered locations before any schema or project change.\n if (c.state !== 'absent') {\n const tables = db.prepare(\"SELECT name FROM sqlite_schema WHERE type='table'\").all() as {\n name: string;\n }[];\n for (const table of ['projects', 'installation_checkouts'])\n if (tables.some(t => t.name === table)) {\n const rows = db.prepare(`SELECT root_path FROM ${table} WHERE root_path IS NOT NULL`).all() as {\n root_path: string;\n }[];\n if (rows.some(r => inside(canonicalInstallationPath(r.root_path), storeRoot)))\n fail('store-unavailable', 'Store path is inside a registered checkout.');\n }\n }\n // Preparation is distinct from project migration checkpoint receipts.\n applyStoreMigrations(db, c.schemaVersion ?? 0);\n db.exec('PRAGMA journal_mode=WAL');\n const rows = db.prepare('SELECT root_path FROM installation_checkouts').all() as {\n root_path: string;\n }[];\n if (rows.some(r => inside(canonicalInstallationPath(r.root_path), storeRoot)))\n fail('store-unavailable', 'Store path is inside a registered checkout.');\n }\n finally {\n db.close();\n }\n }\n finally {\n const current = lstatSync(lockPath, { throwIfNoEntry: false });\n if (current?.isFile() && platform.matchesFileGuard(current, lockGuard)) {\n const value = JSON.parse(readFileSync(lockPath, 'utf8'));\n if (value.token === token)\n unlinkSync(lockPath);\n }\n }\n}\n\n/** Allow schema conversion only inside a setup or update path that was reviewed. */\nexport function withReviewedStoreCompatibilityBridge<T>(fn: () => T): T {\n reviewedStoreBridgeDepth++;\n try {\n return fn();\n }\n finally {\n reviewedStoreBridgeDepth--;\n }\n}\nexport function withInstallationDatabase<T>(projectRoot: string, fn: (db: StoreDatabase) => T, options: {\n storeRoot?: string;\n readOnly?: boolean;\n} = {}): T {\n const root = canonicalInstallationPath(projectRoot);\n const store = validateInstallationStoreRoot(root, options.storeRoot ?? active.get(root)?.storeRoot ?? held.get(root)?.storeRoot ?? resolveStoreRoot());\n if (!options.readOnly && !held.has(root))\n prepareStore(root, store);\n const databasePath = getStoreDatabasePath(store);\n try {\n if (!lstatSync(databasePath, { throwIfNoEntry: false }))\n return fail('store-unavailable', 'The Store is absent. No project files changed. Run setup before this command.');\n }\n catch (error) {\n if (error instanceof InstallationStateError)\n throw error;\n const issue = makeStoreIssue('io-error', databasePath, options.readOnly ? 'read Store database path' : 'write Store database path', error);\n return fail('store-unavailable', formatStoreIssue(issue), issue);\n }\n const release = acquireStoreAccess(store);\n let db: StoreDatabase;\n try {\n db = openStoreSqliteConnection(databasePath, { readOnly: options.readOnly ?? false }, options.readOnly ? 'read' : 'write');\n }\n catch (e) {\n release();\n throw e;\n }\n try {\n try {\n return fn(db);\n }\n catch (error) {\n if (!isSqliteContention(error))\n throw error;\n throw new StoreUnavailableError(makeStoreIssue('contention-timeout', databasePath, options.readOnly ? 'read Store data' : 'write Store data', error, { retryable: true, waitedMs: STORE_BUSY_TIMEOUT_MS }));\n }\n }\n finally {\n db.close();\n release();\n }\n}\nexport function readDeclarativeProjectId(projectRoot: string): string | null {\n const file = path.join(projectRoot, '.make-docs/config.yaml');\n if (!existsSync(file))\n return null;\n assertSafeFilePath(projectRoot, '.make-docs/config.yaml');\n const doc = parseDocument(readFileSync(file, 'utf8'), { uniqueKeys: true });\n if (doc.errors.length)\n return fail('ownership-unverified', 'Project config is malformed; preserve it and correct it before setup.');\n const value = doc.get('projectId');\n if (value === undefined)\n return null;\n if (typeof value !== 'string' || !value.trim() || value.length > 160)\n return fail('ownership-unverified', 'Project config has an invalid projectId.');\n return value;\n}\nfunction checkout(db: StoreDatabase, root: string): Checkout | null {\n const key = platform.comparisonKey(root);\n const rows = db.prepare('SELECT * FROM installation_checkouts').all() as unknown as Checkout[];\n const matches = rows.filter(row => row.root_path_key === key || row.root_path === root || platform.samePath(row.root_path, root));\n if (matches.length > 1)\n fail('ownership-unverified', 'More than one checkout claims this platform path. No Store identity changed.');\n return matches[0] ?? null;\n}\n\nfunction managedContentDigest(root: string, ledgerJson: string | null, operationPaths: string[]): string | null {\n const isCheckoutPath = (relative: string): boolean => {\n if (relative === '.') return false;\n const absolute = path.resolve(root, relative);\n const relation = path.relative(root, absolute);\n return relation !== '..' && !relation.startsWith(`..${path.sep}`) && !path.isAbsolute(relation);\n };\n const paths = new Set(operationPaths.filter(isCheckoutPath));\n if (ledgerJson && ledgerJson !== 'null') {\n const manifest = validateAndMigrateManifest(JSON.parse(ledgerJson), 'Make Docs Store checkout verification ledger');\n for (const relative of Object.keys(manifest.files)) if (isCheckoutPath(relative)) paths.add(relative);\n }\n if (paths.size === 0) return null;\n const facts = [...paths].sort().map(relative => {\n const absolute = path.resolve(root, relative);\n const relation = path.relative(root, absolute);\n const stat = lstatSync(absolute, { throwIfNoEntry: false });\n if (!stat) return [relative, 'missing'];\n if (stat.isSymbolicLink()) return [relative, `link:${readlinkSync(absolute)}`];\n if (stat.isFile()) return [relative, `file:${sha(readFileSync(absolute))}`];\n if (stat.isDirectory()) return [relative, 'directory'];\n return [relative, 'unsupported'];\n });\n return sha(canonicalJson(facts));\n}\n\nfunction checkoutVerificationEvidence(db: StoreDatabase, root: string, projectId: string, checkoutId: string, ledgerJson: string | null): CheckoutVerificationEvidence {\n const config = path.join(root, '.make-docs', 'config.yaml');\n const configStat = lstatSync(config, { throwIfNoEntry: false });\n if (configStat && (!configStat.isFile() || configStat.isSymbolicLink()))\n fail('ownership-unverified', 'The checkout identity file is not a safe regular file.');\n const operationPaths = (db.prepare(`\n SELECT DISTINCT step.relative_path\n FROM installation_steps step\n JOIN installation_operations operation ON operation.operation_id=step.operation_id\n WHERE operation.checkout_id=? AND step.applied=1\n `).all(checkoutId) as Array<{ relative_path: string }>).map(row => row.relative_path);\n return {\n schemaVersion: 1,\n projectId,\n configDigest: configStat ? sha(readFileSync(config)) : null,\n ledgerDigest: ledgerJson && ledgerJson !== 'null' ? sha(ledgerJson) : null,\n managedContentDigest: managedContentDigest(root, ledgerJson, operationPaths),\n };\n}\n\nfunction parseCheckoutVerification(row: Checkout): CheckoutVerificationEvidence | null {\n if (!row.verification_json) return null;\n try {\n const value = JSON.parse(row.verification_json) as Partial<CheckoutVerificationEvidence>;\n return value.schemaVersion === 1 && typeof value.projectId === 'string' &&\n (typeof value.configDigest === 'string' || value.configDigest === null) &&\n (typeof value.ledgerDigest === 'string' || value.ledgerDigest === null) &&\n (typeof value.managedContentDigest === 'string' || value.managedContentDigest === null)\n ? value as CheckoutVerificationEvidence\n : null;\n } catch {\n return null;\n }\n}\n\nfunction sameCheckoutEvidence(left: CheckoutVerificationEvidence, right: CheckoutVerificationEvidence): boolean {\n return left.projectId === right.projectId && left.configDigest === right.configDigest &&\n left.ledgerDigest === right.ledgerDigest && left.managedContentDigest === right.managedContentDigest;\n}\n\nfunction assertCheckoutIdentity(row: Checkout, root: string): void {\n const id = readDeclarativeProjectId(root);\n if (id && id !== row.project_id)\n fail('ownership-unverified', 'The config project identity conflicts with the checkout binding.');\n if (!platform.samePath(row.root_path, root))\n fail('ownership-unverified', 'The checkout path does not match this Store binding.');\n}\nfunction bindCheckout(db: StoreDatabase, root: string, projectId?: string): Checkout {\n const prior = checkout(db, root);\n if (prior) {\n assertCheckoutIdentity(prior, root);\n if (projectId && projectId !== prior.project_id)\n fail('ownership-unverified', 'Conflicting project identity.');\n return prior;\n }\n const declarativeId = readDeclarativeProjectId(root);\n if (declarativeId && projectId && declarativeId !== projectId)\n fail('ownership-unverified', 'The requested project identity conflicts with the checkout config.');\n const id = declarativeId ?? projectId ?? randomUUID();\n const sameProject = db.prepare('SELECT * FROM installation_checkouts WHERE project_id=?').all(id) as unknown as Checkout[];\n const absent = sameProject.filter(row => !existsSync(row.root_path));\n if (absent.length && declarativeId) {\n if (absent.length !== 1)\n fail('ownership-unverified', 'More than one absent checkout can claim this project path. No Store identity changed.');\n const row = absent[0];\n const busy = db.prepare(\"SELECT 1 FROM installation_operations WHERE checkout_id=? AND status='pending'\").get(row.checkout_id);\n if (busy || db.prepare('SELECT 1 FROM installation_locks WHERE root_path=?').get(row.root_path))\n fail('recovery-required', 'Resolve the old checkout operation before rebinding its path.');\n const ledger = (db.prepare('SELECT manifest_json FROM installation_ledgers WHERE checkout_id=?').get(row.checkout_id) as { manifest_json: string } | undefined)?.manifest_json ?? null;\n const priorEvidence = parseCheckoutVerification(row);\n const currentEvidence = checkoutVerificationEvidence(db, root, id, row.checkout_id, ledger);\n if (!priorEvidence || !sameCheckoutEvidence(priorEvidence, currentEvidence))\n fail('ownership-unverified', 'The moved checkout content does not match its last verified Store facts. No Store identity changed.');\n const key = platform.comparisonKey(root);\n const competing = (db.prepare('SELECT * FROM installation_checkouts WHERE checkout_id<>?').all(row.checkout_id) as unknown as Checkout[])\n .some(candidate => candidate.root_path_key === key || platform.samePath(candidate.root_path, root));\n if (competing)\n fail('ownership-unverified', 'Another checkout already claims this platform path. No Store identity changed.');\n const verifiedAt = now();\n const verificationJson = JSON.stringify(currentEvidence);\n db.prepare('UPDATE installation_checkouts SET root_path=?,root_path_key=?,verified_at=?,verification_json=? WHERE checkout_id=?')\n .run(root, key, verifiedAt, verificationJson, row.checkout_id);\n return { ...row, root_path: root, root_path_key: key, verified_at: verifiedAt, verification_json: verificationJson };\n }\n const row: Checkout = { checkout_id: randomUUID(), project_id: id, root_path: root, root_path_key: platform.comparisonKey(root), verified_at: null, verification_json: null };\n db.prepare('INSERT INTO installation_checkouts (checkout_id,project_id,root_path,created_at,root_path_key,verified_at,verification_json) VALUES (?,?,?,?,?,?,?)')\n .run(row.checkout_id, id, root, now(), row.root_path_key, row.verified_at, row.verification_json);\n return row;\n}\nexport function getInstallationCheckoutId(projectRoot: string, storeRoot?: string): string {\n const root = canonicalInstallationPath(projectRoot);\n return withInstallationDatabase(root, db => transaction(db, () => bindCheckout(db, root).checkout_id), { storeRoot });\n}\n/** Read an existing checkout binding without creating or changing Store state. */\nexport function getExistingInstallationCheckoutId(projectRoot: string, storeRoot?: string): string | null {\n const root = canonicalInstallationPath(projectRoot);\n return withInstallationDatabase(root, db => {\n const row = checkout(db, root);\n if (!row)\n return null;\n assertCheckoutIdentity(row, root);\n return row.checkout_id;\n }, { storeRoot, readOnly: true });\n}\nexport function acquireInstallationLock(projectRoot: string, storeRoot?: string): InstallationLock {\n const root = canonicalInstallationPath(projectRoot);\n const existing = held.get(root);\n if (existing) {\n existing.depth++;\n return existing;\n }\n const store = validateInstallationStoreRoot(root, storeRoot ?? resolveStoreRoot());\n prepareStore(root, store);\n const releaseAccess = acquireStoreAccess(store);\n try {\n const token = randomUUID();\n const started = Date.now();\n const deadline = started + STORE_OWNER_WAIT_MS;\n let attempt = 0;\n while (true) {\n const previous = withInstallationDatabase(root, db => transaction(db, () => {\n const machine = db.prepare(\"SELECT operation_id FROM tool_operations WHERE status='pending' LIMIT 1\").get() as {\n operation_id: string;\n } | undefined;\n if (machine)\n fail('recovery-required', `Tool operation ${machine.operation_id} is pending. Inspect project state status before managed changes.`);\n const owner = db.prepare('SELECT pid,hostname FROM installation_locks WHERE root_path=?').get(root) as {\n pid: number;\n hostname: string;\n } | undefined;\n if (!owner)\n db.prepare('INSERT INTO installation_locks VALUES (?,?,?,?,?)').run(root, token, process.pid, platform.hostname, now());\n return owner;\n }), { storeRoot: store });\n if (!previous)\n break;\n const liveness = platform.processLiveness(previous.pid, previous.hostname);\n if (liveness === 'dead')\n fail('recovery-required', `Checkout writer ${previous.pid} stopped. Inspect project state status before recovery. No project files changed.`);\n if (liveness === 'unknown')\n fail('ownership-unverified', `Make Docs cannot verify checkout writer ${previous.pid} on ${previous.hostname}. No project files changed.`);\n if (Date.now() >= deadline)\n fail('writer-active', `Make Docs waited ${Math.ceil((Date.now() - started) / 1000)} seconds for checkout writer ${previous.pid}. The writer is still active. No project files changed. Run the command after it finishes.`);\n waitForStoreRetry(attempt++, deadline);\n }\n const lock = { projectRoot: root, storeRoot: store, token, lockPath: `${getStoreDatabasePath(store)}#installation-lock/${sha(root)}`, depth: 1, releaseAccess };\n held.set(root, lock);\n return lock;\n }\n catch (error) {\n releaseAccess();\n throw error;\n }\n}\nexport function assertInstallationLockActive(lock: InstallationLock): void {\n const current = held.get(lock.projectRoot);\n if (current?.globalLock)\n assertGlobalAssetLockActive(current.globalLock);\n withInstallationDatabase(lock.projectRoot, db => { const identity = checkout(db, lock.projectRoot); if (identity)\n assertCheckoutIdentity(identity, lock.projectRoot); const row = db.prepare('SELECT token FROM installation_locks WHERE root_path=?').get(lock.projectRoot) as {\n token: string;\n } | undefined; if (row?.token !== lock.token)\n fail('writer-active', 'Checkout lock ownership changed.'); }, { storeRoot: lock.storeRoot, readOnly: true });\n}\nexport function releaseInstallationLock(lock: InstallationLock): void {\n const current = held.get(lock.projectRoot);\n if (current && current.token === lock.token && current.depth > 1) {\n current.depth--;\n return;\n }\n const owned = current?.token === lock.token ? current : undefined;\n try {\n withInstallationDatabase(lock.projectRoot, db => {\n const row = db.prepare('SELECT token FROM installation_locks WHERE root_path=?').get(lock.projectRoot) as {\n token: string;\n } | undefined;\n if (row?.token !== lock.token)\n fail('writer-active', 'Checkout lock ownership changed.');\n db.prepare('DELETE FROM installation_locks WHERE root_path=? AND token=?').run(lock.projectRoot, lock.token);\n }, { storeRoot: lock.storeRoot });\n }\n finally {\n if (owned) {\n held.delete(lock.projectRoot);\n try {\n if (owned.globalLock)\n releaseGlobalAssetLock(owned.globalLock);\n }\n finally {\n owned.releaseAccess();\n }\n }\n }\n}\nexport function readInstallationManifest(projectRoot: string, storeRoot?: string): InstallManifest | null {\n const root = canonicalInstallationPath(projectRoot);\n const store = validateInstallationStoreRoot(root, storeRoot ?? active.get(root)?.storeRoot ?? held.get(root)?.storeRoot ?? resolveStoreRoot());\n const c = classifyStoreCheckpoint9State(store);\n if (c.state === 'supported-legacy' || c.state === 'absent')\n return null;\n if (c.state !== 'supported-current') {\n const issue = c.issue ?? {\n code: c.state === 'corrupt' ? 'corrupt' as const : c.state === 'newer-unknown' ? 'schema-newer' as const : 'schema-unknown' as const,\n path: c.databasePath,\n operation: 'inspect',\n retryable: false,\n attempts: 1,\n waitedMs: 0,\n cause: c.reason,\n };\n return fail('store-unavailable', formatStoreIssue(issue), issue);\n }\n return withInstallationDatabase(root, db => {\n const row = checkout(db, root);\n if (!row)\n return null;\n assertCheckoutIdentity(row, root);\n const op = active.get(root);\n const pending = op ? db.prepare('SELECT after_ledger FROM installation_operations WHERE operation_id=?').get(op.id) as {\n after_ledger: string | null;\n } | undefined : undefined;\n const data = pending?.after_ledger ?? (db.prepare('SELECT manifest_json FROM installation_ledgers WHERE checkout_id=?').get(row.checkout_id) as {\n manifest_json: string;\n } | undefined)?.manifest_json;\n return data ? JSON.parse(data) : null;\n }, { storeRoot: store, readOnly: true });\n}\nexport function getInstallationProjectId(projectRoot: string): string { const root = canonicalInstallationPath(projectRoot); const op = active.get(root); if (op)\n return op.projectId; return withInstallationDatabase(root, db => { const row = checkout(db, root); if (!row)\n return fail('ownership-unverified', 'No checkout identity.'); return row.project_id; }, { readOnly: true }); }\nexport function saveInstallationManifest(projectRoot: string, manifest: InstallManifest): string {\n const root = canonicalInstallationPath(projectRoot);\n const op = active.get(root);\n if (!op)\n return withInstallationOperation(root, 'installation.ledger', () => saveInstallationManifest(root, manifest), { projectId: manifest.projectId });\n if (manifest.projectId !== op.projectId)\n fail('ownership-unverified', 'Installation ledger projectId differs from the reserved identity.');\n const paths = Object.keys(manifest.files);\n if (paths.some(p => path.isAbsolute(p))) {\n const lock = held.get(root)!;\n if (!lock.globalLock) lock.globalLock = acquireGlobalAssetLock(root);\n assertGlobalAssetLockActive(lock.globalLock);\n }\n assertNoOtherPendingPathClaims(root, paths, op.storeRoot);\n withInstallationDatabase(root, db => { db.prepare('UPDATE installation_operations SET after_ledger=? WHERE operation_id=?').run(JSON.stringify(manifest), op.id); }, { storeRoot: op.storeRoot });\n return `${getStoreDatabasePath(op.storeRoot)}#installation-ledger/${op.projectId}`;\n}\nexport function removeInstallationManifest(projectRoot: string): void {\n const root = canonicalInstallationPath(projectRoot);\n const op = active.get(root);\n if (!op)\n return withInstallationOperation(root, 'setup.remove', () => removeInstallationManifest(root));\n withInstallationDatabase(root, db => { db.prepare('UPDATE installation_operations SET after_ledger=? WHERE operation_id=?').run('null', op.id); }, { storeRoot: op.storeRoot });\n}\nfunction commitOperation(db: StoreDatabase, id: string, root: string, rollback = false): void {\n transaction(db, () => {\n const op = db.prepare('SELECT * FROM installation_operations WHERE operation_id=?').get(id) as unknown as Operation;\n const ledger = rollback ? op.before_ledger : op.after_ledger;\n if (ledger && ledger !== 'null') {\n const parsed = validateAndMigrateManifest(JSON.parse(ledger), 'Make Docs Store final installation ledger');\n const owner = db.prepare('SELECT project_id FROM installation_checkouts WHERE checkout_id=?').get(op.checkout_id) as {\n project_id: string;\n };\n if (parsed.projectId !== owner.project_id)\n fail('ownership-unverified', 'Final ledger project identity differs from this checkout.');\n }\n if (ledger && ledger !== 'null')\n db.prepare('INSERT INTO installation_ledgers VALUES (?,?,?) ON CONFLICT(checkout_id) DO UPDATE SET manifest_json=excluded.manifest_json,updated_at=excluded.updated_at').run(op.checkout_id, ledger, now());\n else\n db.prepare('DELETE FROM installation_ledgers WHERE checkout_id=?').run(op.checkout_id);\n const owner = db.prepare('SELECT project_id FROM installation_checkouts WHERE checkout_id=?').get(op.checkout_id) as { project_id: string };\n const evidence = checkoutVerificationEvidence(db, root, owner.project_id, op.checkout_id, ledger);\n db.prepare('UPDATE installation_checkouts SET root_path=?,root_path_key=?,verified_at=?,verification_json=? WHERE checkout_id=?')\n .run(root, platform.comparisonKey(root), now(), JSON.stringify(evidence), op.checkout_id);\n db.prepare('UPDATE installation_operations SET status=?,finished_at=? WHERE operation_id=?').run(rollback ? 'rolled-back' : 'completed', now(), id);\n });\n}\nexport function withInstallationOperation<T>(projectRoot: string, operation: string, fn: () => T, options: {\n storeRoot?: string;\n projectId?: string;\n} = {}): T {\n const root = canonicalInstallationPath(projectRoot);\n const parent = active.get(root);\n if (parent) {\n parent.depth++;\n try {\n return fn();\n }\n finally {\n parent.depth--;\n }\n }\n const lock = acquireInstallationLock(root, options.storeRoot);\n let opId: string | null = null;\n let projectMutationStarted = false;\n try {\n const bound = withInstallationDatabase(root, db => transaction(db, () => {\n const row = bindCheckout(db, root, options.projectId);\n const pending = db.prepare(\"SELECT operation_id FROM installation_operations WHERE checkout_id=? AND status='pending'\").get(row.checkout_id) as {\n operation_id: string;\n } | undefined;\n if (pending)\n fail('recovery-required', `Run make-docs project state recover ${pending.operation_id} --resume --dry-run --target-root ${JSON.stringify(root)}.`);\n const ledger = (db.prepare('SELECT manifest_json FROM installation_ledgers WHERE checkout_id=?').get(row.checkout_id) as {\n manifest_json: string;\n } | undefined)?.manifest_json ?? null;\n const id = randomUUID();\n db.prepare('INSERT INTO installation_operations (operation_id,checkout_id,operation,status,before_ledger,after_ledger,created_at,finished_at) VALUES (?,?,?,?,?,?,?,NULL)').run(id, row.checkout_id, operation, 'pending', ledger, ledger, now());\n return { id, projectId: row.project_id };\n }), { storeRoot: lock.storeRoot });\n opId = bound.id;\n active.set(root, { ...bound, storeRoot: lock.storeRoot, depth: 1 });\n if (!existsSync(root)) {\n withInstallationDatabase(root, db => db.prepare('INSERT INTO installation_steps VALUES (?,0,?,?,?,0)').run(bound.id, '.', JSON.stringify({ kind: 'missing' }), JSON.stringify({ kind: 'directory' })), { storeRoot: lock.storeRoot });\n mkdirSync(root, { recursive: true });\n withInstallationDatabase(root, db => transaction(db, () => { db.prepare('UPDATE installation_steps SET applied=1 WHERE operation_id=? AND ordinal=0').run(bound.id); }), { storeRoot: lock.storeRoot });\n }\n projectMutationStarted = true;\n ensureDeclarativeIdentity(root);\n const result = fn();\n if (result && typeof (result as {\n then?: unknown;\n }).then === 'function')\n fail('recovery-required', 'Installation operation callback must be synchronous.');\n sealInstallationOperation(root);\n assertInstallationLockActive(lock);\n withInstallationDatabase(root, db => {\n const rows = db.prepare('SELECT * FROM installation_steps WHERE operation_id=? ORDER BY ordinal').all(bound.id) as unknown as Step[];\n const last = new Map(rows.map(s => [s.relative_path, s]));\n for (const step of last.values())\n if (!subsumedByAncestor(root, step, last) && !matches(root, step.relative_path, JSON.parse(step.after_json)))\n fail('snapshot-drift', `Output changed before final commit: ${step.relative_path}`);\n commitOperation(db, bound.id, root);\n }, { storeRoot: lock.storeRoot });\n return result;\n }\n catch (e) {\n if (e instanceof StoreUnavailableError)\n e.message = formatStoreIssue(e.issue, { projectMutationStarted, ...(opId ? { pendingOperationId: opId } : {}) });\n else if (e instanceof InstallationStateError && e.issue)\n e.message = formatStoreIssue(e.issue, { projectMutationStarted, ...(opId ? { pendingOperationId: opId } : {}) });\n else if (opId && e instanceof Error)\n e.message += projectMutationStarted\n ? ` Project files may have changed. Pending operation: ${opId}. Run make-docs project state status before recovery.`\n : ` No project files changed. Pending operation: ${opId}. Run make-docs project state status.`;\n throw e;\n }\n finally {\n active.delete(root);\n releaseInstallationLock(lock);\n }\n}\nfunction targetPath(root: string, relative: string): string {\n if (path.isAbsolute(relative)) {\n const target = path.join(canonicalInstallationPath(path.dirname(relative)),path.basename(relative));\n const nativeDirectories = [getHarnessSkillDirectory('codex','global'),getHarnessSkillDirectory('claude-code','global')];\n const allowed = ['.agents', '.claude', '.codex'].some(p => canonicalInstallationPath(path.join(platform.userHome(), p)) === target) || ['.agents/skills', '.codex/skills', '.claude/skills', '.make-docs/agentics'].some(p => inside(canonicalInstallationPath(path.join(platform.userHome(), p)), target)) || nativeDirectories.some(p=>inside(canonicalInstallationPath(p),target) || canonicalInstallationPath(path.dirname(p)) === target) || inside(path.join(active.get(root)?.storeRoot ?? resolveStoreRoot(), 'agentics'), target);\n if (!allowed)\n fail('ownership-unverified', `External mutation path is not an approved skill location: ${relative}`);\n return path.join(canonicalInstallationPath(path.dirname(relative)), path.basename(relative));\n }\n const target = path.resolve(root, relative);\n if (!inside(root, target) || relative === '')\n fail('ownership-unverified', 'Unsafe operation path.');\n return target;\n}\nfunction assertSafeFilePath(root: string, relative: string): string {\n if (path.isAbsolute(relative)) {\n let lexicalParent = path.dirname(relative);\n const home = platform.userHome();\n while (lexicalParent !== path.dirname(lexicalParent) && lexicalParent !== home) {\n if (lstatSync(lexicalParent, {throwIfNoEntry: false})?.isSymbolicLink()) fail('ownership-unverified', `Symbolic-link parent: ${lexicalParent}`);\n lexicalParent = path.dirname(lexicalParent);\n }\n }\n const target = targetPath(root, relative);\n let current = path.dirname(target);\n while (current !== path.dirname(current)) {\n if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink())\n fail('ownership-unverified', `Symbolic-link parent: ${current}`);\n if (current === root)\n break;\n current = path.dirname(current);\n }\n return target;\n}\nfunction inspect(root: string, relative: string): FileState {\n const target = assertSafeFilePath(root, relative);\n let st;\n try {\n st = lstatSync(target);\n }\n catch (e) {\n if ((e as NodeJS.ErrnoException).code === 'ENOENT')\n return { kind: 'missing' };\n throw e;\n }\n if (st.isSymbolicLink())\n return { kind: 'symlink', target: readlinkSync(target) };\n if (st.isDirectory())\n return { kind: 'directory', mode: st.mode & 0o777 };\n if (!st.isFile())\n fail('ownership-unverified', 'Unsupported recovery file type.');\n return { kind: 'file', digest: sha(readFileSync(target)), mode: st.mode & 0o777 };\n}\nfunction matches(root: string, relative: string, expected: FileState): boolean { const current = inspect(root, relative); return current.kind === expected.kind && current.digest === expected.digest && current.target === expected.target && (expected.mode === undefined || (current.mode !== undefined && platform.matchesFileMode(current.mode, expected.mode))); }\nfunction savePayload(root: string, opId: string, ordinal: number, label: string, bytes: Uint8Array | string): string {\n const relative = `.make-docs/backup/operations/${opId}/${ordinal}-${label}`;\n const target = assertSafeFilePath(root, relative);\n mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });\n const fd = openSync(target, 'wx', 0o600);\n try {\n writeFileSync(fd, bytes);\n fsyncSync(fd);\n }\n finally {\n closeSync(fd);\n }\n if (sha(readFileSync(target)) !== sha(bytes))\n fail('snapshot-drift', 'Backup payload verification failed.');\n return relative;\n}\nexport function recordPlannedFileChange(projectRoot: string, relativePath: string, after: PlannedFileState, apply: () => void): void { preparePlannedFileChange(projectRoot, relativePath, after, apply)(); }\nexport function sealInstallationOperation(projectRoot: string): void { const root = canonicalInstallationPath(projectRoot); const op = active.get(root); if (!op)\n fail('recovery-required', 'No operation to seal.'); if (op.depth > 1)\n return; withInstallationDatabase(root, db => db.prepare('UPDATE installation_operations SET plan_complete=1 WHERE operation_id=?').run(op.id), { storeRoot: op.storeRoot }); }\nexport function preparePlannedFileChange(projectRoot: string, relativePath: string, after: PlannedFileState, apply: () => void): () => void {\n const root = canonicalInstallationPath(projectRoot);\n if (isRetiredSkillPath(root,relativePath) && after.kind !== 'missing') fail('recovery-required','The retired .make-docs/agentics tree is read/remove-only. Review setup skills --adopt-existing --dry-run for layout cutover.');\n if (relativePath === '.')\n fail('ownership-unverified', 'Only bootstrap can create the target root.');\n const op = active.get(root);\n if (!op)\n return fail('recovery-required', 'File mutation requires a pending installation operation.');\n if (path.isAbsolute(relativePath)) {\n const lock = held.get(root)!;\n if (!lock.globalLock)\n lock.globalLock = acquireGlobalAssetLock(root);\n assertGlobalAssetLockActive(lock.globalLock);\n }\n assertNoOtherPendingPathClaims(root, [relativePath], op.storeRoot);\n const prior = withInstallationDatabase(root, db => db.prepare('SELECT after_json FROM installation_steps WHERE operation_id=? AND relative_path=? ORDER BY ordinal DESC LIMIT 1').get(op.id, relativePath) as {\n after_json: string;\n } | undefined, { storeRoot: op.storeRoot, readOnly: true });\n const before: FileState = prior ? JSON.parse(prior.after_json) : inspect(root, relativePath);\n if (before.kind === 'directory' && after.kind !== 'directory' && readdirSync(targetPath(root, relativePath)).length)\n fail('ownership-unverified', 'Journal individual files before removing a nonempty directory.');\n const ordinal = withInstallationDatabase(root, db => Number((db.prepare('SELECT COALESCE(MAX(ordinal),0)+1 AS next FROM installation_steps WHERE operation_id=?').get(op.id) as {\n next: number;\n }).next), { storeRoot: op.storeRoot });\n // The operation intent already exists before backup payload creation.\n if (before.kind === 'file' && !before.payload)\n before.payload = savePayload(root, op.id, ordinal, 'before', readFileSync(targetPath(root, relativePath)));\n let desired: FileState;\n if (after.kind === 'file')\n desired = { kind: 'file', digest: sha(after.content), payload: savePayload(root, op.id, ordinal, 'after', after.content), mode: after.mode ?? (before.kind === 'file' ? before.mode : 0o644) };\n else\n desired = { ...after };\n withInstallationDatabase(root, db => db.prepare('INSERT INTO installation_steps VALUES (?,?,?,?,?,0)').run(op.id, ordinal, relativePath, JSON.stringify(before), JSON.stringify(desired)), { storeRoot: op.storeRoot });\n return () => {\n if (!matches(root, relativePath, before))\n fail('snapshot-drift', `File changed before replacement: ${relativePath}`);\n assertInstallationLockActive(held.get(root)!);\n try {\n apply();\n }\n catch (error) {\n if (after.kind === 'symlink' && matches(root, relativePath, before))\n withInstallationDatabase(root, db => db.prepare('DELETE FROM installation_steps WHERE operation_id=? AND ordinal=? AND applied=0').run(op.id, ordinal), { storeRoot: op.storeRoot });\n throw error;\n }\n if (after.kind === 'file' && desired.mode !== undefined)\n chmodSync(targetPath(root, relativePath), desired.mode);\n if (!matches(root, relativePath, desired))\n fail('snapshot-drift', `File change did not match the plan: ${relativePath}`);\n withInstallationDatabase(root, db => db.prepare('UPDATE installation_steps SET applied=1 WHERE operation_id=? AND ordinal=?').run(op.id, ordinal), { storeRoot: op.storeRoot });\n };\n}\ninterface AtomicWriteRecord {\n operationId: string;\n ordinal: number;\n temporary: string;\n target: string;\n digest: string;\n mode: number;\n device?: string;\n inode?: string;\n guard?: FileMutationGuard;\n}\nfunction atomicTemporaryPath(operationId: string, ordinal: number, target: string): string {\n return path.posix.join(path.posix.dirname(target), `.make-docs-${operationId}-${ordinal}.tmp`);\n}\nfunction atomicTemporaryStates(db: StoreDatabase, root: string, op: Operation, steps: Step[]): Record<string, FileState> {\n const temporary: Record<string, FileState> = {};\n const rows = db.prepare(\"SELECT record_json FROM installation_migration_records WHERE checkout_id=? AND kind='backup' AND record_id LIKE ?\").all(op.checkout_id, `atomic:${op.operation_id}:%`) as {record_json: string}[];\n for (const row of rows) {\n const record = JSON.parse(row.record_json) as AtomicWriteRecord;\n const step = steps.find(candidate => candidate.ordinal === record.ordinal);\n if (!step || record.operationId !== op.operation_id || record.target !== step.relative_path || record.temporary !== atomicTemporaryPath(op.operation_id, step.ordinal, step.relative_path)) fail('snapshot-drift', 'Temporary file ownership disagrees with the saved operation.');\n const states: FileState[] = [JSON.parse(step.before_json), JSON.parse(step.after_json)];\n const desired = states.find(state => state.kind === 'file' && state.digest === record.digest && state.mode === record.mode && typeof state.contentBase64 === 'string');\n if (!desired) fail('snapshot-drift', 'Temporary file payload does not belong to the saved operation.');\n const target = assertSafeFilePath(root, record.temporary);\n const stat = lstatSync(target, {throwIfNoEntry: false});\n if (!stat) continue;\n if (!stat.isFile() || stat.isSymbolicLink()) fail('snapshot-drift', `Temporary file was replaced: ${record.temporary}`);\n const bytes = readFileSync(target), intended = Buffer.from(desired.contentBase64!, 'base64');\n const mode = stat.mode & 0o777;\n if (sha(intended) !== record.digest || bytes.length > intended.length || !bytes.equals(intended.subarray(0, bytes.length))) fail('snapshot-drift', `Temporary file was changed: ${record.temporary}`);\n if (record.guard) {\n if (!platform.matchesFileIdentity(stat, record.guard)) fail('snapshot-drift', `Temporary file identity changed: ${record.temporary}`);\n } else if (record.device !== undefined || record.inode !== undefined) {\n if (record.device !== String(stat.dev) || record.inode !== String(stat.ino)) fail('snapshot-drift', `Temporary file identity changed: ${record.temporary}`);\n } else if (bytes.length !== 0 || !platform.matchesFileMode(mode, 0o600)) fail('snapshot-drift', `Unproved temporary file creation: ${record.temporary}`);\n if (!platform.matchesFileMode(mode, 0o600) && !(bytes.length === intended.length && platform.matchesFileMode(mode, record.mode))) fail('snapshot-drift', `Temporary file mode changed: ${record.temporary}`);\n temporary[record.temporary] = {kind: 'file', digest: sha(bytes), mode};\n }\n return temporary;\n}\nfunction cleanAtomicTemporaryFiles(root: string, op: Operation, steps: Step[], lock: InstallationLock): void {\n const temporary = withInstallationDatabase(root, db => atomicTemporaryStates(db, root, op, steps), {storeRoot: lock.storeRoot, readOnly: true});\n for (const [relative, expected] of Object.entries(temporary)) {\n assertInstallationLockActive(lock);\n if (!matches(root, relative, expected)) fail('snapshot-drift', `Temporary file changed before cleanup: ${relative}`);\n unlinkSync(assertSafeFilePath(root, relative));\n }\n}\nfunction writeAtomicDetachedFile(root: string, relative: string, state: FileState, bytes: Buffer, context: {op: Operation; step: Step; expected: FileState; lock: InstallationLock}): void {\n const {op, step, lock, expected} = context;\n const temporary = atomicTemporaryPath(op.operation_id, step.ordinal, relative);\n const staged = assertSafeFilePath(root, temporary), target = assertSafeFilePath(root, relative);\n if (lstatSync(staged, {throwIfNoEntry: false})) fail('snapshot-drift', `Temporary destination is occupied: ${temporary}`);\n const record: AtomicWriteRecord = {operationId: op.operation_id, ordinal: step.ordinal, temporary, target: relative, digest: state.digest!, mode: state.mode ?? 0o644};\n const save = () => withInstallationDatabase(root, db => db.prepare(\"INSERT INTO installation_migration_records VALUES (?,'backup',?,?) ON CONFLICT(checkout_id,kind,record_id) DO UPDATE SET record_json=excluded.record_json\").run(op.checkout_id, `atomic:${op.operation_id}:${step.ordinal}`, JSON.stringify(record)), {storeRoot: lock.storeRoot});\n save(); // Intent and the exclusive temporary path precede file creation.\n assertInstallationLockActive(lock);\n const fd = openSync(staged, 'wx', 0o600);\n try {\n fsyncSync(fd);\n const stat = fstatSync(fd);\n record.guard = platform.captureFileGuard(stat, 'file');\n save(); // Inode proof precedes every payload byte.\n writeFileSync(fd, bytes);\n fsyncSync(fd);\n } finally {closeSync(fd);}\n if (sha(readFileSync(staged)) !== state.digest) fail('snapshot-drift', 'Staged replacement bytes changed.');\n chmodSync(staged, state.mode ?? 0o644);\n assertInstallationLockActive(lock);\n if (!matches(root, relative, expected)) fail('snapshot-drift', `File changed before atomic replacement: ${relative}`);\n try {\n platform.atomicReplace(staged, target);\n } catch (error) {\n fail('snapshot-drift', error instanceof Error ? error.message : 'Atomic replacement failed.');\n }\n}\nfunction restoreState(root: string, relative: string, state: FileState, atomic?: {op: Operation; step: Step; expected: FileState; lock: InstallationLock}): void {\n if (isRetiredSkillPath(root,relative) && state.kind !== 'missing') fail('recovery-required','Recovery cannot recreate retired .make-docs/agentics paths. Preserve the saved bytes and inspect forward resume.');\n const target = assertSafeFilePath(root, relative);\n const current = inspect(root, relative);\n let fileBytes: Buffer | undefined;\n if (state.kind === 'file') {\n if (state.contentBase64 !== undefined) fileBytes = Buffer.from(state.contentBase64, 'base64');\n else {\n if (!state.payload) fail('recovery-required', 'Recovery payload reference is absent.');\n const payload = assertSafeFilePath(root, state.payload);\n if (lstatSync(payload).isSymbolicLink()) fail('snapshot-drift', 'Recovery payload changed.');\n fileBytes = readFileSync(payload);\n }\n if (sha(fileBytes) !== state.digest) fail('snapshot-drift', 'Recovery payload changed.');\n }\n if (state.kind === 'missing') {\n if (current.kind === 'directory')\n rmdirSync(target);\n else if (current.kind !== 'missing')\n unlinkSync(target);\n return;\n }\n if (state.kind === 'directory') {\n mkdirSync(target, { recursive: true });\n if (state.mode !== undefined) chmodSync(target, state.mode);\n return;\n }\n if (state.kind === 'file' && atomic) {\n if (current.kind !== 'missing' && current.kind !== 'file') fail('ownership-unverified', 'Atomic layout writes require a regular file or missing destination.');\n writeAtomicDetachedFile(root, relative, state, fileBytes!, atomic);\n return;\n }\n if (current.kind === 'directory')\n rmdirSync(target);\n else if (current.kind === 'symlink')\n unlinkSync(target);\n mkdirSync(path.dirname(target), { recursive: true });\n if (state.kind === 'symlink') {\n if (existsSync(target))\n unlinkSync(target);\n symlinkSync(state.target!, target);\n return;\n }\n const fd = openSync(target, 'w', state.mode ?? 0o644);\n try {\n writeFileSync(fd, fileBytes!);\n fsyncSync(fd);\n }\n finally {\n closeSync(fd);\n }\n chmodSync(target, state.mode ?? 0o644);\n}\nfunction selectDetachedCopyFallback(root: string, op: Operation, plan: DetachedInstallationPlan, step: Step, error: unknown, lock: InstallationLock): boolean {\n const fallback = plan.copyFallbacks?.[step.relative_path];\n const from = JSON.parse(step.before_json) as FileState, to = JSON.parse(step.after_json) as FileState;\n if (op.operation !== 'setup.skills.adopt' || !fallback || plan.selectedCopyFallbacks?.includes(step.relative_path) || from.kind !== 'missing' || to.kind !== 'symlink' || error instanceof InstallationStateError || !['EPERM', 'EACCES', 'ENOSYS', 'ENOTSUP', 'EOPNOTSUPP'].includes((error as NodeJS.ErrnoException)?.code ?? '')) return false;\n assertInstallationLockActive(lock);\n if (!matches(root, step.relative_path, from)) fail('snapshot-drift', 'Failed symlink creation changed the target; no copy fallback is safe.');\n const replacement: DetachedInstallationPlan = structuredClone(plan);\n const index = step.ordinal - 1;\n if (canonicalJson(replacement.changes[index]) !== canonicalJson({path: step.relative_path, before: from, after: to})) fail('snapshot-drift', 'Fallback trigger no longer matches its sealed plan.');\n replacement.changes.splice(index, 1, ...fallback.changes);\n replacement.selectedCopyFallbacks = [...(replacement.selectedCopyFallbacks ?? []), step.relative_path];\n if (!replacement.afterLedger) fail('ownership-unverified', 'Copy fallback has no final ledger.');\n replacement.afterLedger.files[step.relative_path] = fallback.ledgerEntry;\n assertDetachedPaths(root, replacement, false, op.operation);\n validateAndMigrateManifest(replacement.afterLedger, 'Prepared copy fallback ledger');\n withInstallationDatabase(root, db => transaction(db, () => {\n const current = db.prepare('SELECT * FROM installation_operations WHERE operation_id=?').get(op.operation_id) as unknown as Operation;\n if (current.status !== 'pending' || canonicalJson(detachedSnapshot(db, current)) !== canonicalJson(plan)) fail('snapshot-drift', 'Pending operation changed before fallback selection.');\n db.prepare('DELETE FROM installation_steps WHERE operation_id=?').run(op.operation_id);\n for (const [i, change] of replacement.changes.entries()) db.prepare('INSERT INTO installation_steps VALUES (?,?,?,?,?,0)').run(op.operation_id, i + 1, change.path, JSON.stringify(change.before), JSON.stringify(change.after));\n db.prepare('UPDATE installation_operations SET after_ledger=? WHERE operation_id=?').run(JSON.stringify(replacement.afterLedger), op.operation_id);\n db.prepare(\"UPDATE installation_migration_records SET record_json=? WHERE checkout_id=? AND kind='snapshot' AND record_id=?\").run(JSON.stringify({digest: sha(canonicalJson(replacement)), plan: replacement}), op.checkout_id, `detached:${op.operation_id}`);\n }), {storeRoot: lock.storeRoot});\n return true;\n}\nexport function readInstallationStatus(projectRoot: string, storeRoot?: string) {\n const root = canonicalInstallationPath(projectRoot);\n const base = { schemaVersion: 1 as const, projectRoot: root, projectName: path.basename(root) };\n try {\n const id = readDeclarativeProjectId(root);\n const store = validateInstallationStoreRoot(root, storeRoot ?? resolveStoreRoot());\n if (!existsSync(getStoreDatabasePath(store)))\n return { ...base, status: 'unregistered', projectId: id, storeAvailable: false, nextAction: 'Run make-docs setup and review the installation plan.' };\n const c = classifyStoreCheckpoint9State(store);\n if (c.state === 'supported-legacy')\n return { ...base, status: 'unregistered', projectId: id, storeAvailable: true, nextAction: 'Run make-docs setup and review legacy transfer.' };\n if (c.state !== 'supported-current')\n fail('store-unavailable', `Store is ${c.state}.`);\n return withInstallationDatabase(root, db => {\n const toolOperations = (db.prepare(\"SELECT operation_id AS operationId,operation,started_at AS startedAt,status FROM tool_operations WHERE status='pending' ORDER BY started_at LIMIT 10\").all() as {\n operationId: string;\n operation: string;\n startedAt: string;\n status: string;\n }[]).map(op => ({ ...op, nextAction: 'Review the package manager result before completing this tool operation.' }));\n if (toolOperations.length)\n return { ...base, projectId: id, storeAvailable: true, status: 'recovery-required', toolOperations, nextAction: 'A tool operation is pending. Review its package manager result before managed changes.' };\n const row = checkout(db, root);\n if (!row)\n return { ...base, status: id ? 'ownership-unverified' : 'unregistered', projectId: id, storeAvailable: true, nextAction: 'Run make-docs setup and review this checkout.' };\n assertCheckoutIdentity(row, root);\n const lock = db.prepare('SELECT pid,hostname FROM installation_locks WHERE root_path=?').get(root) as {\n pid: number;\n hostname: string;\n } | undefined;\n const pending = db.prepare(\"SELECT * FROM installation_operations WHERE checkout_id=? AND status='pending'\").get(row.checkout_id) as unknown as Operation | undefined;\n const prepared = pending ? detachedSnapshot(db, pending) : null;\n const manifest = (db.prepare('SELECT manifest_json FROM installation_ledgers WHERE checkout_id=?').get(row.checkout_id) as {\n manifest_json: string;\n } | undefined)?.manifest_json;\n const pendingAction = pending\n ? prepared\n ? detachedHooks.get(pending.operation)!.nextAction(root, pending.operation_id, prepared.mode)\n : pending.plan_complete\n ? `make-docs project state recover ${pending.operation_id} --resume --dry-run --target-root ${JSON.stringify(root)}`\n : `make-docs project state recover ${pending.operation_id} --rollback --dry-run --target-root ${JSON.stringify(root)}`\n : null;\n return { ...base, projectId: row.project_id, checkoutId: row.checkout_id, storeAvailable: true, installationVersion: manifest ? JSON.parse(manifest).packageVersion : null, pendingOperation: pending ? {operation_id: pending.operation_id, operation: pending.operation, planComplete: Boolean(pending.plan_complete), ...(prepared ? {mode: prepared.mode, reviewDigest: prepared.reviewDigest} : {})} : null, status: lock && !isDead(lock.pid, lock.hostname) ? 'writer-active' : pending ? 'recovery-required' : manifest ? 'ready' : 'unregistered', nextAction: pendingAction ?? (lock ? 'Wait for the active writer.' : manifest ? 'No recovery is required.' : 'Review setup before installing.') };\n }, { storeRoot: store, readOnly: true });\n }\n catch (e) {\n return { ...base, status: e instanceof InstallationStateError ? e.code : 'store-unavailable', storeAvailable: false, nextAction: e instanceof Error ? e.message : String(e) };\n }\n}\n\n/**\n * Review the latest completed project removal as a possible plain-setup handoff.\n *\n * This is read-only. It accepts only the same verified checkout, an absent\n * current ledger, one sealed completed setup.remove operation, and an exact\n * unchanged backup for every removed file. Project-owned paths that were not\n * removed remain outside Make Docs ownership and are reviewed by the new plan.\n */\nexport function reviewCompletedRemovalHandoff(\n projectRoot: string,\n storeRoot?: string,\n): CompletedRemovalHandoffReview {\n const root = canonicalInstallationPath(projectRoot);\n const noHandoff = (): CompletedRemovalHandoffReview => ({ status: 'none' });\n try {\n const store = validateInstallationStoreRoot(root, storeRoot ?? resolveStoreRoot());\n if (!existsSync(getStoreDatabasePath(store))) return noHandoff();\n if (classifyStoreCheckpoint9State(store).state !== 'supported-current') return noHandoff();\n\n return withInstallationDatabase(root, db => {\n const row = checkout(db, root);\n if (!row) return noHandoff();\n const currentLedger = db.prepare(\n 'SELECT manifest_json FROM installation_ledgers WHERE checkout_id=?',\n ).get(row.checkout_id) as { manifest_json: string } | undefined;\n if (currentLedger) return noHandoff();\n const pending = db.prepare(\n \"SELECT operation_id FROM installation_operations WHERE checkout_id=? AND status='pending' LIMIT 1\",\n ).get(row.checkout_id) as { operation_id: string } | undefined;\n if (pending) return noHandoff();\n\n const operation = db.prepare(\n \"SELECT * FROM installation_operations WHERE checkout_id=? AND status='completed' ORDER BY finished_at DESC, operation_id DESC LIMIT 1\",\n ).get(row.checkout_id) as (Operation & { finished_at: string | null }) | undefined;\n if (!operation || operation.operation !== 'setup.remove' || !operation.before_ledger || operation.before_ledger === 'null') {\n return noHandoff();\n }\n\n const blockers: string[] = [];\n try {\n assertCheckoutIdentity(row, root);\n }\n catch (error) {\n blockers.push(\n `The completed removal checkout identity is not valid: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n let beforeManifest: InstallManifest | null = null;\n try {\n beforeManifest = validateAndMigrateManifest(\n JSON.parse(operation.before_ledger),\n 'completed setup.remove before-ledger',\n );\n }\n catch (error) {\n blockers.push(\n `The completed removal before-ledger is invalid: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (operation.after_ledger !== 'null') {\n blockers.push('The completed removal did not finish with an empty installation ledger.');\n }\n if (!operation.plan_complete) {\n blockers.push('The completed removal plan was not sealed before its file changes.');\n }\n let declaredProjectId: string | null = null;\n try {\n declaredProjectId = readDeclarativeProjectId(root);\n }\n catch (error) {\n blockers.push(\n `The completed removal project identity cannot be verified: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (declaredProjectId !== row.project_id) {\n blockers.push('The project identity no longer matches the completed removal checkout.');\n }\n if (beforeManifest?.projectId !== row.project_id) {\n blockers.push('The completed removal ledger does not match the current project identity.');\n }\n\n const rawSteps = db.prepare(\n 'SELECT * FROM installation_steps WHERE operation_id=? ORDER BY ordinal',\n ).all(operation.operation_id) as unknown as Step[];\n const steps = rawSteps.map(step => ({\n ...step,\n before: parseCompletedRemovalFileState(step.before_json),\n after: parseCompletedRemovalFileState(step.after_json),\n }));\n if (steps.length === 0) blockers.push('The completed removal has no saved file plan.');\n for (const step of steps) {\n if (!step.before || !step.after) {\n blockers.push(`The completed removal has invalid file evidence for ${step.relative_path}.`);\n continue;\n }\n if (!step.applied) {\n blockers.push(`The completed removal did not apply its reviewed action for ${step.relative_path}.`);\n continue;\n }\n try {\n if (!matches(root, step.relative_path, step.after)) {\n blockers.push(`The completed removal output changed at ${step.relative_path}.`);\n }\n }\n catch (error) {\n blockers.push(\n `The completed removal output cannot be verified at ${step.relative_path}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n const backupRootSteps = steps.filter(step => {\n if (!step.before || !step.after) return false;\n const normalized = normalizeOperationPath(step.relative_path);\n return step.before.kind === 'missing'\n && step.after.kind === 'directory'\n && path.posix.dirname(normalized) === '.make-docs/backup';\n });\n if (backupRootSteps.length === 0) return noHandoff();\n if (backupRootSteps.length > 1) {\n blockers.push('The completed removal does not have one exact reviewed backup root.');\n }\n const backupRoot = backupRootSteps[0]\n ? normalizeOperationPath(backupRootSteps[0].relative_path)\n : '';\n if (\n backupRootSteps.length === 1\n && !existsSync(assertSafeFilePath(root, backupRoot))\n ) {\n return noHandoff();\n }\n const insideBackup = (candidate: string) => {\n const normalized = normalizeOperationPath(candidate);\n return backupRoot !== '' && (normalized === backupRoot || normalized.startsWith(`${backupRoot}/`));\n };\n const removedSteps = steps.filter(step =>\n step.before && step.after\n && step.before.kind !== 'missing'\n && step.after.kind === 'missing'\n && !insideBackup(step.relative_path),\n );\n if (removedSteps.length === 0) {\n blockers.push('The completed removal has no reviewed removed paths.');\n }\n const backupFileSteps = new Map(\n steps\n .filter(step => step.after?.kind === 'file' && insideBackup(step.relative_path))\n .map(step => [normalizeOperationPath(step.relative_path), step]),\n );\n for (const removed of removedSteps) {\n if (removed.before?.kind !== 'file' || !backupRoot) continue;\n const backupRelativePath = removalBackupRelativePath(root, removed.relative_path);\n const backupPath = backupRelativePath\n ? path.posix.join(backupRoot, backupRelativePath)\n : null;\n const backup = backupPath ? backupFileSteps.get(backupPath) : undefined;\n if (!backup || backup.after?.kind !== 'file' || backup.after.digest !== removed.before.digest) {\n blockers.push(`The verified backup does not match removed file ${removed.relative_path}.`);\n }\n }\n if (backupRoot) {\n const recordedBackupFiles = new Set(backupFileSteps.keys());\n for (const currentPath of listCompletedRemovalBackupFiles(root, backupRoot)) {\n if (!recordedBackupFiles.has(currentPath)) {\n blockers.push(`The completed removal backup has unreviewed file ${currentPath}.`);\n }\n }\n }\n\n if (!beforeManifest || blockers.length > 0) {\n return {\n status: 'blocked',\n operationId: operation.operation_id,\n projectId: row.project_id,\n checkoutId: row.checkout_id,\n blockers: [...new Set(blockers)].sort(),\n nextAction: 'Restore the completed removal backup, project identity, and target files to their reviewed state. Then run make-docs setup again.',\n };\n }\n\n const removedPaths = [...new Set(removedSteps.map(step => normalizeOperationPath(step.relative_path)))].sort();\n const removedSet = new Set(removedPaths);\n const preservedPaths = Object.keys(beforeManifest.files)\n .map(normalizeOperationPath)\n .filter(relativePath => !removedSet.has(relativePath))\n .sort();\n return {\n status: 'ready',\n operationId: operation.operation_id,\n projectId: row.project_id,\n checkoutId: row.checkout_id,\n beforeManifest,\n backupRoot,\n removedPaths,\n preservedPaths,\n };\n }, { storeRoot: store, readOnly: true });\n }\n catch {\n return noHandoff();\n }\n}\n\nfunction parseCompletedRemovalFileState(value: string): FileState | null {\n try {\n const parsed = JSON.parse(value) as FileState;\n if (!parsed || typeof parsed !== 'object') return null;\n if (parsed.kind === 'missing' || parsed.kind === 'directory') return parsed;\n if (parsed.kind === 'file' && typeof parsed.digest === 'string') return parsed;\n if (parsed.kind === 'symlink' && typeof parsed.target === 'string') return parsed;\n return null;\n }\n catch {\n return null;\n }\n}\n\nfunction normalizeOperationPath(value: string): string {\n return value.split(path.sep).join('/');\n}\n\nfunction removalBackupRelativePath(root: string, operationPath: string): string | null {\n const absolute = path.isAbsolute(operationPath)\n ? path.normalize(operationPath)\n : path.resolve(root, operationPath);\n const projectRelative = path.relative(root, absolute);\n if (projectRelative === '' || (!projectRelative.startsWith('..') && !path.isAbsolute(projectRelative))) {\n return normalizeOperationPath(projectRelative);\n }\n const home = platform.userHome();\n const homeRelative = path.relative(home, absolute);\n if (homeRelative === '' || (!homeRelative.startsWith('..') && !path.isAbsolute(homeRelative))) {\n return path.posix.join('_home', normalizeOperationPath(homeRelative));\n }\n return null;\n}\n\nfunction listCompletedRemovalBackupFiles(root: string, backupRoot: string): string[] {\n const absoluteRoot = assertSafeFilePath(root, backupRoot);\n if (!existsSync(absoluteRoot)) return [];\n const files: string[] = [];\n const stack = [absoluteRoot];\n while (stack.length > 0) {\n const current = stack.pop()!;\n for (const entry of readdirSync(current, { withFileTypes: true })) {\n const absolute = path.join(current, entry.name);\n if (entry.isDirectory()) {\n stack.push(absolute);\n }\n else if (entry.isFile()) {\n files.push(normalizeOperationPath(path.relative(root, absolute)));\n }\n else {\n files.push(normalizeOperationPath(path.relative(root, absolute)));\n }\n }\n }\n return files.sort();\n}\nexport function recoverInstallationOperation(projectRoot: string, operationId: string, mode: 'resume' | 'rollback', dryRun: boolean, storeRoot?: string) {\n if (mode !== 'resume' && mode !== 'rollback')\n return fail('recovery-required', 'Choose exactly one recovery mode.');\n const root = canonicalInstallationPath(projectRoot);\n const store = validateInstallationStoreRoot(root, storeRoot ?? resolveStoreRoot());\n const read = () => withInstallationDatabase(root, db => {\n const row = checkout(db, root);\n if (!row)\n fail('ownership-unverified', 'No checkout binding.');\n assertCheckoutIdentity(row, root);\n const op = db.prepare('SELECT * FROM installation_operations WHERE operation_id=? AND checkout_id=?').get(operationId, row.checkout_id) as unknown as Operation | undefined;\n if (!op)\n fail('ownership-unverified', 'Operation does not belong to this checkout.');\n const steps = db.prepare('SELECT * FROM installation_steps WHERE operation_id=? ORDER BY ordinal').all(operationId) as unknown as Step[];\n const detached = detachedSnapshot(db, op);\n if (detached) assertDetachedPaths(root, detached, false, op.operation);\n const temporary = detached ? atomicTemporaryStates(db, root, op, steps) : undefined;\n return { op, steps, detached, temporary };\n }, { storeRoot: store, readOnly: true });\n const select = (state: ReturnType<typeof read>) => {\n const ordered = mode === 'rollback' ? [...state.steps].reverse() : state.steps;\n const byPath = new Map<string, Step[]>();\n for (const step of state.steps) {\n const group = byPath.get(step.relative_path) ?? [];\n group.push(step);\n byPath.set(step.relative_path, group);\n }\n const selected = new Set<number>();\n const conflicts: string[] = [];\n const equal = (a: FileState, b: FileState) => a.kind === b.kind && a.digest === b.digest && a.target === b.target && (b.mode === undefined || (a.mode !== undefined && platform.matchesFileMode(a.mode, b.mode)));\n const lastSteps = new Map([...byPath].map(([p, items]) => [p, items[items.length - 1]]));\n for (const [relative, steps] of byPath) {\n const current = subsumedByAncestor(root, steps[steps.length - 1], lastSteps) || (state.detached && JSON.parse(steps[0].before_json).kind === 'missing' && underSavedBeforeLink(root,relative,state.detached.changes)) ? { kind: \"missing\" as const } : inspect(root, relative);\n let boundary = -2;\n if (equal(current, JSON.parse(steps[0].before_json)))\n boundary = -1;\n for (let i = 0; i < steps.length; i++)\n if (equal(current, JSON.parse(steps[i].after_json)))\n boundary = i;\n if (boundary === -2) {\n conflicts.push(relative);\n continue;\n }\n for (let i = 0; i < steps.length; i++)\n if (mode === 'resume' ? i > boundary : i <= boundary)\n selected.add(steps[i].ordinal);\n }\n const remaining = ordered.filter(s => selected.has(s.ordinal));\n conflicts.push(...validateDetached(root, state.op, state.detached, state.detached?.mode === 'manual' && mode === 'resume' ? 'after' : 'progress', state.temporary));\n return { ordered, remaining, conflicts };\n };\n const state = read();\n if (state.op.status === 'pending' && mode === 'resume' && state.steps.some(step=>isRetiredSkillPath(root,step.relative_path) && JSON.parse(step.after_json).kind !== 'missing')) return {schemaVersion:1 as const,operationId,mode,dryRun,status:'blocked',changes:[],conflicts:['This saved plan writes retired .make-docs/agentics paths. Preserve its Store evidence and saved bytes; a current reviewed Skill layout cutover is required.']};\n if (state.op.status === 'pending' && mode === 'rollback' && state.steps.some(step=>isRetiredSkillPath(root,step.relative_path) && JSON.parse(step.before_json).kind !== 'missing')) return {schemaVersion:1 as const,operationId,mode,dryRun,status:'blocked',changes:[],conflicts:['Rollback would recreate retired .make-docs/agentics paths. This cutover supports forward resume only. Preserve the reviewed backup and Store bytes; inspect --resume --dry-run.']};\n const { ordered, remaining, conflicts } = select(state);\n const result = { schemaVersion: 1 as const, operationId, mode, dryRun, status: state.op.status === 'pending' ? (conflicts.length ? 'blocked' : 'ready') : state.op.status, changes: ordered.map(s => ({ path: s.relative_path, to: JSON.parse(mode === 'resume' ? s.after_json : s.before_json).kind })), conflicts };\n if (mode === 'resume' && !state.op.plan_complete)\n return { ...result, status: 'blocked', conflicts: ['The complete change plan was not saved. Review rollback; do not infer missing steps.'] };\n if (state.op.operation === 'legacy.recovery')\n return { ...result, status: 'blocked', conflicts: ['Legacy recovery needs its verified migration snapshot; no generic replay is safe.'] };\n if (dryRun || state.op.status !== 'pending')\n return result;\n if (conflicts.length)\n fail('snapshot-drift', `Recovery preserves changed files: ${[...new Set(conflicts)].join(', ')}`);\n recoverDeadStoreLeases(store);\n if (state.steps.some(step => path.isAbsolute(step.relative_path)))\n recoverDeadStoreLeases(canonicalInstallationPath(resolveStoreRoot()));\n // A crashed lock can be released only with same-host process death evidence.\n withInstallationDatabase(root, db => transaction(db, () => { const owner = db.prepare('SELECT pid,hostname FROM installation_locks WHERE root_path=?').get(root) as {\n pid: number;\n hostname: string;\n } | undefined; if (owner) {\n if (!isDead(owner.pid, owner.hostname))\n fail('writer-active', 'Prior writer is live or cannot be proven inactive.');\n db.prepare('DELETE FROM installation_locks WHERE root_path=?').run(root);\n } }), { storeRoot: store });\n const lock = acquireInstallationLock(root, store);\n try {\n if (state.op.operation === 'setup.skills.adopt' || state.steps.some(step => path.isAbsolute(step.relative_path)))\n held.get(root)!.globalLock = acquireGlobalAssetLock(root);\n let current = read();\n if (current.op.status !== 'pending')\n return { ...result, status: current.op.status };\n assertNoOtherPendingPathClaims(root, [...current.steps.map(s => s.relative_path), ...Object.keys(current.op.after_ledger ? JSON.parse(current.op.after_ledger)?.files ?? {} : {})], store);\n const locked = select(current);\n if (locked.conflicts.length)\n fail('snapshot-drift', `Recovery input changed: ${locked.conflicts.join(', ')}`);\n if (current.detached) cleanAtomicTemporaryFiles(root, current.op, current.steps, lock);\n let pendingSteps = current.detached?.mode === 'manual' && mode === 'resume' ? [] : [...locked.remaining];\n let checkedCutoverDestinations = false;\n while (pendingSteps.length) {\n const s = pendingSteps.shift()!;\n assertInstallationLockActive(lock);\n if (!checkedCutoverDestinations && mode === 'resume' && current.detached?.skillScope && isRetiredSkillPath(root, s.relative_path)) {\n const cleanupCheck = detachedHooks.get(current.op.operation)?.beforeRetiredCleanup;\n if (!cleanupCheck) fail('recovery-required', 'This CLI cannot verify all standard Skill destinations before retired source cleanup.');\n const issues = cleanupCheck(root, current.detached.metadata);\n if (issues.length) fail('snapshot-drift', issues.join('\\n'));\n const final = new Map(current.steps.map(step => [step.relative_path, step]));\n for (const step of final.values()) {\n if (isRetiredSkillPath(root, step.relative_path) || subsumedByAncestor(root, step, final)) continue;\n if (!matches(root, step.relative_path, JSON.parse(step.after_json))) fail('snapshot-drift', `Standard Skill destination must match before retired source cleanup: ${step.relative_path}`);\n }\n checkedCutoverDestinations = true;\n }\n const from: FileState = JSON.parse(mode === 'resume' ? s.before_json : s.after_json);\n const to: FileState = JSON.parse(mode === 'resume' ? s.after_json : s.before_json);\n if (matches(root, s.relative_path, to))\n continue;\n if (!matches(root, s.relative_path, from))\n fail('snapshot-drift', `Recovery input changed: ${s.relative_path}`);\n try {\n restoreState(root, s.relative_path, to, current.detached ? {op: current.op, step: s, expected: from, lock} : undefined);\n } catch (error) {\n if (mode !== 'resume' || !current.detached || !selectDetachedCopyFallback(root, current.op, current.detached, s, error, lock)) throw error;\n current = read();\n const reselected = select(current);\n if (reselected.conflicts.length) fail('snapshot-drift', `Fallback inputs changed: ${reselected.conflicts.join(', ')}`);\n pendingSteps = [...reselected.remaining];\n continue;\n }\n if (!matches(root, s.relative_path, to))\n fail('snapshot-drift', 'Recovery output verification failed.');\n }\n const finalSteps = new Map<string, Step>();\n for (const step of (mode === 'rollback' ? [...current.steps].reverse() : current.steps))\n finalSteps.set(step.relative_path, step);\n for (const step of finalSteps.values()) {\n if (mode === 'resume' && subsumedByAncestor(root, step, finalSteps))\n continue;\n if (!matches(root, step.relative_path, JSON.parse(mode === 'resume' ? step.after_json : step.before_json)))\n fail('snapshot-drift', `Recovery output changed before commit: ${step.relative_path}`);\n }\n assertInstallationLockActive(lock);\n const finalIssues = validateDetached(root, current.op, current.detached, mode === 'rollback' ? 'before' : 'after');\n if (finalIssues.length) fail('snapshot-drift', finalIssues.join('\\n'));\n if (mode === 'resume' && current.detached?.skillScope && current.detached.afterLedger) for (const exposure of Object.keys(current.detached.skillScope.symlinkTargets)) {\n const entry = current.detached.afterLedger.files[exposure];\n const finalStep = finalSteps.get(exposure);\n if (!entry && finalStep && JSON.parse(finalStep.after_json).kind === 'missing' && matches(root, exposure, {kind: 'missing'})) continue;\n const recorded = entry?.skillExposure?.mode;\n if (!recorded || inspect(root, exposure).kind !== (recorded === 'symlink' ? 'symlink' : 'directory')) fail('snapshot-drift', 'Final native exposure and ownership mode disagree.');\n }\n withInstallationDatabase(root, db => commitOperation(db, operationId, root, mode === 'rollback'), { storeRoot: store });\n return { ...result, changes: current.steps.map(s => ({path: s.relative_path, to: JSON.parse(mode === 'resume' ? s.after_json : s.before_json).kind})), status: mode === 'resume' ? 'completed' : 'rolled-back' };\n }\n finally {\n releaseInstallationLock(lock);\n }\n}\nexport type MigrationRecordKind = 'receipt' | 'quiescence' | 'snapshot' | 'backup' | 'legacy-import';\nexport function recordMigrationState(projectRoot: string, kind: MigrationRecordKind, id: string, value: unknown, storeRoot?: string): void { const cid = getInstallationCheckoutId(projectRoot, storeRoot); withInstallationDatabase(projectRoot, db => db.prepare('INSERT INTO installation_migration_records VALUES (?,?,?,?) ON CONFLICT(checkout_id,kind,record_id) DO UPDATE SET record_json=excluded.record_json').run(cid, kind, id, JSON.stringify(value)), { storeRoot }); }\nexport function readMigrationState<T = unknown>(projectRoot: string, kind: MigrationRecordKind, id: string, storeRoot?: string): T | null { if (!hasInstallationSchema(projectRoot, storeRoot))\n return null; return withInstallationDatabase(projectRoot, db => { const row = checkout(db, canonicalInstallationPath(projectRoot)); if (!row)\n return null; assertCheckoutIdentity(row, canonicalInstallationPath(projectRoot)); const record = db.prepare('SELECT record_json FROM installation_migration_records WHERE checkout_id=? AND kind=? AND record_id=?').get(row.checkout_id, kind, id) as {\n record_json: string;\n} | undefined; return record ? JSON.parse(record.record_json) : null; }, { storeRoot, readOnly: true }); }\nexport function listMigrationState<T = unknown>(projectRoot: string, kind: MigrationRecordKind, storeRoot?: string): T[] { if (!hasInstallationSchema(projectRoot, storeRoot))\n return []; return withInstallationDatabase(projectRoot, db => { const row = checkout(db, canonicalInstallationPath(projectRoot)); if (!row)\n return []; assertCheckoutIdentity(row, canonicalInstallationPath(projectRoot)); return (db.prepare('SELECT record_json FROM installation_migration_records WHERE checkout_id=? AND kind=?').all(row.checkout_id, kind) as {\n record_json: string;\n}[]).map(r => JSON.parse(r.record_json)); }, { storeRoot, readOnly: true }); }\nexport function deleteMigrationState(projectRoot: string, kind: MigrationRecordKind, id: string, storeRoot?: string): void { withInstallationDatabase(projectRoot, db => { const row = checkout(db, canonicalInstallationPath(projectRoot)); if (row)\n db.prepare('DELETE FROM installation_migration_records WHERE checkout_id=? AND kind=? AND record_id=?').run(row.checkout_id, kind, id); }, { storeRoot }); }\n\nfunction isSetupBridgeIdentityRecord(row: {\n kind: string;\n record_id: string;\n record_json: string;\n}): boolean {\n let value: Record<string, unknown>;\n try {\n const parsed = JSON.parse(row.record_json) as unknown;\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))\n return false;\n value = parsed as Record<string, unknown>;\n }\n catch {\n return false;\n }\n if (row.kind === 'quiescence' && row.record_id === 'legacy') {\n return value.schemaVersion === 1 && value.status === 'active' &&\n typeof value.snapshotId === 'string' && /^sha256:[a-f0-9]{64}$/.test(value.snapshotId) &&\n typeof value.lockTokenDigest === 'string' && /^[a-f0-9]{64}$/.test(value.lockTokenDigest) &&\n Array.isArray(value.legacyOperations);\n }\n if (row.kind === 'receipt') {\n return value.schemaVersion === 1 && value.status === 'completed' && value.checkpoint === 9 &&\n value.receiptId === row.record_id && typeof value.receiptId === 'string' &&\n /^sha256:[a-f0-9]{64}$/.test(value.receiptId) &&\n typeof value.snapshotId === 'string' && /^sha256:[a-f0-9]{64}$/.test(value.snapshotId);\n }\n return false;\n}\n\n/**\n * A schema-1/2 Store can retain the project id in `projects` while the setup\n * bridge creates its first installation checkout under a temporary id.\n * Adopt the old id only while that checkout still contains bridge-only state.\n */\nfunction adoptLegacyProjectIdentity(db: StoreDatabase, root: string, projectId: string): void {\n const current = checkout(db, root);\n if (!current || current.project_id === projectId)\n return;\n const declarativeId = readDeclarativeProjectId(root);\n if (declarativeId && declarativeId !== projectId)\n fail('ownership-unverified', 'The legacy project identity conflicts with the checkout config.');\n const legacy = db.prepare('SELECT project_id,root_path FROM projects WHERE project_id=?').all(projectId) as Array<{\n project_id: string;\n root_path: string;\n }>;\n if (legacy.length !== 1 || !platform.samePath(legacy[0].root_path, root))\n fail('ownership-unverified', 'The legacy project identity has no matching project registry path.');\n const legacyPathOwners = (db.prepare('SELECT project_id,root_path FROM projects').all() as Array<{\n project_id: string;\n root_path: string;\n }>).filter(row => platform.samePath(row.root_path, root));\n if (legacyPathOwners.length !== 1 || legacyPathOwners[0].project_id !== projectId)\n fail('ownership-unverified', 'More than one legacy project identity claims this checkout path.');\n const competing = (db.prepare('SELECT checkout_id FROM installation_checkouts WHERE project_id=?').all(projectId) as Array<{\n checkout_id: string;\n }>).filter(row => row.checkout_id !== current.checkout_id);\n if (competing.length)\n fail('ownership-unverified', 'Another checkout already owns the legacy project identity.');\n if (db.prepare('SELECT 1 FROM installation_ledgers WHERE checkout_id=?').get(current.checkout_id))\n fail('ownership-unverified', 'The temporary checkout already has an installation ledger.');\n if (db.prepare('SELECT 1 FROM installation_operations WHERE checkout_id=?').get(current.checkout_id))\n fail('recovery-required', 'The temporary checkout has project work that requires recovery.');\n if (db.prepare('SELECT 1 FROM installation_transfers WHERE checkout_id=?').get(current.checkout_id))\n fail('ownership-unverified', 'The temporary checkout has legacy transfer history.');\n if (current.verified_at !== null || current.verification_json !== null)\n fail('ownership-unverified', 'The checkout identity already has verification evidence.');\n const records = db.prepare('SELECT kind,record_id,record_json FROM installation_migration_records WHERE checkout_id=?').all(current.checkout_id) as Array<{\n kind: string;\n record_id: string;\n record_json: string;\n }>;\n if (records.some(record => !isSetupBridgeIdentityRecord(record)))\n fail('ownership-unverified', 'The temporary checkout contains non-bridge migration state.');\n const verifiedAt = now();\n const verificationJson = JSON.stringify(checkoutVerificationEvidence(\n db,\n root,\n projectId,\n current.checkout_id,\n null,\n ));\n db.prepare('UPDATE installation_checkouts SET project_id=?,verified_at=?,verification_json=? WHERE checkout_id=?')\n .run(projectId, verifiedAt, verificationJson, current.checkout_id);\n}\n\n/** Save useful legacy records and exact source provenance in one Store transaction. */\nexport function importInstallationState(projectRoot: string, input: {\n manifest: InstallManifest | null;\n records: {\n kind: MigrationRecordKind;\n id: string;\n value: unknown;\n }[];\n importId: string;\n sources: {\n relativePath: string;\n digest: string;\n }[];\n recoveryRequired: boolean;\n}, storeRoot?: string): void {\n const root = canonicalInstallationPath(projectRoot);\n const lock = acquireInstallationLock(root, storeRoot);\n try {\n withInstallationDatabase(root, db => transaction(db, () => {\n if (input.manifest?.projectId)\n adoptLegacyProjectIdentity(db, root, input.manifest.projectId);\n const row = bindCheckout(db, root, input.manifest?.projectId);\n const prior = db.prepare(\"SELECT record_json FROM installation_migration_records WHERE checkout_id=? AND kind='legacy-import' AND record_id=?\").get(row.checkout_id, input.importId);\n if (prior)\n return;\n const ledger = db.prepare('SELECT manifest_json FROM installation_ledgers WHERE checkout_id=?').get(row.checkout_id) as {\n manifest_json: string;\n } | undefined;\n if (ledger && input.manifest && JSON.stringify(JSON.parse(ledger.manifest_json)) !== JSON.stringify(input.manifest))\n fail('ownership-unverified', 'Legacy ledger conflicts with existing Store ownership.');\n if (input.manifest)\n db.prepare('INSERT INTO installation_ledgers VALUES (?,?,?) ON CONFLICT(checkout_id) DO NOTHING').run(row.checkout_id, JSON.stringify({ ...input.manifest, projectId: row.project_id }), now());\n for (const record of input.records) {\n const existing = db.prepare('SELECT record_json FROM installation_migration_records WHERE checkout_id=? AND kind=? AND record_id=?').get(row.checkout_id, record.kind, record.id) as {\n record_json: string;\n } | undefined;\n if (existing && canonicalJson(JSON.parse(existing.record_json)) !== canonicalJson(record.value))\n fail('ownership-unverified', 'Legacy record conflicts with existing Store evidence.');\n }\n for (const record of input.records)\n db.prepare('INSERT INTO installation_migration_records VALUES (?,?,?,?) ON CONFLICT(checkout_id,kind,record_id) DO NOTHING').run(row.checkout_id, record.kind, record.id, JSON.stringify(record.value));\n db.prepare(\"INSERT INTO installation_migration_records VALUES (?,'legacy-import',?,?)\").run(row.checkout_id, input.importId, JSON.stringify({ sources: input.sources, recoveryRequired: input.recoveryRequired, importedAt: now() }));\n if (input.recoveryRequired)\n db.prepare(\"INSERT INTO installation_operations (operation_id,checkout_id,operation,status,before_ledger,after_ledger,created_at,finished_at) VALUES (?,?,?,'pending',?,?,?,NULL)\").run(input.importId, row.checkout_id, 'legacy.recovery', ledger?.manifest_json ?? null, input.manifest ? JSON.stringify(input.manifest) : null, now());\n }), { storeRoot: lock.storeRoot });\n if (!input.recoveryRequired)\n withInstallationOperation(root, 'legacy.identity', () => ensureDeclarativeIdentity(root), { storeRoot: lock.storeRoot, projectId: input.manifest?.projectId });\n }\n finally {\n releaseInstallationLock(lock);\n }\n}\nfunction ensureDeclarativeIdentity(root: string): void {\n const id = getInstallationProjectId(root);\n const prior = readDeclarativeProjectId(root);\n if (prior) {\n if (prior !== id)\n fail('ownership-unverified', 'Conflicting project identity.');\n return;\n }\n const relative = '.make-docs/config.yaml';\n const file = assertSafeFilePath(root, relative);\n const doc = parseDocument(existsSync(file) ? readFileSync(file, 'utf8') : '', { uniqueKeys: true });\n if (doc.errors.length || (doc.contents !== null && !doc.toJS()) || (doc.contents !== null && typeof doc.toJS() !== 'object') || Array.isArray(doc.toJS()))\n fail('ownership-unverified', 'Unsupported project config.');\n doc.set('projectId', id);\n const content = doc.toString();\n recordPlannedFileChange(root, relative, { kind: 'file', content }, () => { mkdirSync(path.dirname(file), { recursive: true }); writeFileSync(file, content); });\n}\nfunction hasInstallationSchema(root: string, override?: string): boolean { const canonical = canonicalInstallationPath(root); const store = validateInstallationStoreRoot(canonical, override ?? active.get(canonical)?.storeRoot ?? held.get(canonical)?.storeRoot ?? resolveStoreRoot()); const c = classifyStoreCheckpoint9State(store); if (c.state === 'absent' || c.state === 'supported-legacy')\n return false; if (c.state !== 'supported-current')\n fail('store-unavailable', `Store is ${c.state}.`); return true; }\nfunction canonicalJson(value: unknown): string { const sort = (v: any): any => Array.isArray(v) ? v.map(sort) : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map(k => [k, sort(v[k])])) : v; return JSON.stringify(sort(value)); }\nfunction subsumedByAncestor(root: string, step: Step, last: Map<string, Step>): boolean { for (const candidate of [...last.values()].sort((a, b) => a.relative_path.split(path.sep).length - b.relative_path.split(path.sep).length)) {\n if (candidate.ordinal <= step.ordinal)\n continue;\n const rel = path.relative(path.resolve(root, candidate.relative_path), path.resolve(root, step.relative_path));\n if (!rel || rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel))\n continue;\n const after: FileState = JSON.parse(candidate.after_json);\n if ((after.kind === 'missing' || after.kind === 'symlink') && matches(root, candidate.relative_path, after))\n return true;\n} return false; }\n","const ALIAS = Symbol.for('yaml.alias');\nconst DOC = Symbol.for('yaml.document');\nconst MAP = Symbol.for('yaml.map');\nconst PAIR = Symbol.for('yaml.pair');\nconst SCALAR = Symbol.for('yaml.scalar');\nconst SEQ = Symbol.for('yaml.seq');\nconst NODE_TYPE = Symbol.for('yaml.node.type');\nconst isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;\nconst isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;\nconst isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;\nconst isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;\nconst isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;\nconst isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;\nfunction isCollection(node) {\n if (node && typeof node === 'object')\n switch (node[NODE_TYPE]) {\n case MAP:\n case SEQ:\n return true;\n }\n return false;\n}\nfunction isNode(node) {\n if (node && typeof node === 'object')\n switch (node[NODE_TYPE]) {\n case ALIAS:\n case MAP:\n case SCALAR:\n case SEQ:\n return true;\n }\n return false;\n}\nconst hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;\n\nexport { ALIAS, DOC, MAP, NODE_TYPE, PAIR, SCALAR, SEQ, hasAnchor, isAlias, isCollection, isDocument, isMap, isNode, isPair, isScalar, isSeq };\n","import { isDocument, isNode, isPair, isCollection, isMap, isSeq, isScalar, isAlias } from './nodes/identity.js';\n\nconst BREAK = Symbol('break visit');\nconst SKIP = Symbol('skip children');\nconst REMOVE = Symbol('remove node');\n/**\n * Apply a visitor to an AST node or document.\n *\n * Walks through the tree (depth-first) starting from `node`, calling a\n * `visitor` function with three arguments:\n * - `key`: For sequence values and map `Pair`, the node's index in the\n * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.\n * `null` for the root node.\n * - `node`: The current node.\n * - `path`: The ancestry of the current node.\n *\n * The return value of the visitor may be used to control the traversal:\n * - `undefined` (default): Do nothing and continue\n * - `visit.SKIP`: Do not visit the children of this node, continue with next\n * sibling\n * - `visit.BREAK`: Terminate traversal completely\n * - `visit.REMOVE`: Remove the current node, then continue with the next one\n * - `Node`: Replace the current node, then continue by visiting it\n * - `number`: While iterating the items of a sequence or map, set the index\n * of the next step. This is useful especially if the index of the current\n * node has changed.\n *\n * If `visitor` is a single function, it will be called with all values\n * encountered in the tree, including e.g. `null` values. Alternatively,\n * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,\n * `Alias` and `Scalar` node. To define the same visitor function for more than\n * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)\n * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most\n * specific defined one will be used for each node.\n */\nfunction visit(node, visitor) {\n const visitor_ = initVisitor(visitor);\n if (isDocument(node)) {\n const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));\n if (cd === REMOVE)\n node.contents = null;\n }\n else\n visit_(null, node, visitor_, Object.freeze([]));\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisit.BREAK = BREAK;\n/** Do not visit the children of the current node */\nvisit.SKIP = SKIP;\n/** Remove the current node */\nvisit.REMOVE = REMOVE;\nfunction visit_(key, node, visitor, path) {\n const ctrl = callVisitor(key, node, visitor, path);\n if (isNode(ctrl) || isPair(ctrl)) {\n replaceNode(key, path, ctrl);\n return visit_(key, ctrl, visitor, path);\n }\n if (typeof ctrl !== 'symbol') {\n if (isCollection(node)) {\n path = Object.freeze(path.concat(node));\n for (let i = 0; i < node.items.length; ++i) {\n const ci = visit_(i, node.items[i], visitor, path);\n if (typeof ci === 'number')\n i = ci - 1;\n else if (ci === BREAK)\n return BREAK;\n else if (ci === REMOVE) {\n node.items.splice(i, 1);\n i -= 1;\n }\n }\n }\n else if (isPair(node)) {\n path = Object.freeze(path.concat(node));\n const ck = visit_('key', node.key, visitor, path);\n if (ck === BREAK)\n return BREAK;\n else if (ck === REMOVE)\n node.key = null;\n const cv = visit_('value', node.value, visitor, path);\n if (cv === BREAK)\n return BREAK;\n else if (cv === REMOVE)\n node.value = null;\n }\n }\n return ctrl;\n}\n/**\n * Apply an async visitor to an AST node or document.\n *\n * Walks through the tree (depth-first) starting from `node`, calling a\n * `visitor` function with three arguments:\n * - `key`: For sequence values and map `Pair`, the node's index in the\n * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.\n * `null` for the root node.\n * - `node`: The current node.\n * - `path`: The ancestry of the current node.\n *\n * The return value of the visitor may be used to control the traversal:\n * - `Promise`: Must resolve to one of the following values\n * - `undefined` (default): Do nothing and continue\n * - `visit.SKIP`: Do not visit the children of this node, continue with next\n * sibling\n * - `visit.BREAK`: Terminate traversal completely\n * - `visit.REMOVE`: Remove the current node, then continue with the next one\n * - `Node`: Replace the current node, then continue by visiting it\n * - `number`: While iterating the items of a sequence or map, set the index\n * of the next step. This is useful especially if the index of the current\n * node has changed.\n *\n * If `visitor` is a single function, it will be called with all values\n * encountered in the tree, including e.g. `null` values. Alternatively,\n * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,\n * `Alias` and `Scalar` node. To define the same visitor function for more than\n * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)\n * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most\n * specific defined one will be used for each node.\n */\nasync function visitAsync(node, visitor) {\n const visitor_ = initVisitor(visitor);\n if (isDocument(node)) {\n const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));\n if (cd === REMOVE)\n node.contents = null;\n }\n else\n await visitAsync_(null, node, visitor_, Object.freeze([]));\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisitAsync.BREAK = BREAK;\n/** Do not visit the children of the current node */\nvisitAsync.SKIP = SKIP;\n/** Remove the current node */\nvisitAsync.REMOVE = REMOVE;\nasync function visitAsync_(key, node, visitor, path) {\n const ctrl = await callVisitor(key, node, visitor, path);\n if (isNode(ctrl) || isPair(ctrl)) {\n replaceNode(key, path, ctrl);\n return visitAsync_(key, ctrl, visitor, path);\n }\n if (typeof ctrl !== 'symbol') {\n if (isCollection(node)) {\n path = Object.freeze(path.concat(node));\n for (let i = 0; i < node.items.length; ++i) {\n const ci = await visitAsync_(i, node.items[i], visitor, path);\n if (typeof ci === 'number')\n i = ci - 1;\n else if (ci === BREAK)\n return BREAK;\n else if (ci === REMOVE) {\n node.items.splice(i, 1);\n i -= 1;\n }\n }\n }\n else if (isPair(node)) {\n path = Object.freeze(path.concat(node));\n const ck = await visitAsync_('key', node.key, visitor, path);\n if (ck === BREAK)\n return BREAK;\n else if (ck === REMOVE)\n node.key = null;\n const cv = await visitAsync_('value', node.value, visitor, path);\n if (cv === BREAK)\n return BREAK;\n else if (cv === REMOVE)\n node.value = null;\n }\n }\n return ctrl;\n}\nfunction initVisitor(visitor) {\n if (typeof visitor === 'object' &&\n (visitor.Collection || visitor.Node || visitor.Value)) {\n return Object.assign({\n Alias: visitor.Node,\n Map: visitor.Node,\n Scalar: visitor.Node,\n Seq: visitor.Node\n }, visitor.Value && {\n Map: visitor.Value,\n Scalar: visitor.Value,\n Seq: visitor.Value\n }, visitor.Collection && {\n Map: visitor.Collection,\n Seq: visitor.Collection\n }, visitor);\n }\n return visitor;\n}\nfunction callVisitor(key, node, visitor, path) {\n if (typeof visitor === 'function')\n return visitor(key, node, path);\n if (isMap(node))\n return visitor.Map?.(key, node, path);\n if (isSeq(node))\n return visitor.Seq?.(key, node, path);\n if (isPair(node))\n return visitor.Pair?.(key, node, path);\n if (isScalar(node))\n return visitor.Scalar?.(key, node, path);\n if (isAlias(node))\n return visitor.Alias?.(key, node, path);\n return undefined;\n}\nfunction replaceNode(key, path, node) {\n const parent = path[path.length - 1];\n if (isCollection(parent)) {\n parent.items[key] = node;\n }\n else if (isPair(parent)) {\n if (key === 'key')\n parent.key = node;\n else\n parent.value = node;\n }\n else if (isDocument(parent)) {\n parent.contents = node;\n }\n else {\n const pt = isAlias(parent) ? 'alias' : 'scalar';\n throw new Error(`Cannot replace node with ${pt} parent`);\n }\n}\n\nexport { visit, visitAsync };\n","import { isNode } from '../nodes/identity.js';\nimport { visit } from '../visit.js';\n\nconst escapeChars = {\n '!': '%21',\n ',': '%2C',\n '[': '%5B',\n ']': '%5D',\n '{': '%7B',\n '}': '%7D'\n};\nconst escapeTagName = (tn) => tn.replace(/[!,[\\]{}]/g, ch => escapeChars[ch]);\nclass Directives {\n constructor(yaml, tags) {\n /**\n * The directives-end/doc-start marker `---`. If `null`, a marker may still be\n * included in the document's stringified representation.\n */\n this.docStart = null;\n /** The doc-end marker `...`. */\n this.docEnd = false;\n this.yaml = Object.assign({}, Directives.defaultYaml, yaml);\n this.tags = Object.assign({}, Directives.defaultTags, tags);\n }\n clone() {\n const copy = new Directives(this.yaml, this.tags);\n copy.docStart = this.docStart;\n return copy;\n }\n /**\n * During parsing, get a Directives instance for the current document and\n * update the stream state according to the current version's spec.\n */\n atDocument() {\n const res = new Directives(this.yaml, this.tags);\n switch (this.yaml.version) {\n case '1.1':\n this.atNextDocument = true;\n break;\n case '1.2':\n this.atNextDocument = false;\n this.yaml = {\n explicit: Directives.defaultYaml.explicit,\n version: '1.2'\n };\n this.tags = Object.assign({}, Directives.defaultTags);\n break;\n }\n return res;\n }\n /**\n * @param onError - May be called even if the action was successful\n * @returns `true` on success\n */\n add(line, onError) {\n if (this.atNextDocument) {\n this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' };\n this.tags = Object.assign({}, Directives.defaultTags);\n this.atNextDocument = false;\n }\n const parts = line.trim().split(/[ \\t]+/);\n const name = parts.shift();\n switch (name) {\n case '%TAG': {\n if (parts.length !== 2) {\n onError(0, '%TAG directive should contain exactly two parts');\n if (parts.length < 2)\n return false;\n }\n const [handle, prefix] = parts;\n this.tags[handle] = prefix;\n return true;\n }\n case '%YAML': {\n this.yaml.explicit = true;\n if (parts.length !== 1) {\n onError(0, '%YAML directive should contain exactly one part');\n return false;\n }\n const [version] = parts;\n if (version === '1.1' || version === '1.2') {\n this.yaml.version = version;\n return true;\n }\n else {\n const isValid = /^\\d+\\.\\d+$/.test(version);\n onError(6, `Unsupported YAML version ${version}`, isValid);\n return false;\n }\n }\n default:\n onError(0, `Unknown directive ${name}`, true);\n return false;\n }\n }\n /**\n * Resolves a tag, matching handles to those defined in %TAG directives.\n *\n * @returns Resolved tag, which may also be the non-specific tag `'!'` or a\n * `'!local'` tag, or `null` if unresolvable.\n */\n tagName(source, onError) {\n if (source === '!')\n return '!'; // non-specific tag\n if (source[0] !== '!') {\n onError(`Not a valid tag: ${source}`);\n return null;\n }\n if (source[1] === '<') {\n const verbatim = source.slice(2, -1);\n if (verbatim === '!' || verbatim === '!!') {\n onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);\n return null;\n }\n if (source[source.length - 1] !== '>')\n onError('Verbatim tags must end with a >');\n return verbatim;\n }\n const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);\n if (!suffix)\n onError(`The ${source} tag has no suffix`);\n const prefix = this.tags[handle];\n if (prefix) {\n try {\n return prefix + decodeURIComponent(suffix);\n }\n catch (error) {\n onError(String(error));\n return null;\n }\n }\n if (handle === '!')\n return source; // local tag\n onError(`Could not resolve tag: ${source}`);\n return null;\n }\n /**\n * Given a fully resolved tag, returns its printable string form,\n * taking into account current tag prefixes and defaults.\n */\n tagString(tag) {\n for (const [handle, prefix] of Object.entries(this.tags)) {\n if (tag.startsWith(prefix))\n return handle + escapeTagName(tag.substring(prefix.length));\n }\n return tag[0] === '!' ? tag : `!<${tag}>`;\n }\n toString(doc) {\n const lines = this.yaml.explicit\n ? [`%YAML ${this.yaml.version || '1.2'}`]\n : [];\n const tagEntries = Object.entries(this.tags);\n let tagNames;\n if (doc && tagEntries.length > 0 && isNode(doc.contents)) {\n const tags = {};\n visit(doc.contents, (_key, node) => {\n if (isNode(node) && node.tag)\n tags[node.tag] = true;\n });\n tagNames = Object.keys(tags);\n }\n else\n tagNames = [];\n for (const [handle, prefix] of tagEntries) {\n if (handle === '!!' && prefix === 'tag:yaml.org,2002:')\n continue;\n if (!doc || tagNames.some(tn => tn.startsWith(prefix)))\n lines.push(`%TAG ${handle} ${prefix}`);\n }\n return lines.join('\\n');\n }\n}\nDirectives.defaultYaml = { explicit: false, version: '1.2' };\nDirectives.defaultTags = { '!!': 'tag:yaml.org,2002:' };\n\nexport { Directives };\n","import { isScalar, isCollection } from '../nodes/identity.js';\nimport { visit } from '../visit.js';\n\n/**\n * Verify that the input string is a valid anchor.\n *\n * Will throw on errors.\n */\nfunction anchorIsValid(anchor) {\n if (/[\\x00-\\x19\\s,[\\]{}]/.test(anchor)) {\n const sa = JSON.stringify(anchor);\n const msg = `Anchor must not contain whitespace or control characters: ${sa}`;\n throw new Error(msg);\n }\n return true;\n}\nfunction anchorNames(root) {\n const anchors = new Set();\n visit(root, {\n Value(_key, node) {\n if (node.anchor)\n anchors.add(node.anchor);\n }\n });\n return anchors;\n}\n/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */\nfunction findNewAnchor(prefix, exclude) {\n for (let i = 1; true; ++i) {\n const name = `${prefix}${i}`;\n if (!exclude.has(name))\n return name;\n }\n}\nfunction createNodeAnchors(doc, prefix) {\n const aliasObjects = [];\n const sourceObjects = new Map();\n let prevAnchors = null;\n return {\n onAnchor: (source) => {\n aliasObjects.push(source);\n prevAnchors ?? (prevAnchors = anchorNames(doc));\n const anchor = findNewAnchor(prefix, prevAnchors);\n prevAnchors.add(anchor);\n return anchor;\n },\n /**\n * With circular references, the source node is only resolved after all\n * of its child nodes are. This is why anchors are set only after all of\n * the nodes have been created.\n */\n setAnchors: () => {\n for (const source of aliasObjects) {\n const ref = sourceObjects.get(source);\n if (typeof ref === 'object' &&\n ref.anchor &&\n (isScalar(ref.node) || isCollection(ref.node))) {\n ref.node.anchor = ref.anchor;\n }\n else {\n const error = new Error('Failed to resolve repeated object (this should not happen)');\n error.source = source;\n throw error;\n }\n }\n },\n sourceObjects\n };\n}\n\nexport { anchorIsValid, anchorNames, createNodeAnchors, findNewAnchor };\n","/**\n * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,\n * in section 24.5.1.1 \"Runtime Semantics: InternalizeJSONProperty\" of the\n * 2021 edition: https://tc39.es/ecma262/#sec-json.parse\n *\n * Includes extensions for handling Map and Set objects.\n */\nfunction applyReviver(reviver, obj, key, val) {\n if (val && typeof val === 'object') {\n if (Array.isArray(val)) {\n for (let i = 0, len = val.length; i < len; ++i) {\n const v0 = val[i];\n const v1 = applyReviver(reviver, val, String(i), v0);\n // eslint-disable-next-line @typescript-eslint/no-array-delete\n if (v1 === undefined)\n delete val[i];\n else if (v1 !== v0)\n val[i] = v1;\n }\n }\n else if (val instanceof Map) {\n for (const k of Array.from(val.keys())) {\n const v0 = val.get(k);\n const v1 = applyReviver(reviver, val, k, v0);\n if (v1 === undefined)\n val.delete(k);\n else if (v1 !== v0)\n val.set(k, v1);\n }\n }\n else if (val instanceof Set) {\n for (const v0 of Array.from(val)) {\n const v1 = applyReviver(reviver, val, v0, v0);\n if (v1 === undefined)\n val.delete(v0);\n else if (v1 !== v0) {\n val.delete(v0);\n val.add(v1);\n }\n }\n }\n else {\n for (const [k, v0] of Object.entries(val)) {\n const v1 = applyReviver(reviver, val, k, v0);\n if (v1 === undefined)\n delete val[k];\n else if (v1 !== v0)\n val[k] = v1;\n }\n }\n }\n return reviver.call(obj, key, val);\n}\n\nexport { applyReviver };\n","import { hasAnchor } from './identity.js';\n\n/**\n * Recursively convert any node or its contents to native JavaScript\n *\n * @param value - The input value\n * @param arg - If `value` defines a `toJSON()` method, use this\n * as its first argument\n * @param ctx - Conversion context, originally set in Document#toJS(). If\n * `{ keep: true }` is not set, output should be suitable for JSON\n * stringification.\n */\nfunction toJS(value, arg, ctx) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n if (Array.isArray(value))\n return value.map((v, i) => toJS(v, String(i), ctx));\n if (value && typeof value.toJSON === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n if (!ctx || !hasAnchor(value))\n return value.toJSON(arg, ctx);\n const data = { aliasCount: 0, count: 1, res: undefined };\n ctx.anchors.set(value, data);\n ctx.onCreate = res => {\n data.res = res;\n delete ctx.onCreate;\n };\n const res = value.toJSON(arg, ctx);\n if (ctx.onCreate)\n ctx.onCreate(res);\n return res;\n }\n if (typeof value === 'bigint' && !ctx?.keep)\n return Number(value);\n return value;\n}\n\nexport { toJS };\n","import { applyReviver } from '../doc/applyReviver.js';\nimport { NODE_TYPE, isDocument } from './identity.js';\nimport { toJS } from './toJS.js';\n\nclass NodeBase {\n constructor(type) {\n Object.defineProperty(this, NODE_TYPE, { value: type });\n }\n /** Create a copy of this node. */\n clone() {\n const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));\n if (this.range)\n copy.range = this.range.slice();\n return copy;\n }\n /** A plain JavaScript representation of this node. */\n toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {\n if (!isDocument(doc))\n throw new TypeError('A document argument is required');\n const ctx = {\n anchors: new Map(),\n doc,\n keep: true,\n mapAsMap: mapAsMap === true,\n mapKeyWarned: false,\n maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100\n };\n const res = toJS(this, '', ctx);\n if (typeof onAnchor === 'function')\n for (const { count, res } of ctx.anchors.values())\n onAnchor(res, count);\n return typeof reviver === 'function'\n ? applyReviver(reviver, { '': res }, '', res)\n : res;\n }\n}\n\nexport { NodeBase };\n","import { anchorIsValid } from '../doc/anchors.js';\nimport { visit } from '../visit.js';\nimport { ALIAS, isAlias, isCollection, isPair, hasAnchor } from './identity.js';\nimport { NodeBase } from './Node.js';\nimport { toJS } from './toJS.js';\n\nclass Alias extends NodeBase {\n constructor(source) {\n super(ALIAS);\n this.source = source;\n Object.defineProperty(this, 'tag', {\n set() {\n throw new Error('Alias nodes cannot have tags');\n }\n });\n }\n /**\n * Resolve the value of this alias within `doc`, finding the last\n * instance of the `source` anchor before this node.\n */\n resolve(doc, ctx) {\n if (ctx?.maxAliasCount === 0)\n throw new ReferenceError('Alias resolution is disabled');\n let nodes;\n if (ctx?.aliasResolveCache) {\n nodes = ctx.aliasResolveCache;\n }\n else {\n nodes = [];\n visit(doc, {\n Node: (_key, node) => {\n if (isAlias(node) || hasAnchor(node))\n nodes.push(node);\n }\n });\n if (ctx)\n ctx.aliasResolveCache = nodes;\n }\n let found = undefined;\n for (const node of nodes) {\n if (node === this)\n break;\n if (node.anchor === this.source)\n found = node;\n }\n return found;\n }\n toJSON(_arg, ctx) {\n if (!ctx)\n return { source: this.source };\n const { anchors, doc, maxAliasCount } = ctx;\n const source = this.resolve(doc, ctx);\n if (!source) {\n const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;\n throw new ReferenceError(msg);\n }\n let data = anchors.get(source);\n if (!data) {\n // Resolve anchors for Node.prototype.toJS()\n toJS(source, null, ctx);\n data = anchors.get(source);\n }\n /* istanbul ignore if */\n if (data?.res === undefined) {\n const msg = 'This should not happen: Alias anchor was not resolved?';\n throw new ReferenceError(msg);\n }\n if (maxAliasCount >= 0) {\n data.count += 1;\n if (data.aliasCount === 0)\n data.aliasCount = getAliasCount(doc, source, anchors);\n if (data.count * data.aliasCount > maxAliasCount) {\n const msg = 'Excessive alias count indicates a resource exhaustion attack';\n throw new ReferenceError(msg);\n }\n }\n return data.res;\n }\n toString(ctx, _onComment, _onChompKeep) {\n const src = `*${this.source}`;\n if (ctx) {\n anchorIsValid(this.source);\n if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {\n const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;\n throw new Error(msg);\n }\n if (ctx.implicitKey)\n return `${src} `;\n }\n return src;\n }\n}\nfunction getAliasCount(doc, node, anchors) {\n if (isAlias(node)) {\n const source = node.resolve(doc);\n const anchor = anchors && source && anchors.get(source);\n return anchor ? anchor.count * anchor.aliasCount : 0;\n }\n else if (isCollection(node)) {\n let count = 0;\n for (const item of node.items) {\n const c = getAliasCount(doc, item, anchors);\n if (c > count)\n count = c;\n }\n return count;\n }\n else if (isPair(node)) {\n const kc = getAliasCount(doc, node.key, anchors);\n const vc = getAliasCount(doc, node.value, anchors);\n return Math.max(kc, vc);\n }\n return 1;\n}\n\nexport { Alias };\n","import { SCALAR } from './identity.js';\nimport { NodeBase } from './Node.js';\nimport { toJS } from './toJS.js';\n\nconst isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');\nclass Scalar extends NodeBase {\n constructor(value) {\n super(SCALAR);\n this.value = value;\n }\n toJSON(arg, ctx) {\n return ctx?.keep ? this.value : toJS(this.value, arg, ctx);\n }\n toString() {\n return String(this.value);\n }\n}\nScalar.BLOCK_FOLDED = 'BLOCK_FOLDED';\nScalar.BLOCK_LITERAL = 'BLOCK_LITERAL';\nScalar.PLAIN = 'PLAIN';\nScalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE';\nScalar.QUOTE_SINGLE = 'QUOTE_SINGLE';\n\nexport { Scalar, isScalarValue };\n","import { Alias } from '../nodes/Alias.js';\nimport { isNode, isPair, MAP, SEQ, isDocument } from '../nodes/identity.js';\nimport { Scalar } from '../nodes/Scalar.js';\n\nconst defaultTagPrefix = 'tag:yaml.org,2002:';\nfunction findTagObject(value, tagName, tags) {\n if (tagName) {\n const match = tags.filter(t => t.tag === tagName);\n const tagObj = match.find(t => !t.format) ?? match[0];\n if (!tagObj)\n throw new Error(`Tag ${tagName} not found`);\n return tagObj;\n }\n return tags.find(t => t.identify?.(value) && !t.format);\n}\nfunction createNode(value, tagName, ctx) {\n if (isDocument(value))\n value = value.contents;\n if (isNode(value))\n return value;\n if (isPair(value)) {\n const map = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx);\n map.items.push(value);\n return map;\n }\n if (value instanceof String ||\n value instanceof Number ||\n value instanceof Boolean ||\n (typeof BigInt !== 'undefined' && value instanceof BigInt) // not supported everywhere\n ) {\n // https://tc39.es/ecma262/#sec-serializejsonproperty\n value = value.valueOf();\n }\n const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;\n // Detect duplicate references to the same object & use Alias nodes for all\n // after first. The `ref` wrapper allows for circular references to resolve.\n let ref = undefined;\n if (aliasDuplicateObjects && value && typeof value === 'object') {\n ref = sourceObjects.get(value);\n if (ref) {\n ref.anchor ?? (ref.anchor = onAnchor(value));\n return new Alias(ref.anchor);\n }\n else {\n ref = { anchor: null, node: null };\n sourceObjects.set(value, ref);\n }\n }\n if (tagName?.startsWith('!!'))\n tagName = defaultTagPrefix + tagName.slice(2);\n let tagObj = findTagObject(value, tagName, schema.tags);\n if (!tagObj) {\n if (value && typeof value.toJSON === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n value = value.toJSON();\n }\n if (!value || typeof value !== 'object') {\n const node = new Scalar(value);\n if (ref)\n ref.node = node;\n return node;\n }\n tagObj =\n value instanceof Map\n ? schema[MAP]\n : Symbol.iterator in Object(value)\n ? schema[SEQ]\n : schema[MAP];\n }\n if (onTagObj) {\n onTagObj(tagObj);\n delete ctx.onTagObj;\n }\n const node = tagObj?.createNode\n ? tagObj.createNode(ctx.schema, value, ctx)\n : typeof tagObj?.nodeClass?.from === 'function'\n ? tagObj.nodeClass.from(ctx.schema, value, ctx)\n : new Scalar(value);\n if (tagName)\n node.tag = tagName;\n else if (!tagObj.default)\n node.tag = tagObj.tag;\n if (ref)\n ref.node = node;\n return node;\n}\n\nexport { createNode };\n","import { createNode } from '../doc/createNode.js';\nimport { isNode, isPair, isCollection, isScalar } from './identity.js';\nimport { NodeBase } from './Node.js';\n\nfunction collectionFromPath(schema, path, value) {\n let v = value;\n for (let i = path.length - 1; i >= 0; --i) {\n const k = path[i];\n if (typeof k === 'number' && Number.isInteger(k) && k >= 0) {\n const a = [];\n a[k] = v;\n v = a;\n }\n else {\n v = new Map([[k, v]]);\n }\n }\n return createNode(v, undefined, {\n aliasDuplicateObjects: false,\n keepUndefined: false,\n onAnchor: () => {\n throw new Error('This should not happen, please report a bug.');\n },\n schema,\n sourceObjects: new Map()\n });\n}\n// Type guard is intentionally a little wrong so as to be more useful,\n// as it does not cover untypable empty non-string iterables (e.g. []).\nconst isEmptyPath = (path) => path == null ||\n (typeof path === 'object' && !!path[Symbol.iterator]().next().done);\nclass Collection extends NodeBase {\n constructor(type, schema) {\n super(type);\n Object.defineProperty(this, 'schema', {\n value: schema,\n configurable: true,\n enumerable: false,\n writable: true\n });\n }\n /**\n * Create a copy of this collection.\n *\n * @param schema - If defined, overwrites the original's schema\n */\n clone(schema) {\n const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));\n if (schema)\n copy.schema = schema;\n copy.items = copy.items.map(it => isNode(it) || isPair(it) ? it.clone(schema) : it);\n if (this.range)\n copy.range = this.range.slice();\n return copy;\n }\n /**\n * Adds a value to the collection. For `!!map` and `!!omap` the value must\n * be a Pair instance or a `{ key, value }` object, which may not have a key\n * that already exists in the map.\n */\n addIn(path, value) {\n if (isEmptyPath(path))\n this.add(value);\n else {\n const [key, ...rest] = path;\n const node = this.get(key, true);\n if (isCollection(node))\n node.addIn(rest, value);\n else if (node === undefined && this.schema)\n this.set(key, collectionFromPath(this.schema, rest, value));\n else\n throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n }\n }\n /**\n * Removes a value from the collection.\n * @returns `true` if the item was found and removed.\n */\n deleteIn(path) {\n const [key, ...rest] = path;\n if (rest.length === 0)\n return this.delete(key);\n const node = this.get(key, true);\n if (isCollection(node))\n return node.deleteIn(rest);\n else\n throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n }\n /**\n * Returns item at `key`, or `undefined` if not found. By default unwraps\n * scalar values from their surrounding node; to disable set `keepScalar` to\n * `true` (collections are always returned intact).\n */\n getIn(path, keepScalar) {\n const [key, ...rest] = path;\n const node = this.get(key, true);\n if (rest.length === 0)\n return !keepScalar && isScalar(node) ? node.value : node;\n else\n return isCollection(node) ? node.getIn(rest, keepScalar) : undefined;\n }\n hasAllNullValues(allowScalar) {\n return this.items.every(node => {\n if (!isPair(node))\n return false;\n const n = node.value;\n return (n == null ||\n (allowScalar &&\n isScalar(n) &&\n n.value == null &&\n !n.commentBefore &&\n !n.comment &&\n !n.tag));\n });\n }\n /**\n * Checks if the collection includes a value with the key `key`.\n */\n hasIn(path) {\n const [key, ...rest] = path;\n if (rest.length === 0)\n return this.has(key);\n const node = this.get(key, true);\n return isCollection(node) ? node.hasIn(rest) : false;\n }\n /**\n * Sets a value in this collection. For `!!set`, `value` needs to be a\n * boolean to add/remove the item from the set.\n */\n setIn(path, value) {\n const [key, ...rest] = path;\n if (rest.length === 0) {\n this.set(key, value);\n }\n else {\n const node = this.get(key, true);\n if (isCollection(node))\n node.setIn(rest, value);\n else if (node === undefined && this.schema)\n this.set(key, collectionFromPath(this.schema, rest, value));\n else\n throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n }\n }\n}\n\nexport { Collection, collectionFromPath, isEmptyPath };\n","/**\n * Stringifies a comment.\n *\n * Empty comment lines are left empty,\n * lines consisting of a single space are replaced by `#`,\n * and all other lines are prefixed with a `#`.\n */\nconst stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#');\nfunction indentComment(comment, indent) {\n if (/^\\n+$/.test(comment))\n return comment.substring(1);\n return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;\n}\nconst lineComment = (str, indent, comment) => str.endsWith('\\n')\n ? indentComment(comment, indent)\n : comment.includes('\\n')\n ? '\\n' + indentComment(comment, indent)\n : (str.endsWith(' ') ? '' : ' ') + comment;\n\nexport { indentComment, lineComment, stringifyComment };\n","const FOLD_FLOW = 'flow';\nconst FOLD_BLOCK = 'block';\nconst FOLD_QUOTED = 'quoted';\n/**\n * Tries to keep input at up to `lineWidth` characters, splitting only on spaces\n * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are\n * terminated with `\\n` and started with `indent`.\n */\nfunction foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {\n if (!lineWidth || lineWidth < 0)\n return text;\n if (lineWidth < minContentWidth)\n minContentWidth = 0;\n const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);\n if (text.length <= endStep)\n return text;\n const folds = [];\n const escapedFolds = {};\n let end = lineWidth - indent.length;\n if (typeof indentAtStart === 'number') {\n if (indentAtStart > lineWidth - Math.max(2, minContentWidth))\n folds.push(0);\n else\n end = lineWidth - indentAtStart;\n }\n let split = undefined;\n let prev = undefined;\n let overflow = false;\n let i = -1;\n let escStart = -1;\n let escEnd = -1;\n if (mode === FOLD_BLOCK) {\n i = consumeMoreIndentedLines(text, i, indent.length);\n if (i !== -1)\n end = i + endStep;\n }\n for (let ch; (ch = text[(i += 1)]);) {\n if (mode === FOLD_QUOTED && ch === '\\\\') {\n escStart = i;\n switch (text[i + 1]) {\n case 'x':\n i += 3;\n break;\n case 'u':\n i += 5;\n break;\n case 'U':\n i += 9;\n break;\n default:\n i += 1;\n }\n escEnd = i;\n }\n if (ch === '\\n') {\n if (mode === FOLD_BLOCK)\n i = consumeMoreIndentedLines(text, i, indent.length);\n end = i + indent.length + endStep;\n split = undefined;\n }\n else {\n if (ch === ' ' &&\n prev &&\n prev !== ' ' &&\n prev !== '\\n' &&\n prev !== '\\t') {\n // space surrounded by non-space can be replaced with newline + indent\n const next = text[i + 1];\n if (next && next !== ' ' && next !== '\\n' && next !== '\\t')\n split = i;\n }\n if (i >= end) {\n if (split) {\n folds.push(split);\n end = split + endStep;\n split = undefined;\n }\n else if (mode === FOLD_QUOTED) {\n // white-space collected at end may stretch past lineWidth\n while (prev === ' ' || prev === '\\t') {\n prev = ch;\n ch = text[(i += 1)];\n overflow = true;\n }\n // Account for newline escape, but don't break preceding escape\n const j = i > escEnd + 1 ? i - 2 : escStart - 1;\n // Bail out if lineWidth & minContentWidth are shorter than an escape string\n if (escapedFolds[j])\n return text;\n folds.push(j);\n escapedFolds[j] = true;\n end = j + endStep;\n split = undefined;\n }\n else {\n overflow = true;\n }\n }\n }\n prev = ch;\n }\n if (overflow && onOverflow)\n onOverflow();\n if (folds.length === 0)\n return text;\n if (onFold)\n onFold();\n let res = text.slice(0, folds[0]);\n for (let i = 0; i < folds.length; ++i) {\n const fold = folds[i];\n const end = folds[i + 1] || text.length;\n if (fold === 0)\n res = `\\n${indent}${text.slice(0, end)}`;\n else {\n if (mode === FOLD_QUOTED && escapedFolds[fold])\n res += `${text[fold]}\\\\`;\n res += `\\n${indent}${text.slice(fold + 1, end)}`;\n }\n }\n return res;\n}\n/**\n * Presumes `i + 1` is at the start of a line\n * @returns index of last newline in more-indented block\n */\nfunction consumeMoreIndentedLines(text, i, indent) {\n let end = i;\n let start = i + 1;\n let ch = text[start];\n while (ch === ' ' || ch === '\\t') {\n if (i < start + indent) {\n ch = text[++i];\n }\n else {\n do {\n ch = text[++i];\n } while (ch && ch !== '\\n');\n end = i;\n start = i + 1;\n ch = text[start];\n }\n }\n return end;\n}\n\nexport { FOLD_BLOCK, FOLD_FLOW, FOLD_QUOTED, foldFlowLines };\n","import { Scalar } from '../nodes/Scalar.js';\nimport { foldFlowLines, FOLD_FLOW, FOLD_QUOTED, FOLD_BLOCK } from './foldFlowLines.js';\n\nconst getFoldOptions = (ctx, isBlock) => ({\n indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,\n lineWidth: ctx.options.lineWidth,\n minContentWidth: ctx.options.minContentWidth\n});\n// Also checks for lines starting with %, as parsing the output as YAML 1.1 will\n// presume that's starting a new document.\nconst containsDocumentMarker = (str) => /^(%|---|\\.\\.\\.)/m.test(str);\nfunction lineLengthOverLimit(str, lineWidth, indentLength) {\n if (!lineWidth || lineWidth < 0)\n return false;\n const limit = lineWidth - indentLength;\n const strLen = str.length;\n if (strLen <= limit)\n return false;\n for (let i = 0, start = 0; i < strLen; ++i) {\n if (str[i] === '\\n') {\n if (i - start > limit)\n return true;\n start = i + 1;\n if (strLen - start <= limit)\n return false;\n }\n }\n return true;\n}\nfunction doubleQuotedString(value, ctx) {\n const json = JSON.stringify(value);\n if (ctx.options.doubleQuotedAsJSON)\n return json;\n const { implicitKey } = ctx;\n const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;\n const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');\n let str = '';\n let start = 0;\n for (let i = 0, ch = json[i]; ch; ch = json[++i]) {\n if (ch === ' ' && json[i + 1] === '\\\\' && json[i + 2] === 'n') {\n // space before newline needs to be escaped to not be folded\n str += json.slice(start, i) + '\\\\ ';\n i += 1;\n start = i;\n ch = '\\\\';\n }\n if (ch === '\\\\')\n switch (json[i + 1]) {\n case 'u':\n {\n str += json.slice(start, i);\n const code = json.substr(i + 2, 4);\n switch (code) {\n case '0000':\n str += '\\\\0';\n break;\n case '0007':\n str += '\\\\a';\n break;\n case '000b':\n str += '\\\\v';\n break;\n case '001b':\n str += '\\\\e';\n break;\n case '0085':\n str += '\\\\N';\n break;\n case '00a0':\n str += '\\\\_';\n break;\n case '2028':\n str += '\\\\L';\n break;\n case '2029':\n str += '\\\\P';\n break;\n default:\n if (code.substr(0, 2) === '00')\n str += '\\\\x' + code.substr(2);\n else\n str += json.substr(i, 6);\n }\n i += 5;\n start = i + 1;\n }\n break;\n case 'n':\n if (implicitKey ||\n json[i + 2] === '\"' ||\n json.length < minMultiLineLength) {\n i += 1;\n }\n else {\n // folding will eat first newline\n str += json.slice(start, i) + '\\n\\n';\n while (json[i + 2] === '\\\\' &&\n json[i + 3] === 'n' &&\n json[i + 4] !== '\"') {\n str += '\\n';\n i += 2;\n }\n str += indent;\n // space after newline needs to be escaped to not be folded\n if (json[i + 2] === ' ')\n str += '\\\\';\n i += 1;\n start = i + 1;\n }\n break;\n default:\n i += 1;\n }\n }\n str = start ? str + json.slice(start) : json;\n return implicitKey\n ? str\n : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx, false));\n}\nfunction singleQuotedString(value, ctx) {\n if (ctx.options.singleQuote === false ||\n (ctx.implicitKey && value.includes('\\n')) ||\n /[ \\t]\\n|\\n[ \\t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline\n )\n return doubleQuotedString(value, ctx);\n const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');\n const res = \"'\" + value.replace(/'/g, \"''\").replace(/\\n+/g, `$&\\n${indent}`) + \"'\";\n return ctx.implicitKey\n ? res\n : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false));\n}\nfunction quotedString(value, ctx) {\n const { singleQuote } = ctx.options;\n let qs;\n if (singleQuote === false)\n qs = doubleQuotedString;\n else {\n const hasDouble = value.includes('\"');\n const hasSingle = value.includes(\"'\");\n if (hasDouble && !hasSingle)\n qs = singleQuotedString;\n else if (hasSingle && !hasDouble)\n qs = doubleQuotedString;\n else\n qs = singleQuote ? singleQuotedString : doubleQuotedString;\n }\n return qs(value, ctx);\n}\n// The negative lookbehind avoids a polynomial search,\n// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind\nlet blockEndNewlines;\ntry {\n blockEndNewlines = new RegExp('(^|(?<!\\n))\\n+(?!\\n|$)', 'g');\n}\ncatch {\n blockEndNewlines = /\\n+(?!\\n|$)/g;\n}\nfunction blockString({ comment, type, value }, ctx, onComment, onChompKeep) {\n const { blockQuote, commentString, lineWidth } = ctx.options;\n // 1. Block can't end in whitespace unless the last line is non-empty.\n // 2. Strings consisting of only whitespace are best rendered explicitly.\n if (!blockQuote || /\\n[\\t ]+$/.test(value)) {\n return quotedString(value, ctx);\n }\n const indent = ctx.indent ||\n (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : '');\n const literal = blockQuote === 'literal'\n ? true\n : blockQuote === 'folded' || type === Scalar.BLOCK_FOLDED\n ? false\n : type === Scalar.BLOCK_LITERAL\n ? true\n : !lineLengthOverLimit(value, lineWidth, indent.length);\n if (!value)\n return literal ? '|\\n' : '>\\n';\n // determine chomping from whitespace at value end\n let chomp;\n let endStart;\n for (endStart = value.length; endStart > 0; --endStart) {\n const ch = value[endStart - 1];\n if (ch !== '\\n' && ch !== '\\t' && ch !== ' ')\n break;\n }\n let end = value.substring(endStart);\n const endNlPos = end.indexOf('\\n');\n if (endNlPos === -1) {\n chomp = '-'; // strip\n }\n else if (value === end || endNlPos !== end.length - 1) {\n chomp = '+'; // keep\n if (onChompKeep)\n onChompKeep();\n }\n else {\n chomp = ''; // clip\n }\n if (end) {\n value = value.slice(0, -end.length);\n if (end[end.length - 1] === '\\n')\n end = end.slice(0, -1);\n end = end.replace(blockEndNewlines, `$&${indent}`);\n }\n // determine indent indicator from whitespace at value start\n let startWithSpace = false;\n let startEnd;\n let startNlPos = -1;\n for (startEnd = 0; startEnd < value.length; ++startEnd) {\n const ch = value[startEnd];\n if (ch === ' ')\n startWithSpace = true;\n else if (ch === '\\n')\n startNlPos = startEnd;\n else\n break;\n }\n let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);\n if (start) {\n value = value.substring(start.length);\n start = start.replace(/\\n+/g, `$&${indent}`);\n }\n const indentSize = indent ? '2' : '1'; // root is at -1\n // Leading | or > is added later\n let header = (startWithSpace ? indentSize : '') + chomp;\n if (comment) {\n header += ' ' + commentString(comment.replace(/ ?[\\r\\n]+/g, ' '));\n if (onComment)\n onComment();\n }\n if (!literal) {\n const foldedValue = value\n .replace(/\\n+/g, '\\n$&')\n .replace(/(?:^|\\n)([\\t ].*)(?:([\\n\\t ]*)\\n(?![\\n\\t ]))?/g, '$1$2') // more-indented lines aren't folded\n // ^ more-ind. ^ empty ^ capture next empty lines only at end of indent\n .replace(/\\n+/g, `$&${indent}`);\n let literalFallback = false;\n const foldOptions = getFoldOptions(ctx, true);\n if (blockQuote !== 'folded' && type !== Scalar.BLOCK_FOLDED) {\n foldOptions.onOverflow = () => {\n literalFallback = true;\n };\n }\n const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions);\n if (!literalFallback)\n return `>${header}\\n${indent}${body}`;\n }\n value = value.replace(/\\n+/g, `$&${indent}`);\n return `|${header}\\n${indent}${start}${value}${end}`;\n}\nfunction plainString(item, ctx, onComment, onChompKeep) {\n const { type, value } = item;\n const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;\n if ((implicitKey && value.includes('\\n')) ||\n (inFlow && /[[\\]{},]/.test(value))) {\n return quotedString(value, ctx);\n }\n if (/^[\\n\\t ,[\\]{}#&*!|>'\"%@`]|^[?-]$|^[?-][ \\t]|[\\n:][ \\t]|[ \\t]\\n|[\\n\\t ]#|[\\n\\t :]$/.test(value)) {\n // not allowed:\n // - '-' or '?'\n // - start with an indicator character (except [?:-]) or /[?-] /\n // - '\\n ', ': ' or ' \\n' anywhere\n // - '#' not preceded by a non-space char\n // - end with ' ' or ':'\n return implicitKey || inFlow || !value.includes('\\n')\n ? quotedString(value, ctx)\n : blockString(item, ctx, onComment, onChompKeep);\n }\n if (!implicitKey &&\n !inFlow &&\n type !== Scalar.PLAIN &&\n value.includes('\\n')) {\n // Where allowed & type not set explicitly, prefer block style for multiline strings\n return blockString(item, ctx, onComment, onChompKeep);\n }\n if (containsDocumentMarker(value)) {\n if (indent === '') {\n ctx.forceBlockIndent = true;\n return blockString(item, ctx, onComment, onChompKeep);\n }\n else if (implicitKey && indent === indentStep) {\n return quotedString(value, ctx);\n }\n }\n const str = value.replace(/\\n+/g, `$&\\n${indent}`);\n // Verify that output will be parsed as a string, as e.g. plain numbers and\n // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),\n // and others in v1.1.\n if (actualString) {\n const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str);\n const { compat, tags } = ctx.doc.schema;\n if (tags.some(test) || compat?.some(test))\n return quotedString(value, ctx);\n }\n return implicitKey\n ? str\n : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx, false));\n}\nfunction stringifyString(item, ctx, onComment, onChompKeep) {\n const { implicitKey, inFlow } = ctx;\n const ss = typeof item.value === 'string'\n ? item\n : Object.assign({}, item, { value: String(item.value) });\n let { type } = item;\n if (type !== Scalar.QUOTE_DOUBLE) {\n // force double quotes on control characters & unpaired surrogates\n if (/[\\x00-\\x08\\x0b-\\x1f\\x7f-\\x9f\\u{D800}-\\u{DFFF}]/u.test(ss.value))\n type = Scalar.QUOTE_DOUBLE;\n }\n const _stringify = (_type) => {\n switch (_type) {\n case Scalar.BLOCK_FOLDED:\n case Scalar.BLOCK_LITERAL:\n return implicitKey || inFlow\n ? quotedString(ss.value, ctx) // blocks are not valid inside flow containers\n : blockString(ss, ctx, onComment, onChompKeep);\n case Scalar.QUOTE_DOUBLE:\n return doubleQuotedString(ss.value, ctx);\n case Scalar.QUOTE_SINGLE:\n return singleQuotedString(ss.value, ctx);\n case Scalar.PLAIN:\n return plainString(ss, ctx, onComment, onChompKeep);\n default:\n return null;\n }\n };\n let res = _stringify(type);\n if (res === null) {\n const { defaultKeyType, defaultStringType } = ctx.options;\n const t = (implicitKey && defaultKeyType) || defaultStringType;\n res = _stringify(t);\n if (res === null)\n throw new Error(`Unsupported default string type ${t}`);\n }\n return res;\n}\n\nexport { stringifyString };\n","import { anchorIsValid } from '../doc/anchors.js';\nimport { isPair, isAlias, isNode, isScalar, isCollection } from '../nodes/identity.js';\nimport { stringifyComment } from './stringifyComment.js';\nimport { stringifyString } from './stringifyString.js';\n\nfunction createStringifyContext(doc, options) {\n const opt = Object.assign({\n blockQuote: true,\n commentString: stringifyComment,\n defaultKeyType: null,\n defaultStringType: 'PLAIN',\n directives: null,\n doubleQuotedAsJSON: false,\n doubleQuotedMinMultiLineLength: 40,\n falseStr: 'false',\n flowCollectionPadding: true,\n indentSeq: true,\n lineWidth: 80,\n minContentWidth: 20,\n nullStr: 'null',\n simpleKeys: false,\n singleQuote: null,\n trailingComma: false,\n trueStr: 'true',\n verifyAliasOrder: true\n }, doc.schema.toStringOptions, options);\n let inFlow;\n switch (opt.collectionStyle) {\n case 'block':\n inFlow = false;\n break;\n case 'flow':\n inFlow = true;\n break;\n default:\n inFlow = null;\n }\n return {\n anchors: new Set(),\n doc,\n flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '',\n indent: '',\n indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : ' ',\n inFlow,\n options: opt\n };\n}\nfunction getTagObject(tags, item) {\n if (item.tag) {\n const match = tags.filter(t => t.tag === item.tag);\n if (match.length > 0)\n return match.find(t => t.format === item.format) ?? match[0];\n }\n let tagObj = undefined;\n let obj;\n if (isScalar(item)) {\n obj = item.value;\n let match = tags.filter(t => t.identify?.(obj));\n if (match.length > 1) {\n const testMatch = match.filter(t => t.test);\n if (testMatch.length > 0)\n match = testMatch;\n }\n tagObj =\n match.find(t => t.format === item.format) ?? match.find(t => !t.format);\n }\n else {\n obj = item;\n tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);\n }\n if (!tagObj) {\n const name = obj?.constructor?.name ?? (obj === null ? 'null' : typeof obj);\n throw new Error(`Tag not resolved for ${name} value`);\n }\n return tagObj;\n}\n// needs to be called before value stringifier to allow for circular anchor refs\nfunction stringifyProps(node, tagObj, { anchors, doc }) {\n if (!doc.directives)\n return '';\n const props = [];\n const anchor = (isScalar(node) || isCollection(node)) && node.anchor;\n if (anchor && anchorIsValid(anchor)) {\n anchors.add(anchor);\n props.push(`&${anchor}`);\n }\n const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);\n if (tag)\n props.push(doc.directives.tagString(tag));\n return props.join(' ');\n}\nfunction stringify(item, ctx, onComment, onChompKeep) {\n if (isPair(item))\n return item.toString(ctx, onComment, onChompKeep);\n if (isAlias(item)) {\n if (ctx.doc.directives)\n return item.toString(ctx);\n if (ctx.resolvedAliases?.has(item)) {\n throw new TypeError(`Cannot stringify circular structure without alias nodes`);\n }\n else {\n if (ctx.resolvedAliases)\n ctx.resolvedAliases.add(item);\n else\n ctx.resolvedAliases = new Set([item]);\n item = item.resolve(ctx.doc);\n }\n }\n let tagObj = undefined;\n const node = isNode(item)\n ? item\n : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) });\n tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));\n const props = stringifyProps(node, tagObj, ctx);\n if (props.length > 0)\n ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;\n const str = typeof tagObj.stringify === 'function'\n ? tagObj.stringify(node, ctx, onComment, onChompKeep)\n : isScalar(node)\n ? stringifyString(node, ctx, onComment, onChompKeep)\n : node.toString(ctx, onComment, onChompKeep);\n if (!props)\n return str;\n return isScalar(node) || str[0] === '{' || str[0] === '['\n ? `${props} ${str}`\n : `${props}\\n${ctx.indent}${str}`;\n}\n\nexport { createStringifyContext, stringify };\n","import { isCollection, isNode, isScalar, isSeq } from '../nodes/identity.js';\nimport { Scalar } from '../nodes/Scalar.js';\nimport { stringify } from './stringify.js';\nimport { lineComment, indentComment } from './stringifyComment.js';\n\nfunction stringifyPair({ key, value }, ctx, onComment, onChompKeep) {\n const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;\n let keyComment = (isNode(key) && key.comment) || null;\n if (simpleKeys) {\n if (keyComment) {\n throw new Error('With simple keys, key nodes cannot have comments');\n }\n if (isCollection(key) || (!isNode(key) && typeof key === 'object')) {\n const msg = 'With simple keys, collection cannot be used as a key value';\n throw new Error(msg);\n }\n }\n let explicitKey = !simpleKeys &&\n (!key ||\n (keyComment && value == null && !ctx.inFlow) ||\n isCollection(key) ||\n (isScalar(key)\n ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL\n : typeof key === 'object'));\n ctx = Object.assign({}, ctx, {\n allNullValues: false,\n implicitKey: !explicitKey && (simpleKeys || !allNullValues),\n indent: indent + indentStep\n });\n let keyCommentDone = false;\n let chompKeep = false;\n let str = stringify(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true));\n if (!explicitKey && !ctx.inFlow && str.length > 1024) {\n if (simpleKeys)\n throw new Error('With simple keys, single line scalar must not span more than 1024 characters');\n explicitKey = true;\n }\n if (ctx.inFlow) {\n if (allNullValues || value == null) {\n if (keyCommentDone && onComment)\n onComment();\n return str === '' ? '?' : explicitKey ? `? ${str}` : str;\n }\n }\n else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) {\n str = `? ${str}`;\n if (keyComment && !keyCommentDone) {\n str += lineComment(str, ctx.indent, commentString(keyComment));\n }\n else if (chompKeep && onChompKeep)\n onChompKeep();\n return str;\n }\n if (keyCommentDone)\n keyComment = null;\n if (explicitKey) {\n if (keyComment)\n str += lineComment(str, ctx.indent, commentString(keyComment));\n str = `? ${str}\\n${indent}:`;\n }\n else {\n str = `${str}:`;\n if (keyComment)\n str += lineComment(str, ctx.indent, commentString(keyComment));\n }\n let vsb, vcb, valueComment;\n if (isNode(value)) {\n vsb = !!value.spaceBefore;\n vcb = value.commentBefore;\n valueComment = value.comment;\n }\n else {\n vsb = false;\n vcb = null;\n valueComment = null;\n if (value && typeof value === 'object')\n value = doc.createNode(value);\n }\n ctx.implicitKey = false;\n if (!explicitKey && !keyComment && isScalar(value))\n ctx.indentAtStart = str.length + 1;\n chompKeep = false;\n if (!indentSeq &&\n indentStep.length >= 2 &&\n !ctx.inFlow &&\n !explicitKey &&\n isSeq(value) &&\n !value.flow &&\n !value.tag &&\n !value.anchor) {\n // If indentSeq === false, consider '- ' as part of indentation where possible\n ctx.indent = ctx.indent.substring(2);\n }\n let valueCommentDone = false;\n const valueStr = stringify(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true));\n let ws = ' ';\n if (keyComment || vsb || vcb) {\n ws = vsb ? '\\n' : '';\n if (vcb) {\n const cs = commentString(vcb);\n ws += `\\n${indentComment(cs, ctx.indent)}`;\n }\n if (valueStr === '' && !ctx.inFlow) {\n if (ws === '\\n' && valueComment)\n ws = '\\n\\n';\n }\n else {\n ws += `\\n${ctx.indent}`;\n }\n }\n else if (!explicitKey && isCollection(value)) {\n const vs0 = valueStr[0];\n const nl0 = valueStr.indexOf('\\n');\n const hasNewline = nl0 !== -1;\n const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;\n if (hasNewline || !flow) {\n let hasPropsLine = false;\n if (hasNewline && (vs0 === '&' || vs0 === '!')) {\n let sp0 = valueStr.indexOf(' ');\n if (vs0 === '&' &&\n sp0 !== -1 &&\n sp0 < nl0 &&\n valueStr[sp0 + 1] === '!') {\n sp0 = valueStr.indexOf(' ', sp0 + 1);\n }\n if (sp0 === -1 || nl0 < sp0)\n hasPropsLine = true;\n }\n if (!hasPropsLine)\n ws = `\\n${ctx.indent}`;\n }\n }\n else if (valueStr === '' || valueStr[0] === '\\n') {\n ws = '';\n }\n str += ws + valueStr;\n if (ctx.inFlow) {\n if (valueCommentDone && onComment)\n onComment();\n }\n else if (valueComment && !valueCommentDone) {\n str += lineComment(str, ctx.indent, commentString(valueComment));\n }\n else if (chompKeep && onChompKeep) {\n onChompKeep();\n }\n return str;\n}\n\nexport { stringifyPair };\n","function debug(logLevel, ...messages) {\n if (logLevel === 'debug')\n console.log(...messages);\n}\nfunction warn(logLevel, warning) {\n if (logLevel === 'debug' || logLevel === 'warn') {\n console.warn(warning);\n }\n}\n\nexport { debug, warn };\n","import { isScalar, isSeq, isAlias, isMap } from '../../nodes/identity.js';\nimport { Scalar } from '../../nodes/Scalar.js';\n\n// If the value associated with a merge key is a single mapping node, each of\n// its key/value pairs is inserted into the current mapping, unless the key\n// already exists in it. If the value associated with the merge key is a\n// sequence, then this sequence is expected to contain mapping nodes and each\n// of these nodes is merged in turn according to its order in the sequence.\n// Keys in mapping nodes earlier in the sequence override keys specified in\n// later mapping nodes. -- http://yaml.org/type/merge.html\nconst MERGE_KEY = '<<';\nconst merge = {\n identify: value => value === MERGE_KEY ||\n (typeof value === 'symbol' && value.description === MERGE_KEY),\n default: 'key',\n tag: 'tag:yaml.org,2002:merge',\n test: /^<<$/,\n resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), {\n addToJSMap: addMergeToJSMap\n }),\n stringify: () => MERGE_KEY\n};\nconst isMergeKey = (ctx, key) => (merge.identify(key) ||\n (isScalar(key) &&\n (!key.type || key.type === Scalar.PLAIN) &&\n merge.identify(key.value))) &&\n ctx?.doc.schema.tags.some(tag => tag.tag === merge.tag && tag.default);\nfunction addMergeToJSMap(ctx, map, value) {\n const source = resolveAliasValue(ctx, value);\n if (isSeq(source))\n for (const it of source.items)\n mergeValue(ctx, map, it);\n else if (Array.isArray(source))\n for (const it of source)\n mergeValue(ctx, map, it);\n else\n mergeValue(ctx, map, source);\n}\nfunction mergeValue(ctx, map, value) {\n const source = resolveAliasValue(ctx, value);\n if (!isMap(source))\n throw new Error('Merge sources must be maps or map aliases');\n const srcMap = source.toJSON(null, ctx, Map);\n for (const [key, value] of srcMap) {\n if (map instanceof Map) {\n if (!map.has(key))\n map.set(key, value);\n }\n else if (map instanceof Set) {\n map.add(key);\n }\n else if (!Object.prototype.hasOwnProperty.call(map, key)) {\n Object.defineProperty(map, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true\n });\n }\n }\n return map;\n}\nfunction resolveAliasValue(ctx, value) {\n return ctx && isAlias(value) ? value.resolve(ctx.doc, ctx) : value;\n}\n\nexport { addMergeToJSMap, isMergeKey, merge };\n","import { warn } from '../log.js';\nimport { isMergeKey, addMergeToJSMap } from '../schema/yaml-1.1/merge.js';\nimport { createStringifyContext } from '../stringify/stringify.js';\nimport { isNode } from './identity.js';\nimport { toJS } from './toJS.js';\n\nfunction addPairToJSMap(ctx, map, { key, value }) {\n if (isNode(key) && key.addToJSMap)\n key.addToJSMap(ctx, map, value);\n // TODO: Should drop this special case for bare << handling\n else if (isMergeKey(ctx, key))\n addMergeToJSMap(ctx, map, value);\n else {\n const jsKey = toJS(key, '', ctx);\n if (map instanceof Map) {\n map.set(jsKey, toJS(value, jsKey, ctx));\n }\n else if (map instanceof Set) {\n map.add(jsKey);\n }\n else {\n const stringKey = stringifyKey(key, jsKey, ctx);\n const jsValue = toJS(value, stringKey, ctx);\n if (stringKey in map)\n Object.defineProperty(map, stringKey, {\n value: jsValue,\n writable: true,\n enumerable: true,\n configurable: true\n });\n else\n map[stringKey] = jsValue;\n }\n }\n return map;\n}\nfunction stringifyKey(key, jsKey, ctx) {\n if (jsKey === null)\n return '';\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n if (typeof jsKey !== 'object')\n return String(jsKey);\n if (isNode(key) && ctx?.doc) {\n const strCtx = createStringifyContext(ctx.doc, {});\n strCtx.anchors = new Set();\n for (const node of ctx.anchors.keys())\n strCtx.anchors.add(node.anchor);\n strCtx.inFlow = true;\n strCtx.inStringifyKey = true;\n const strKey = key.toString(strCtx);\n if (!ctx.mapKeyWarned) {\n let jsonStr = JSON.stringify(strKey);\n if (jsonStr.length > 40)\n jsonStr = jsonStr.substring(0, 36) + '...\"';\n warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);\n ctx.mapKeyWarned = true;\n }\n return strKey;\n }\n return JSON.stringify(jsKey);\n}\n\nexport { addPairToJSMap };\n","import { createNode } from '../doc/createNode.js';\nimport { stringifyPair } from '../stringify/stringifyPair.js';\nimport { addPairToJSMap } from './addPairToJSMap.js';\nimport { NODE_TYPE, PAIR, isNode } from './identity.js';\n\nfunction createPair(key, value, ctx) {\n const k = createNode(key, undefined, ctx);\n const v = createNode(value, undefined, ctx);\n return new Pair(k, v);\n}\nclass Pair {\n constructor(key, value = null) {\n Object.defineProperty(this, NODE_TYPE, { value: PAIR });\n this.key = key;\n this.value = value;\n }\n clone(schema) {\n let { key, value } = this;\n if (isNode(key))\n key = key.clone(schema);\n if (isNode(value))\n value = value.clone(schema);\n return new Pair(key, value);\n }\n toJSON(_, ctx) {\n const pair = ctx?.mapAsMap ? new Map() : {};\n return addPairToJSMap(ctx, pair, this);\n }\n toString(ctx, onComment, onChompKeep) {\n return ctx?.doc\n ? stringifyPair(this, ctx, onComment, onChompKeep)\n : JSON.stringify(this);\n }\n}\n\nexport { Pair, createPair };\n","import { isNode, isPair } from '../nodes/identity.js';\nimport { stringify } from './stringify.js';\nimport { lineComment, indentComment } from './stringifyComment.js';\n\nfunction stringifyCollection(collection, ctx, options) {\n const flow = ctx.inFlow ?? collection.flow;\n const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;\n return stringify(collection, ctx, options);\n}\nfunction stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {\n const { indent, options: { commentString } } = ctx;\n const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });\n let chompKeep = false; // flag for the preceding node's status\n const lines = [];\n for (let i = 0; i < items.length; ++i) {\n const item = items[i];\n let comment = null;\n if (isNode(item)) {\n if (!chompKeep && item.spaceBefore)\n lines.push('');\n addCommentBefore(ctx, lines, item.commentBefore, chompKeep);\n if (item.comment)\n comment = item.comment;\n }\n else if (isPair(item)) {\n const ik = isNode(item.key) ? item.key : null;\n if (ik) {\n if (!chompKeep && ik.spaceBefore)\n lines.push('');\n addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);\n }\n }\n chompKeep = false;\n let str = stringify(item, itemCtx, () => (comment = null), () => (chompKeep = true));\n if (comment)\n str += lineComment(str, itemIndent, commentString(comment));\n if (chompKeep && comment)\n chompKeep = false;\n lines.push(blockItemPrefix + str);\n }\n let str;\n if (lines.length === 0) {\n str = flowChars.start + flowChars.end;\n }\n else {\n str = lines[0];\n for (let i = 1; i < lines.length; ++i) {\n const line = lines[i];\n str += line ? `\\n${indent}${line}` : '\\n';\n }\n }\n if (comment) {\n str += '\\n' + indentComment(commentString(comment), indent);\n if (onComment)\n onComment();\n }\n else if (chompKeep && onChompKeep)\n onChompKeep();\n return str;\n}\nfunction stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {\n const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;\n itemIndent += indentStep;\n const itemCtx = Object.assign({}, ctx, {\n indent: itemIndent,\n inFlow: true,\n type: null\n });\n let reqNewline = false;\n let linesAtValue = 0;\n const lines = [];\n for (let i = 0; i < items.length; ++i) {\n const item = items[i];\n let comment = null;\n if (isNode(item)) {\n if (item.spaceBefore)\n lines.push('');\n addCommentBefore(ctx, lines, item.commentBefore, false);\n if (item.comment)\n comment = item.comment;\n }\n else if (isPair(item)) {\n const ik = isNode(item.key) ? item.key : null;\n if (ik) {\n if (ik.spaceBefore)\n lines.push('');\n addCommentBefore(ctx, lines, ik.commentBefore, false);\n if (ik.comment)\n reqNewline = true;\n }\n const iv = isNode(item.value) ? item.value : null;\n if (iv) {\n if (iv.comment)\n comment = iv.comment;\n if (iv.commentBefore)\n reqNewline = true;\n }\n else if (item.value == null && ik?.comment) {\n comment = ik.comment;\n }\n }\n if (comment)\n reqNewline = true;\n let str = stringify(item, itemCtx, () => (comment = null));\n reqNewline || (reqNewline = lines.length > linesAtValue || str.includes('\\n'));\n if (i < items.length - 1) {\n str += ',';\n }\n else if (ctx.options.trailingComma) {\n if (ctx.options.lineWidth > 0) {\n reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) +\n (str.length + 2) >\n ctx.options.lineWidth);\n }\n if (reqNewline) {\n str += ',';\n }\n }\n if (comment)\n str += lineComment(str, itemIndent, commentString(comment));\n lines.push(str);\n linesAtValue = lines.length;\n }\n const { start, end } = flowChars;\n if (lines.length === 0) {\n return start + end;\n }\n else {\n if (!reqNewline) {\n const len = lines.reduce((sum, line) => sum + line.length + 2, 2);\n reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;\n }\n if (reqNewline) {\n let str = start;\n for (const line of lines)\n str += line ? `\\n${indentStep}${indent}${line}` : '\\n';\n return `${str}\\n${indent}${end}`;\n }\n else {\n return `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`;\n }\n }\n}\nfunction addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {\n if (comment && chompKeep)\n comment = comment.replace(/^\\n+/, '');\n if (comment) {\n const ic = indentComment(commentString(comment), indent);\n lines.push(ic.trimStart()); // Avoid double indent on first line\n }\n}\n\nexport { stringifyCollection };\n","import { stringifyCollection } from '../stringify/stringifyCollection.js';\nimport { addPairToJSMap } from './addPairToJSMap.js';\nimport { Collection } from './Collection.js';\nimport { MAP, isPair, isScalar } from './identity.js';\nimport { Pair, createPair } from './Pair.js';\nimport { isScalarValue } from './Scalar.js';\n\nfunction findPair(items, key) {\n const k = isScalar(key) ? key.value : key;\n for (const it of items) {\n if (isPair(it)) {\n if (it.key === key || it.key === k)\n return it;\n if (isScalar(it.key) && it.key.value === k)\n return it;\n }\n }\n return undefined;\n}\nclass YAMLMap extends Collection {\n static get tagName() {\n return 'tag:yaml.org,2002:map';\n }\n constructor(schema) {\n super(MAP, schema);\n this.items = [];\n }\n /**\n * A generic collection parsing method that can be extended\n * to other node classes that inherit from YAMLMap\n */\n static from(schema, obj, ctx) {\n const { keepUndefined, replacer } = ctx;\n const map = new this(schema);\n const add = (key, value) => {\n if (typeof replacer === 'function')\n value = replacer.call(obj, key, value);\n else if (Array.isArray(replacer) && !replacer.includes(key))\n return;\n if (value !== undefined || keepUndefined)\n map.items.push(createPair(key, value, ctx));\n };\n if (obj instanceof Map) {\n for (const [key, value] of obj)\n add(key, value);\n }\n else if (obj && typeof obj === 'object') {\n for (const key of Object.keys(obj))\n add(key, obj[key]);\n }\n if (typeof schema.sortMapEntries === 'function') {\n map.items.sort(schema.sortMapEntries);\n }\n return map;\n }\n /**\n * Adds a value to the collection.\n *\n * @param overwrite - If not set `true`, using a key that is already in the\n * collection will throw. Otherwise, overwrites the previous value.\n */\n add(pair, overwrite) {\n let _pair;\n if (isPair(pair))\n _pair = pair;\n else if (!pair || typeof pair !== 'object' || !('key' in pair)) {\n // In TypeScript, this never happens.\n _pair = new Pair(pair, pair?.value);\n }\n else\n _pair = new Pair(pair.key, pair.value);\n const prev = findPair(this.items, _pair.key);\n const sortEntries = this.schema?.sortMapEntries;\n if (prev) {\n if (!overwrite)\n throw new Error(`Key ${_pair.key} already set`);\n // For scalars, keep the old node & its comments and anchors\n if (isScalar(prev.value) && isScalarValue(_pair.value))\n prev.value.value = _pair.value;\n else\n prev.value = _pair.value;\n }\n else if (sortEntries) {\n const i = this.items.findIndex(item => sortEntries(_pair, item) < 0);\n if (i === -1)\n this.items.push(_pair);\n else\n this.items.splice(i, 0, _pair);\n }\n else {\n this.items.push(_pair);\n }\n }\n delete(key) {\n const it = findPair(this.items, key);\n if (!it)\n return false;\n const del = this.items.splice(this.items.indexOf(it), 1);\n return del.length > 0;\n }\n get(key, keepScalar) {\n const it = findPair(this.items, key);\n const node = it?.value;\n return (!keepScalar && isScalar(node) ? node.value : node) ?? undefined;\n }\n has(key) {\n return !!findPair(this.items, key);\n }\n set(key, value) {\n this.add(new Pair(key, value), true);\n }\n /**\n * @param ctx - Conversion context, originally set in Document#toJS()\n * @param {Class} Type - If set, forces the returned collection type\n * @returns Instance of Type, Map, or Object\n */\n toJSON(_, ctx, Type) {\n const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {};\n if (ctx?.onCreate)\n ctx.onCreate(map);\n for (const item of this.items)\n addPairToJSMap(ctx, map, item);\n return map;\n }\n toString(ctx, onComment, onChompKeep) {\n if (!ctx)\n return JSON.stringify(this);\n for (const item of this.items) {\n if (!isPair(item))\n throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);\n }\n if (!ctx.allNullValues && this.hasAllNullValues(false))\n ctx = Object.assign({}, ctx, { allNullValues: true });\n return stringifyCollection(this, ctx, {\n blockItemPrefix: '',\n flowChars: { start: '{', end: '}' },\n itemIndent: ctx.indent || '',\n onChompKeep,\n onComment\n });\n }\n}\n\nexport { YAMLMap, findPair };\n","import { isMap } from '../../nodes/identity.js';\nimport { YAMLMap } from '../../nodes/YAMLMap.js';\n\nconst map = {\n collection: 'map',\n default: true,\n nodeClass: YAMLMap,\n tag: 'tag:yaml.org,2002:map',\n resolve(map, onError) {\n if (!isMap(map))\n onError('Expected a mapping for this tag');\n return map;\n },\n createNode: (schema, obj, ctx) => YAMLMap.from(schema, obj, ctx)\n};\n\nexport { map };\n","import { createNode } from '../doc/createNode.js';\nimport { stringifyCollection } from '../stringify/stringifyCollection.js';\nimport { Collection } from './Collection.js';\nimport { SEQ, isScalar } from './identity.js';\nimport { isScalarValue } from './Scalar.js';\nimport { toJS } from './toJS.js';\n\nclass YAMLSeq extends Collection {\n static get tagName() {\n return 'tag:yaml.org,2002:seq';\n }\n constructor(schema) {\n super(SEQ, schema);\n this.items = [];\n }\n add(value) {\n this.items.push(value);\n }\n /**\n * Removes a value from the collection.\n *\n * `key` must contain a representation of an integer for this to succeed.\n * It may be wrapped in a `Scalar`.\n *\n * @returns `true` if the item was found and removed.\n */\n delete(key) {\n const idx = asItemIndex(key);\n if (typeof idx !== 'number')\n return false;\n const del = this.items.splice(idx, 1);\n return del.length > 0;\n }\n get(key, keepScalar) {\n const idx = asItemIndex(key);\n if (typeof idx !== 'number')\n return undefined;\n const it = this.items[idx];\n return !keepScalar && isScalar(it) ? it.value : it;\n }\n /**\n * Checks if the collection includes a value with the key `key`.\n *\n * `key` must contain a representation of an integer for this to succeed.\n * It may be wrapped in a `Scalar`.\n */\n has(key) {\n const idx = asItemIndex(key);\n return typeof idx === 'number' && idx < this.items.length;\n }\n /**\n * Sets a value in this collection. For `!!set`, `value` needs to be a\n * boolean to add/remove the item from the set.\n *\n * If `key` does not contain a representation of an integer, this will throw.\n * It may be wrapped in a `Scalar`.\n */\n set(key, value) {\n const idx = asItemIndex(key);\n if (typeof idx !== 'number')\n throw new Error(`Expected a valid index, not ${key}.`);\n const prev = this.items[idx];\n if (isScalar(prev) && isScalarValue(value))\n prev.value = value;\n else\n this.items[idx] = value;\n }\n toJSON(_, ctx) {\n const seq = [];\n if (ctx?.onCreate)\n ctx.onCreate(seq);\n let i = 0;\n for (const item of this.items)\n seq.push(toJS(item, String(i++), ctx));\n return seq;\n }\n toString(ctx, onComment, onChompKeep) {\n if (!ctx)\n return JSON.stringify(this);\n return stringifyCollection(this, ctx, {\n blockItemPrefix: '- ',\n flowChars: { start: '[', end: ']' },\n itemIndent: (ctx.indent || '') + ' ',\n onChompKeep,\n onComment\n });\n }\n static from(schema, obj, ctx) {\n const { replacer } = ctx;\n const seq = new this(schema);\n if (obj && Symbol.iterator in Object(obj)) {\n let i = 0;\n for (let it of obj) {\n if (typeof replacer === 'function') {\n const key = obj instanceof Set ? it : String(i++);\n it = replacer.call(obj, key, it);\n }\n seq.items.push(createNode(it, undefined, ctx));\n }\n }\n return seq;\n }\n}\nfunction asItemIndex(key) {\n let idx = isScalar(key) ? key.value : key;\n if (idx && typeof idx === 'string')\n idx = Number(idx);\n return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0\n ? idx\n : null;\n}\n\nexport { YAMLSeq };\n","import { isSeq } from '../../nodes/identity.js';\nimport { YAMLSeq } from '../../nodes/YAMLSeq.js';\n\nconst seq = {\n collection: 'seq',\n default: true,\n nodeClass: YAMLSeq,\n tag: 'tag:yaml.org,2002:seq',\n resolve(seq, onError) {\n if (!isSeq(seq))\n onError('Expected a sequence for this tag');\n return seq;\n },\n createNode: (schema, obj, ctx) => YAMLSeq.from(schema, obj, ctx)\n};\n\nexport { seq };\n","import { stringifyString } from '../../stringify/stringifyString.js';\n\nconst string = {\n identify: value => typeof value === 'string',\n default: true,\n tag: 'tag:yaml.org,2002:str',\n resolve: str => str,\n stringify(item, ctx, onComment, onChompKeep) {\n ctx = Object.assign({ actualString: true }, ctx);\n return stringifyString(item, ctx, onComment, onChompKeep);\n }\n};\n\nexport { string };\n","import { Scalar } from '../../nodes/Scalar.js';\n\nconst nullTag = {\n identify: value => value == null,\n createNode: () => new Scalar(null),\n default: true,\n tag: 'tag:yaml.org,2002:null',\n test: /^(?:~|[Nn]ull|NULL)?$/,\n resolve: () => new Scalar(null),\n stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source)\n ? source\n : ctx.options.nullStr\n};\n\nexport { nullTag };\n","import { Scalar } from '../../nodes/Scalar.js';\n\nconst boolTag = {\n identify: value => typeof value === 'boolean',\n default: true,\n tag: 'tag:yaml.org,2002:bool',\n test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,\n resolve: str => new Scalar(str[0] === 't' || str[0] === 'T'),\n stringify({ source, value }, ctx) {\n if (source && boolTag.test.test(source)) {\n const sv = source[0] === 't' || source[0] === 'T';\n if (value === sv)\n return source;\n }\n return value ? ctx.options.trueStr : ctx.options.falseStr;\n }\n};\n\nexport { boolTag };\n","function stringifyNumber({ format, minFractionDigits, tag, value }) {\n if (typeof value === 'bigint')\n return String(value);\n const num = typeof value === 'number' ? value : Number(value);\n if (!isFinite(num))\n return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf';\n let n = Object.is(value, -0) ? '-0' : JSON.stringify(value);\n if (!format &&\n minFractionDigits &&\n (!tag || tag === 'tag:yaml.org,2002:float') &&\n /^-?\\d/.test(n) &&\n !n.includes('e')) {\n let i = n.indexOf('.');\n if (i < 0) {\n i = n.length;\n n += '.';\n }\n let d = minFractionDigits - (n.length - i - 1);\n while (d-- > 0)\n n += '0';\n }\n return n;\n}\n\nexport { stringifyNumber };\n","import { Scalar } from '../../nodes/Scalar.js';\nimport { stringifyNumber } from '../../stringify/stringifyNumber.js';\n\nconst floatNaN = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,\n resolve: str => str.slice(-3).toLowerCase() === 'nan'\n ? NaN\n : str[0] === '-'\n ? Number.NEGATIVE_INFINITY\n : Number.POSITIVE_INFINITY,\n stringify: stringifyNumber\n};\nconst floatExp = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n format: 'EXP',\n test: /^[-+]?(?:\\.[0-9]+|[0-9]+(?:\\.[0-9]*)?)[eE][-+]?[0-9]+$/,\n resolve: str => parseFloat(str),\n stringify(node) {\n const num = Number(node.value);\n return isFinite(num) ? num.toExponential() : stringifyNumber(node);\n }\n};\nconst float = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^[-+]?(?:\\.[0-9]+|[0-9]+\\.[0-9]*)$/,\n resolve(str) {\n const node = new Scalar(parseFloat(str));\n const dot = str.indexOf('.');\n if (dot !== -1 && str[str.length - 1] === '0')\n node.minFractionDigits = str.length - dot - 1;\n return node;\n },\n stringify: stringifyNumber\n};\n\nexport { float, floatExp, floatNaN };\n","import { stringifyNumber } from '../../stringify/stringifyNumber.js';\n\nconst intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);\nconst intResolve = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix));\nfunction intStringify(node, radix, prefix) {\n const { value } = node;\n if (intIdentify(value) && value >= 0)\n return prefix + value.toString(radix);\n return stringifyNumber(node);\n}\nconst intOct = {\n identify: value => intIdentify(value) && value >= 0,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'OCT',\n test: /^0o[0-7]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),\n stringify: node => intStringify(node, 8, '0o')\n};\nconst int = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n test: /^[-+]?[0-9]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),\n stringify: stringifyNumber\n};\nconst intHex = {\n identify: value => intIdentify(value) && value >= 0,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'HEX',\n test: /^0x[0-9a-fA-F]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),\n stringify: node => intStringify(node, 16, '0x')\n};\n\nexport { int, intHex, intOct };\n","import { map } from '../common/map.js';\nimport { nullTag } from '../common/null.js';\nimport { seq } from '../common/seq.js';\nimport { string } from '../common/string.js';\nimport { boolTag } from './bool.js';\nimport { floatNaN, floatExp, float } from './float.js';\nimport { intOct, int, intHex } from './int.js';\n\nconst schema = [\n map,\n seq,\n string,\n nullTag,\n boolTag,\n intOct,\n int,\n intHex,\n floatNaN,\n floatExp,\n float\n];\n\nexport { schema };\n","import { Scalar } from '../../nodes/Scalar.js';\nimport { map } from '../common/map.js';\nimport { seq } from '../common/seq.js';\n\nfunction intIdentify(value) {\n return typeof value === 'bigint' || Number.isInteger(value);\n}\nconst stringifyJSON = ({ value }) => JSON.stringify(value);\nconst jsonScalars = [\n {\n identify: value => typeof value === 'string',\n default: true,\n tag: 'tag:yaml.org,2002:str',\n resolve: str => str,\n stringify: stringifyJSON\n },\n {\n identify: value => value == null,\n createNode: () => new Scalar(null),\n default: true,\n tag: 'tag:yaml.org,2002:null',\n test: /^null$/,\n resolve: () => null,\n stringify: stringifyJSON\n },\n {\n identify: value => typeof value === 'boolean',\n default: true,\n tag: 'tag:yaml.org,2002:bool',\n test: /^true$|^false$/,\n resolve: str => str === 'true',\n stringify: stringifyJSON\n },\n {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n test: /^-?(?:0|[1-9][0-9]*)$/,\n resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),\n stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)\n },\n {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,\n resolve: str => parseFloat(str),\n stringify: stringifyJSON\n }\n];\nconst jsonError = {\n default: true,\n tag: '',\n test: /^/,\n resolve(str, onError) {\n onError(`Unresolved plain scalar ${JSON.stringify(str)}`);\n return str;\n }\n};\nconst schema = [map, seq].concat(jsonScalars, jsonError);\n\nexport { schema };\n","import { Scalar } from '../../nodes/Scalar.js';\nimport { stringifyString } from '../../stringify/stringifyString.js';\n\nconst binary = {\n identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array\n default: false,\n tag: 'tag:yaml.org,2002:binary',\n /**\n * Returns a Buffer in node and an Uint8Array in browsers\n *\n * To use the resulting buffer as an image, you'll want to do something like:\n *\n * const blob = new Blob([buffer], { type: 'image/jpeg' })\n * document.querySelector('#photo').src = URL.createObjectURL(blob)\n */\n resolve(src, onError) {\n if (typeof atob === 'function') {\n // On IE 11, atob() can't handle newlines\n const str = atob(src.replace(/[\\n\\r]/g, ''));\n const buffer = new Uint8Array(str.length);\n for (let i = 0; i < str.length; ++i)\n buffer[i] = str.charCodeAt(i);\n return buffer;\n }\n else {\n onError('This environment does not support reading binary tags; either Buffer or atob is required');\n return src;\n }\n },\n stringify({ comment, type, value }, ctx, onComment, onChompKeep) {\n if (!value)\n return '';\n const buf = value; // checked earlier by binary.identify()\n let str;\n if (typeof btoa === 'function') {\n let s = '';\n for (let i = 0; i < buf.length; ++i)\n s += String.fromCharCode(buf[i]);\n str = btoa(s);\n }\n else {\n throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');\n }\n type ?? (type = Scalar.BLOCK_LITERAL);\n if (type !== Scalar.QUOTE_DOUBLE) {\n const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);\n const n = Math.ceil(str.length / lineWidth);\n const lines = new Array(n);\n for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {\n lines[i] = str.substr(o, lineWidth);\n }\n str = lines.join(type === Scalar.BLOCK_LITERAL ? '\\n' : ' ');\n }\n return stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);\n }\n};\n\nexport { binary };\n","import { isSeq, isPair, isMap } from '../../nodes/identity.js';\nimport { createPair, Pair } from '../../nodes/Pair.js';\nimport { Scalar } from '../../nodes/Scalar.js';\nimport { YAMLSeq } from '../../nodes/YAMLSeq.js';\n\nfunction resolvePairs(seq, onError) {\n if (isSeq(seq)) {\n for (let i = 0; i < seq.items.length; ++i) {\n let item = seq.items[i];\n if (isPair(item))\n continue;\n else if (isMap(item)) {\n if (item.items.length > 1)\n onError('Each pair must have its own sequence indicator');\n const pair = item.items[0] || new Pair(new Scalar(null));\n if (item.commentBefore)\n pair.key.commentBefore = pair.key.commentBefore\n ? `${item.commentBefore}\\n${pair.key.commentBefore}`\n : item.commentBefore;\n if (item.comment) {\n const cn = pair.value ?? pair.key;\n cn.comment = cn.comment\n ? `${item.comment}\\n${cn.comment}`\n : item.comment;\n }\n item = pair;\n }\n seq.items[i] = isPair(item) ? item : new Pair(item);\n }\n }\n else\n onError('Expected a sequence for this tag');\n return seq;\n}\nfunction createPairs(schema, iterable, ctx) {\n const { replacer } = ctx;\n const pairs = new YAMLSeq(schema);\n pairs.tag = 'tag:yaml.org,2002:pairs';\n let i = 0;\n if (iterable && Symbol.iterator in Object(iterable))\n for (let it of iterable) {\n if (typeof replacer === 'function')\n it = replacer.call(iterable, String(i++), it);\n let key, value;\n if (Array.isArray(it)) {\n if (it.length === 2) {\n key = it[0];\n value = it[1];\n }\n else\n throw new TypeError(`Expected [key, value] tuple: ${it}`);\n }\n else if (it && it instanceof Object) {\n const keys = Object.keys(it);\n if (keys.length === 1) {\n key = keys[0];\n value = it[key];\n }\n else {\n throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);\n }\n }\n else {\n key = it;\n }\n pairs.items.push(createPair(key, value, ctx));\n }\n return pairs;\n}\nconst pairs = {\n collection: 'seq',\n default: false,\n tag: 'tag:yaml.org,2002:pairs',\n resolve: resolvePairs,\n createNode: createPairs\n};\n\nexport { createPairs, pairs, resolvePairs };\n","import { isScalar, isPair } from '../../nodes/identity.js';\nimport { toJS } from '../../nodes/toJS.js';\nimport { YAMLMap } from '../../nodes/YAMLMap.js';\nimport { YAMLSeq } from '../../nodes/YAMLSeq.js';\nimport { resolvePairs, createPairs } from './pairs.js';\n\nclass YAMLOMap extends YAMLSeq {\n constructor() {\n super();\n this.add = YAMLMap.prototype.add.bind(this);\n this.delete = YAMLMap.prototype.delete.bind(this);\n this.get = YAMLMap.prototype.get.bind(this);\n this.has = YAMLMap.prototype.has.bind(this);\n this.set = YAMLMap.prototype.set.bind(this);\n this.tag = YAMLOMap.tag;\n }\n /**\n * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,\n * but TypeScript won't allow widening the signature of a child method.\n */\n toJSON(_, ctx) {\n if (!ctx)\n return super.toJSON(_);\n const map = new Map();\n if (ctx?.onCreate)\n ctx.onCreate(map);\n for (const pair of this.items) {\n let key, value;\n if (isPair(pair)) {\n key = toJS(pair.key, '', ctx);\n value = toJS(pair.value, key, ctx);\n }\n else {\n key = toJS(pair, '', ctx);\n }\n if (map.has(key))\n throw new Error('Ordered maps must not include duplicate keys');\n map.set(key, value);\n }\n return map;\n }\n static from(schema, iterable, ctx) {\n const pairs = createPairs(schema, iterable, ctx);\n const omap = new this();\n omap.items = pairs.items;\n return omap;\n }\n}\nYAMLOMap.tag = 'tag:yaml.org,2002:omap';\nconst omap = {\n collection: 'seq',\n identify: value => value instanceof Map,\n nodeClass: YAMLOMap,\n default: false,\n tag: 'tag:yaml.org,2002:omap',\n resolve(seq, onError) {\n const pairs = resolvePairs(seq, onError);\n const seenKeys = [];\n for (const { key } of pairs.items) {\n if (isScalar(key)) {\n if (seenKeys.includes(key.value)) {\n onError(`Ordered maps must not include duplicate keys: ${key.value}`);\n }\n else {\n seenKeys.push(key.value);\n }\n }\n }\n return Object.assign(new YAMLOMap(), pairs);\n },\n createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)\n};\n\nexport { YAMLOMap, omap };\n","import { Scalar } from '../../nodes/Scalar.js';\n\nfunction boolStringify({ value, source }, ctx) {\n const boolObj = value ? trueTag : falseTag;\n if (source && boolObj.test.test(source))\n return source;\n return value ? ctx.options.trueStr : ctx.options.falseStr;\n}\nconst trueTag = {\n identify: value => value === true,\n default: true,\n tag: 'tag:yaml.org,2002:bool',\n test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,\n resolve: () => new Scalar(true),\n stringify: boolStringify\n};\nconst falseTag = {\n identify: value => value === false,\n default: true,\n tag: 'tag:yaml.org,2002:bool',\n test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,\n resolve: () => new Scalar(false),\n stringify: boolStringify\n};\n\nexport { falseTag, trueTag };\n","import { Scalar } from '../../nodes/Scalar.js';\nimport { stringifyNumber } from '../../stringify/stringifyNumber.js';\n\nconst floatNaN = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,\n resolve: (str) => str.slice(-3).toLowerCase() === 'nan'\n ? NaN\n : str[0] === '-'\n ? Number.NEGATIVE_INFINITY\n : Number.POSITIVE_INFINITY,\n stringify: stringifyNumber\n};\nconst floatExp = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n format: 'EXP',\n test: /^[-+]?(?:[0-9][0-9_]*)?(?:\\.[0-9_]*)?[eE][-+]?[0-9]+$/,\n resolve: (str) => parseFloat(str.replace(/_/g, '')),\n stringify(node) {\n const num = Number(node.value);\n return isFinite(num) ? num.toExponential() : stringifyNumber(node);\n }\n};\nconst float = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^[-+]?(?:[0-9][0-9_]*)?\\.[0-9_]*$/,\n resolve(str) {\n const node = new Scalar(parseFloat(str.replace(/_/g, '')));\n const dot = str.indexOf('.');\n if (dot !== -1) {\n const f = str.substring(dot + 1).replace(/_/g, '');\n if (f[f.length - 1] === '0')\n node.minFractionDigits = f.length;\n }\n return node;\n },\n stringify: stringifyNumber\n};\n\nexport { float, floatExp, floatNaN };\n","import { stringifyNumber } from '../../stringify/stringifyNumber.js';\n\nconst intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);\nfunction intResolve(str, offset, radix, { intAsBigInt }) {\n const sign = str[0];\n if (sign === '-' || sign === '+')\n offset += 1;\n str = str.substring(offset).replace(/_/g, '');\n if (intAsBigInt) {\n switch (radix) {\n case 2:\n str = `0b${str}`;\n break;\n case 8:\n str = `0o${str}`;\n break;\n case 16:\n str = `0x${str}`;\n break;\n }\n const n = BigInt(str);\n return sign === '-' ? BigInt(-1) * n : n;\n }\n const n = parseInt(str, radix);\n return sign === '-' ? -1 * n : n;\n}\nfunction intStringify(node, radix, prefix) {\n const { value } = node;\n if (intIdentify(value)) {\n const str = value.toString(radix);\n return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;\n }\n return stringifyNumber(node);\n}\nconst intBin = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'BIN',\n test: /^[-+]?0b[0-1_]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),\n stringify: node => intStringify(node, 2, '0b')\n};\nconst intOct = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'OCT',\n test: /^[-+]?0[0-7_]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),\n stringify: node => intStringify(node, 8, '0')\n};\nconst int = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n test: /^[-+]?[0-9][0-9_]*$/,\n resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),\n stringify: stringifyNumber\n};\nconst intHex = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'HEX',\n test: /^[-+]?0x[0-9a-fA-F_]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),\n stringify: node => intStringify(node, 16, '0x')\n};\n\nexport { int, intBin, intHex, intOct };\n","import { isMap, isPair, isScalar } from '../../nodes/identity.js';\nimport { Pair, createPair } from '../../nodes/Pair.js';\nimport { YAMLMap, findPair } from '../../nodes/YAMLMap.js';\n\nclass YAMLSet extends YAMLMap {\n constructor(schema) {\n super(schema);\n this.tag = YAMLSet.tag;\n }\n add(key) {\n let pair;\n if (isPair(key))\n pair = key;\n else if (key &&\n typeof key === 'object' &&\n 'key' in key &&\n 'value' in key &&\n key.value === null)\n pair = new Pair(key.key, null);\n else\n pair = new Pair(key, null);\n const prev = findPair(this.items, pair.key);\n if (!prev)\n this.items.push(pair);\n }\n /**\n * If `keepPair` is `true`, returns the Pair matching `key`.\n * Otherwise, returns the value of that Pair's key.\n */\n get(key, keepPair) {\n const pair = findPair(this.items, key);\n return !keepPair && isPair(pair)\n ? isScalar(pair.key)\n ? pair.key.value\n : pair.key\n : pair;\n }\n set(key, value) {\n if (typeof value !== 'boolean')\n throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);\n const prev = findPair(this.items, key);\n if (prev && !value) {\n this.items.splice(this.items.indexOf(prev), 1);\n }\n else if (!prev && value) {\n this.items.push(new Pair(key));\n }\n }\n toJSON(_, ctx) {\n return super.toJSON(_, ctx, Set);\n }\n toString(ctx, onComment, onChompKeep) {\n if (!ctx)\n return JSON.stringify(this);\n if (this.hasAllNullValues(true))\n return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);\n else\n throw new Error('Set items must all have null values');\n }\n static from(schema, iterable, ctx) {\n const { replacer } = ctx;\n const set = new this(schema);\n if (iterable && Symbol.iterator in Object(iterable))\n for (let value of iterable) {\n if (typeof replacer === 'function')\n value = replacer.call(iterable, value, value);\n set.items.push(createPair(value, null, ctx));\n }\n return set;\n }\n}\nYAMLSet.tag = 'tag:yaml.org,2002:set';\nconst set = {\n collection: 'map',\n identify: value => value instanceof Set,\n nodeClass: YAMLSet,\n default: false,\n tag: 'tag:yaml.org,2002:set',\n createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),\n resolve(map, onError) {\n if (isMap(map)) {\n if (map.hasAllNullValues(true))\n return Object.assign(new YAMLSet(), map);\n else\n onError('Set items must all have null values');\n }\n else\n onError('Expected a mapping for this tag');\n return map;\n }\n};\n\nexport { YAMLSet, set };\n","import { stringifyNumber } from '../../stringify/stringifyNumber.js';\n\n/** Internal types handle bigint as number, because TS can't figure it out. */\nfunction parseSexagesimal(str, asBigInt) {\n const sign = str[0];\n const parts = sign === '-' || sign === '+' ? str.substring(1) : str;\n const num = (n) => asBigInt ? BigInt(n) : Number(n);\n const res = parts\n .replace(/_/g, '')\n .split(':')\n .reduce((res, p) => res * num(60) + num(p), num(0));\n return (sign === '-' ? num(-1) * res : res);\n}\n/**\n * hhhh:mm:ss.sss\n *\n * Internal types handle bigint as number, because TS can't figure it out.\n */\nfunction stringifySexagesimal(node) {\n let { value } = node;\n let num = (n) => n;\n if (typeof value === 'bigint')\n num = n => BigInt(n);\n else if (isNaN(value) || !isFinite(value))\n return stringifyNumber(node);\n let sign = '';\n if (value < 0) {\n sign = '-';\n value *= num(-1);\n }\n const _60 = num(60);\n const parts = [value % _60]; // seconds, including ms\n if (value < 60) {\n parts.unshift(0); // at least one : is required\n }\n else {\n value = (value - parts[0]) / _60;\n parts.unshift(value % _60); // minutes\n if (value >= 60) {\n value = (value - parts[0]) / _60;\n parts.unshift(value); // hours\n }\n }\n return (sign +\n parts\n .map(n => String(n).padStart(2, '0'))\n .join(':')\n .replace(/000000\\d*$/, '') // % 60 may introduce error\n );\n}\nconst intTime = {\n identify: value => typeof value === 'bigint' || Number.isInteger(value),\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'TIME',\n test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,\n resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),\n stringify: stringifySexagesimal\n};\nconst floatTime = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n format: 'TIME',\n test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*$/,\n resolve: str => parseSexagesimal(str, false),\n stringify: stringifySexagesimal\n};\nconst timestamp = {\n identify: value => value instanceof Date,\n default: true,\n tag: 'tag:yaml.org,2002:timestamp',\n // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part\n // may be omitted altogether, resulting in a date format. In such a case, the time part is\n // assumed to be 00:00:00Z (start of day, UTC).\n test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd\n '(?:' + // time is optional\n '(?:t|T|[ \\\\t]+)' + // t | T | whitespace\n '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?\n '(?:[ \\\\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30\n ')?$'),\n resolve(str) {\n const match = str.match(timestamp.test);\n if (!match)\n throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd');\n const [, year, month, day, hour, minute, second] = match.map(Number);\n const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0;\n let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);\n const tz = match[8];\n if (tz && tz !== 'Z') {\n let d = parseSexagesimal(tz, false);\n if (Math.abs(d) < 30)\n d *= 60;\n date -= 60000 * d;\n }\n return new Date(date);\n },\n stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\\.000Z$/, '') ?? ''\n};\n\nexport { floatTime, intTime, timestamp };\n","import { map } from '../common/map.js';\nimport { nullTag } from '../common/null.js';\nimport { seq } from '../common/seq.js';\nimport { string } from '../common/string.js';\nimport { binary } from './binary.js';\nimport { trueTag, falseTag } from './bool.js';\nimport { floatNaN, floatExp, float } from './float.js';\nimport { intBin, intOct, int, intHex } from './int.js';\nimport { merge } from './merge.js';\nimport { omap } from './omap.js';\nimport { pairs } from './pairs.js';\nimport { set } from './set.js';\nimport { intTime, floatTime, timestamp } from './timestamp.js';\n\nconst schema = [\n map,\n seq,\n string,\n nullTag,\n trueTag,\n falseTag,\n intBin,\n intOct,\n int,\n intHex,\n floatNaN,\n floatExp,\n float,\n binary,\n merge,\n omap,\n pairs,\n set,\n intTime,\n floatTime,\n timestamp\n];\n\nexport { schema };\n","import { map } from './common/map.js';\nimport { nullTag } from './common/null.js';\nimport { seq } from './common/seq.js';\nimport { string } from './common/string.js';\nimport { boolTag } from './core/bool.js';\nimport { floatNaN, floatExp, float } from './core/float.js';\nimport { intOct, intHex, int } from './core/int.js';\nimport { schema } from './core/schema.js';\nimport { schema as schema$1 } from './json/schema.js';\nimport { binary } from './yaml-1.1/binary.js';\nimport { merge } from './yaml-1.1/merge.js';\nimport { omap } from './yaml-1.1/omap.js';\nimport { pairs } from './yaml-1.1/pairs.js';\nimport { schema as schema$2 } from './yaml-1.1/schema.js';\nimport { set } from './yaml-1.1/set.js';\nimport { timestamp, intTime, floatTime } from './yaml-1.1/timestamp.js';\n\nconst schemas = new Map([\n ['core', schema],\n ['failsafe', [map, seq, string]],\n ['json', schema$1],\n ['yaml11', schema$2],\n ['yaml-1.1', schema$2]\n]);\nconst tagsByName = {\n binary,\n bool: boolTag,\n float,\n floatExp,\n floatNaN,\n floatTime,\n int,\n intHex,\n intOct,\n intTime,\n map,\n merge,\n null: nullTag,\n omap,\n pairs,\n seq,\n set,\n timestamp\n};\nconst coreKnownTags = {\n 'tag:yaml.org,2002:binary': binary,\n 'tag:yaml.org,2002:merge': merge,\n 'tag:yaml.org,2002:omap': omap,\n 'tag:yaml.org,2002:pairs': pairs,\n 'tag:yaml.org,2002:set': set,\n 'tag:yaml.org,2002:timestamp': timestamp\n};\nfunction getTags(customTags, schemaName, addMergeTag) {\n const schemaTags = schemas.get(schemaName);\n if (schemaTags && !customTags) {\n return addMergeTag && !schemaTags.includes(merge)\n ? schemaTags.concat(merge)\n : schemaTags.slice();\n }\n let tags = schemaTags;\n if (!tags) {\n if (Array.isArray(customTags))\n tags = [];\n else {\n const keys = Array.from(schemas.keys())\n .filter(key => key !== 'yaml11')\n .map(key => JSON.stringify(key))\n .join(', ');\n throw new Error(`Unknown schema \"${schemaName}\"; use one of ${keys} or define customTags array`);\n }\n }\n if (Array.isArray(customTags)) {\n for (const tag of customTags)\n tags = tags.concat(tag);\n }\n else if (typeof customTags === 'function') {\n tags = customTags(tags.slice());\n }\n if (addMergeTag)\n tags = tags.concat(merge);\n return tags.reduce((tags, tag) => {\n const tagObj = typeof tag === 'string' ? tagsByName[tag] : tag;\n if (!tagObj) {\n const tagName = JSON.stringify(tag);\n const keys = Object.keys(tagsByName)\n .map(key => JSON.stringify(key))\n .join(', ');\n throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);\n }\n if (!tags.includes(tagObj))\n tags.push(tagObj);\n return tags;\n }, []);\n}\n\nexport { coreKnownTags, getTags };\n","import { MAP, SCALAR, SEQ } from '../nodes/identity.js';\nimport { map } from './common/map.js';\nimport { seq } from './common/seq.js';\nimport { string } from './common/string.js';\nimport { getTags, coreKnownTags } from './tags.js';\n\nconst sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;\nclass Schema {\n constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {\n this.compat = Array.isArray(compat)\n ? getTags(compat, 'compat')\n : compat\n ? getTags(null, compat)\n : null;\n this.name = (typeof schema === 'string' && schema) || 'core';\n this.knownTags = resolveKnownTags ? coreKnownTags : {};\n this.tags = getTags(customTags, this.name, merge);\n this.toStringOptions = toStringDefaults ?? null;\n Object.defineProperty(this, MAP, { value: map });\n Object.defineProperty(this, SCALAR, { value: string });\n Object.defineProperty(this, SEQ, { value: seq });\n // Used by createMap()\n this.sortMapEntries =\n typeof sortMapEntries === 'function'\n ? sortMapEntries\n : sortMapEntries === true\n ? sortMapEntriesByKey\n : null;\n }\n clone() {\n const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));\n copy.tags = this.tags.slice();\n return copy;\n }\n}\n\nexport { Schema };\n","import { isNode } from '../nodes/identity.js';\nimport { createStringifyContext, stringify } from './stringify.js';\nimport { indentComment, lineComment } from './stringifyComment.js';\n\nfunction stringifyDocument(doc, options) {\n const lines = [];\n let hasDirectives = options.directives === true;\n if (options.directives !== false && doc.directives) {\n const dir = doc.directives.toString(doc);\n if (dir) {\n lines.push(dir);\n hasDirectives = true;\n }\n else if (doc.directives.docStart)\n hasDirectives = true;\n }\n if (hasDirectives)\n lines.push('---');\n const ctx = createStringifyContext(doc, options);\n const { commentString } = ctx.options;\n if (doc.commentBefore) {\n if (lines.length !== 1)\n lines.unshift('');\n const cs = commentString(doc.commentBefore);\n lines.unshift(indentComment(cs, ''));\n }\n let chompKeep = false;\n let contentComment = null;\n if (doc.contents) {\n if (isNode(doc.contents)) {\n if (doc.contents.spaceBefore && hasDirectives)\n lines.push('');\n if (doc.contents.commentBefore) {\n const cs = commentString(doc.contents.commentBefore);\n lines.push(indentComment(cs, ''));\n }\n // top-level block scalars need to be indented if followed by a comment\n ctx.forceBlockIndent = !!doc.comment;\n contentComment = doc.contents.comment;\n }\n const onChompKeep = contentComment ? undefined : () => (chompKeep = true);\n let body = stringify(doc.contents, ctx, () => (contentComment = null), onChompKeep);\n if (contentComment)\n body += lineComment(body, '', commentString(contentComment));\n if ((body[0] === '|' || body[0] === '>') &&\n lines[lines.length - 1] === '---') {\n // Top-level block scalars with a preceding doc marker ought to use the\n // same line for their header.\n lines[lines.length - 1] = `--- ${body}`;\n }\n else\n lines.push(body);\n }\n else {\n lines.push(stringify(doc.contents, ctx));\n }\n if (doc.directives?.docEnd) {\n if (doc.comment) {\n const cs = commentString(doc.comment);\n if (cs.includes('\\n')) {\n lines.push('...');\n lines.push(indentComment(cs, ''));\n }\n else {\n lines.push(`... ${cs}`);\n }\n }\n else {\n lines.push('...');\n }\n }\n else {\n let dc = doc.comment;\n if (dc && chompKeep)\n dc = dc.replace(/^\\n+/, '');\n if (dc) {\n if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')\n lines.push('');\n lines.push(indentComment(commentString(dc), ''));\n }\n }\n return lines.join('\\n') + '\\n';\n}\n\nexport { stringifyDocument };\n","import { Alias } from '../nodes/Alias.js';\nimport { isEmptyPath, collectionFromPath } from '../nodes/Collection.js';\nimport { NODE_TYPE, DOC, isNode, isCollection, isScalar } from '../nodes/identity.js';\nimport { Pair } from '../nodes/Pair.js';\nimport { toJS } from '../nodes/toJS.js';\nimport { Schema } from '../schema/Schema.js';\nimport { stringifyDocument } from '../stringify/stringifyDocument.js';\nimport { anchorNames, findNewAnchor, createNodeAnchors } from './anchors.js';\nimport { applyReviver } from './applyReviver.js';\nimport { createNode } from './createNode.js';\nimport { Directives } from './directives.js';\n\nclass Document {\n constructor(value, replacer, options) {\n /** A comment before this Document */\n this.commentBefore = null;\n /** A comment immediately after this Document */\n this.comment = null;\n /** Errors encountered during parsing. */\n this.errors = [];\n /** Warnings encountered during parsing. */\n this.warnings = [];\n Object.defineProperty(this, NODE_TYPE, { value: DOC });\n let _replacer = null;\n if (typeof replacer === 'function' || Array.isArray(replacer)) {\n _replacer = replacer;\n }\n else if (options === undefined && replacer) {\n options = replacer;\n replacer = undefined;\n }\n const opt = Object.assign({\n intAsBigInt: false,\n keepSourceTokens: false,\n logLevel: 'warn',\n prettyErrors: true,\n strict: true,\n stringKeys: false,\n uniqueKeys: true,\n version: '1.2'\n }, options);\n this.options = opt;\n let { version } = opt;\n if (options?._directives) {\n this.directives = options._directives.atDocument();\n if (this.directives.yaml.explicit)\n version = this.directives.yaml.version;\n }\n else\n this.directives = new Directives({ version });\n this.setSchema(version, options);\n // @ts-expect-error We can't really know that this matches Contents.\n this.contents =\n value === undefined ? null : this.createNode(value, _replacer, options);\n }\n /**\n * Create a deep copy of this Document and its contents.\n *\n * Custom Node values that inherit from `Object` still refer to their original instances.\n */\n clone() {\n const copy = Object.create(Document.prototype, {\n [NODE_TYPE]: { value: DOC }\n });\n copy.commentBefore = this.commentBefore;\n copy.comment = this.comment;\n copy.errors = this.errors.slice();\n copy.warnings = this.warnings.slice();\n copy.options = Object.assign({}, this.options);\n if (this.directives)\n copy.directives = this.directives.clone();\n copy.schema = this.schema.clone();\n // @ts-expect-error We can't really know that this matches Contents.\n copy.contents = isNode(this.contents)\n ? this.contents.clone(copy.schema)\n : this.contents;\n if (this.range)\n copy.range = this.range.slice();\n return copy;\n }\n /** Adds a value to the document. */\n add(value) {\n if (assertCollection(this.contents))\n this.contents.add(value);\n }\n /** Adds a value to the document. */\n addIn(path, value) {\n if (assertCollection(this.contents))\n this.contents.addIn(path, value);\n }\n /**\n * Create a new `Alias` node, ensuring that the target `node` has the required anchor.\n *\n * If `node` already has an anchor, `name` is ignored.\n * Otherwise, the `node.anchor` value will be set to `name`,\n * or if an anchor with that name is already present in the document,\n * `name` will be used as a prefix for a new unique anchor.\n * If `name` is undefined, the generated anchor will use 'a' as a prefix.\n */\n createAlias(node, name) {\n if (!node.anchor) {\n const prev = anchorNames(this);\n node.anchor =\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n !name || prev.has(name) ? findNewAnchor(name || 'a', prev) : name;\n }\n return new Alias(node.anchor);\n }\n createNode(value, replacer, options) {\n let _replacer = undefined;\n if (typeof replacer === 'function') {\n value = replacer.call({ '': value }, '', value);\n _replacer = replacer;\n }\n else if (Array.isArray(replacer)) {\n const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number;\n const asStr = replacer.filter(keyToStr).map(String);\n if (asStr.length > 0)\n replacer = replacer.concat(asStr);\n _replacer = replacer;\n }\n else if (options === undefined && replacer) {\n options = replacer;\n replacer = undefined;\n }\n const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};\n const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors(this, \n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n anchorPrefix || 'a');\n const ctx = {\n aliasDuplicateObjects: aliasDuplicateObjects ?? true,\n keepUndefined: keepUndefined ?? false,\n onAnchor,\n onTagObj,\n replacer: _replacer,\n schema: this.schema,\n sourceObjects\n };\n const node = createNode(value, tag, ctx);\n if (flow && isCollection(node))\n node.flow = true;\n setAnchors();\n return node;\n }\n /**\n * Convert a key and a value into a `Pair` using the current schema,\n * recursively wrapping all values as `Scalar` or `Collection` nodes.\n */\n createPair(key, value, options = {}) {\n const k = this.createNode(key, null, options);\n const v = this.createNode(value, null, options);\n return new Pair(k, v);\n }\n /**\n * Removes a value from the document.\n * @returns `true` if the item was found and removed.\n */\n delete(key) {\n return assertCollection(this.contents) ? this.contents.delete(key) : false;\n }\n /**\n * Removes a value from the document.\n * @returns `true` if the item was found and removed.\n */\n deleteIn(path) {\n if (isEmptyPath(path)) {\n if (this.contents == null)\n return false;\n // @ts-expect-error Presumed impossible if Strict extends false\n this.contents = null;\n return true;\n }\n return assertCollection(this.contents)\n ? this.contents.deleteIn(path)\n : false;\n }\n /**\n * Returns item at `key`, or `undefined` if not found. By default unwraps\n * scalar values from their surrounding node; to disable set `keepScalar` to\n * `true` (collections are always returned intact).\n */\n get(key, keepScalar) {\n return isCollection(this.contents)\n ? this.contents.get(key, keepScalar)\n : undefined;\n }\n /**\n * Returns item at `path`, or `undefined` if not found. By default unwraps\n * scalar values from their surrounding node; to disable set `keepScalar` to\n * `true` (collections are always returned intact).\n */\n getIn(path, keepScalar) {\n if (isEmptyPath(path))\n return !keepScalar && isScalar(this.contents)\n ? this.contents.value\n : this.contents;\n return isCollection(this.contents)\n ? this.contents.getIn(path, keepScalar)\n : undefined;\n }\n /**\n * Checks if the document includes a value with the key `key`.\n */\n has(key) {\n return isCollection(this.contents) ? this.contents.has(key) : false;\n }\n /**\n * Checks if the document includes a value at `path`.\n */\n hasIn(path) {\n if (isEmptyPath(path))\n return this.contents !== undefined;\n return isCollection(this.contents) ? this.contents.hasIn(path) : false;\n }\n /**\n * Sets a value in this document. For `!!set`, `value` needs to be a\n * boolean to add/remove the item from the set.\n */\n set(key, value) {\n if (this.contents == null) {\n // @ts-expect-error We can't really know that this matches Contents.\n this.contents = collectionFromPath(this.schema, [key], value);\n }\n else if (assertCollection(this.contents)) {\n this.contents.set(key, value);\n }\n }\n /**\n * Sets a value in this document. For `!!set`, `value` needs to be a\n * boolean to add/remove the item from the set.\n */\n setIn(path, value) {\n if (isEmptyPath(path)) {\n // @ts-expect-error We can't really know that this matches Contents.\n this.contents = value;\n }\n else if (this.contents == null) {\n // @ts-expect-error We can't really know that this matches Contents.\n this.contents = collectionFromPath(this.schema, Array.from(path), value);\n }\n else if (assertCollection(this.contents)) {\n this.contents.setIn(path, value);\n }\n }\n /**\n * Change the YAML version and schema used by the document.\n * A `null` version disables support for directives, explicit tags, anchors, and aliases.\n * It also requires the `schema` option to be given as a `Schema` instance value.\n *\n * Overrides all previously set schema options.\n */\n setSchema(version, options = {}) {\n if (typeof version === 'number')\n version = String(version);\n let opt;\n switch (version) {\n case '1.1':\n if (this.directives)\n this.directives.yaml.version = '1.1';\n else\n this.directives = new Directives({ version: '1.1' });\n opt = { resolveKnownTags: false, schema: 'yaml-1.1' };\n break;\n case '1.2':\n case 'next':\n if (this.directives)\n this.directives.yaml.version = version;\n else\n this.directives = new Directives({ version });\n opt = { resolveKnownTags: true, schema: 'core' };\n break;\n case null:\n if (this.directives)\n delete this.directives;\n opt = null;\n break;\n default: {\n const sv = JSON.stringify(version);\n throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);\n }\n }\n // Not using `instanceof Schema` to allow for duck typing\n if (options.schema instanceof Object)\n this.schema = options.schema;\n else if (opt)\n this.schema = new Schema(Object.assign(opt, options));\n else\n throw new Error(`With a null YAML version, the { schema: Schema } option is required`);\n }\n // json & jsonArg are only used from toJSON()\n toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {\n const ctx = {\n anchors: new Map(),\n doc: this,\n keep: !json,\n mapAsMap: mapAsMap === true,\n mapKeyWarned: false,\n maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100\n };\n const res = toJS(this.contents, jsonArg ?? '', ctx);\n if (typeof onAnchor === 'function')\n for (const { count, res } of ctx.anchors.values())\n onAnchor(res, count);\n return typeof reviver === 'function'\n ? applyReviver(reviver, { '': res }, '', res)\n : res;\n }\n /**\n * A JSON representation of the document `contents`.\n *\n * @param jsonArg Used by `JSON.stringify` to indicate the array index or\n * property name.\n */\n toJSON(jsonArg, onAnchor) {\n return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });\n }\n /** A YAML representation of the document. */\n toString(options = {}) {\n if (this.errors.length > 0)\n throw new Error('Document with errors cannot be stringified');\n if ('indent' in options &&\n (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {\n const s = JSON.stringify(options.indent);\n throw new Error(`\"indent\" option must be a positive integer, not ${s}`);\n }\n return stringifyDocument(this, options);\n }\n}\nfunction assertCollection(contents) {\n if (isCollection(contents))\n return true;\n throw new Error('Expected a YAML collection as document contents');\n}\n\nexport { Document };\n","class YAMLError extends Error {\n constructor(name, pos, code, message) {\n super();\n this.name = name;\n this.code = code;\n this.message = message;\n this.pos = pos;\n }\n}\nclass YAMLParseError extends YAMLError {\n constructor(pos, code, message) {\n super('YAMLParseError', pos, code, message);\n }\n}\nclass YAMLWarning extends YAMLError {\n constructor(pos, code, message) {\n super('YAMLWarning', pos, code, message);\n }\n}\nconst prettifyError = (src, lc) => (error) => {\n if (error.pos[0] === -1)\n return;\n error.linePos = error.pos.map(pos => lc.linePos(pos));\n const { line, col } = error.linePos[0];\n error.message += ` at line ${line}, column ${col}`;\n let ci = col - 1;\n let lineStr = src\n .substring(lc.lineStarts[line - 1], lc.lineStarts[line])\n .replace(/[\\n\\r]+$/, '');\n // Trim to max 80 chars, keeping col position near the middle\n if (ci >= 60 && lineStr.length > 80) {\n const trimStart = Math.min(ci - 39, lineStr.length - 79);\n lineStr = '…' + lineStr.substring(trimStart);\n ci -= trimStart - 1;\n }\n if (lineStr.length > 80)\n lineStr = lineStr.substring(0, 79) + '…';\n // Include previous line in context if pointing at line start\n if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {\n // Regexp won't match if start is trimmed\n let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);\n if (prev.length > 80)\n prev = prev.substring(0, 79) + '…\\n';\n lineStr = prev + lineStr;\n }\n if (/[^ ]/.test(lineStr)) {\n let count = 1;\n const end = error.linePos[1];\n if (end?.line === line && end.col > col) {\n count = Math.max(1, Math.min(end.col - col, 80 - ci));\n }\n const pointer = ' '.repeat(ci) + '^'.repeat(count);\n error.message += `:\\n\\n${lineStr}\\n${pointer}\\n`;\n }\n};\n\nexport { YAMLError, YAMLParseError, YAMLWarning, prettifyError };\n","function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {\n let spaceBefore = false;\n let atNewline = startOnNewline;\n let hasSpace = startOnNewline;\n let comment = '';\n let commentSep = '';\n let hasNewline = false;\n let reqSpace = false;\n let tab = null;\n let anchor = null;\n let tag = null;\n let newlineAfterProp = null;\n let comma = null;\n let found = null;\n let start = null;\n for (const token of tokens) {\n if (reqSpace) {\n if (token.type !== 'space' &&\n token.type !== 'newline' &&\n token.type !== 'comma')\n onError(token.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');\n reqSpace = false;\n }\n if (tab) {\n if (atNewline && token.type !== 'comment' && token.type !== 'newline') {\n onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');\n }\n tab = null;\n }\n switch (token.type) {\n case 'space':\n // At the doc level, tabs at line start may be parsed\n // as leading white space rather than indentation.\n // In a flow collection, only the parser handles indent.\n if (!flow &&\n (indicator !== 'doc-start' || next?.type !== 'flow-collection') &&\n token.source.includes('\\t')) {\n tab = token;\n }\n hasSpace = true;\n break;\n case 'comment': {\n if (!hasSpace)\n onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');\n const cb = token.source.substring(1) || ' ';\n if (!comment)\n comment = cb;\n else\n comment += commentSep + cb;\n commentSep = '';\n atNewline = false;\n break;\n }\n case 'newline':\n if (atNewline) {\n if (comment)\n comment += token.source;\n else if (!found || indicator !== 'seq-item-ind')\n spaceBefore = true;\n }\n else\n commentSep += token.source;\n atNewline = true;\n hasNewline = true;\n if (anchor || tag)\n newlineAfterProp = token;\n hasSpace = true;\n break;\n case 'anchor':\n if (anchor)\n onError(token, 'MULTIPLE_ANCHORS', 'A node can have at most one anchor');\n if (token.source.endsWith(':'))\n onError(token.offset + token.source.length - 1, 'BAD_ALIAS', 'Anchor ending in : is ambiguous', true);\n anchor = token;\n start ?? (start = token.offset);\n atNewline = false;\n hasSpace = false;\n reqSpace = true;\n break;\n case 'tag': {\n if (tag)\n onError(token, 'MULTIPLE_TAGS', 'A node can have at most one tag');\n tag = token;\n start ?? (start = token.offset);\n atNewline = false;\n hasSpace = false;\n reqSpace = true;\n break;\n }\n case indicator:\n // Could here handle preceding comments differently\n if (anchor || tag)\n onError(token, 'BAD_PROP_ORDER', `Anchors and tags must be after the ${token.source} indicator`);\n if (found)\n onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.source} in ${flow ?? 'collection'}`);\n found = token;\n atNewline =\n indicator === 'seq-item-ind' || indicator === 'explicit-key-ind';\n hasSpace = false;\n break;\n case 'comma':\n if (flow) {\n if (comma)\n onError(token, 'UNEXPECTED_TOKEN', `Unexpected , in ${flow}`);\n comma = token;\n atNewline = false;\n hasSpace = false;\n break;\n }\n // else fallthrough\n default:\n onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.type} token`);\n atNewline = false;\n hasSpace = false;\n }\n }\n const last = tokens[tokens.length - 1];\n const end = last ? last.offset + last.source.length : offset;\n if (reqSpace &&\n next &&\n next.type !== 'space' &&\n next.type !== 'newline' &&\n next.type !== 'comma' &&\n (next.type !== 'scalar' || next.source !== '')) {\n onError(next.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');\n }\n if (tab &&\n ((atNewline && tab.indent <= parentIndent) ||\n next?.type === 'block-map' ||\n next?.type === 'block-seq'))\n onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');\n return {\n comma,\n found,\n spaceBefore,\n comment,\n hasNewline,\n anchor,\n tag,\n newlineAfterProp,\n end,\n start: start ?? end\n };\n}\n\nexport { resolveProps };\n","function containsNewline(key) {\n if (!key)\n return null;\n switch (key.type) {\n case 'alias':\n case 'scalar':\n case 'double-quoted-scalar':\n case 'single-quoted-scalar':\n if (key.source.includes('\\n'))\n return true;\n if (key.end)\n for (const st of key.end)\n if (st.type === 'newline')\n return true;\n return false;\n case 'flow-collection':\n for (const it of key.items) {\n for (const st of it.start)\n if (st.type === 'newline')\n return true;\n if (it.sep)\n for (const st of it.sep)\n if (st.type === 'newline')\n return true;\n if (containsNewline(it.key) || containsNewline(it.value))\n return true;\n }\n return false;\n default:\n return true;\n }\n}\n\nexport { containsNewline };\n","import { containsNewline } from './util-contains-newline.js';\n\nfunction flowIndentCheck(indent, fc, onError) {\n if (fc?.type === 'flow-collection') {\n const end = fc.end[0];\n if (end.indent === indent &&\n (end.source === ']' || end.source === '}') &&\n containsNewline(fc)) {\n const msg = 'Flow end indicator should be more indented than parent';\n onError(end, 'BAD_INDENT', msg, true);\n }\n }\n}\n\nexport { flowIndentCheck };\n","import { isScalar } from '../nodes/identity.js';\n\nfunction mapIncludes(ctx, items, search) {\n const { uniqueKeys } = ctx.options;\n if (uniqueKeys === false)\n return false;\n const isEqual = typeof uniqueKeys === 'function'\n ? uniqueKeys\n : (a, b) => a === b || (isScalar(a) && isScalar(b) && a.value === b.value);\n return items.some(pair => isEqual(pair.key, search));\n}\n\nexport { mapIncludes };\n","import { Pair } from '../nodes/Pair.js';\nimport { YAMLMap } from '../nodes/YAMLMap.js';\nimport { resolveProps } from './resolve-props.js';\nimport { containsNewline } from './util-contains-newline.js';\nimport { flowIndentCheck } from './util-flow-indent-check.js';\nimport { mapIncludes } from './util-map-includes.js';\n\nconst startColMsg = 'All mapping items must start at the same column';\nfunction resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {\n const NodeClass = tag?.nodeClass ?? YAMLMap;\n const map = new NodeClass(ctx.schema);\n if (ctx.atRoot)\n ctx.atRoot = false;\n let offset = bm.offset;\n let commentEnd = null;\n for (const collItem of bm.items) {\n const { start, key, sep, value } = collItem;\n // key properties\n const keyProps = resolveProps(start, {\n indicator: 'explicit-key-ind',\n next: key ?? sep?.[0],\n offset,\n onError,\n parentIndent: bm.indent,\n startOnNewline: true\n });\n const implicitKey = !keyProps.found;\n if (implicitKey) {\n if (key) {\n if (key.type === 'block-seq')\n onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'A block sequence may not be used as an implicit map key');\n else if ('indent' in key && key.indent !== bm.indent)\n onError(offset, 'BAD_INDENT', startColMsg);\n }\n if (!keyProps.anchor && !keyProps.tag && !sep) {\n commentEnd = keyProps.end;\n if (keyProps.comment) {\n if (map.comment)\n map.comment += '\\n' + keyProps.comment;\n else\n map.comment = keyProps.comment;\n }\n continue;\n }\n if (keyProps.newlineAfterProp || containsNewline(key)) {\n onError(key ?? start[start.length - 1], 'MULTILINE_IMPLICIT_KEY', 'Implicit keys need to be on a single line');\n }\n }\n else if (keyProps.found?.indent !== bm.indent) {\n onError(offset, 'BAD_INDENT', startColMsg);\n }\n // key value\n ctx.atKey = true;\n const keyStart = keyProps.end;\n const keyNode = key\n ? composeNode(ctx, key, keyProps, onError)\n : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);\n if (ctx.schema.compat)\n flowIndentCheck(bm.indent, key, onError);\n ctx.atKey = false;\n if (mapIncludes(ctx, map.items, keyNode))\n onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');\n // value properties\n const valueProps = resolveProps(sep ?? [], {\n indicator: 'map-value-ind',\n next: value,\n offset: keyNode.range[2],\n onError,\n parentIndent: bm.indent,\n startOnNewline: !key || key.type === 'block-scalar'\n });\n offset = valueProps.end;\n if (valueProps.found) {\n if (implicitKey) {\n if (value?.type === 'block-map' && !valueProps.hasNewline)\n onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'Nested mappings are not allowed in compact mappings');\n if (ctx.options.strict &&\n keyProps.start < valueProps.found.offset - 1024)\n onError(keyNode.range, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit block mapping key');\n }\n // value value\n const valueNode = value\n ? composeNode(ctx, value, valueProps, onError)\n : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);\n if (ctx.schema.compat)\n flowIndentCheck(bm.indent, value, onError);\n offset = valueNode.range[2];\n const pair = new Pair(keyNode, valueNode);\n if (ctx.options.keepSourceTokens)\n pair.srcToken = collItem;\n map.items.push(pair);\n }\n else {\n // key with no value\n if (implicitKey)\n onError(keyNode.range, 'MISSING_CHAR', 'Implicit map keys need to be followed by map values');\n if (valueProps.comment) {\n if (keyNode.comment)\n keyNode.comment += '\\n' + valueProps.comment;\n else\n keyNode.comment = valueProps.comment;\n }\n const pair = new Pair(keyNode);\n if (ctx.options.keepSourceTokens)\n pair.srcToken = collItem;\n map.items.push(pair);\n }\n }\n if (commentEnd && commentEnd < offset)\n onError(commentEnd, 'IMPOSSIBLE', 'Map comment with trailing content');\n map.range = [bm.offset, offset, commentEnd ?? offset];\n return map;\n}\n\nexport { resolveBlockMap };\n","import { YAMLSeq } from '../nodes/YAMLSeq.js';\nimport { resolveProps } from './resolve-props.js';\nimport { flowIndentCheck } from './util-flow-indent-check.js';\n\nfunction resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {\n const NodeClass = tag?.nodeClass ?? YAMLSeq;\n const seq = new NodeClass(ctx.schema);\n if (ctx.atRoot)\n ctx.atRoot = false;\n if (ctx.atKey)\n ctx.atKey = false;\n let offset = bs.offset;\n let commentEnd = null;\n for (const { start, value } of bs.items) {\n const props = resolveProps(start, {\n indicator: 'seq-item-ind',\n next: value,\n offset,\n onError,\n parentIndent: bs.indent,\n startOnNewline: true\n });\n if (!props.found) {\n if (props.anchor || props.tag || value) {\n if (value?.type === 'block-seq')\n onError(props.end, 'BAD_INDENT', 'All sequence items must start at the same column');\n else\n onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator');\n }\n else {\n commentEnd = props.end;\n if (props.comment)\n seq.comment = props.comment;\n continue;\n }\n }\n const node = value\n ? composeNode(ctx, value, props, onError)\n : composeEmptyNode(ctx, props.end, start, null, props, onError);\n if (ctx.schema.compat)\n flowIndentCheck(bs.indent, value, onError);\n offset = node.range[2];\n seq.items.push(node);\n }\n seq.range = [bs.offset, offset, commentEnd ?? offset];\n return seq;\n}\n\nexport { resolveBlockSeq };\n","function resolveEnd(end, offset, reqSpace, onError) {\n let comment = '';\n if (end) {\n let hasSpace = false;\n let sep = '';\n for (const token of end) {\n const { source, type } = token;\n switch (type) {\n case 'space':\n hasSpace = true;\n break;\n case 'comment': {\n if (reqSpace && !hasSpace)\n onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');\n const cb = source.substring(1) || ' ';\n if (!comment)\n comment = cb;\n else\n comment += sep + cb;\n sep = '';\n break;\n }\n case 'newline':\n if (comment)\n sep += source;\n hasSpace = true;\n break;\n default:\n onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${type} at node end`);\n }\n offset += source.length;\n }\n }\n return { comment, offset };\n}\n\nexport { resolveEnd };\n","import { isPair } from '../nodes/identity.js';\nimport { Pair } from '../nodes/Pair.js';\nimport { YAMLMap } from '../nodes/YAMLMap.js';\nimport { YAMLSeq } from '../nodes/YAMLSeq.js';\nimport { resolveEnd } from './resolve-end.js';\nimport { resolveProps } from './resolve-props.js';\nimport { containsNewline } from './util-contains-newline.js';\nimport { mapIncludes } from './util-map-includes.js';\n\nconst blockMsg = 'Block collections are not allowed within flow collections';\nconst isBlock = (token) => token && (token.type === 'block-map' || token.type === 'block-seq');\nfunction resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {\n const isMap = fc.start.source === '{';\n const fcName = isMap ? 'flow map' : 'flow sequence';\n const NodeClass = (tag?.nodeClass ?? (isMap ? YAMLMap : YAMLSeq));\n const coll = new NodeClass(ctx.schema);\n coll.flow = true;\n const atRoot = ctx.atRoot;\n if (atRoot)\n ctx.atRoot = false;\n if (ctx.atKey)\n ctx.atKey = false;\n let offset = fc.offset + fc.start.source.length;\n for (let i = 0; i < fc.items.length; ++i) {\n const collItem = fc.items[i];\n const { start, key, sep, value } = collItem;\n const props = resolveProps(start, {\n flow: fcName,\n indicator: 'explicit-key-ind',\n next: key ?? sep?.[0],\n offset,\n onError,\n parentIndent: fc.indent,\n startOnNewline: false\n });\n if (!props.found) {\n if (!props.anchor && !props.tag && !sep && !value) {\n if (i === 0 && props.comma)\n onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);\n else if (i < fc.items.length - 1)\n onError(props.start, 'UNEXPECTED_TOKEN', `Unexpected empty item in ${fcName}`);\n if (props.comment) {\n if (coll.comment)\n coll.comment += '\\n' + props.comment;\n else\n coll.comment = props.comment;\n }\n offset = props.end;\n continue;\n }\n if (!isMap && ctx.options.strict && containsNewline(key))\n onError(key, // checked by containsNewline()\n 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');\n }\n if (i === 0) {\n if (props.comma)\n onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);\n }\n else {\n if (!props.comma)\n onError(props.start, 'MISSING_CHAR', `Missing , between ${fcName} items`);\n if (props.comment) {\n let prevItemComment = '';\n loop: for (const st of start) {\n switch (st.type) {\n case 'comma':\n case 'space':\n break;\n case 'comment':\n prevItemComment = st.source.substring(1);\n break loop;\n default:\n break loop;\n }\n }\n if (prevItemComment) {\n let prev = coll.items[coll.items.length - 1];\n if (isPair(prev))\n prev = prev.value ?? prev.key;\n if (prev.comment)\n prev.comment += '\\n' + prevItemComment;\n else\n prev.comment = prevItemComment;\n props.comment = props.comment.substring(prevItemComment.length + 1);\n }\n }\n }\n if (!isMap && !sep && !props.found) {\n // item is a value in a seq\n // → key & sep are empty, start does not include ? or :\n const valueNode = value\n ? composeNode(ctx, value, props, onError)\n : composeEmptyNode(ctx, props.end, sep, null, props, onError);\n coll.items.push(valueNode);\n offset = valueNode.range[2];\n if (isBlock(value))\n onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);\n }\n else {\n // item is a key+value pair\n // key value\n ctx.atKey = true;\n const keyStart = props.end;\n const keyNode = key\n ? composeNode(ctx, key, props, onError)\n : composeEmptyNode(ctx, keyStart, start, null, props, onError);\n if (isBlock(key))\n onError(keyNode.range, 'BLOCK_IN_FLOW', blockMsg);\n ctx.atKey = false;\n // value properties\n const valueProps = resolveProps(sep ?? [], {\n flow: fcName,\n indicator: 'map-value-ind',\n next: value,\n offset: keyNode.range[2],\n onError,\n parentIndent: fc.indent,\n startOnNewline: false\n });\n if (valueProps.found) {\n if (!isMap && !props.found && ctx.options.strict) {\n if (sep)\n for (const st of sep) {\n if (st === valueProps.found)\n break;\n if (st.type === 'newline') {\n onError(st, 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');\n break;\n }\n }\n if (props.start < valueProps.found.offset - 1024)\n onError(valueProps.found, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit flow sequence key');\n }\n }\n else if (value) {\n if ('source' in value && value.source?.[0] === ':')\n onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`);\n else\n onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`);\n }\n // value value\n const valueNode = value\n ? composeNode(ctx, value, valueProps, onError)\n : valueProps.found\n ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError)\n : null;\n if (valueNode) {\n if (isBlock(value))\n onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);\n }\n else if (valueProps.comment) {\n if (keyNode.comment)\n keyNode.comment += '\\n' + valueProps.comment;\n else\n keyNode.comment = valueProps.comment;\n }\n const pair = new Pair(keyNode, valueNode);\n if (ctx.options.keepSourceTokens)\n pair.srcToken = collItem;\n if (isMap) {\n const map = coll;\n if (mapIncludes(ctx, map.items, keyNode))\n onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');\n map.items.push(pair);\n }\n else {\n const map = new YAMLMap(ctx.schema);\n map.flow = true;\n map.items.push(pair);\n const endRange = (valueNode ?? keyNode).range;\n map.range = [keyNode.range[0], endRange[1], endRange[2]];\n coll.items.push(map);\n }\n offset = valueNode ? valueNode.range[2] : valueProps.end;\n }\n }\n const expectedEnd = isMap ? '}' : ']';\n const [ce, ...ee] = fc.end;\n let cePos = offset;\n if (ce?.source === expectedEnd)\n cePos = ce.offset + ce.source.length;\n else {\n const name = fcName[0].toUpperCase() + fcName.substring(1);\n const msg = atRoot\n ? `${name} must end with a ${expectedEnd}`\n : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;\n onError(offset, atRoot ? 'MISSING_CHAR' : 'BAD_INDENT', msg);\n if (ce && ce.source.length !== 1)\n ee.unshift(ce);\n }\n if (ee.length > 0) {\n const end = resolveEnd(ee, cePos, ctx.options.strict, onError);\n if (end.comment) {\n if (coll.comment)\n coll.comment += '\\n' + end.comment;\n else\n coll.comment = end.comment;\n }\n coll.range = [fc.offset, cePos, end.offset];\n }\n else {\n coll.range = [fc.offset, cePos, cePos];\n }\n return coll;\n}\n\nexport { resolveFlowCollection };\n","import { isNode } from '../nodes/identity.js';\nimport { Scalar } from '../nodes/Scalar.js';\nimport { YAMLMap } from '../nodes/YAMLMap.js';\nimport { YAMLSeq } from '../nodes/YAMLSeq.js';\nimport { resolveBlockMap } from './resolve-block-map.js';\nimport { resolveBlockSeq } from './resolve-block-seq.js';\nimport { resolveFlowCollection } from './resolve-flow-collection.js';\n\nfunction resolveCollection(CN, ctx, token, onError, tagName, tag) {\n const coll = token.type === 'block-map'\n ? resolveBlockMap(CN, ctx, token, onError, tag)\n : token.type === 'block-seq'\n ? resolveBlockSeq(CN, ctx, token, onError, tag)\n : resolveFlowCollection(CN, ctx, token, onError, tag);\n const Coll = coll.constructor;\n // If we got a tagName matching the class, or the tag name is '!',\n // then use the tagName from the node class used to create it.\n if (tagName === '!' || tagName === Coll.tagName) {\n coll.tag = Coll.tagName;\n return coll;\n }\n if (tagName)\n coll.tag = tagName;\n return coll;\n}\nfunction composeCollection(CN, ctx, token, props, onError) {\n const tagToken = props.tag;\n const tagName = !tagToken\n ? null\n : ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));\n if (token.type === 'block-seq') {\n const { anchor, newlineAfterProp: nl } = props;\n const lastProp = anchor && tagToken\n ? anchor.offset > tagToken.offset\n ? anchor\n : tagToken\n : (anchor ?? tagToken);\n if (lastProp && (!nl || nl.offset < lastProp.offset)) {\n const message = 'Missing newline after block sequence props';\n onError(lastProp, 'MISSING_CHAR', message);\n }\n }\n const expType = token.type === 'block-map'\n ? 'map'\n : token.type === 'block-seq'\n ? 'seq'\n : token.start.source === '{'\n ? 'map'\n : 'seq';\n // shortcut: check if it's a generic YAMLMap or YAMLSeq\n // before jumping into the custom tag logic.\n if (!tagToken ||\n !tagName ||\n tagName === '!' ||\n (tagName === YAMLMap.tagName && expType === 'map') ||\n (tagName === YAMLSeq.tagName && expType === 'seq')) {\n return resolveCollection(CN, ctx, token, onError, tagName);\n }\n let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType);\n if (!tag) {\n const kt = ctx.schema.knownTags[tagName];\n if (kt?.collection === expType) {\n ctx.schema.tags.push(Object.assign({}, kt, { default: false }));\n tag = kt;\n }\n else {\n if (kt) {\n onError(tagToken, 'BAD_COLLECTION_TYPE', `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? 'scalar'}`, true);\n }\n else {\n onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);\n }\n return resolveCollection(CN, ctx, token, onError, tagName);\n }\n }\n const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);\n const res = tag.resolve?.(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options) ?? coll;\n const node = isNode(res)\n ? res\n : new Scalar(res);\n node.range = coll.range;\n node.tag = tagName;\n if (tag?.format)\n node.format = tag.format;\n return node;\n}\n\nexport { composeCollection };\n","import { Scalar } from '../nodes/Scalar.js';\n\nfunction resolveBlockScalar(ctx, scalar, onError) {\n const start = scalar.offset;\n const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);\n if (!header)\n return { value: '', type: null, comment: '', range: [start, start, start] };\n const type = header.mode === '>' ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL;\n const lines = scalar.source ? splitLines(scalar.source) : [];\n // determine the end of content & start of chomping\n let chompStart = lines.length;\n for (let i = lines.length - 1; i >= 0; --i) {\n const content = lines[i][1];\n if (content === '' || content === '\\r')\n chompStart = i;\n else\n break;\n }\n // shortcut for empty contents\n if (chompStart === 0) {\n const value = header.chomp === '+' && lines.length > 0\n ? '\\n'.repeat(Math.max(1, lines.length - 1))\n : '';\n let end = start + header.length;\n if (scalar.source)\n end += scalar.source.length;\n return { value, type, comment: header.comment, range: [start, end, end] };\n }\n // find the indentation level to trim from start\n let trimIndent = scalar.indent + header.indent;\n let offset = scalar.offset + header.length;\n let contentStart = 0;\n for (let i = 0; i < chompStart; ++i) {\n const [indent, content] = lines[i];\n if (content === '' || content === '\\r') {\n if (header.indent === 0 && indent.length > trimIndent)\n trimIndent = indent.length;\n }\n else {\n if (indent.length < trimIndent) {\n const message = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';\n onError(offset + indent.length, 'MISSING_CHAR', message);\n }\n if (header.indent === 0)\n trimIndent = indent.length;\n contentStart = i;\n if (trimIndent === 0 && !ctx.atRoot) {\n const message = 'Block scalar values in collections must be indented';\n onError(offset, 'BAD_INDENT', message);\n }\n break;\n }\n offset += indent.length + content.length + 1;\n }\n // include trailing more-indented empty lines in content\n for (let i = lines.length - 1; i >= chompStart; --i) {\n if (lines[i][0].length > trimIndent)\n chompStart = i + 1;\n }\n let value = '';\n let sep = '';\n let prevMoreIndented = false;\n // leading whitespace is kept intact\n for (let i = 0; i < contentStart; ++i)\n value += lines[i][0].slice(trimIndent) + '\\n';\n for (let i = contentStart; i < chompStart; ++i) {\n let [indent, content] = lines[i];\n offset += indent.length + content.length + 1;\n const crlf = content[content.length - 1] === '\\r';\n if (crlf)\n content = content.slice(0, -1);\n /* istanbul ignore if already caught in lexer */\n if (content && indent.length < trimIndent) {\n const src = header.indent\n ? 'explicit indentation indicator'\n : 'first line';\n const message = `Block scalar lines must not be less indented than their ${src}`;\n onError(offset - content.length - (crlf ? 2 : 1), 'BAD_INDENT', message);\n indent = '';\n }\n if (type === Scalar.BLOCK_LITERAL) {\n value += sep + indent.slice(trimIndent) + content;\n sep = '\\n';\n }\n else if (indent.length > trimIndent || content[0] === '\\t') {\n // more-indented content within a folded block\n if (sep === ' ')\n sep = '\\n';\n else if (!prevMoreIndented && sep === '\\n')\n sep = '\\n\\n';\n value += sep + indent.slice(trimIndent) + content;\n sep = '\\n';\n prevMoreIndented = true;\n }\n else if (content === '') {\n // empty line\n if (sep === '\\n')\n value += '\\n';\n else\n sep = '\\n';\n }\n else {\n value += sep + content;\n sep = ' ';\n prevMoreIndented = false;\n }\n }\n switch (header.chomp) {\n case '-':\n break;\n case '+':\n for (let i = chompStart; i < lines.length; ++i)\n value += '\\n' + lines[i][0].slice(trimIndent);\n if (value[value.length - 1] !== '\\n')\n value += '\\n';\n break;\n default:\n value += '\\n';\n }\n const end = start + header.length + scalar.source.length;\n return { value, type, comment: header.comment, range: [start, end, end] };\n}\nfunction parseBlockScalarHeader({ offset, props }, strict, onError) {\n /* istanbul ignore if should not happen */\n if (props[0].type !== 'block-scalar-header') {\n onError(props[0], 'IMPOSSIBLE', 'Block scalar header not found');\n return null;\n }\n const { source } = props[0];\n const mode = source[0];\n let indent = 0;\n let chomp = '';\n let error = -1;\n for (let i = 1; i < source.length; ++i) {\n const ch = source[i];\n if (!chomp && (ch === '-' || ch === '+'))\n chomp = ch;\n else {\n const n = Number(ch);\n if (!indent && n)\n indent = n;\n else if (error === -1)\n error = offset + i;\n }\n }\n if (error !== -1)\n onError(error, 'UNEXPECTED_TOKEN', `Block scalar header includes extra characters: ${source}`);\n let hasSpace = false;\n let comment = '';\n let length = source.length;\n for (let i = 1; i < props.length; ++i) {\n const token = props[i];\n switch (token.type) {\n case 'space':\n hasSpace = true;\n // fallthrough\n case 'newline':\n length += token.source.length;\n break;\n case 'comment':\n if (strict && !hasSpace) {\n const message = 'Comments must be separated from other tokens by white space characters';\n onError(token, 'MISSING_CHAR', message);\n }\n length += token.source.length;\n comment = token.source.substring(1);\n break;\n case 'error':\n onError(token, 'UNEXPECTED_TOKEN', token.message);\n length += token.source.length;\n break;\n /* istanbul ignore next should not happen */\n default: {\n const message = `Unexpected token in block scalar header: ${token.type}`;\n onError(token, 'UNEXPECTED_TOKEN', message);\n const ts = token.source;\n if (ts && typeof ts === 'string')\n length += ts.length;\n }\n }\n }\n return { mode, indent, chomp, comment, length };\n}\n/** @returns Array of lines split up as `[indent, content]` */\nfunction splitLines(source) {\n const split = source.split(/\\n( *)/);\n const first = split[0];\n const m = first.match(/^( *)/);\n const line0 = m?.[1]\n ? [m[1], first.slice(m[1].length)]\n : ['', first];\n const lines = [line0];\n for (let i = 1; i < split.length; i += 2)\n lines.push([split[i], split[i + 1]]);\n return lines;\n}\n\nexport { resolveBlockScalar };\n","import { Scalar } from '../nodes/Scalar.js';\nimport { resolveEnd } from './resolve-end.js';\n\nfunction resolveFlowScalar(scalar, strict, onError) {\n const { offset, type, source, end } = scalar;\n let _type;\n let value;\n const _onError = (rel, code, msg) => onError(offset + rel, code, msg);\n switch (type) {\n case 'scalar':\n _type = Scalar.PLAIN;\n value = plainValue(source, _onError);\n break;\n case 'single-quoted-scalar':\n _type = Scalar.QUOTE_SINGLE;\n value = singleQuotedValue(source, _onError);\n break;\n case 'double-quoted-scalar':\n _type = Scalar.QUOTE_DOUBLE;\n value = doubleQuotedValue(source, _onError);\n break;\n /* istanbul ignore next should not happen */\n default:\n onError(scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}`);\n return {\n value: '',\n type: null,\n comment: '',\n range: [offset, offset + source.length, offset + source.length]\n };\n }\n const valueEnd = offset + source.length;\n const re = resolveEnd(end, valueEnd, strict, onError);\n return {\n value,\n type: _type,\n comment: re.comment,\n range: [offset, valueEnd, re.offset]\n };\n}\nfunction plainValue(source, onError) {\n let badChar = '';\n switch (source[0]) {\n /* istanbul ignore next should not happen */\n case '\\t':\n badChar = 'a tab character';\n break;\n case ',':\n badChar = 'flow indicator character ,';\n break;\n case '%':\n badChar = 'directive indicator character %';\n break;\n case '|':\n case '>': {\n badChar = `block scalar indicator ${source[0]}`;\n break;\n }\n case '@':\n case '`': {\n badChar = `reserved character ${source[0]}`;\n break;\n }\n }\n if (badChar)\n onError(0, 'BAD_SCALAR_START', `Plain value cannot start with ${badChar}`);\n return foldLines(source);\n}\nfunction singleQuotedValue(source, onError) {\n if (source[source.length - 1] !== \"'\" || source.length === 1)\n onError(source.length, 'MISSING_CHAR', \"Missing closing 'quote\");\n return foldLines(source.slice(1, -1)).replace(/''/g, \"'\");\n}\nfunction foldLines(source) {\n /**\n * The negative lookbehind here and in the `re` RegExp is to\n * prevent causing a polynomial search time in certain cases.\n *\n * The try-catch is for Safari, which doesn't support this yet:\n * https://caniuse.com/js-regexp-lookbehind\n */\n let first, line;\n try {\n first = new RegExp('(.*?)(?<![ \\t])[ \\t]*\\r?\\n', 'sy');\n line = new RegExp('[ \\t]*(.*?)(?:(?<![ \\t])[ \\t]*)?\\r?\\n', 'sy');\n }\n catch {\n first = /(.*?)[ \\t]*\\r?\\n/sy;\n line = /[ \\t]*(.*?)[ \\t]*\\r?\\n/sy;\n }\n let match = first.exec(source);\n if (!match)\n return source;\n let res = match[1];\n let sep = ' ';\n let pos = first.lastIndex;\n line.lastIndex = pos;\n while ((match = line.exec(source))) {\n if (match[1] === '') {\n if (sep === '\\n')\n res += sep;\n else\n sep = '\\n';\n }\n else {\n res += sep + match[1];\n sep = ' ';\n }\n pos = line.lastIndex;\n }\n const last = /[ \\t]*(.*)/sy;\n last.lastIndex = pos;\n match = last.exec(source);\n return res + sep + (match?.[1] ?? '');\n}\nfunction doubleQuotedValue(source, onError) {\n let res = '';\n for (let i = 1; i < source.length - 1; ++i) {\n const ch = source[i];\n if (ch === '\\r' && source[i + 1] === '\\n')\n continue;\n if (ch === '\\n') {\n const { fold, offset } = foldNewline(source, i);\n res += fold;\n i = offset;\n }\n else if (ch === '\\\\') {\n let next = source[++i];\n const cc = escapeCodes[next];\n if (cc)\n res += cc;\n else if (next === '\\n') {\n // skip escaped newlines, but still trim the following line\n next = source[i + 1];\n while (next === ' ' || next === '\\t')\n next = source[++i + 1];\n }\n else if (next === '\\r' && source[i + 1] === '\\n') {\n // skip escaped CRLF newlines, but still trim the following line\n next = source[++i + 1];\n while (next === ' ' || next === '\\t')\n next = source[++i + 1];\n }\n else if (next === 'x' || next === 'u' || next === 'U') {\n const length = next === 'x' ? 2 : next === 'u' ? 4 : 8;\n res += parseCharCode(source, i + 1, length, onError);\n i += length;\n }\n else {\n const raw = source.substr(i - 1, 2);\n onError(i - 1, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);\n res += raw;\n }\n }\n else if (ch === ' ' || ch === '\\t') {\n // trim trailing whitespace\n const wsStart = i;\n let next = source[i + 1];\n while (next === ' ' || next === '\\t')\n next = source[++i + 1];\n if (next !== '\\n' && !(next === '\\r' && source[i + 2] === '\\n'))\n res += i > wsStart ? source.slice(wsStart, i + 1) : ch;\n }\n else {\n res += ch;\n }\n }\n if (source[source.length - 1] !== '\"' || source.length === 1)\n onError(source.length, 'MISSING_CHAR', 'Missing closing \"quote');\n return res;\n}\n/**\n * Fold a single newline into a space, multiple newlines to N - 1 newlines.\n * Presumes `source[offset] === '\\n'`\n */\nfunction foldNewline(source, offset) {\n let fold = '';\n let ch = source[offset + 1];\n while (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r') {\n if (ch === '\\r' && source[offset + 2] !== '\\n')\n break;\n if (ch === '\\n')\n fold += '\\n';\n offset += 1;\n ch = source[offset + 1];\n }\n if (!fold)\n fold = ' ';\n return { fold, offset };\n}\nconst escapeCodes = {\n '0': '\\0', // null character\n a: '\\x07', // bell character\n b: '\\b', // backspace\n e: '\\x1b', // escape character\n f: '\\f', // form feed\n n: '\\n', // line feed\n r: '\\r', // carriage return\n t: '\\t', // horizontal tab\n v: '\\v', // vertical tab\n N: '\\u0085', // Unicode next line\n _: '\\u00a0', // Unicode non-breaking space\n L: '\\u2028', // Unicode line separator\n P: '\\u2029', // Unicode paragraph separator\n ' ': ' ',\n '\"': '\"',\n '/': '/',\n '\\\\': '\\\\',\n '\\t': '\\t'\n};\nfunction parseCharCode(source, offset, length, onError) {\n const cc = source.substr(offset, length);\n const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);\n const code = ok ? parseInt(cc, 16) : NaN;\n try {\n return String.fromCodePoint(code);\n }\n catch {\n const raw = source.substr(offset - 2, length + 2);\n onError(offset - 2, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);\n return raw;\n }\n}\n\nexport { resolveFlowScalar };\n","import { isScalar, SCALAR } from '../nodes/identity.js';\nimport { Scalar } from '../nodes/Scalar.js';\nimport { resolveBlockScalar } from './resolve-block-scalar.js';\nimport { resolveFlowScalar } from './resolve-flow-scalar.js';\n\nfunction composeScalar(ctx, token, tagToken, onError) {\n const { value, type, comment, range } = token.type === 'block-scalar'\n ? resolveBlockScalar(ctx, token, onError)\n : resolveFlowScalar(token, ctx.options.strict, onError);\n const tagName = tagToken\n ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg))\n : null;\n let tag;\n if (ctx.options.stringKeys && ctx.atKey) {\n tag = ctx.schema[SCALAR];\n }\n else if (tagName)\n tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError);\n else if (token.type === 'scalar')\n tag = findScalarTagByTest(ctx, value, token, onError);\n else\n tag = ctx.schema[SCALAR];\n let scalar;\n try {\n const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options);\n scalar = isScalar(res) ? res : new Scalar(res);\n }\n catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg);\n scalar = new Scalar(value);\n }\n scalar.range = range;\n scalar.source = value;\n if (type)\n scalar.type = type;\n if (tagName)\n scalar.tag = tagName;\n if (tag.format)\n scalar.format = tag.format;\n if (comment)\n scalar.comment = comment;\n return scalar;\n}\nfunction findScalarTagByName(schema, value, tagName, tagToken, onError) {\n if (tagName === '!')\n return schema[SCALAR]; // non-specific tag\n const matchWithTest = [];\n for (const tag of schema.tags) {\n if (!tag.collection && tag.tag === tagName) {\n if (tag.default && tag.test)\n matchWithTest.push(tag);\n else\n return tag;\n }\n }\n for (const tag of matchWithTest)\n if (tag.test?.test(value))\n return tag;\n const kt = schema.knownTags[tagName];\n if (kt && !kt.collection) {\n // Ensure that the known tag is available for stringifying,\n // but does not get used by default.\n schema.tags.push(Object.assign({}, kt, { default: false, test: undefined }));\n return kt;\n }\n onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str');\n return schema[SCALAR];\n}\nfunction findScalarTagByTest({ atKey, directives, schema }, value, token, onError) {\n const tag = schema.tags.find(tag => (tag.default === true || (atKey && tag.default === 'key')) &&\n tag.test?.test(value)) || schema[SCALAR];\n if (schema.compat) {\n const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ??\n schema[SCALAR];\n if (tag.tag !== compat.tag) {\n const ts = directives.tagString(tag.tag);\n const cs = directives.tagString(compat.tag);\n const msg = `Value may be parsed as either ${ts} or ${cs}`;\n onError(token, 'TAG_RESOLVE_FAILED', msg, true);\n }\n }\n return tag;\n}\n\nexport { composeScalar };\n","function emptyScalarPosition(offset, before, pos) {\n if (before) {\n pos ?? (pos = before.length);\n for (let i = pos - 1; i >= 0; --i) {\n let st = before[i];\n switch (st.type) {\n case 'space':\n case 'comment':\n case 'newline':\n offset -= st.source.length;\n continue;\n }\n // Technically, an empty scalar is immediately after the last non-empty\n // node, but it's more useful to place it after any whitespace.\n st = before[++i];\n while (st?.type === 'space') {\n offset += st.source.length;\n st = before[++i];\n }\n break;\n }\n }\n return offset;\n}\n\nexport { emptyScalarPosition };\n","import { Alias } from '../nodes/Alias.js';\nimport { isScalar } from '../nodes/identity.js';\nimport { composeCollection } from './compose-collection.js';\nimport { composeScalar } from './compose-scalar.js';\nimport { resolveEnd } from './resolve-end.js';\nimport { emptyScalarPosition } from './util-empty-scalar-position.js';\n\nconst CN = { composeNode, composeEmptyNode };\nfunction composeNode(ctx, token, props, onError) {\n const atKey = ctx.atKey;\n const { spaceBefore, comment, anchor, tag } = props;\n let node;\n let isSrcToken = true;\n switch (token.type) {\n case 'alias':\n node = composeAlias(ctx, token, onError);\n if (anchor || tag)\n onError(token, 'ALIAS_PROPS', 'An alias node must not specify any properties');\n break;\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar':\n case 'block-scalar':\n node = composeScalar(ctx, token, tag, onError);\n if (anchor)\n node.anchor = anchor.source.substring(1);\n break;\n case 'block-map':\n case 'block-seq':\n case 'flow-collection':\n try {\n node = composeCollection(CN, ctx, token, props, onError);\n if (anchor)\n node.anchor = anchor.source.substring(1);\n }\n catch (error) {\n // Almost certainly here due to a stack overflow\n const message = error instanceof Error ? error.message : String(error);\n onError(token, 'RESOURCE_EXHAUSTION', message);\n }\n break;\n default: {\n const message = token.type === 'error'\n ? token.message\n : `Unsupported token (type: ${token.type})`;\n onError(token, 'UNEXPECTED_TOKEN', message);\n isSrcToken = false;\n }\n }\n node ?? (node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError));\n if (anchor && node.anchor === '')\n onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');\n if (atKey &&\n ctx.options.stringKeys &&\n (!isScalar(node) ||\n typeof node.value !== 'string' ||\n (node.tag && node.tag !== 'tag:yaml.org,2002:str'))) {\n const msg = 'With stringKeys, all keys must be strings';\n onError(tag ?? token, 'NON_STRING_KEY', msg);\n }\n if (spaceBefore)\n node.spaceBefore = true;\n if (comment) {\n if (token.type === 'scalar' && token.source === '')\n node.comment = comment;\n else\n node.commentBefore = comment;\n }\n // @ts-expect-error Type checking misses meaning of isSrcToken\n if (ctx.options.keepSourceTokens && isSrcToken)\n node.srcToken = token;\n return node;\n}\nfunction composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {\n const token = {\n type: 'scalar',\n offset: emptyScalarPosition(offset, before, pos),\n indent: -1,\n source: ''\n };\n const node = composeScalar(ctx, token, tag, onError);\n if (anchor) {\n node.anchor = anchor.source.substring(1);\n if (node.anchor === '')\n onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');\n }\n if (spaceBefore)\n node.spaceBefore = true;\n if (comment) {\n node.comment = comment;\n node.range[2] = end;\n }\n return node;\n}\nfunction composeAlias({ options }, { offset, source, end }, onError) {\n const alias = new Alias(source.substring(1));\n if (alias.source === '')\n onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string');\n if (alias.source.endsWith(':'))\n onError(offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true);\n const valueEnd = offset + source.length;\n const re = resolveEnd(end, valueEnd, options.strict, onError);\n alias.range = [offset, valueEnd, re.offset];\n if (re.comment)\n alias.comment = re.comment;\n return alias;\n}\n\nexport { composeEmptyNode, composeNode };\n","import { Document } from '../doc/Document.js';\nimport { composeNode, composeEmptyNode } from './compose-node.js';\nimport { resolveEnd } from './resolve-end.js';\nimport { resolveProps } from './resolve-props.js';\n\nfunction composeDoc(options, directives, { offset, start, value, end }, onError) {\n const opts = Object.assign({ _directives: directives }, options);\n const doc = new Document(undefined, opts);\n const ctx = {\n atKey: false,\n atRoot: true,\n directives: doc.directives,\n options: doc.options,\n schema: doc.schema\n };\n const props = resolveProps(start, {\n indicator: 'doc-start',\n next: value ?? end?.[0],\n offset,\n onError,\n parentIndent: 0,\n startOnNewline: true\n });\n if (props.found) {\n doc.directives.docStart = true;\n if (value &&\n (value.type === 'block-map' || value.type === 'block-seq') &&\n !props.hasNewline)\n onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker');\n }\n // @ts-expect-error If Contents is set, let's trust the user\n doc.contents = value\n ? composeNode(ctx, value, props, onError)\n : composeEmptyNode(ctx, props.end, start, null, props, onError);\n const contentEnd = doc.contents.range[2];\n const re = resolveEnd(end, contentEnd, false, onError);\n if (re.comment)\n doc.comment = re.comment;\n doc.range = [offset, contentEnd, re.offset];\n return doc;\n}\n\nexport { composeDoc };\n","import { Directives } from '../doc/directives.js';\nimport { Document } from '../doc/Document.js';\nimport { YAMLWarning, YAMLParseError } from '../errors.js';\nimport { isCollection, isPair } from '../nodes/identity.js';\nimport { composeDoc } from './compose-doc.js';\nimport { resolveEnd } from './resolve-end.js';\n\nfunction getErrorPos(src) {\n if (typeof src === 'number')\n return [src, src + 1];\n if (Array.isArray(src))\n return src.length === 2 ? src : [src[0], src[1]];\n const { offset, source } = src;\n return [offset, offset + (typeof source === 'string' ? source.length : 1)];\n}\nfunction parsePrelude(prelude) {\n let comment = '';\n let atComment = false;\n let afterEmptyLine = false;\n for (let i = 0; i < prelude.length; ++i) {\n const source = prelude[i];\n switch (source[0]) {\n case '#':\n comment +=\n (comment === '' ? '' : afterEmptyLine ? '\\n\\n' : '\\n') +\n (source.substring(1) || ' ');\n atComment = true;\n afterEmptyLine = false;\n break;\n case '%':\n if (prelude[i + 1]?.[0] !== '#')\n i += 1;\n atComment = false;\n break;\n default:\n // This may be wrong after doc-end, but in that case it doesn't matter\n if (!atComment)\n afterEmptyLine = true;\n atComment = false;\n }\n }\n return { comment, afterEmptyLine };\n}\n/**\n * Compose a stream of CST nodes into a stream of YAML Documents.\n *\n * ```ts\n * import { Composer, Parser } from 'yaml'\n *\n * const src: string = ...\n * const tokens = new Parser().parse(src)\n * const docs = new Composer().compose(tokens)\n * ```\n */\nclass Composer {\n constructor(options = {}) {\n this.doc = null;\n this.atDirectives = false;\n this.prelude = [];\n this.errors = [];\n this.warnings = [];\n this.onError = (source, code, message, warning) => {\n const pos = getErrorPos(source);\n if (warning)\n this.warnings.push(new YAMLWarning(pos, code, message));\n else\n this.errors.push(new YAMLParseError(pos, code, message));\n };\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n this.directives = new Directives({ version: options.version || '1.2' });\n this.options = options;\n }\n decorate(doc, afterDoc) {\n const { comment, afterEmptyLine } = parsePrelude(this.prelude);\n //console.log({ dc: doc.comment, prelude, comment })\n if (comment) {\n const dc = doc.contents;\n if (afterDoc) {\n doc.comment = doc.comment ? `${doc.comment}\\n${comment}` : comment;\n }\n else if (afterEmptyLine || doc.directives.docStart || !dc) {\n doc.commentBefore = comment;\n }\n else if (isCollection(dc) && !dc.flow && dc.items.length > 0) {\n let it = dc.items[0];\n if (isPair(it))\n it = it.key;\n const cb = it.commentBefore;\n it.commentBefore = cb ? `${comment}\\n${cb}` : comment;\n }\n else {\n const cb = dc.commentBefore;\n dc.commentBefore = cb ? `${comment}\\n${cb}` : comment;\n }\n }\n if (afterDoc) {\n for (let i = 0; i < this.errors.length; ++i)\n doc.errors.push(this.errors[i]);\n for (let i = 0; i < this.warnings.length; ++i)\n doc.warnings.push(this.warnings[i]);\n }\n else {\n doc.errors = this.errors;\n doc.warnings = this.warnings;\n }\n this.prelude = [];\n this.errors = [];\n this.warnings = [];\n }\n /**\n * Current stream status information.\n *\n * Mostly useful at the end of input for an empty stream.\n */\n streamInfo() {\n return {\n comment: parsePrelude(this.prelude).comment,\n directives: this.directives,\n errors: this.errors,\n warnings: this.warnings\n };\n }\n /**\n * Compose tokens into documents.\n *\n * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.\n * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.\n */\n *compose(tokens, forceDoc = false, endOffset = -1) {\n for (const token of tokens)\n yield* this.next(token);\n yield* this.end(forceDoc, endOffset);\n }\n /** Advance the composer by one CST token. */\n *next(token) {\n switch (token.type) {\n case 'directive':\n this.directives.add(token.source, (offset, message, warning) => {\n const pos = getErrorPos(token);\n pos[0] += offset;\n this.onError(pos, 'BAD_DIRECTIVE', message, warning);\n });\n this.prelude.push(token.source);\n this.atDirectives = true;\n break;\n case 'document': {\n const doc = composeDoc(this.options, this.directives, token, this.onError);\n if (this.atDirectives && !doc.directives.docStart)\n this.onError(token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line');\n this.decorate(doc, false);\n if (this.doc)\n yield this.doc;\n this.doc = doc;\n this.atDirectives = false;\n break;\n }\n case 'byte-order-mark':\n case 'space':\n break;\n case 'comment':\n case 'newline':\n this.prelude.push(token.source);\n break;\n case 'error': {\n const msg = token.source\n ? `${token.message}: ${JSON.stringify(token.source)}`\n : token.message;\n const error = new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg);\n if (this.atDirectives || !this.doc)\n this.errors.push(error);\n else\n this.doc.errors.push(error);\n break;\n }\n case 'doc-end': {\n if (!this.doc) {\n const msg = 'Unexpected doc-end without preceding document';\n this.errors.push(new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg));\n break;\n }\n this.doc.directives.docEnd = true;\n const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);\n this.decorate(this.doc, true);\n if (end.comment) {\n const dc = this.doc.comment;\n this.doc.comment = dc ? `${dc}\\n${end.comment}` : end.comment;\n }\n this.doc.range[2] = end.offset;\n break;\n }\n default:\n this.errors.push(new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}`));\n }\n }\n /**\n * Call at end of input to yield any remaining document.\n *\n * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.\n * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.\n */\n *end(forceDoc = false, endOffset = -1) {\n if (this.doc) {\n this.decorate(this.doc, true);\n yield this.doc;\n this.doc = null;\n }\n else if (forceDoc) {\n const opts = Object.assign({ _directives: this.directives }, this.options);\n const doc = new Document(undefined, opts);\n if (this.atDirectives)\n this.onError(endOffset, 'MISSING_CHAR', 'Missing directives-end indicator line');\n doc.range = [0, endOffset, endOffset];\n this.decorate(doc, false);\n yield doc;\n }\n }\n}\n\nexport { Composer };\n","const BREAK = Symbol('break visit');\nconst SKIP = Symbol('skip children');\nconst REMOVE = Symbol('remove item');\n/**\n * Apply a visitor to a CST document or item.\n *\n * Walks through the tree (depth-first) starting from the root, calling a\n * `visitor` function with two arguments when entering each item:\n * - `item`: The current item, which included the following members:\n * - `start: SourceToken[]` – Source tokens before the key or value,\n * possibly including its anchor or tag.\n * - `key?: Token | null` – Set for pair values. May then be `null`, if\n * the key before the `:` separator is empty.\n * - `sep?: SourceToken[]` – Source tokens between the key and the value,\n * which should include the `:` map value indicator if `value` is set.\n * - `value?: Token` – The value of a sequence item, or of a map pair.\n * - `path`: The steps from the root to the current node, as an array of\n * `['key' | 'value', number]` tuples.\n *\n * The return value of the visitor may be used to control the traversal:\n * - `undefined` (default): Do nothing and continue\n * - `visit.SKIP`: Do not visit the children of this token, continue with\n * next sibling\n * - `visit.BREAK`: Terminate traversal completely\n * - `visit.REMOVE`: Remove the current item, then continue with the next one\n * - `number`: Set the index of the next step. This is useful especially if\n * the index of the current token has changed.\n * - `function`: Define the next visitor for this item. After the original\n * visitor is called on item entry, next visitors are called after handling\n * a non-empty `key` and when exiting the item.\n */\nfunction visit(cst, visitor) {\n if ('type' in cst && cst.type === 'document')\n cst = { start: cst.start, value: cst.value };\n _visit(Object.freeze([]), cst, visitor);\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisit.BREAK = BREAK;\n/** Do not visit the children of the current item */\nvisit.SKIP = SKIP;\n/** Remove the current item */\nvisit.REMOVE = REMOVE;\n/** Find the item at `path` from `cst` as the root */\nvisit.itemAtPath = (cst, path) => {\n let item = cst;\n for (const [field, index] of path) {\n const tok = item?.[field];\n if (tok && 'items' in tok) {\n item = tok.items[index];\n }\n else\n return undefined;\n }\n return item;\n};\n/**\n * Get the immediate parent collection of the item at `path` from `cst` as the root.\n *\n * Throws an error if the collection is not found, which should never happen if the item itself exists.\n */\nvisit.parentCollection = (cst, path) => {\n const parent = visit.itemAtPath(cst, path.slice(0, -1));\n const field = path[path.length - 1][0];\n const coll = parent?.[field];\n if (coll && 'items' in coll)\n return coll;\n throw new Error('Parent collection not found');\n};\nfunction _visit(path, item, visitor) {\n let ctrl = visitor(item, path);\n if (typeof ctrl === 'symbol')\n return ctrl;\n for (const field of ['key', 'value']) {\n const token = item[field];\n if (token && 'items' in token) {\n for (let i = 0; i < token.items.length; ++i) {\n const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);\n if (typeof ci === 'number')\n i = ci - 1;\n else if (ci === BREAK)\n return BREAK;\n else if (ci === REMOVE) {\n token.items.splice(i, 1);\n i -= 1;\n }\n }\n if (typeof ctrl === 'function' && field === 'key')\n ctrl = ctrl(item, path);\n }\n }\n return typeof ctrl === 'function' ? ctrl(item, path) : ctrl;\n}\n\nexport { visit };\n","export { createScalarToken, resolveAsScalar, setScalarValue } from './cst-scalar.js';\nexport { stringify } from './cst-stringify.js';\nexport { visit } from './cst-visit.js';\n\n/** The byte order mark */\nconst BOM = '\\u{FEFF}';\n/** Start of doc-mode */\nconst DOCUMENT = '\\x02'; // C0: Start of Text\n/** Unexpected end of flow-mode */\nconst FLOW_END = '\\x18'; // C0: Cancel\n/** Next token is a scalar value */\nconst SCALAR = '\\x1f'; // C0: Unit Separator\n/** @returns `true` if `token` is a flow or block collection */\nconst isCollection = (token) => !!token && 'items' in token;\n/** @returns `true` if `token` is a flow or block scalar; not an alias */\nconst isScalar = (token) => !!token &&\n (token.type === 'scalar' ||\n token.type === 'single-quoted-scalar' ||\n token.type === 'double-quoted-scalar' ||\n token.type === 'block-scalar');\n/* istanbul ignore next */\n/** Get a printable representation of a lexer token */\nfunction prettyToken(token) {\n switch (token) {\n case BOM:\n return '<BOM>';\n case DOCUMENT:\n return '<DOC>';\n case FLOW_END:\n return '<FLOW_END>';\n case SCALAR:\n return '<SCALAR>';\n default:\n return JSON.stringify(token);\n }\n}\n/** Identify the type of a lexer token. May return `null` for unknown tokens. */\nfunction tokenType(source) {\n switch (source) {\n case BOM:\n return 'byte-order-mark';\n case DOCUMENT:\n return 'doc-mode';\n case FLOW_END:\n return 'flow-error-end';\n case SCALAR:\n return 'scalar';\n case '---':\n return 'doc-start';\n case '...':\n return 'doc-end';\n case '':\n case '\\n':\n case '\\r\\n':\n return 'newline';\n case '-':\n return 'seq-item-ind';\n case '?':\n return 'explicit-key-ind';\n case ':':\n return 'map-value-ind';\n case '{':\n return 'flow-map-start';\n case '}':\n return 'flow-map-end';\n case '[':\n return 'flow-seq-start';\n case ']':\n return 'flow-seq-end';\n case ',':\n return 'comma';\n }\n switch (source[0]) {\n case ' ':\n case '\\t':\n return 'space';\n case '#':\n return 'comment';\n case '%':\n return 'directive-line';\n case '*':\n return 'alias';\n case '&':\n return 'anchor';\n case '!':\n return 'tag';\n case \"'\":\n return 'single-quoted-scalar';\n case '\"':\n return 'double-quoted-scalar';\n case '|':\n case '>':\n return 'block-scalar-header';\n }\n return null;\n}\n\nexport { BOM, DOCUMENT, FLOW_END, SCALAR, isCollection, isScalar, prettyToken, tokenType };\n","import { BOM, DOCUMENT, FLOW_END, SCALAR } from './cst.js';\n\n/*\nSTART -> stream\n\nstream\n directive -> line-end -> stream\n indent + line-end -> stream\n [else] -> line-start\n\nline-end\n comment -> line-end\n newline -> .\n input-end -> END\n\nline-start\n doc-start -> doc\n doc-end -> stream\n [else] -> indent -> block-start\n\nblock-start\n seq-item-start -> block-start\n explicit-key-start -> block-start\n map-value-start -> block-start\n [else] -> doc\n\ndoc\n line-end -> line-start\n spaces -> doc\n anchor -> doc\n tag -> doc\n flow-start -> flow -> doc\n flow-end -> error -> doc\n seq-item-start -> error -> doc\n explicit-key-start -> error -> doc\n map-value-start -> doc\n alias -> doc\n quote-start -> quoted-scalar -> doc\n block-scalar-header -> line-end -> block-scalar(min) -> line-start\n [else] -> plain-scalar(false, min) -> doc\n\nflow\n line-end -> flow\n spaces -> flow\n anchor -> flow\n tag -> flow\n flow-start -> flow -> flow\n flow-end -> .\n seq-item-start -> error -> flow\n explicit-key-start -> flow\n map-value-start -> flow\n alias -> flow\n quote-start -> quoted-scalar -> flow\n comma -> flow\n [else] -> plain-scalar(true, 0) -> flow\n\nquoted-scalar\n quote-end -> .\n [else] -> quoted-scalar\n\nblock-scalar(min)\n newline + peek(indent < min) -> .\n [else] -> block-scalar(min)\n\nplain-scalar(is-flow, min)\n scalar-end(is-flow) -> .\n peek(newline + (indent < min)) -> .\n [else] -> plain-scalar(min)\n*/\nfunction isEmpty(ch) {\n switch (ch) {\n case undefined:\n case ' ':\n case '\\n':\n case '\\r':\n case '\\t':\n return true;\n default:\n return false;\n }\n}\nconst hexDigits = new Set('0123456789ABCDEFabcdef');\nconst tagChars = new Set(\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()\");\nconst flowIndicatorChars = new Set(',[]{}');\nconst invalidAnchorChars = new Set(' ,[]{}\\n\\r\\t');\nconst isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);\n/**\n * Splits an input string into lexical tokens, i.e. smaller strings that are\n * easily identifiable by `tokens.tokenType()`.\n *\n * Lexing starts always in a \"stream\" context. Incomplete input may be buffered\n * until a complete token can be emitted.\n *\n * In addition to slices of the original input, the following control characters\n * may also be emitted:\n *\n * - `\\x02` (Start of Text): A document starts with the next token\n * - `\\x18` (Cancel): Unexpected end of flow-mode (indicates an error)\n * - `\\x1f` (Unit Separator): Next token is a scalar value\n * - `\\u{FEFF}` (Byte order mark): Emitted separately outside documents\n */\nclass Lexer {\n constructor() {\n /**\n * Flag indicating whether the end of the current buffer marks the end of\n * all input\n */\n this.atEnd = false;\n /**\n * Explicit indent set in block scalar header, as an offset from the current\n * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not\n * explicitly set.\n */\n this.blockScalarIndent = -1;\n /**\n * Block scalars that include a + (keep) chomping indicator in their header\n * include trailing empty lines, which are otherwise excluded from the\n * scalar's contents.\n */\n this.blockScalarKeep = false;\n /** Current input */\n this.buffer = '';\n /**\n * Flag noting whether the map value indicator : can immediately follow this\n * node within a flow context.\n */\n this.flowKey = false;\n /** Count of surrounding flow collection levels. */\n this.flowLevel = 0;\n /**\n * Minimum level of indentation required for next lines to be parsed as a\n * part of the current scalar value.\n */\n this.indentNext = 0;\n /** Indentation level of the current line. */\n this.indentValue = 0;\n /** Position of the next \\n character. */\n this.lineEndPos = null;\n /** Stores the state of the lexer if reaching the end of incpomplete input */\n this.next = null;\n /** A pointer to `buffer`; the current position of the lexer. */\n this.pos = 0;\n }\n /**\n * Generate YAML tokens from the `source` string. If `incomplete`,\n * a part of the last line may be left as a buffer for the next call.\n *\n * @returns A generator of lexical tokens\n */\n *lex(source, incomplete = false) {\n if (source) {\n if (typeof source !== 'string')\n throw TypeError('source is not a string');\n this.buffer = this.buffer ? this.buffer + source : source;\n this.lineEndPos = null;\n }\n this.atEnd = !incomplete;\n let next = this.next ?? 'stream';\n while (next && (incomplete || this.hasChars(1)))\n next = yield* this.parseNext(next);\n }\n atLineEnd() {\n let i = this.pos;\n let ch = this.buffer[i];\n while (ch === ' ' || ch === '\\t')\n ch = this.buffer[++i];\n if (!ch || ch === '#' || ch === '\\n')\n return true;\n if (ch === '\\r')\n return this.buffer[i + 1] === '\\n';\n return false;\n }\n charAt(n) {\n return this.buffer[this.pos + n];\n }\n continueScalar(offset) {\n let ch = this.buffer[offset];\n if (this.indentNext > 0) {\n let indent = 0;\n while (ch === ' ')\n ch = this.buffer[++indent + offset];\n if (ch === '\\r') {\n const next = this.buffer[indent + offset + 1];\n if (next === '\\n' || (!next && !this.atEnd))\n return offset + indent + 1;\n }\n return ch === '\\n' || indent >= this.indentNext || (!ch && !this.atEnd)\n ? offset + indent\n : -1;\n }\n if (ch === '-' || ch === '.') {\n const dt = this.buffer.substr(offset, 3);\n if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3]))\n return -1;\n }\n return offset;\n }\n getLine() {\n let end = this.lineEndPos;\n if (typeof end !== 'number' || (end !== -1 && end < this.pos)) {\n end = this.buffer.indexOf('\\n', this.pos);\n this.lineEndPos = end;\n }\n if (end === -1)\n return this.atEnd ? this.buffer.substring(this.pos) : null;\n if (this.buffer[end - 1] === '\\r')\n end -= 1;\n return this.buffer.substring(this.pos, end);\n }\n hasChars(n) {\n return this.pos + n <= this.buffer.length;\n }\n setNext(state) {\n this.buffer = this.buffer.substring(this.pos);\n this.pos = 0;\n this.lineEndPos = null;\n this.next = state;\n return null;\n }\n peek(n) {\n return this.buffer.substr(this.pos, n);\n }\n *parseNext(next) {\n switch (next) {\n case 'stream':\n return yield* this.parseStream();\n case 'line-start':\n return yield* this.parseLineStart();\n case 'block-start':\n return yield* this.parseBlockStart();\n case 'doc':\n return yield* this.parseDocument();\n case 'flow':\n return yield* this.parseFlowCollection();\n case 'quoted-scalar':\n return yield* this.parseQuotedScalar();\n case 'block-scalar':\n return yield* this.parseBlockScalar();\n case 'plain-scalar':\n return yield* this.parsePlainScalar();\n }\n }\n *parseStream() {\n let line = this.getLine();\n if (line === null)\n return this.setNext('stream');\n if (line[0] === BOM) {\n yield* this.pushCount(1);\n line = line.substring(1);\n }\n if (line[0] === '%') {\n let dirEnd = line.length;\n let cs = line.indexOf('#');\n while (cs !== -1) {\n const ch = line[cs - 1];\n if (ch === ' ' || ch === '\\t') {\n dirEnd = cs - 1;\n break;\n }\n else {\n cs = line.indexOf('#', cs + 1);\n }\n }\n while (true) {\n const ch = line[dirEnd - 1];\n if (ch === ' ' || ch === '\\t')\n dirEnd -= 1;\n else\n break;\n }\n const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));\n yield* this.pushCount(line.length - n); // possible comment\n this.pushNewline();\n return 'stream';\n }\n if (this.atLineEnd()) {\n const sp = yield* this.pushSpaces(true);\n yield* this.pushCount(line.length - sp);\n yield* this.pushNewline();\n return 'stream';\n }\n yield DOCUMENT;\n return yield* this.parseLineStart();\n }\n *parseLineStart() {\n const ch = this.charAt(0);\n if (!ch && !this.atEnd)\n return this.setNext('line-start');\n if (ch === '-' || ch === '.') {\n if (!this.atEnd && !this.hasChars(4))\n return this.setNext('line-start');\n const s = this.peek(3);\n if ((s === '---' || s === '...') && isEmpty(this.charAt(3))) {\n yield* this.pushCount(3);\n this.indentValue = 0;\n this.indentNext = 0;\n return s === '---' ? 'doc' : 'stream';\n }\n }\n this.indentValue = yield* this.pushSpaces(false);\n if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))\n this.indentNext = this.indentValue;\n return yield* this.parseBlockStart();\n }\n *parseBlockStart() {\n const [ch0, ch1] = this.peek(2);\n if (!ch1 && !this.atEnd)\n return this.setNext('block-start');\n if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) {\n const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));\n this.indentNext = this.indentValue + 1;\n this.indentValue += n;\n return 'block-start';\n }\n return 'doc';\n }\n *parseDocument() {\n yield* this.pushSpaces(true);\n const line = this.getLine();\n if (line === null)\n return this.setNext('doc');\n let n = yield* this.pushIndicators();\n switch (line[n]) {\n case '#':\n yield* this.pushCount(line.length - n);\n // fallthrough\n case undefined:\n yield* this.pushNewline();\n return yield* this.parseLineStart();\n case '{':\n case '[':\n yield* this.pushCount(1);\n this.flowKey = false;\n this.flowLevel = 1;\n return 'flow';\n case '}':\n case ']':\n // this is an error\n yield* this.pushCount(1);\n return 'doc';\n case '*':\n yield* this.pushUntil(isNotAnchorChar);\n return 'doc';\n case '\"':\n case \"'\":\n return yield* this.parseQuotedScalar();\n case '|':\n case '>':\n n += yield* this.parseBlockScalarHeader();\n n += yield* this.pushSpaces(true);\n yield* this.pushCount(line.length - n);\n yield* this.pushNewline();\n return yield* this.parseBlockScalar();\n default:\n return yield* this.parsePlainScalar();\n }\n }\n *parseFlowCollection() {\n let nl, sp;\n let indent = -1;\n do {\n nl = yield* this.pushNewline();\n if (nl > 0) {\n sp = yield* this.pushSpaces(false);\n this.indentValue = indent = sp;\n }\n else {\n sp = 0;\n }\n sp += yield* this.pushSpaces(true);\n } while (nl + sp > 0);\n const line = this.getLine();\n if (line === null)\n return this.setNext('flow');\n if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') ||\n (indent === 0 &&\n (line.startsWith('---') || line.startsWith('...')) &&\n isEmpty(line[3]))) {\n // Allowing for the terminal ] or } at the same (rather than greater)\n // indent level as the initial [ or { is technically invalid, but\n // failing here would be surprising to users.\n const atFlowEndMarker = indent === this.indentNext - 1 &&\n this.flowLevel === 1 &&\n (line[0] === ']' || line[0] === '}');\n if (!atFlowEndMarker) {\n // this is an error\n this.flowLevel = 0;\n yield FLOW_END;\n return yield* this.parseLineStart();\n }\n }\n let n = 0;\n while (line[n] === ',') {\n n += yield* this.pushCount(1);\n n += yield* this.pushSpaces(true);\n this.flowKey = false;\n }\n n += yield* this.pushIndicators();\n switch (line[n]) {\n case undefined:\n return 'flow';\n case '#':\n yield* this.pushCount(line.length - n);\n return 'flow';\n case '{':\n case '[':\n yield* this.pushCount(1);\n this.flowKey = false;\n this.flowLevel += 1;\n return 'flow';\n case '}':\n case ']':\n yield* this.pushCount(1);\n this.flowKey = true;\n this.flowLevel -= 1;\n return this.flowLevel ? 'flow' : 'doc';\n case '*':\n yield* this.pushUntil(isNotAnchorChar);\n return 'flow';\n case '\"':\n case \"'\":\n this.flowKey = true;\n return yield* this.parseQuotedScalar();\n case ':': {\n const next = this.charAt(1);\n if (this.flowKey || isEmpty(next) || next === ',') {\n this.flowKey = false;\n yield* this.pushCount(1);\n yield* this.pushSpaces(true);\n return 'flow';\n }\n }\n // fallthrough\n default:\n this.flowKey = false;\n return yield* this.parsePlainScalar();\n }\n }\n *parseQuotedScalar() {\n const quote = this.charAt(0);\n let end = this.buffer.indexOf(quote, this.pos + 1);\n if (quote === \"'\") {\n while (end !== -1 && this.buffer[end + 1] === \"'\")\n end = this.buffer.indexOf(\"'\", end + 2);\n }\n else {\n // double-quote\n while (end !== -1) {\n let n = 0;\n while (this.buffer[end - 1 - n] === '\\\\')\n n += 1;\n if (n % 2 === 0)\n break;\n end = this.buffer.indexOf('\"', end + 1);\n }\n }\n // Only looking for newlines within the quotes\n const qb = this.buffer.substring(0, end);\n let nl = qb.indexOf('\\n', this.pos);\n if (nl !== -1) {\n while (nl !== -1) {\n const cs = this.continueScalar(nl + 1);\n if (cs === -1)\n break;\n nl = qb.indexOf('\\n', cs);\n }\n if (nl !== -1) {\n // this is an error caused by an unexpected unindent\n end = nl - (qb[nl - 1] === '\\r' ? 2 : 1);\n }\n }\n if (end === -1) {\n if (!this.atEnd)\n return this.setNext('quoted-scalar');\n end = this.buffer.length;\n }\n yield* this.pushToIndex(end + 1, false);\n return this.flowLevel ? 'flow' : 'doc';\n }\n *parseBlockScalarHeader() {\n this.blockScalarIndent = -1;\n this.blockScalarKeep = false;\n let i = this.pos;\n while (true) {\n const ch = this.buffer[++i];\n if (ch === '+')\n this.blockScalarKeep = true;\n else if (ch > '0' && ch <= '9')\n this.blockScalarIndent = Number(ch) - 1;\n else if (ch !== '-')\n break;\n }\n return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#');\n }\n *parseBlockScalar() {\n let nl = this.pos - 1; // may be -1 if this.pos === 0\n let indent = 0;\n let ch;\n loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) {\n switch (ch) {\n case ' ':\n indent += 1;\n break;\n case '\\n':\n nl = i;\n indent = 0;\n break;\n case '\\r': {\n const next = this.buffer[i + 1];\n if (!next && !this.atEnd)\n return this.setNext('block-scalar');\n if (next === '\\n')\n break;\n } // fallthrough\n default:\n break loop;\n }\n }\n if (!ch && !this.atEnd)\n return this.setNext('block-scalar');\n if (indent >= this.indentNext) {\n if (this.blockScalarIndent === -1)\n this.indentNext = indent;\n else {\n this.indentNext =\n this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);\n }\n do {\n const cs = this.continueScalar(nl + 1);\n if (cs === -1)\n break;\n nl = this.buffer.indexOf('\\n', cs);\n } while (nl !== -1);\n if (nl === -1) {\n if (!this.atEnd)\n return this.setNext('block-scalar');\n nl = this.buffer.length;\n }\n }\n // Trailing insufficiently indented tabs are invalid.\n // To catch that during parsing, we include them in the block scalar value.\n let i = nl + 1;\n ch = this.buffer[i];\n while (ch === ' ')\n ch = this.buffer[++i];\n if (ch === '\\t') {\n while (ch === '\\t' || ch === ' ' || ch === '\\r' || ch === '\\n')\n ch = this.buffer[++i];\n nl = i - 1;\n }\n else if (!this.blockScalarKeep) {\n do {\n let i = nl - 1;\n let ch = this.buffer[i];\n if (ch === '\\r')\n ch = this.buffer[--i];\n const lastChar = i; // Drop the line if last char not more indented\n while (ch === ' ')\n ch = this.buffer[--i];\n if (ch === '\\n' && i >= this.pos && i + 1 + indent > lastChar)\n nl = i;\n else\n break;\n } while (true);\n }\n yield SCALAR;\n yield* this.pushToIndex(nl + 1, true);\n return yield* this.parseLineStart();\n }\n *parsePlainScalar() {\n const inFlow = this.flowLevel > 0;\n let end = this.pos - 1;\n let i = this.pos - 1;\n let ch;\n while ((ch = this.buffer[++i])) {\n if (ch === ':') {\n const next = this.buffer[i + 1];\n if (isEmpty(next) || (inFlow && flowIndicatorChars.has(next)))\n break;\n end = i;\n }\n else if (isEmpty(ch)) {\n let next = this.buffer[i + 1];\n if (ch === '\\r') {\n if (next === '\\n') {\n i += 1;\n ch = '\\n';\n next = this.buffer[i + 1];\n }\n else\n end = i;\n }\n if (next === '#' || (inFlow && flowIndicatorChars.has(next)))\n break;\n if (ch === '\\n') {\n const cs = this.continueScalar(i + 1);\n if (cs === -1)\n break;\n i = Math.max(i, cs - 2); // to advance, but still account for ' #'\n }\n }\n else {\n if (inFlow && flowIndicatorChars.has(ch))\n break;\n end = i;\n }\n }\n if (!ch && !this.atEnd)\n return this.setNext('plain-scalar');\n yield SCALAR;\n yield* this.pushToIndex(end + 1, true);\n return inFlow ? 'flow' : 'doc';\n }\n *pushCount(n) {\n if (n > 0) {\n yield this.buffer.substr(this.pos, n);\n this.pos += n;\n return n;\n }\n return 0;\n }\n *pushToIndex(i, allowEmpty) {\n const s = this.buffer.slice(this.pos, i);\n if (s) {\n yield s;\n this.pos += s.length;\n return s.length;\n }\n else if (allowEmpty)\n yield '';\n return 0;\n }\n *pushIndicators() {\n let n = 0;\n loop: while (true) {\n switch (this.charAt(0)) {\n case '!':\n n += yield* this.pushTag();\n n += yield* this.pushSpaces(true);\n continue loop;\n case '&':\n n += yield* this.pushUntil(isNotAnchorChar);\n n += yield* this.pushSpaces(true);\n continue loop;\n case '-': // this is an error\n case '?': // this is an error outside flow collections\n case ':': {\n const inFlow = this.flowLevel > 0;\n const ch1 = this.charAt(1);\n if (isEmpty(ch1) || (inFlow && flowIndicatorChars.has(ch1))) {\n if (!inFlow)\n this.indentNext = this.indentValue + 1;\n else if (this.flowKey)\n this.flowKey = false;\n n += yield* this.pushCount(1);\n n += yield* this.pushSpaces(true);\n continue loop;\n }\n }\n }\n break loop;\n }\n return n;\n }\n *pushTag() {\n if (this.charAt(1) === '<') {\n let i = this.pos + 2;\n let ch = this.buffer[i];\n while (!isEmpty(ch) && ch !== '>')\n ch = this.buffer[++i];\n return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false);\n }\n else {\n let i = this.pos + 1;\n let ch = this.buffer[i];\n while (ch) {\n if (tagChars.has(ch))\n ch = this.buffer[++i];\n else if (ch === '%' &&\n hexDigits.has(this.buffer[i + 1]) &&\n hexDigits.has(this.buffer[i + 2])) {\n ch = this.buffer[(i += 3)];\n }\n else\n break;\n }\n return yield* this.pushToIndex(i, false);\n }\n }\n *pushNewline() {\n const ch = this.buffer[this.pos];\n if (ch === '\\n')\n return yield* this.pushCount(1);\n else if (ch === '\\r' && this.charAt(1) === '\\n')\n return yield* this.pushCount(2);\n else\n return 0;\n }\n *pushSpaces(allowTabs) {\n let i = this.pos - 1;\n let ch;\n do {\n ch = this.buffer[++i];\n } while (ch === ' ' || (allowTabs && ch === '\\t'));\n const n = i - this.pos;\n if (n > 0) {\n yield this.buffer.substr(this.pos, n);\n this.pos = i;\n }\n return n;\n }\n *pushUntil(test) {\n let i = this.pos;\n let ch = this.buffer[i];\n while (!test(ch))\n ch = this.buffer[++i];\n return yield* this.pushToIndex(i, false);\n }\n}\n\nexport { Lexer };\n","/**\n * Tracks newlines during parsing in order to provide an efficient API for\n * determining the one-indexed `{ line, col }` position for any offset\n * within the input.\n */\nclass LineCounter {\n constructor() {\n this.lineStarts = [];\n /**\n * Should be called in ascending order. Otherwise, call\n * `lineCounter.lineStarts.sort()` before calling `linePos()`.\n */\n this.addNewLine = (offset) => this.lineStarts.push(offset);\n /**\n * Performs a binary search and returns the 1-indexed { line, col }\n * position of `offset`. If `line === 0`, `addNewLine` has never been\n * called or `offset` is before the first known newline.\n */\n this.linePos = (offset) => {\n let low = 0;\n let high = this.lineStarts.length;\n while (low < high) {\n const mid = (low + high) >> 1; // Math.floor((low + high) / 2)\n if (this.lineStarts[mid] < offset)\n low = mid + 1;\n else\n high = mid;\n }\n if (this.lineStarts[low] === offset)\n return { line: low + 1, col: 1 };\n if (low === 0)\n return { line: 0, col: offset };\n const start = this.lineStarts[low - 1];\n return { line: low, col: offset - start + 1 };\n };\n }\n}\n\nexport { LineCounter };\n","import { tokenType } from './cst.js';\nimport { Lexer } from './lexer.js';\n\nfunction includesToken(list, type) {\n for (let i = 0; i < list.length; ++i)\n if (list[i].type === type)\n return true;\n return false;\n}\nfunction findNonEmptyIndex(list) {\n for (let i = 0; i < list.length; ++i) {\n switch (list[i].type) {\n case 'space':\n case 'comment':\n case 'newline':\n break;\n default:\n return i;\n }\n }\n return -1;\n}\nfunction isFlowToken(token) {\n switch (token?.type) {\n case 'alias':\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar':\n case 'flow-collection':\n return true;\n default:\n return false;\n }\n}\nfunction getPrevProps(parent) {\n switch (parent.type) {\n case 'document':\n return parent.start;\n case 'block-map': {\n const it = parent.items[parent.items.length - 1];\n return it.sep ?? it.start;\n }\n case 'block-seq':\n return parent.items[parent.items.length - 1].start;\n /* istanbul ignore next should not happen */\n default:\n return [];\n }\n}\n/** Note: May modify input array */\nfunction getFirstKeyStartProps(prev) {\n if (prev.length === 0)\n return [];\n let i = prev.length;\n loop: while (--i >= 0) {\n switch (prev[i].type) {\n case 'doc-start':\n case 'explicit-key-ind':\n case 'map-value-ind':\n case 'seq-item-ind':\n case 'newline':\n break loop;\n }\n }\n while (prev[++i]?.type === 'space') {\n /* loop */\n }\n return prev.splice(i, prev.length);\n}\nfunction arrayPushArray(target, source) {\n // May exhaust call stack with large `source` array\n if (source.length < 1e5)\n Array.prototype.push.apply(target, source);\n else\n for (let i = 0; i < source.length; ++i)\n target.push(source[i]);\n}\nfunction fixFlowSeqItems(fc) {\n if (fc.start.type === 'flow-seq-start') {\n for (const it of fc.items) {\n if (it.sep &&\n !it.value &&\n !includesToken(it.start, 'explicit-key-ind') &&\n !includesToken(it.sep, 'map-value-ind')) {\n if (it.key)\n it.value = it.key;\n delete it.key;\n if (isFlowToken(it.value)) {\n if (it.value.end)\n arrayPushArray(it.value.end, it.sep);\n else\n it.value.end = it.sep;\n }\n else\n arrayPushArray(it.start, it.sep);\n delete it.sep;\n }\n }\n }\n}\n/**\n * A YAML concrete syntax tree (CST) parser\n *\n * ```ts\n * const src: string = ...\n * for (const token of new Parser().parse(src)) {\n * // token: Token\n * }\n * ```\n *\n * To use the parser with a user-provided lexer:\n *\n * ```ts\n * function* parse(source: string, lexer: Lexer) {\n * const parser = new Parser()\n * for (const lexeme of lexer.lex(source))\n * yield* parser.next(lexeme)\n * yield* parser.end()\n * }\n *\n * const src: string = ...\n * const lexer = new Lexer()\n * for (const token of parse(src, lexer)) {\n * // token: Token\n * }\n * ```\n */\nclass Parser {\n /**\n * @param onNewLine - If defined, called separately with the start position of\n * each new line (in `parse()`, including the start of input).\n */\n constructor(onNewLine) {\n /** If true, space and sequence indicators count as indentation */\n this.atNewLine = true;\n /** If true, next token is a scalar value */\n this.atScalar = false;\n /** Current indentation level */\n this.indent = 0;\n /** Current offset since the start of parsing */\n this.offset = 0;\n /** On the same line with a block map key */\n this.onKeyLine = false;\n /** Top indicates the node that's currently being built */\n this.stack = [];\n /** The source of the current token, set in parse() */\n this.source = '';\n /** The type of the current token, set in parse() */\n this.type = '';\n // Must be defined after `next()`\n this.lexer = new Lexer();\n this.onNewLine = onNewLine;\n }\n /**\n * Parse `source` as a YAML stream.\n * If `incomplete`, a part of the last line may be left as a buffer for the next call.\n *\n * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.\n *\n * @returns A generator of tokens representing each directive, document, and other structure.\n */\n *parse(source, incomplete = false) {\n if (this.onNewLine && this.offset === 0)\n this.onNewLine(0);\n for (const lexeme of this.lexer.lex(source, incomplete))\n yield* this.next(lexeme);\n if (!incomplete)\n yield* this.end();\n }\n /**\n * Advance the parser by the `source` of one lexical token.\n */\n *next(source) {\n this.source = source;\n if (this.atScalar) {\n this.atScalar = false;\n yield* this.step();\n this.offset += source.length;\n return;\n }\n const type = tokenType(source);\n if (!type) {\n const message = `Not a YAML token: ${source}`;\n yield* this.pop({ type: 'error', offset: this.offset, message, source });\n this.offset += source.length;\n }\n else if (type === 'scalar') {\n this.atNewLine = false;\n this.atScalar = true;\n this.type = 'scalar';\n }\n else {\n this.type = type;\n yield* this.step();\n switch (type) {\n case 'newline':\n this.atNewLine = true;\n this.indent = 0;\n if (this.onNewLine)\n this.onNewLine(this.offset + source.length);\n break;\n case 'space':\n if (this.atNewLine && source[0] === ' ')\n this.indent += source.length;\n break;\n case 'explicit-key-ind':\n case 'map-value-ind':\n case 'seq-item-ind':\n if (this.atNewLine)\n this.indent += source.length;\n break;\n case 'doc-mode':\n case 'flow-error-end':\n return;\n default:\n this.atNewLine = false;\n }\n this.offset += source.length;\n }\n }\n /** Call at end of input to push out any remaining constructions */\n *end() {\n while (this.stack.length > 0)\n yield* this.pop();\n }\n get sourceToken() {\n const st = {\n type: this.type,\n offset: this.offset,\n indent: this.indent,\n source: this.source\n };\n return st;\n }\n *step() {\n const top = this.peek(1);\n if (this.type === 'doc-end' && top?.type !== 'doc-end') {\n while (this.stack.length > 0)\n yield* this.pop();\n this.stack.push({\n type: 'doc-end',\n offset: this.offset,\n source: this.source\n });\n return;\n }\n if (!top)\n return yield* this.stream();\n switch (top.type) {\n case 'document':\n return yield* this.document(top);\n case 'alias':\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar':\n return yield* this.scalar(top);\n case 'block-scalar':\n return yield* this.blockScalar(top);\n case 'block-map':\n return yield* this.blockMap(top);\n case 'block-seq':\n return yield* this.blockSequence(top);\n case 'flow-collection':\n return yield* this.flowCollection(top);\n case 'doc-end':\n return yield* this.documentEnd(top);\n }\n /* istanbul ignore next should not happen */\n yield* this.pop();\n }\n peek(n) {\n return this.stack[this.stack.length - n];\n }\n *pop(error) {\n const token = error ?? this.stack.pop();\n /* istanbul ignore if should not happen */\n if (!token) {\n const message = 'Tried to pop an empty stack';\n yield { type: 'error', offset: this.offset, source: '', message };\n }\n else if (this.stack.length === 0) {\n yield token;\n }\n else {\n const top = this.peek(1);\n if (token.type === 'block-scalar') {\n // Block scalars use their parent rather than header indent\n token.indent = 'indent' in top ? top.indent : 0;\n }\n else if (token.type === 'flow-collection' && top.type === 'document') {\n // Ignore all indent for top-level flow collections\n token.indent = 0;\n }\n if (token.type === 'flow-collection')\n fixFlowSeqItems(token);\n switch (top.type) {\n case 'document':\n top.value = token;\n break;\n case 'block-scalar':\n top.props.push(token); // error\n break;\n case 'block-map': {\n const it = top.items[top.items.length - 1];\n if (it.value) {\n top.items.push({ start: [], key: token, sep: [] });\n this.onKeyLine = true;\n return;\n }\n else if (it.sep) {\n it.value = token;\n }\n else {\n Object.assign(it, { key: token, sep: [] });\n this.onKeyLine = !it.explicitKey;\n return;\n }\n break;\n }\n case 'block-seq': {\n const it = top.items[top.items.length - 1];\n if (it.value)\n top.items.push({ start: [], value: token });\n else\n it.value = token;\n break;\n }\n case 'flow-collection': {\n const it = top.items[top.items.length - 1];\n if (!it || it.value)\n top.items.push({ start: [], key: token, sep: [] });\n else if (it.sep)\n it.value = token;\n else\n Object.assign(it, { key: token, sep: [] });\n return;\n }\n /* istanbul ignore next should not happen */\n default:\n yield* this.pop();\n yield* this.pop(token);\n }\n if ((top.type === 'document' ||\n top.type === 'block-map' ||\n top.type === 'block-seq') &&\n (token.type === 'block-map' || token.type === 'block-seq')) {\n const last = token.items[token.items.length - 1];\n if (last &&\n !last.sep &&\n !last.value &&\n last.start.length > 0 &&\n findNonEmptyIndex(last.start) === -1 &&\n (token.indent === 0 ||\n last.start.every(st => st.type !== 'comment' || st.indent < token.indent))) {\n if (top.type === 'document')\n top.end = last.start;\n else\n top.items.push({ start: last.start });\n token.items.splice(-1, 1);\n }\n }\n }\n }\n *stream() {\n switch (this.type) {\n case 'directive-line':\n yield { type: 'directive', offset: this.offset, source: this.source };\n return;\n case 'byte-order-mark':\n case 'space':\n case 'comment':\n case 'newline':\n yield this.sourceToken;\n return;\n case 'doc-mode':\n case 'doc-start': {\n const doc = {\n type: 'document',\n offset: this.offset,\n start: []\n };\n if (this.type === 'doc-start')\n doc.start.push(this.sourceToken);\n this.stack.push(doc);\n return;\n }\n }\n yield {\n type: 'error',\n offset: this.offset,\n message: `Unexpected ${this.type} token in YAML stream`,\n source: this.source\n };\n }\n *document(doc) {\n if (doc.value)\n return yield* this.lineEnd(doc);\n switch (this.type) {\n case 'doc-start': {\n if (findNonEmptyIndex(doc.start) !== -1) {\n yield* this.pop();\n yield* this.step();\n }\n else\n doc.start.push(this.sourceToken);\n return;\n }\n case 'anchor':\n case 'tag':\n case 'space':\n case 'comment':\n case 'newline':\n doc.start.push(this.sourceToken);\n return;\n }\n const bv = this.startBlockValue(doc);\n if (bv)\n this.stack.push(bv);\n else {\n yield {\n type: 'error',\n offset: this.offset,\n message: `Unexpected ${this.type} token in YAML document`,\n source: this.source\n };\n }\n }\n *scalar(scalar) {\n if (this.type === 'map-value-ind') {\n const prev = getPrevProps(this.peek(2));\n const start = getFirstKeyStartProps(prev);\n let sep;\n if (scalar.end) {\n sep = scalar.end;\n sep.push(this.sourceToken);\n delete scalar.end;\n }\n else\n sep = [this.sourceToken];\n const map = {\n type: 'block-map',\n offset: scalar.offset,\n indent: scalar.indent,\n items: [{ start, key: scalar, sep }]\n };\n this.onKeyLine = true;\n this.stack[this.stack.length - 1] = map;\n }\n else\n yield* this.lineEnd(scalar);\n }\n *blockScalar(scalar) {\n switch (this.type) {\n case 'space':\n case 'comment':\n case 'newline':\n scalar.props.push(this.sourceToken);\n return;\n case 'scalar':\n scalar.source = this.source;\n // block-scalar source includes trailing newline\n this.atNewLine = true;\n this.indent = 0;\n if (this.onNewLine) {\n let nl = this.source.indexOf('\\n') + 1;\n while (nl !== 0) {\n this.onNewLine(this.offset + nl);\n nl = this.source.indexOf('\\n', nl) + 1;\n }\n }\n yield* this.pop();\n break;\n /* istanbul ignore next should not happen */\n default:\n yield* this.pop();\n yield* this.step();\n }\n }\n *blockMap(map) {\n const it = map.items[map.items.length - 1];\n // it.sep is true-ish if pair already has key or : separator\n switch (this.type) {\n case 'newline':\n this.onKeyLine = false;\n if (it.value) {\n const end = 'end' in it.value ? it.value.end : undefined;\n const last = Array.isArray(end) ? end[end.length - 1] : undefined;\n if (last?.type === 'comment')\n end?.push(this.sourceToken);\n else\n map.items.push({ start: [this.sourceToken] });\n }\n else if (it.sep) {\n it.sep.push(this.sourceToken);\n }\n else {\n it.start.push(this.sourceToken);\n }\n return;\n case 'space':\n case 'comment':\n if (it.value) {\n map.items.push({ start: [this.sourceToken] });\n }\n else if (it.sep) {\n it.sep.push(this.sourceToken);\n }\n else {\n if (this.atIndentedComment(it.start, map.indent)) {\n const prev = map.items[map.items.length - 2];\n const end = prev?.value?.end;\n if (Array.isArray(end)) {\n arrayPushArray(end, it.start);\n end.push(this.sourceToken);\n map.items.pop();\n return;\n }\n }\n it.start.push(this.sourceToken);\n }\n return;\n }\n if (this.indent >= map.indent) {\n const atMapIndent = !this.onKeyLine && this.indent === map.indent;\n const atNextItem = atMapIndent &&\n (it.sep || it.explicitKey) &&\n this.type !== 'seq-item-ind';\n // For empty nodes, assign newline-separated not indented empty tokens to following node\n let start = [];\n if (atNextItem && it.sep && !it.value) {\n const nl = [];\n for (let i = 0; i < it.sep.length; ++i) {\n const st = it.sep[i];\n switch (st.type) {\n case 'newline':\n nl.push(i);\n break;\n case 'space':\n break;\n case 'comment':\n if (st.indent > map.indent)\n nl.length = 0;\n break;\n default:\n nl.length = 0;\n }\n }\n if (nl.length >= 2)\n start = it.sep.splice(nl[1]);\n }\n switch (this.type) {\n case 'anchor':\n case 'tag':\n if (atNextItem || it.value) {\n start.push(this.sourceToken);\n map.items.push({ start });\n this.onKeyLine = true;\n }\n else if (it.sep) {\n it.sep.push(this.sourceToken);\n }\n else {\n it.start.push(this.sourceToken);\n }\n return;\n case 'explicit-key-ind':\n if (!it.sep && !it.explicitKey) {\n it.start.push(this.sourceToken);\n it.explicitKey = true;\n }\n else if (atNextItem || it.value) {\n start.push(this.sourceToken);\n map.items.push({ start, explicitKey: true });\n }\n else {\n this.stack.push({\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start: [this.sourceToken], explicitKey: true }]\n });\n }\n this.onKeyLine = true;\n return;\n case 'map-value-ind':\n if (it.explicitKey) {\n if (!it.sep) {\n if (includesToken(it.start, 'newline')) {\n Object.assign(it, { key: null, sep: [this.sourceToken] });\n }\n else {\n const start = getFirstKeyStartProps(it.start);\n this.stack.push({\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start, key: null, sep: [this.sourceToken] }]\n });\n }\n }\n else if (it.value) {\n map.items.push({ start: [], key: null, sep: [this.sourceToken] });\n }\n else if (includesToken(it.sep, 'map-value-ind')) {\n this.stack.push({\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start, key: null, sep: [this.sourceToken] }]\n });\n }\n else if (isFlowToken(it.key) &&\n !includesToken(it.sep, 'newline')) {\n const start = getFirstKeyStartProps(it.start);\n const key = it.key;\n const sep = it.sep;\n sep.push(this.sourceToken);\n // @ts-expect-error type guard is wrong here\n delete it.key;\n // @ts-expect-error type guard is wrong here\n delete it.sep;\n this.stack.push({\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start, key, sep }]\n });\n }\n else if (start.length > 0) {\n // Not actually at next item\n it.sep = it.sep.concat(start, this.sourceToken);\n }\n else {\n it.sep.push(this.sourceToken);\n }\n }\n else {\n if (!it.sep) {\n Object.assign(it, { key: null, sep: [this.sourceToken] });\n }\n else if (it.value || atNextItem) {\n map.items.push({ start, key: null, sep: [this.sourceToken] });\n }\n else if (includesToken(it.sep, 'map-value-ind')) {\n this.stack.push({\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start: [], key: null, sep: [this.sourceToken] }]\n });\n }\n else {\n it.sep.push(this.sourceToken);\n }\n }\n this.onKeyLine = true;\n return;\n case 'alias':\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar': {\n const fs = this.flowScalar(this.type);\n if (atNextItem || it.value) {\n map.items.push({ start, key: fs, sep: [] });\n this.onKeyLine = true;\n }\n else if (it.sep) {\n this.stack.push(fs);\n }\n else {\n Object.assign(it, { key: fs, sep: [] });\n this.onKeyLine = true;\n }\n return;\n }\n default: {\n const bv = this.startBlockValue(map);\n if (bv) {\n if (bv.type === 'block-seq') {\n if (!it.explicitKey &&\n it.sep &&\n !includesToken(it.sep, 'newline')) {\n yield* this.pop({\n type: 'error',\n offset: this.offset,\n message: 'Unexpected block-seq-ind on same line with key',\n source: this.source\n });\n return;\n }\n }\n else if (atMapIndent) {\n map.items.push({ start });\n }\n this.stack.push(bv);\n return;\n }\n }\n }\n }\n yield* this.pop();\n yield* this.step();\n }\n *blockSequence(seq) {\n const it = seq.items[seq.items.length - 1];\n switch (this.type) {\n case 'newline':\n if (it.value) {\n const end = 'end' in it.value ? it.value.end : undefined;\n const last = Array.isArray(end) ? end[end.length - 1] : undefined;\n if (last?.type === 'comment')\n end?.push(this.sourceToken);\n else\n seq.items.push({ start: [this.sourceToken] });\n }\n else\n it.start.push(this.sourceToken);\n return;\n case 'space':\n case 'comment':\n if (it.value)\n seq.items.push({ start: [this.sourceToken] });\n else {\n if (this.atIndentedComment(it.start, seq.indent)) {\n const prev = seq.items[seq.items.length - 2];\n const end = prev?.value?.end;\n if (Array.isArray(end)) {\n arrayPushArray(end, it.start);\n end.push(this.sourceToken);\n seq.items.pop();\n return;\n }\n }\n it.start.push(this.sourceToken);\n }\n return;\n case 'anchor':\n case 'tag':\n if (it.value || this.indent <= seq.indent)\n break;\n it.start.push(this.sourceToken);\n return;\n case 'seq-item-ind':\n if (this.indent !== seq.indent)\n break;\n if (it.value || includesToken(it.start, 'seq-item-ind'))\n seq.items.push({ start: [this.sourceToken] });\n else\n it.start.push(this.sourceToken);\n return;\n }\n if (this.indent > seq.indent) {\n const bv = this.startBlockValue(seq);\n if (bv) {\n this.stack.push(bv);\n return;\n }\n }\n yield* this.pop();\n yield* this.step();\n }\n *flowCollection(fc) {\n const it = fc.items[fc.items.length - 1];\n if (this.type === 'flow-error-end') {\n let top;\n do {\n yield* this.pop();\n top = this.peek(1);\n } while (top?.type === 'flow-collection');\n }\n else if (fc.end.length === 0) {\n switch (this.type) {\n case 'comma':\n case 'explicit-key-ind':\n if (!it || it.sep)\n fc.items.push({ start: [this.sourceToken] });\n else\n it.start.push(this.sourceToken);\n return;\n case 'map-value-ind':\n if (!it || it.value)\n fc.items.push({ start: [], key: null, sep: [this.sourceToken] });\n else if (it.sep)\n it.sep.push(this.sourceToken);\n else\n Object.assign(it, { key: null, sep: [this.sourceToken] });\n return;\n case 'space':\n case 'comment':\n case 'newline':\n case 'anchor':\n case 'tag':\n if (!it || it.value)\n fc.items.push({ start: [this.sourceToken] });\n else if (it.sep)\n it.sep.push(this.sourceToken);\n else\n it.start.push(this.sourceToken);\n return;\n case 'alias':\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar': {\n const fs = this.flowScalar(this.type);\n if (!it || it.value)\n fc.items.push({ start: [], key: fs, sep: [] });\n else if (it.sep)\n this.stack.push(fs);\n else\n Object.assign(it, { key: fs, sep: [] });\n return;\n }\n case 'flow-map-end':\n case 'flow-seq-end':\n fc.end.push(this.sourceToken);\n return;\n }\n const bv = this.startBlockValue(fc);\n /* istanbul ignore else should not happen */\n if (bv)\n this.stack.push(bv);\n else {\n yield* this.pop();\n yield* this.step();\n }\n }\n else {\n const parent = this.peek(2);\n if (parent.type === 'block-map' &&\n ((this.type === 'map-value-ind' && parent.indent === fc.indent) ||\n (this.type === 'newline' &&\n !parent.items[parent.items.length - 1].sep))) {\n yield* this.pop();\n yield* this.step();\n }\n else if (this.type === 'map-value-ind' &&\n parent.type !== 'flow-collection') {\n const prev = getPrevProps(parent);\n const start = getFirstKeyStartProps(prev);\n fixFlowSeqItems(fc);\n const sep = fc.end.splice(1, fc.end.length);\n sep.push(this.sourceToken);\n const map = {\n type: 'block-map',\n offset: fc.offset,\n indent: fc.indent,\n items: [{ start, key: fc, sep }]\n };\n this.onKeyLine = true;\n this.stack[this.stack.length - 1] = map;\n }\n else {\n yield* this.lineEnd(fc);\n }\n }\n }\n flowScalar(type) {\n if (this.onNewLine) {\n let nl = this.source.indexOf('\\n') + 1;\n while (nl !== 0) {\n this.onNewLine(this.offset + nl);\n nl = this.source.indexOf('\\n', nl) + 1;\n }\n }\n return {\n type,\n offset: this.offset,\n indent: this.indent,\n source: this.source\n };\n }\n startBlockValue(parent) {\n switch (this.type) {\n case 'alias':\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar':\n return this.flowScalar(this.type);\n case 'block-scalar-header':\n return {\n type: 'block-scalar',\n offset: this.offset,\n indent: this.indent,\n props: [this.sourceToken],\n source: ''\n };\n case 'flow-map-start':\n case 'flow-seq-start':\n return {\n type: 'flow-collection',\n offset: this.offset,\n indent: this.indent,\n start: this.sourceToken,\n items: [],\n end: []\n };\n case 'seq-item-ind':\n return {\n type: 'block-seq',\n offset: this.offset,\n indent: this.indent,\n items: [{ start: [this.sourceToken] }]\n };\n case 'explicit-key-ind': {\n this.onKeyLine = true;\n const prev = getPrevProps(parent);\n const start = getFirstKeyStartProps(prev);\n start.push(this.sourceToken);\n return {\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start, explicitKey: true }]\n };\n }\n case 'map-value-ind': {\n this.onKeyLine = true;\n const prev = getPrevProps(parent);\n const start = getFirstKeyStartProps(prev);\n return {\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start, key: null, sep: [this.sourceToken] }]\n };\n }\n }\n return null;\n }\n atIndentedComment(start, indent) {\n if (this.type !== 'comment')\n return false;\n if (this.indent <= indent)\n return false;\n return start.every(st => st.type === 'newline' || st.type === 'space');\n }\n *documentEnd(docEnd) {\n if (this.type !== 'doc-mode') {\n if (docEnd.end)\n docEnd.end.push(this.sourceToken);\n else\n docEnd.end = [this.sourceToken];\n if (this.type === 'newline')\n yield* this.pop();\n }\n }\n *lineEnd(token) {\n switch (this.type) {\n case 'comma':\n case 'doc-start':\n case 'doc-end':\n case 'flow-seq-end':\n case 'flow-map-end':\n case 'map-value-ind':\n yield* this.pop();\n yield* this.step();\n break;\n case 'newline':\n this.onKeyLine = false;\n // fallthrough\n case 'space':\n case 'comment':\n default:\n // all other values are errors\n if (token.end)\n token.end.push(this.sourceToken);\n else\n token.end = [this.sourceToken];\n if (this.type === 'newline')\n yield* this.pop();\n }\n }\n}\n\nexport { Parser };\n","import { Composer } from './compose/composer.js';\nimport { Document } from './doc/Document.js';\nimport { prettifyError, YAMLParseError } from './errors.js';\nimport { warn } from './log.js';\nimport { isDocument } from './nodes/identity.js';\nimport { LineCounter } from './parse/line-counter.js';\nimport { Parser } from './parse/parser.js';\n\nfunction parseOptions(options) {\n const prettyErrors = options.prettyErrors !== false;\n const lineCounter = options.lineCounter || (prettyErrors && new LineCounter()) || null;\n return { lineCounter, prettyErrors };\n}\n/**\n * Parse the input as a stream of YAML documents.\n *\n * Documents should be separated from each other by `...` or `---` marker lines.\n *\n * @returns If an empty `docs` array is returned, it will be of type\n * EmptyStream and contain additional stream information. In\n * TypeScript, you should use `'empty' in docs` as a type guard for it.\n */\nfunction parseAllDocuments(source, options = {}) {\n const { lineCounter, prettyErrors } = parseOptions(options);\n const parser = new Parser(lineCounter?.addNewLine);\n const composer = new Composer(options);\n const docs = Array.from(composer.compose(parser.parse(source)));\n if (prettyErrors && lineCounter)\n for (const doc of docs) {\n doc.errors.forEach(prettifyError(source, lineCounter));\n doc.warnings.forEach(prettifyError(source, lineCounter));\n }\n if (docs.length > 0)\n return docs;\n return Object.assign([], { empty: true }, composer.streamInfo());\n}\n/** Parse an input string into a single YAML.Document */\nfunction parseDocument(source, options = {}) {\n const { lineCounter, prettyErrors } = parseOptions(options);\n const parser = new Parser(lineCounter?.addNewLine);\n const composer = new Composer(options);\n // `doc` is always set by compose.end(true) at the very latest\n let doc = null;\n for (const _doc of composer.compose(parser.parse(source), true, source.length)) {\n if (!doc)\n doc = _doc;\n else if (doc.options.logLevel !== 'silent') {\n doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()'));\n break;\n }\n }\n if (prettyErrors && lineCounter) {\n doc.errors.forEach(prettifyError(source, lineCounter));\n doc.warnings.forEach(prettifyError(source, lineCounter));\n }\n return doc;\n}\nfunction parse(src, reviver, options) {\n let _reviver = undefined;\n if (typeof reviver === 'function') {\n _reviver = reviver;\n }\n else if (options === undefined && reviver && typeof reviver === 'object') {\n options = reviver;\n }\n const doc = parseDocument(src, options);\n if (!doc)\n return null;\n doc.warnings.forEach(warning => warn(doc.options.logLevel, warning));\n if (doc.errors.length > 0) {\n if (doc.options.logLevel !== 'silent')\n throw doc.errors[0];\n else\n doc.errors = [];\n }\n return doc.toJS(Object.assign({ reviver: _reviver }, options));\n}\nfunction stringify(value, replacer, options) {\n let _replacer = null;\n if (typeof replacer === 'function' || Array.isArray(replacer)) {\n _replacer = replacer;\n }\n else if (options === undefined && replacer) {\n options = replacer;\n }\n if (typeof options === 'string')\n options = options.length;\n if (typeof options === 'number') {\n const indent = Math.round(options);\n options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };\n }\n if (value === undefined) {\n const { keepUndefined } = options ?? replacer ?? {};\n if (!keepUndefined)\n return undefined;\n }\n if (isDocument(value) && !_replacer)\n return value.toString(options);\n return new Document(value, _replacer, options).toString(options);\n}\n\nexport { parse, parseAllDocuments, parseDocument, stringify };\n","import { randomUUID } from \"node:crypto\";\nimport { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, unlinkSync, type Stats } from \"node:fs\";\nimport path from \"node:path\";\nimport { recoverDeadStoreAccessSessions, tryCreateExclusiveStoreLease } from \"./database\";\nimport { platform } from \"../platform\";\n\n/** Writers and Store removal must check this marker before and after acquisition. */\nexport const STORE_LEASE_RECOVERY_FILE = \"installation-lease-recovery.lock\";\nconst RECOVERABLE_LEASES = [\"installation-bootstrap.lock\", \"global-assets.lock\"] as const;\n\nexport class StoreLeaseRecoveryError extends Error {\n readonly code = \"writer-active\";\n constructor(message: string) { super(message); this.name = \"StoreLeaseRecoveryError\"; }\n}\n\ninterface LeaseSnapshot {\n file: string;\n bytes: Buffer;\n stat: Stats;\n token: string;\n pid: number;\n hostname: string;\n}\n\nfunction blocked(message: string): never {\n throw new StoreLeaseRecoveryError(`${message} The Store leases and pending operation must be preserved.`);\n}\n\nfunction sameFile(left: Stats, right: Stats): boolean {\n return platform.sameFileObject(left, right, \"file\");\n}\n\nfunction readLease(file: string): LeaseSnapshot | null {\n const initial = lstatSync(file, { throwIfNoEntry: false });\n if (!initial) return null;\n if (!initial.isFile() || initial.isSymbolicLink() || initial.size > 16_384) blocked(`Unsafe lease file: ${path.basename(file)}.`);\n const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);\n try {\n const stat = fstatSync(fd);\n if (!sameFile(initial, stat)) blocked(`Lease changed during inspection: ${path.basename(file)}.`);\n const bytes = readFileSync(fd);\n let record: Record<string, unknown>;\n try { record = JSON.parse(bytes.toString(\"utf8\")); } catch { return blocked(`Unreadable lease owner: ${path.basename(file)}.`); }\n if (!record || typeof record !== \"object\" || typeof record.token !== \"string\" || !record.token ||\n typeof record.hostname !== \"string\" || !record.hostname || typeof record.pid !== \"number\" || !Number.isSafeInteger(record.pid) || record.pid <= 0) {\n blocked(`Unverified lease owner: ${path.basename(file)}.`);\n }\n return { file, bytes, stat, token: record.token, pid: record.pid, hostname: record.hostname };\n } finally { closeSync(fd); }\n}\n\nfunction assertOwnerDead(lease: LeaseSnapshot): void {\n const state = platform.processLiveness(lease.pid, lease.hostname);\n if (state === \"dead\") return;\n if (state === \"alive\") blocked(`A live process owns ${path.basename(lease.file)} (${lease.pid}).`);\n blocked(`The lease owner's death cannot be verified: ${path.basename(lease.file)}.`);\n}\n\nfunction assertUnchanged(lease: LeaseSnapshot): void {\n const current = readLease(lease.file);\n if (!current || !sameFile(lease.stat, current.stat) || current.token !== lease.token || !current.bytes.equals(lease.bytes)) {\n blocked(`Lease changed during recovery: ${path.basename(lease.file)}.`);\n }\n}\n\n/**\n * Explicit recovery only. This does not open SQLite or alter pending SQL state.\n * No age or timeout is evidence that a writer stopped. An existing recovery\n * guard is preserved; its owner must finish before another recovery can enter.\n */\nexport function recoverDeadStoreLeases(storeRoot: string): { removed: string[] } {\n const root = platform.describePath(storeRoot).canonicalPath;\n const rootStat = lstatSync(root, { throwIfNoEntry: false });\n if (!rootStat) return { removed: [] };\n if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) blocked(\"The Store root is unsafe.\");\n if (lstatSync(path.join(root, \"removal.lock\"), { throwIfNoEntry: false })) blocked(\"Store removal is active or requires review.\");\n const guard = path.join(root, STORE_LEASE_RECOVERY_FILE);\n const token = randomUUID();\n const created = tryCreateExclusiveStoreLease(guard, { token, pid: process.pid, hostname: platform.hostname, startedAt: new Date().toISOString() });\n if (!created.created) return blocked(\"Another lease recovery owns the recovery guard. Inspect its owner before retrying.\");\n const guardStat = created.stat;\n try {\n if (lstatSync(path.join(root, \"removal.lock\"), { throwIfNoEntry: false })) blocked(\"Store removal began during recovery.\");\n const leases = RECOVERABLE_LEASES.map(name => readLease(path.join(root, name))).filter((lease): lease is LeaseSnapshot => lease !== null);\n // Validate the entire set first. A live bootstrap/access owner prevents any cleanup.\n for (const lease of leases) assertOwnerDead(lease);\n try {\n const sessions = recoverDeadStoreAccessSessions(root, false);\n if (sessions.active.length > 0) blocked(`A live process owns ${sessions.active.map((session) => path.basename(session.file)).join(\", \")}.`);\n } catch (error) {\n blocked(error instanceof Error ? error.message : String(error));\n }\n for (const lease of leases) { assertUnchanged(lease); assertOwnerDead(lease); }\n const removed: string[] = [];\n for (const lease of leases) {\n assertUnchanged(lease);\n unlinkSync(lease.file);\n removed.push(path.basename(lease.file));\n }\n try {\n const sessions = recoverDeadStoreAccessSessions(root);\n if (sessions.active.length > 0) {\n blocked(`A live process owns ${sessions.active.map((session) => path.basename(session.file)).join(\", \")}.`);\n }\n removed.push(...sessions.removed);\n } catch (error) {\n blocked(error instanceof Error ? error.message : String(error));\n }\n const order = [\"installation-bootstrap.lock\", \"store-access.lock\", \"global-assets.lock\"];\n removed.sort((left, right) => order.indexOf(left.split(path.sep)[0]) - order.indexOf(right.split(path.sep)[0]));\n return { removed };\n } finally {\n const current = readLease(guard);\n if (current && sameFile(guardStat, current.stat) && current.token === token) unlinkSync(guard);\n }\n}\n","import {\n closeSync,\n constants,\n fstatSync,\n fsyncSync,\n lstatSync,\n linkSync,\n mkdirSync,\n openSync,\n readFileSync,\n readdirSync,\n rmdirSync,\n rmSync,\n unlinkSync,\n writeFileSync,\n type Stats,\n} from \"node:fs\";\nimport path from \"node:path\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { createRequire } from \"node:module\";\nimport { platform } from \"../platform\";\nimport { getStoreDatabasePath } from \"./paths\";\n\n/**\n * SQLite operational database for the global store (R-DB-1 through R-DB-4).\n *\n * Driver: the Node built-in `node:sqlite` module, loaded lazily via\n * `createRequire` so the CLI still loads on runtimes without it.\n * The package requires Node >= 24.0.0, where `node:sqlite` needs no flag. If a runtime\n * lacks the module, the store database reports `unavailable` through the same path that\n * R-DB-4 mandates for a missing database; nothing else in the CLI is\n * affected. See the module README for the full driver tradeoff record.\n *\n * Locking discipline (R-DB-3):\n * - `journal_mode = WAL` so readers never block the single writer.\n * - `busy_timeout = 5000` so contending writers queue instead of failing.\n * - Connections are short-lived: open, operate, close (`withStoreDatabase`).\n * - Multi-statement writes run inside `BEGIN IMMEDIATE` transactions so the\n * write lock is acquired up front and held briefly.\n */\n\n/** Current schema version of the operational database (recorded in `PRAGMA user_version`). */\nexport const CURRENT_STORE_SCHEMA_VERSION = 6;\n\n/** Milliseconds a connection waits on a locked database before erroring. */\nexport const STORE_BUSY_TIMEOUT_MS = 5000;\n\n/** Maximum time to wait for a live Store owner before reporting contention. */\nexport const STORE_OWNER_WAIT_MS = 30_000;\n\n/** The legacy file path is now a directory of shared process sessions. */\nexport const STORE_ACCESS_PATH = \"store-access.lock\";\nconst STORE_SESSION_VERSION = 1;\n\nconst STORE_WAIT_MIN_MS = 25;\nconst STORE_WAIT_MAX_MS = 250;\nconst waitBuffer = new Int32Array(new SharedArrayBuffer(4));\n\nfunction storeSessionHostTag(hostname: string): string {\n const hostKey = createHash(\"sha256\").update(hostname).digest(\"hex\").slice(0, 16);\n return `h${hostKey}`;\n}\n\nexport function storeSessionPendingName(pid: number, hostname: string, token: string): string {\n return `.pending-${pid}.${storeSessionHostTag(hostname)}.${token}`;\n}\n\ntype SqliteModule = typeof import(\"node:sqlite\");\n\n/** A live connection to the store database. */\nexport type StoreDatabase = import(\"node:sqlite\").DatabaseSync;\n\nexport interface StoreMigration {\n /** Schema version this migration produces. */\n version: number;\n description: string;\n statements: string[];\n}\n\n/**\n * Ordered, append-only migration list. A fresh database replays the full list;\n * an existing database replays only versions greater than its recorded\n * `user_version`. `update` (the installer apply flow) invokes this via\n * {@link openStoreDatabase}, satisfying R-DB-2 / R-LIFE-3.\n */\nexport const STORE_MIGRATIONS: StoreMigration[] = [\n {\n version: 1,\n description:\n \"Initial schema: install/directory registry mirror plus the two project-state facets (Playbook run-state and work-execution evidence).\",\n statements: [\n // Install and directory registry: a mirror/index of each project's\n // canonical .make-docs/manifest.json (R-MIR-1). Keyed by the\n // manifest-minted project id; root_path is secondary lookup metadata\n // only (R-ID-2) and is local-only data (R-PRIV-1).\n `CREATE TABLE projects (\n project_id TEXT PRIMARY KEY,\n root_path TEXT NOT NULL,\n package_name TEXT,\n package_version TEXT,\n registered_at TEXT NOT NULL,\n last_seen_at TEXT NOT NULL\n )`,\n `CREATE INDEX idx_projects_root_path ON projects (root_path)`,\n // Playbook run-state facet: relocated and canonical here (R-MIR-2).\n // The record column holds the run record as opaque JSON; its shape and\n // progression semantics are owned by the W18 R7 lineage (R-SCOPE-1).\n `CREATE TABLE playbook_runs (\n project_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n record TEXT NOT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (project_id, run_id)\n )`,\n // Work-execution evidence facet: recorded sign-offs and decisions that\n // cannot be re-derived from the repository or git (R-PS-1). Keyed by\n // project id plus the canonical work-item identity components (wave\n // slug, phase path) produced by the work-item identity resolver\n // (R-PS-3); repo_root is secondary metadata, never the key (R-ID-2).\n `CREATE TABLE work_evidence (\n project_id TEXT NOT NULL,\n wave_slug TEXT NOT NULL,\n phase_path TEXT NOT NULL,\n evidence_kind TEXT NOT NULL,\n payload TEXT NOT NULL,\n repo_root TEXT,\n recorded_at TEXT NOT NULL,\n PRIMARY KEY (project_id, wave_slug, phase_path, evidence_kind)\n )`,\n `CREATE INDEX idx_work_evidence_project ON work_evidence (project_id)`,\n ],\n },\n {\n version: 2,\n description:\n \"Checkpoint 9: general lifecycle runs and bounded evidence references, without changing legacy Playbook state.\",\n statements: [\n `CREATE TABLE runs (\n project_id TEXT NOT NULL CHECK (length(project_id) BETWEEN 1 AND 160),\n run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 160),\n run_type TEXT NOT NULL CHECK (run_type = 'lifecycle'),\n lifecycle_stage TEXT NOT NULL CHECK (lifecycle_stage IN (\n 'design', 'plan', 'prd', 'work', 'implementation', 'release', 'archive', 'retrospective'\n )),\n status TEXT NOT NULL CHECK (status IN (\n 'active', 'paused', 'completed', 'failed', 'abandoned'\n )),\n checkpoint TEXT CHECK (checkpoint IS NULL OR length(checkpoint) BETWEEN 1 AND 256),\n version INTEGER NOT NULL CHECK (version >= 1),\n metadata TEXT NOT NULL CHECK (length(metadata) <= 4096),\n started_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n finished_at TEXT,\n PRIMARY KEY (project_id, run_id)\n )`,\n `CREATE INDEX idx_runs_project_status\n ON runs (project_id, status, started_at, run_id)`,\n `CREATE TABLE run_evidence (\n project_id TEXT NOT NULL CHECK (length(project_id) BETWEEN 1 AND 160),\n run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 160),\n evidence_id TEXT NOT NULL CHECK (length(evidence_id) BETWEEN 1 AND 160),\n evidence_kind TEXT NOT NULL CHECK (length(evidence_kind) BETWEEN 1 AND 64),\n reference_type TEXT NOT NULL CHECK (reference_type IN ('project-path', 'external')),\n reference_value TEXT NOT NULL CHECK (length(reference_value) BETWEEN 1 AND 2048),\n digest TEXT CHECK (\n digest IS NULL OR (\n length(digest) = 71 AND\n substr(digest, 1, 7) = 'sha256:' AND\n substr(digest, 8) NOT GLOB '*[^0-9a-f]*'\n )\n ),\n recorded_at TEXT NOT NULL,\n PRIMARY KEY (project_id, run_id, evidence_id),\n FOREIGN KEY (project_id, run_id) REFERENCES runs (project_id, run_id)\n )`,\n `CREATE INDEX idx_run_evidence_run\n ON run_evidence (project_id, run_id, recorded_at, evidence_id)`,\n `CREATE TABLE store_checkpoint_journal (\n receipt_id TEXT PRIMARY KEY CHECK (length(receipt_id) = 71),\n checkpoint INTEGER NOT NULL CHECK (checkpoint = 9),\n project_root_digest TEXT NOT NULL CHECK (length(project_root_digest) = 64),\n snapshot_id TEXT NOT NULL CHECK (length(snapshot_id) = 71),\n committed_at TEXT NOT NULL,\n receipt_json TEXT NOT NULL CHECK (length(receipt_json) BETWEEN 2 AND 16384)\n )`,\n `CREATE INDEX idx_store_checkpoint_journal_project\n ON store_checkpoint_journal (project_root_digest, checkpoint, committed_at, receipt_id)`,\n ],\n },\n {\n version: 3,\n description: \"Store-owned installation ledger, checkout writers, recovery and legacy transfer provenance.\",\n statements: [\n `CREATE TABLE installation_checkouts (checkout_id TEXT PRIMARY KEY, project_id TEXT NOT NULL, root_path TEXT NOT NULL UNIQUE, root_device TEXT NOT NULL, root_inode TEXT NOT NULL, created_at TEXT NOT NULL)`,\n `CREATE TABLE installation_ledgers (checkout_id TEXT PRIMARY KEY REFERENCES installation_checkouts(checkout_id), manifest_json TEXT NOT NULL, updated_at TEXT NOT NULL)`,\n `CREATE TABLE installation_operations (operation_id TEXT PRIMARY KEY, checkout_id TEXT NOT NULL REFERENCES installation_checkouts(checkout_id), operation TEXT NOT NULL, status TEXT NOT NULL CHECK(status IN ('pending','completed','rolled-back')), before_ledger TEXT, after_ledger TEXT, created_at TEXT NOT NULL, finished_at TEXT, plan_complete INTEGER NOT NULL DEFAULT 0)`,\n `CREATE TABLE installation_steps (operation_id TEXT NOT NULL REFERENCES installation_operations(operation_id), ordinal INTEGER NOT NULL, relative_path TEXT NOT NULL, before_json TEXT NOT NULL, after_json TEXT NOT NULL, applied INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(operation_id, ordinal))`,\n `CREATE TABLE installation_locks (root_path TEXT PRIMARY KEY, token TEXT NOT NULL, pid INTEGER NOT NULL, hostname TEXT NOT NULL, acquired_at TEXT NOT NULL)`,\n `CREATE TABLE installation_migration_records (checkout_id TEXT NOT NULL REFERENCES installation_checkouts(checkout_id), kind TEXT NOT NULL CHECK(kind IN ('receipt','quiescence','snapshot','backup','legacy-import')), record_id TEXT NOT NULL, record_json TEXT NOT NULL, PRIMARY KEY(checkout_id,kind,record_id))`,\n `CREATE TABLE installation_transfers (checkout_id TEXT NOT NULL REFERENCES installation_checkouts(checkout_id), source_path TEXT NOT NULL, source_digest TEXT NOT NULL, status TEXT NOT NULL CHECK(status IN ('imported','removed')), imported_at TEXT NOT NULL, PRIMARY KEY(checkout_id,source_path,source_digest))`,\n `CREATE TABLE tool_operations (operation_id TEXT PRIMARY KEY, operation TEXT NOT NULL, status TEXT NOT NULL CHECK(status IN ('pending','completed','failed')), pid INTEGER NOT NULL, hostname TEXT NOT NULL, metadata_json TEXT NOT NULL, started_at TEXT NOT NULL, finished_at TEXT)`,\n `CREATE TABLE store_schema_journal (schema_version INTEGER PRIMARY KEY, description TEXT NOT NULL, committed_at TEXT NOT NULL)`,\n `INSERT INTO store_schema_journal VALUES (3, 'Store-owned installation state', strftime('%Y-%m-%dT%H:%M:%fZ','now'))`,\n ],\n },\n {\n version: 4,\n description: \"Platform-neutral checkout path keys and bounded verification evidence.\",\n statements: [\n `ALTER TABLE installation_checkouts ADD COLUMN root_path_key TEXT`,\n `ALTER TABLE installation_checkouts ADD COLUMN verified_at TEXT`,\n `ALTER TABLE installation_checkouts ADD COLUMN verification_json TEXT`,\n `UPDATE installation_checkouts\n SET root_path_key = root_path,\n verified_at = created_at,\n verification_json = '{\"schemaVersion\":1,\"kind\":\"legacy-path-import\"}'\n WHERE root_path_key IS NULL`,\n `CREATE INDEX idx_installation_checkouts_path_key\n ON installation_checkouts (root_path_key)`,\n `INSERT INTO store_schema_journal VALUES (\n 4,\n 'Platform-neutral checkout path verification',\n strftime('%Y-%m-%dT%H:%M:%fZ','now')\n )`,\n ],\n },\n {\n version: 5,\n description: \"W22 P5 compatibility bridge: target migration receipts and retired durable object-number identity.\",\n statements: [\n `INSERT INTO tool_operations\n (operation_id, operation, status, pid, hostname, metadata_json, started_at, finished_at)\n SELECT\n 'compatibility-bridge:w22-p5:v5',\n 'compatibility.bridge',\n 'pending',\n 0,\n 'schema-migration',\n '{\"schemaVersion\":1,\"bridgeId\":\"w22-p5-store-schema-v5\",\"sourceSchemaMaximum\":4,\"targetSchema\":5}',\n strftime('%Y-%m-%dT%H:%M:%fZ','now'),\n NULL\n WHERE EXISTS (SELECT 1 FROM installation_checkouts)\n OR EXISTS (SELECT 1 FROM installation_ledgers)\n OR EXISTS (SELECT 1 FROM installation_transfers)\n OR EXISTS (SELECT 1 FROM store_checkpoint_journal)`,\n `CREATE TABLE store_migration_receipts (\n receipt_id TEXT PRIMARY KEY CHECK (length(receipt_id) = 71),\n operation TEXT NOT NULL CHECK (operation = 'store.schema.migrate'),\n project_root_digest TEXT NOT NULL CHECK (length(project_root_digest) = 64),\n source_schema_version INTEGER NOT NULL CHECK (source_schema_version BETWEEN 0 AND 4),\n target_schema_version INTEGER NOT NULL CHECK (target_schema_version = 5),\n snapshot_id TEXT NOT NULL CHECK (length(snapshot_id) = 71),\n result TEXT NOT NULL CHECK (result = 'completed'),\n committed_at TEXT NOT NULL,\n receipt_json TEXT NOT NULL CHECK (length(receipt_json) BETWEEN 2 AND 16384)\n )`,\n `CREATE INDEX idx_store_migration_receipts_project\n ON store_migration_receipts (project_root_digest, operation, committed_at, receipt_id)`,\n `INSERT INTO store_migration_receipts\n (receipt_id, operation, project_root_digest, source_schema_version,\n target_schema_version, snapshot_id, result, committed_at, receipt_json)\n SELECT receipt_id, 'store.schema.migrate', project_root_digest, 2, 5,\n snapshot_id, 'completed', committed_at, receipt_json\n FROM store_checkpoint_journal`,\n `INSERT INTO installation_migration_records\n (checkout_id, kind, record_id, record_json)\n SELECT checkout_id,\n 'legacy-import',\n 'w22-p5:checkout-object-numbers:v4',\n json_object(\n 'schemaVersion', 1,\n 'bridgeId', 'w22-p5-checkout-object-numbers',\n 'rootDevice', root_device,\n 'rootInode', root_inode,\n 'retainedAs', 'legacy-comparison-evidence'\n )\n FROM installation_checkouts`,\n `ALTER TABLE installation_checkouts DROP COLUMN root_device`,\n `ALTER TABLE installation_checkouts DROP COLUMN root_inode`,\n `UPDATE tool_operations\n SET status = 'completed',\n finished_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')\n WHERE operation_id = 'compatibility-bridge:w22-p5:v5'\n AND operation = 'compatibility.bridge'\n AND status = 'pending'`,\n `INSERT INTO store_schema_journal VALUES (\n 5,\n 'W22 P5 compatibility bridge',\n strftime('%Y-%m-%dT%H:%M:%fZ','now')\n )`,\n ],\n },\n {\n version: 6,\n description:\n \"W23 R0 P5: optional, rebuildable per-record backlog review cache.\",\n statements: [\n `CREATE TABLE backlog_review_cache (\n checkout_id TEXT NOT NULL REFERENCES installation_checkouts(checkout_id) ON DELETE CASCADE,\n record_path TEXT NOT NULL CHECK (\n length(record_path) BETWEEN 1 AND 2048 AND\n substr(record_path, 1, 1) <> '/' AND\n instr(record_path, '\\\\') = 0\n ),\n record_digest TEXT NOT NULL CHECK (\n length(record_digest) = 64 AND\n record_digest NOT GLOB '*[^0-9a-f]*'\n ),\n snapshot_schema_version INTEGER NOT NULL CHECK (snapshot_schema_version >= 1),\n rule_catalog_version INTEGER NOT NULL CHECK (rule_catalog_version >= 1),\n skill_version INTEGER NOT NULL CHECK (skill_version >= 1),\n fragment_json TEXT NOT NULL CHECK (length(fragment_json) BETWEEN 2 AND 65536),\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (\n checkout_id,\n record_path,\n record_digest,\n snapshot_schema_version,\n rule_catalog_version,\n skill_version\n )\n )`,\n `CREATE INDEX idx_backlog_review_cache_checkout_updated\n ON backlog_review_cache (checkout_id, updated_at DESC, record_path)`,\n `INSERT INTO store_schema_journal VALUES (\n 6,\n 'W23 R0 P5 backlog review cache',\n strftime('%Y-%m-%dT%H:%M:%fZ','now')\n )`,\n ],\n },\n];\n\n/** Thrown when the database was written by a newer CLI schema (R-DB-2). */\nexport class StoreSchemaNewerError extends Error {\n readonly code = \"store-unavailable\";\n readonly databaseSchemaVersion: number;\n readonly cliSchemaVersion: number;\n readonly issue: StoreIssue;\n\n constructor(databaseSchemaVersion: number, cliSchemaVersion: number, databasePath: string) {\n const issue: StoreIssue = { code: \"schema-newer\", path: databasePath, operation: \"open Store\", retryable: false, attempts: 1, waitedMs: 0, cause: `The Store uses schema version ${databaseSchemaVersion}, but this CLI supports up to version ${cliSchemaVersion}.` };\n super(formatStoreIssue(issue));\n this.name = \"StoreSchemaNewerError\";\n this.databaseSchemaVersion = databaseSchemaVersion;\n this.cliSchemaVersion = cliSchemaVersion;\n this.issue = issue;\n }\n}\n\nexport type StoreIssueCode =\n | \"access-denied\"\n | \"read-only-filesystem\"\n | \"sqlite-unavailable\"\n | \"contention-timeout\"\n | \"io-error\"\n | \"unsafe-path\"\n | \"corrupt\"\n | \"schema-newer\"\n | \"schema-unknown\"\n | \"owner-unverified\";\n\n/** Structured detail for CLI and MCP Store failures. */\nexport interface StoreIssue {\n code: StoreIssueCode;\n path: string;\n operation: string;\n systemCode?: string;\n retryable: boolean;\n attempts: number;\n waitedMs: number;\n cause: string;\n}\n\n/** Thrown when the Store cannot be used safely. */\nexport class StoreUnavailableError extends Error {\n readonly code = \"store-unavailable\";\n readonly issue: StoreIssue;\n\n constructor(reason: string | StoreIssue) {\n const issue = typeof reason === \"string\"\n ? makeStoreIssue(\"io-error\", \"Store\", \"open\", new Error(reason))\n : reason;\n super(formatStoreIssue(issue));\n this.name = \"StoreUnavailableError\";\n this.issue = issue;\n }\n}\n\n/** Formats one cause without hiding it behind a generic Store state. */\nexport function formatStoreIssue(\n issue: StoreIssue,\n context: { projectMutationStarted?: boolean; pendingOperationId?: string } = {},\n): string {\n let summary: string;\n switch (issue.code) {\n case \"access-denied\":\n summary = `Make Docs cannot access the Store at ${issue.path}. This process needs read and write access to the Store directory and its SQLite support files.`;\n break;\n case \"read-only-filesystem\":\n summary = `Make Docs cannot write the Store at ${issue.path} because the file system is read-only.`;\n break;\n case \"sqlite-unavailable\":\n summary = `Make Docs cannot ${issue.operation} the Store at ${issue.path} because SQLite support is not available. ${issue.cause}`;\n break;\n case \"contention-timeout\":\n summary = `Make Docs waited ${Math.ceil(issue.waitedMs / 1000)} seconds to ${issue.operation} at ${issue.path}. ${issue.cause}`;\n break;\n case \"unsafe-path\":\n summary = `Unsafe Store path: ${issue.path}. Make Docs refused it. ${issue.cause}`;\n break;\n case \"corrupt\":\n case \"schema-unknown\":\n summary = `Make Docs preserved the Store at ${issue.path}. ${issue.cause}`;\n break;\n case \"schema-newer\":\n summary = `Make Docs preserved the Store at ${issue.path}. The Store uses a newer schema. ${issue.cause}`;\n break;\n case \"owner-unverified\":\n summary = `Make Docs cannot verify the Store owner at ${issue.path}. ${issue.cause}`;\n break;\n default:\n summary = `Make Docs could not complete the Store operation \"${issue.operation}\" at ${issue.path}${issue.systemCode ? ` (${issue.systemCode})` : \"\"}. ${issue.cause}`;\n }\n if (context.projectMutationStarted) {\n return `${summary} Project files may have changed.${context.pendingOperationId ? ` Pending operation: ${context.pendingOperationId}.` : \"\"} Run make-docs project state status before recovery.`;\n }\n const action = issue.code === \"access-denied\"\n ? \"Give this process Store access, then run the command again.\"\n : issue.code === \"contention-timeout\"\n ? \"Wait for the owner to finish, then run the command again.\"\n : issue.code === \"owner-unverified\"\n ? \"Verify the owner before you recover its lease.\"\n : issue.code === \"sqlite-unavailable\"\n ? \"Use a supported Node.js runtime with SQLite, then run the command again.\"\n : issue.code === \"schema-newer\"\n ? \"Update make-docs to a version that supports this Store.\"\n : issue.code === \"corrupt\" || issue.code === \"schema-unknown\"\n ? \"Repair or restore this Store before you run the command again. Do not create a replacement Store.\"\n : \"Correct the Store condition and run the command again.\";\n return `${summary} No project files changed. ${action}`;\n}\n\n/** An existing Store needs the explicit checkpoint-9 migration path. */\nexport class StoreMigrationRequiredError extends Error {\n readonly databaseSchemaVersion: number;\n readonly cliSchemaVersion: number;\n\n constructor(databaseSchemaVersion: number, cliSchemaVersion: number, databasePath: string) {\n super(\n `The make-docs store database at ${databasePath} uses schema version ${databaseSchemaVersion} ` +\n `and requires the explicit checkpoint-9 migration to version ${cliSchemaVersion}. ` +\n \"Run the reviewed Make Docs update or setup migration before other Store operations.\",\n );\n this.name = \"StoreMigrationRequiredError\";\n this.databaseSchemaVersion = databaseSchemaVersion;\n this.cliSchemaVersion = cliSchemaVersion;\n }\n}\n\nexport type StoreCheckpoint9Classification =\n | { state: \"absent\"; databasePath: string; schemaVersion: null }\n | { state: \"supported-current\"; databasePath: string; schemaVersion: 6 }\n | { state: \"supported-legacy\"; databasePath: string; schemaVersion: 1 | 2 | 3 | 4 | 5 }\n | { state: \"newer-unknown\"; databasePath: string; schemaVersion: number; reason: string; issue?: StoreIssue }\n | { state: \"corrupt\"; databasePath: string; schemaVersion: null; reason: string; issue?: StoreIssue }\n | { state: \"unknown\"; databasePath: string; schemaVersion: number; reason: string; issue?: StoreIssue }\n | { state: \"indeterminate\"; databasePath: string; schemaVersion: null; reason: string; issue: StoreIssue };\n\nexport type UnsafeStoreCheckpoint9Classification = Extract<\n StoreCheckpoint9Classification,\n { state: \"newer-unknown\" | \"corrupt\" | \"unknown\" | \"indeterminate\" }\n>;\n\nexport class StoreCheckpoint9StateError extends Error {\n readonly code = \"store-unavailable\";\n readonly issue: StoreIssue;\n\n constructor(readonly classification: UnsafeStoreCheckpoint9Classification) {\n const issue = classification.issue ?? makeStoreIssue(\n classification.state === \"corrupt\" ? \"corrupt\" : classification.state === \"newer-unknown\" ? \"schema-newer\" : \"schema-unknown\",\n classification.databasePath,\n \"inspect Store\",\n new Error(classification.reason),\n );\n super(formatStoreIssue(issue));\n this.name = \"StoreCheckpoint9StateError\";\n this.issue = issue;\n }\n}\n\nexport interface StoreCheckpoint9JournalEntry {\n receiptId: string;\n checkpoint: 9;\n projectRootDigest: string;\n snapshotId: string;\n committedAt: string;\n receiptJson: string;\n}\n\nexport type SqliteDriverResult =\n | { available: true; sqlite: SqliteModule }\n | { available: false; reason: string };\n\nlet cachedDriver: SqliteDriverResult | null = null;\n\n/**\n * Loads the built-in `node:sqlite` driver if this runtime provides it.\n * The result is cached for the process lifetime.\n */\nexport function loadSqliteDriver(): SqliteDriverResult {\n if (cachedDriver) {\n return cachedDriver;\n }\n try {\n const require = createRequire(import.meta.url);\n const sqlite = require(\"node:sqlite\") as SqliteModule;\n cachedDriver = { available: true, sqlite };\n } catch {\n cachedDriver = {\n available: false,\n reason: `this Node runtime (${process.version}) does not provide the built-in node:sqlite module (Make Docs requires Node >= 24.0.0 with node:sqlite enabled).`,\n };\n }\n return cachedDriver;\n}\n\nexport interface OpenStoreDatabaseResult {\n db: StoreDatabase;\n databasePath: string;\n /** True when no database file existed and a fresh one was created. */\n created: boolean;\n /** True when a corrupt database was quarantined and a fresh one created. */\n recovered: boolean;\n /** Quarantine location of the corrupt database, when `recovered` is true. */\n quarantinedPath: string | null;\n /** Schema version before this open (null for a fresh database). */\n previousSchemaVersion: number | null;\n /** Schema version after migrations (always {@link CURRENT_STORE_SCHEMA_VERSION}). */\n schemaVersion: number;\n}\n\n/**\n * Opens the store database. Fresh databases replay the full schema. Existing\n * legacy databases always require the explicit checkpoint-9 migration entry\n * point. The ordinary open path cannot bypass its journal transaction.\n *\n * - Missing file: created fresh at the current schema (R-DB-4).\n * - Corrupt or unknown file: preserved; the caller reports Store unavailable.\n * - Newer schema: throws {@link StoreSchemaNewerError} without reading or\n * writing any table (R-DB-2).\n * - Missing driver: throws {@link StoreUnavailableError}.\n */\nexport function openStoreDatabase(\n storeRoot: string,\n options: { recoverCorrupt?: boolean } = {},\n): OpenStoreDatabaseResult {\n const driver = loadSqliteDriver();\n if (!driver.available) throw new StoreUnavailableError({\n code: \"sqlite-unavailable\",\n path: getStoreDatabasePath(storeRoot),\n operation: \"open\",\n retryable: false,\n attempts: 1,\n waitedMs: 0,\n cause: driver.reason,\n });\n const release = acquireStoreAccess(storeRoot);\n let db: StoreDatabase | null = null;\n try {\n const classification = classifyStoreCheckpoint9State(storeRoot);\n const databasePath = getStoreDatabasePath(storeRoot);\n if (classification.state === \"newer-unknown\") throw new StoreSchemaNewerError(classification.schemaVersion, CURRENT_STORE_SCHEMA_VERSION, databasePath);\n if (classification.state === \"supported-legacy\") throw new StoreMigrationRequiredError(classification.schemaVersion, CURRENT_STORE_SCHEMA_VERSION, databasePath);\n if (classification.state !== \"absent\" && classification.state !== \"supported-current\") throw new StoreCheckpoint9StateError(classification);\n db = connect(driver.sqlite, databasePath, classification.state !== \"absent\");\n if (classification.state === \"absent\") applyStoreMigrations(db, 0);\n const close = db.close.bind(db);\n db.close = () => { try { close(); } finally { release(); } };\n return {db, databasePath, created: classification.state === \"absent\", recovered: false, quarantinedPath: null, previousSchemaVersion: classification.schemaVersion, schemaVersion: CURRENT_STORE_SCHEMA_VERSION};\n } catch (error) { closeQuietly(db); release(); throw error; }\n}\n\ninterface StoreLeaseSnapshot {\n file: string;\n stat: Stats;\n bytes: Buffer;\n token: string;\n pid: number;\n hostname: string;\n}\n\nexport interface StoreSessionRecoveryResult {\n removed: string[];\n active: Array<{ file: string; pid: number; hostname: string }>;\n}\n\n/** One process lease is shared by all nested Store calls in that process. */\nconst accessLeases = new Map<string, { count: number; release: () => void }>();\n\nfunction systemCode(error: unknown): string | undefined {\n const code = (error as NodeJS.ErrnoException | null)?.code;\n return typeof code === \"string\" ? code : undefined;\n}\n\nfunction readStoreEntry(file: string, operation: string): Stats | null {\n try {\n return lstatSync(file, { throwIfNoEntry: false }) ?? null;\n } catch (error) {\n if (systemCode(error) === \"ENOENT\") return null;\n throw new StoreUnavailableError(makeStoreIssue(\"io-error\", file, operation, error));\n }\n}\n\nexport function makeStoreIssue(\n fallback: StoreIssueCode,\n targetPath: string,\n operation: string,\n error: unknown,\n details: Partial<Pick<StoreIssue, \"attempts\" | \"waitedMs\" | \"retryable\">> = {},\n): StoreIssue {\n const code = systemCode(error);\n const issueCode: StoreIssueCode = code === \"EACCES\" || code === \"EPERM\"\n ? \"access-denied\"\n : code === \"EROFS\"\n ? \"read-only-filesystem\"\n : fallback;\n return {\n code: issueCode,\n path: targetPath,\n operation,\n ...(code ? { systemCode: code } : {}),\n retryable: details.retryable ?? false,\n attempts: details.attempts ?? 1,\n waitedMs: details.waitedMs ?? 0,\n cause: error instanceof Error ? error.message : String(error),\n };\n}\n\nfunction pause(attempt: number, deadline: number): void {\n const base = Math.min(STORE_WAIT_MAX_MS, STORE_WAIT_MIN_MS * (2 ** Math.min(attempt, 4)));\n const jitter = Math.floor(Math.random() * STORE_WAIT_MIN_MS);\n const remaining = Math.max(0, deadline - Date.now());\n Atomics.wait(waitBuffer, 0, 0, Math.min(remaining, base + jitter));\n}\n\n/** Share the bounded retry timing with checkout-level lock acquisition. */\nexport function waitForStoreRetry(attempt: number, deadline: number): void {\n pause(attempt, deadline);\n}\n\nfunction sameFile(left: Stats, right: Stats): boolean {\n return platform.sameFileObject(left, right, \"file\");\n}\n\nfunction readOwnerLease(file: string, operation: string, expectedVersion?: number): StoreLeaseSnapshot | null {\n const initial = readStoreEntry(file, operation);\n if (!initial) return null;\n if (!initial.isFile() || initial.isSymbolicLink() || initial.size > 16_384) {\n throw new StoreUnavailableError(makeStoreIssue(\n initial.isSymbolicLink() ? \"unsafe-path\" : \"owner-unverified\",\n file,\n operation,\n new Error(\"The lease owner record is missing or unsafe.\"),\n ));\n }\n let fd: number;\n try {\n fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);\n } catch (error) {\n if (systemCode(error) === \"ENOENT\") return null;\n throw new StoreUnavailableError(makeStoreIssue(\"io-error\", file, operation, error));\n }\n try {\n const stat = fstatSync(fd);\n if (!sameFile(initial, stat)) {\n throw new StoreUnavailableError(makeStoreIssue(\"owner-unverified\", file, operation, new Error(\"The lease changed during inspection.\")));\n }\n const bytes = readFileSync(fd);\n let record: Record<string, unknown>;\n try {\n record = JSON.parse(bytes.toString(\"utf8\")) as Record<string, unknown>;\n } catch {\n throw new StoreUnavailableError(makeStoreIssue(\"owner-unverified\", file, operation, new Error(\"The lease owner record is unreadable.\")));\n }\n if (typeof record.token !== \"string\" || !record.token || typeof record.hostname !== \"string\" || !record.hostname ||\n typeof record.pid !== \"number\" || !Number.isSafeInteger(record.pid) || record.pid <= 0) {\n throw new StoreUnavailableError(makeStoreIssue(\"owner-unverified\", file, operation, new Error(\"The lease owner record is incomplete.\")));\n }\n if (expectedVersion !== undefined && record.version !== expectedVersion) {\n throw new StoreUnavailableError(makeStoreIssue(\"owner-unverified\", file, operation, new Error(`The Store session version is not supported: ${String(record.version)}.`)));\n }\n if (expectedVersion !== undefined && (typeof record.startedAt !== \"string\" || Number.isNaN(Date.parse(record.startedAt)))) {\n throw new StoreUnavailableError(makeStoreIssue(\"owner-unverified\", file, operation, new Error(\"The Store session start time is missing or invalid.\")));\n }\n return { file, stat, bytes, token: record.token, pid: record.pid, hostname: record.hostname };\n } finally {\n closeSync(fd);\n }\n}\n\nfunction processOwnerState(pid: number, hostname: string, file: string): \"alive\" | \"dead\" {\n const state = platform.processLiveness(pid, hostname);\n if (state === \"alive\" || state === \"dead\") return state;\n throw new StoreUnavailableError(makeStoreIssue(\n \"owner-unverified\",\n file,\n \"inspect owner\",\n new Error(\"The lease owner is on another host or its state cannot be verified.\"),\n ));\n}\n\nfunction ownerState(lease: StoreLeaseSnapshot): \"alive\" | \"dead\" {\n return processOwnerState(lease.pid, lease.hostname, lease.file);\n}\n\nfunction unlinkLeaseIfUnchanged(lease: StoreLeaseSnapshot): boolean {\n const current = readStoreEntry(lease.file, \"verify Store lease\");\n if (!current) return false;\n let bytes: Buffer;\n try {\n bytes = readFileSync(lease.file);\n } catch (error) {\n if (systemCode(error) === \"ENOENT\") return false;\n throw new StoreUnavailableError(makeStoreIssue(\"io-error\", lease.file, \"verify Store lease\", error));\n }\n if (!sameFile(lease.stat, current) || !bytes.equals(lease.bytes)) {\n throw new StoreUnavailableError(makeStoreIssue(\"owner-unverified\", lease.file, \"recover lease\", new Error(\"The lease changed during recovery.\")));\n }\n try {\n unlinkSync(lease.file);\n } catch (error) {\n if (systemCode(error) === \"ENOENT\") return false;\n throw new StoreUnavailableError(makeStoreIssue(\"io-error\", lease.file, \"remove stopped Store lease\", error));\n }\n return true;\n}\n\nfunction removeOwnedSession(file: string, token: string, stat: Stats | null, operation: string): boolean {\n if (!stat) return false;\n const lease = readOwnerLease(file, operation, STORE_SESSION_VERSION);\n if (!lease || !sameFile(stat, lease.stat) || lease.token !== token) return false;\n return unlinkLeaseIfUnchanged(lease);\n}\n\nfunction removePendingSession(file: string, stat: Stats | null): boolean {\n if (!stat) return false;\n const current = readStoreEntry(file, \"clean pending Store session\");\n if (!current || !sameFile(stat, current)) return false;\n try {\n unlinkSync(file);\n return true;\n } catch (error) {\n if (systemCode(error) === \"ENOENT\") return false;\n throw new StoreUnavailableError(makeStoreIssue(\"io-error\", file, \"clean pending Store session\", error));\n }\n}\n\n/** Publish a complete exclusive owner record without an unreadable creation window. */\nexport function tryCreateExclusiveStoreLease(\n lockPath: string,\n owner: { token: string; pid: number; hostname: string; startedAt?: string },\n): { created: true; stat: Stats } | { created: false } {\n const directory = path.dirname(lockPath);\n const pending = path.join(directory, `.pending-${path.basename(lockPath)}.${process.pid}.${randomUUID()}`);\n let fd: number | null = null;\n let stat: Stats | null = null;\n try {\n fd = openSync(pending, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);\n platform.applyPrivateMode(fd, 0o600);\n writeFileSync(fd, JSON.stringify(owner));\n fsyncSync(fd);\n stat = fstatSync(fd);\n try {\n linkSync(pending, lockPath);\n } catch (error) {\n if (systemCode(error) === \"EEXIST\") return { created: false };\n throw new StoreUnavailableError(makeStoreIssue(\"io-error\", lockPath, \"publish exclusive Store lock\", error));\n }\n const published = readStoreEntry(lockPath, \"verify exclusive Store lock\");\n if (!published || !sameFile(stat, published)) {\n throw new StoreUnavailableError(makeStoreIssue(\"owner-unverified\", lockPath, \"verify exclusive Store lock\", new Error(\"The exclusive Store lock changed during publication.\")));\n }\n return { created: true, stat };\n } catch (error) {\n if (error instanceof StoreUnavailableError) throw error;\n throw new StoreUnavailableError(makeStoreIssue(\"io-error\", lockPath, \"create exclusive Store lock\", error));\n } finally {\n if (fd !== null) closeSync(fd);\n removePendingSession(pending, stat);\n }\n}\n\nfunction assertSafeStoreEntry(file: string, operation: string): void {\n const stat = readStoreEntry(file, operation);\n if (stat?.isSymbolicLink()) {\n throw new StoreUnavailableError(makeStoreIssue(\"unsafe-path\", file, operation, new Error(\"Symbolic links are not allowed for Store state.\")));\n }\n}\n\nfunction exclusiveBlocker(storeRoot: string, preparing: boolean): StoreLeaseSnapshot | null {\n const names = [\"installation-lease-recovery.lock\", \"removal.lock\", ...(!preparing ? [\"installation-bootstrap.lock\"] : [])];\n for (const name of names) {\n const file = path.join(storeRoot, name);\n if (!readStoreEntry(file, \"inspect Store maintenance lock\")) continue;\n const lease = readOwnerLease(file, \"wait for Store maintenance\");\n if (lease) return lease;\n }\n return null;\n}\n\nfunction cleanupAccessDirectory(directory: string): void {\n try {\n rmdirSync(directory);\n } catch (error) {\n if (!new Set([\"ENOENT\", \"ENOTEMPTY\", \"EEXIST\"]).has(systemCode(error) ?? \"\")) {\n throw new StoreUnavailableError(makeStoreIssue(\"io-error\", directory, \"clean session directory\", error));\n }\n }\n}\n\n/** Inspect shared sessions and remove only proven-dead local owners. */\nexport function recoverDeadStoreAccessSessions(storeRoot: string, remove = true): StoreSessionRecoveryResult {\n const root = path.resolve(storeRoot);\n const directory = path.join(root, STORE_ACCESS_PATH);\n const stat = readStoreEntry(directory, \"recover Store sessions\");\n if (!stat) return { removed: [], active: [] };\n if (stat.isSymbolicLink()) {\n throw new StoreUnavailableError(makeStoreIssue(\"unsafe-path\", directory, \"recover Store sessions\", new Error(\"The Store access path is a symbolic link.\")));\n }\n if (!stat.isFile() && !stat.isDirectory()) {\n throw new StoreUnavailableError(makeStoreIssue(\"unsafe-path\", directory, \"recover Store sessions\", new Error(\"The Store access path is not a file or directory.\")));\n }\n let files: string[];\n try {\n files = stat.isFile()\n ? [directory]\n : readdirSync(directory).sort().map((entry) => path.join(directory, entry));\n } catch (error) {\n if (systemCode(error) === \"ENOENT\") return { removed: [], active: [] };\n throw new StoreUnavailableError(makeStoreIssue(\"io-error\", directory, \"read Store sessions\", error));\n }\n const removed: string[] = [];\n const active: StoreSessionRecoveryResult[\"active\"] = [];\n for (const file of files) {\n const pending = /^\\.pending-(\\d+)\\.([A-Za-z0-9_-]+)\\.[0-9a-f-]+$/.exec(path.basename(file));\n if (pending) {\n const stat = readStoreEntry(file, \"recover pending Store session\");\n if (!stat) continue;\n if (!stat.isFile() || stat.isSymbolicLink()) {\n throw new StoreUnavailableError(makeStoreIssue(\"unsafe-path\", file, \"recover Store sessions\", new Error(\"The pending session path is unsafe.\")));\n }\n const pid = Number(pending[1]);\n let hostname: string;\n if (/^h[0-9a-f]{16}$/.test(pending[2])) {\n if (pending[2] !== storeSessionHostTag(platform.hostname)) {\n throw new StoreUnavailableError(makeStoreIssue(\"owner-unverified\", file, \"recover Store sessions\", new Error(\"The pending session owner is on another host.\")));\n }\n hostname = platform.hostname;\n } else try {\n hostname = Buffer.from(pending[2], \"base64url\").toString(\"utf8\");\n } catch {\n throw new StoreUnavailableError(makeStoreIssue(\"owner-unverified\", file, \"recover Store sessions\", new Error(\"The pending session owner is unreadable.\")));\n }\n if (!Number.isSafeInteger(pid) || pid <= 0 || !hostname) {\n throw new StoreUnavailableError(makeStoreIssue(\"owner-unverified\", file, \"recover Store sessions\", new Error(\"The pending session owner is incomplete.\")));\n }\n if (processOwnerState(pid, hostname, file) === \"alive\") {\n active.push({ file, pid, hostname });\n } else if (remove) {\n if (removePendingSession(file, stat)) {\n removed.push(path.relative(root, file).split(path.sep).join(path.posix.sep));\n }\n }\n continue;\n }\n const lease = readOwnerLease(file, \"recover Store sessions\", stat.isDirectory() ? STORE_SESSION_VERSION : undefined);\n if (!lease) continue;\n if (ownerState(lease) === \"alive\") {\n active.push({ file, pid: lease.pid, hostname: lease.hostname });\n } else if (remove && unlinkLeaseIfUnchanged(lease)) {\n removed.push(path.relative(root, file).split(path.sep).join(path.posix.sep));\n }\n }\n if (remove && stat.isDirectory() && active.length === 0) cleanupAccessDirectory(directory);\n return { removed, active };\n}\n\n/** Wait until an exclusive maintenance task can safely open or remove the Store. */\nexport function waitForStoreAccessToDrain(storeRoot: string, timeoutMs = STORE_OWNER_WAIT_MS): string[] {\n const started = Date.now();\n const deadline = started + timeoutMs;\n let attempt = 0;\n const removed: string[] = [];\n while (true) {\n let result: StoreSessionRecoveryResult;\n try {\n result = recoverDeadStoreAccessSessions(storeRoot);\n } catch (error) {\n const code = error instanceof StoreUnavailableError ? error.issue.systemCode : systemCode(error);\n if (platform.kind === \"win32\" && new Set([\"EPERM\", \"EACCES\", \"EBUSY\"]).has(code ?? \"\") && Date.now() < deadline) {\n pause(attempt++, deadline);\n continue;\n }\n throw error;\n }\n removed.push(...result.removed);\n if (result.active.length === 0) return removed;\n if (Date.now() >= deadline) {\n throw new StoreUnavailableError({\n code: \"contention-timeout\",\n path: path.join(path.resolve(storeRoot), STORE_ACCESS_PATH),\n operation: \"wait for Store sessions\",\n retryable: true,\n attempts: attempt + 1,\n waitedMs: Date.now() - started,\n cause: `A live process still owns a Store session (${result.active.map((owner) => owner.pid).join(\", \")}).`,\n });\n }\n pause(attempt++, deadline);\n }\n}\n\n/** Acquire one shared Store session. Nested calls in this process reuse it. */\nexport function acquireStoreAccess(storeRoot: string, preparing = false, timeoutMs = STORE_OWNER_WAIT_MS): () => void {\n const requestedStoreRoot = path.resolve(storeRoot);\n try {\n storeRoot = platform.describePath(requestedStoreRoot).canonicalPath;\n } catch (error) {\n throw new StoreUnavailableError(makeStoreIssue(\"io-error\", requestedStoreRoot, \"resolve Store root\", error));\n }\n const prior = accessLeases.get(storeRoot);\n if (prior) {\n prior.count++;\n let done = false;\n return () => {\n if (!done) {\n done = true;\n prior.release();\n }\n };\n }\n\n const started = Date.now();\n const deadline = started + timeoutMs;\n let attempt = 0;\n while (true) {\n for (const suffix of [\"store.db\", \"store.db-wal\", \"store.db-shm\", STORE_ACCESS_PATH, \"removal.lock\", \"installation-bootstrap.lock\", \"installation-lease-recovery.lock\"]) {\n assertSafeStoreEntry(path.join(storeRoot, suffix), \"open Store session\");\n }\n try {\n mkdirSync(storeRoot, { recursive: true, mode: 0o700 });\n } catch (error) {\n throw new StoreUnavailableError(makeStoreIssue(\"io-error\", storeRoot, \"create\", error));\n }\n\n const blocker = exclusiveBlocker(storeRoot, preparing);\n if (blocker) {\n if (blocker.pid === process.pid && blocker.hostname === platform.hostname) {\n throw new StoreUnavailableError({ code: \"contention-timeout\", path: blocker.file, operation: \"open a Store session\", retryable: false, attempts: attempt + 1, waitedMs: Date.now() - started, cause: \"This process already owns the exclusive Store lock.\" });\n }\n if (ownerState(blocker) !== \"alive\") {\n throw new StoreUnavailableError(makeStoreIssue(\"owner-unverified\", blocker.file, \"wait for Store maintenance\", new Error(\"A stopped maintenance owner requires lease recovery.\")));\n }\n if (Date.now() >= deadline) {\n throw new StoreUnavailableError({ code: \"contention-timeout\", path: blocker.file, operation: \"wait for Store maintenance\", retryable: true, attempts: attempt + 1, waitedMs: Date.now() - started, cause: `Process ${blocker.pid} is still active.` });\n }\n pause(attempt++, deadline);\n continue;\n }\n\n const directory = path.join(storeRoot, STORE_ACCESS_PATH);\n const existing = readStoreEntry(directory, \"open Store session\");\n if (existing?.isFile()) {\n const legacy = readOwnerLease(directory, \"open legacy Store session\");\n if (!legacy) continue;\n if (ownerState(legacy) === \"dead\") {\n unlinkLeaseIfUnchanged(legacy);\n continue;\n }\n if (Date.now() >= deadline) {\n throw new StoreUnavailableError({ code: \"contention-timeout\", path: directory, operation: \"wait for legacy Store session\", retryable: true, attempts: attempt + 1, waitedMs: Date.now() - started, cause: `Process ${legacy.pid} is still active.` });\n }\n pause(attempt++, deadline);\n continue;\n }\n if (existing && !existing.isDirectory()) {\n throw new StoreUnavailableError(makeStoreIssue(\"unsafe-path\", directory, \"open Store session\", new Error(\"The Store access path is not a directory.\")));\n }\n if (existing?.isDirectory()) {\n try {\n recoverDeadStoreAccessSessions(storeRoot);\n } catch (error) {\n const code = error instanceof StoreUnavailableError ? error.issue.systemCode : systemCode(error);\n if (platform.kind === \"win32\" && new Set([\"EPERM\", \"EACCES\", \"EBUSY\"]).has(code ?? \"\") && Date.now() < deadline) {\n pause(attempt++, deadline);\n continue;\n }\n throw error;\n }\n }\n try {\n mkdirSync(directory, { mode: 0o700 });\n } catch (error) {\n if (systemCode(error) !== \"EEXIST\") throw new StoreUnavailableError(makeStoreIssue(\"io-error\", directory, \"create session directory\", error));\n }\n let directoryFd: number | null = null;\n try {\n directoryFd = openSync(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);\n const opened = fstatSync(directoryFd);\n const named = readStoreEntry(directory, \"verify session directory\");\n if (!named) {\n if (Date.now() < deadline) {\n pause(attempt++, deadline);\n continue;\n }\n throw Object.assign(new Error(\"The Store session directory disappeared.\"), { code: \"ENOENT\" });\n }\n if (named.isSymbolicLink() || !named.isDirectory()) {\n throw new StoreUnavailableError(makeStoreIssue(\"unsafe-path\", directory, \"verify session directory\", new Error(\"The Store session path is not a safe directory.\")));\n }\n if (!platform.sameFileObject(opened, named, \"directory\")) {\n if (Date.now() < deadline) {\n pause(attempt++, deadline);\n continue;\n }\n throw new StoreUnavailableError(makeStoreIssue(\"owner-unverified\", directory, \"verify session directory\", new Error(\"The Store session directory changed during admission.\")));\n }\n platform.applyPrivateMode(directoryFd, 0o700);\n } catch (error) {\n if (error instanceof StoreUnavailableError) throw error;\n const code = systemCode(error);\n if (code === \"ENOENT\" && Date.now() < deadline) {\n pause(attempt++, deadline);\n continue;\n }\n throw new StoreUnavailableError(makeStoreIssue(code === \"ELOOP\" ? \"unsafe-path\" : \"io-error\", directory, \"secure session directory\", error));\n } finally {\n if (directoryFd !== null) closeSync(directoryFd);\n }\n\n const token = randomUUID();\n const file = path.join(directory, `${token}.json`);\n const pendingFile = path.join(directory, storeSessionPendingName(process.pid, platform.hostname, token));\n let fd: number | null = null;\n let leaseStat: Stats | null = null;\n try {\n // O_EXCL makes an existing file or link fail. macOS rejects O_NOFOLLOW\n // when O_CREAT creates a new file, so it must not be used here.\n fd = openSync(pendingFile, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);\n platform.applyPrivateMode(fd, 0o600);\n writeFileSync(fd, JSON.stringify({ version: STORE_SESSION_VERSION, token, pid: process.pid, hostname: platform.hostname, startedAt: new Date().toISOString() }));\n fsyncSync(fd);\n leaseStat = fstatSync(fd);\n platform.atomicReplace(pendingFile, file);\n const lateBlocker = exclusiveBlocker(storeRoot, preparing);\n if (lateBlocker) {\n closeSync(fd);\n fd = null;\n removeOwnedSession(file, token, leaseStat, \"cancel Store session\");\n cleanupAccessDirectory(directory);\n if (lateBlocker.pid === process.pid && lateBlocker.hostname === platform.hostname) {\n throw new StoreUnavailableError({ code: \"contention-timeout\", path: lateBlocker.file, operation: \"open a Store session\", retryable: false, attempts: attempt + 1, waitedMs: Date.now() - started, cause: \"This process already owns the exclusive Store lock.\" });\n }\n if (ownerState(lateBlocker) !== \"alive\") {\n throw new StoreUnavailableError(makeStoreIssue(\"owner-unverified\", lateBlocker.file, \"wait for Store maintenance\", new Error(\"A stopped maintenance owner requires lease recovery.\")));\n }\n if (Date.now() >= deadline) {\n throw new StoreUnavailableError({ code: \"contention-timeout\", path: lateBlocker.file, operation: \"wait for Store maintenance\", retryable: true, attempts: attempt + 1, waitedMs: Date.now() - started, cause: `Process ${lateBlocker.pid} is still active.` });\n }\n pause(attempt++, deadline);\n continue;\n }\n\n let released = false;\n const lease = { count: 1, release: () => {} };\n const release = () => {\n if (released || --lease.count > 0) return;\n released = true;\n accessLeases.delete(storeRoot);\n try {\n removeOwnedSession(file, token, leaseStat, \"release Store session\");\n cleanupAccessDirectory(directory);\n } finally {\n if (fd !== null) closeSync(fd);\n }\n };\n lease.release = release;\n accessLeases.set(storeRoot, lease);\n return release;\n } catch (error) {\n if (fd !== null) closeSync(fd);\n removeOwnedSession(file, token, leaseStat, \"clean failed Store session\");\n removePendingSession(pendingFile, leaseStat);\n cleanupAccessDirectory(directory);\n if (error instanceof StoreUnavailableError) throw error;\n const code = systemCode(error);\n const retryableSessionOpenError = new Set([\"ENOENT\", \"EEXIST\", \"ENOTEMPTY\"]).has(code ?? \"\")\n || (platform.kind === \"darwin\" && code === \"EINVAL\");\n if (retryableSessionOpenError && Date.now() < deadline) {\n pause(attempt++, deadline);\n continue;\n }\n throw new StoreUnavailableError(makeStoreIssue(\"io-error\", file, \"open Store session\", error, { attempts: attempt + 1, waitedMs: Date.now() - started }));\n }\n }\n}\n\nexport interface StoreCheckpoint9MigrationResult {\n databasePath: string;\n previousSchemaVersion: number | null;\n schemaVersion: number;\n migrated: boolean;\n journal: StoreCheckpoint9JournalEntry | null;\n /** Verified pre-conversion Store backup. Null for a fresh or current Store. */\n backupPath: string | null;\n}\n\nexport type StoreCheckpoint9Requirement =\n | \"absent\"\n | \"current\"\n | \"migration-required\";\n\nconst VERSION_ONE_TABLES = [\"playbook_runs\", \"projects\", \"work_evidence\"] as const;\nconst VERSION_TWO_TABLES = [\n ...VERSION_ONE_TABLES,\n \"run_evidence\",\n \"runs\",\n \"store_checkpoint_journal\",\n] as const;\n\nconst VERSION_THREE_TABLES = [...VERSION_TWO_TABLES, \"installation_checkouts\", \"installation_ledgers\", \"installation_operations\", \"installation_steps\", \"installation_locks\", \"installation_migration_records\", \"installation_transfers\", \"tool_operations\", \"store_schema_journal\"] as const;\nconst VERSION_FOUR_TABLES = VERSION_THREE_TABLES;\nconst VERSION_FIVE_TABLES = [...VERSION_FOUR_TABLES, \"store_migration_receipts\"] as const;\nconst VERSION_SIX_TABLES = [...VERSION_FIVE_TABLES, \"backlog_review_cache\"] as const;\n\n/** Classifies the Store without creating a directory, database, sidecar, or table. */\nexport function classifyStoreCheckpoint9State(\n storeRoot: string,\n): StoreCheckpoint9Classification {\n const databasePath = getStoreDatabasePath(storeRoot);\n let databaseEntry: Stats | null;\n try {\n databaseEntry = readStoreEntry(databasePath, \"inspect Store database\");\n } catch (error) {\n const issue = error instanceof StoreUnavailableError\n ? error.issue\n : makeStoreIssue(\"io-error\", databasePath, \"inspect Store database\", error);\n return { state: \"indeterminate\", databasePath, schemaVersion: null, reason: issue.cause, issue };\n }\n if (!databaseEntry) {\n return { state: \"absent\", databasePath, schemaVersion: null };\n }\n if (databaseEntry.isSymbolicLink() || !databaseEntry.isFile()) {\n const issue = makeStoreIssue(\n \"unsafe-path\",\n databasePath,\n \"inspect Store database\",\n new Error(databaseEntry.isSymbolicLink()\n ? \"The Store database is a symbolic link.\"\n : \"The Store database path is not a file.\"),\n );\n return { state: \"indeterminate\", databasePath, schemaVersion: null, reason: issue.cause, issue };\n }\n const driver = loadSqliteDriver();\n if (!driver.available) {\n const issue: StoreIssue = {\n code: \"sqlite-unavailable\",\n path: databasePath,\n operation: \"open\",\n retryable: false,\n attempts: 1,\n waitedMs: 0,\n cause: driver.reason,\n };\n return {\n state: \"indeterminate\",\n databasePath,\n schemaVersion: null,\n reason: driver.reason,\n issue,\n };\n }\n let db: StoreDatabase | null = null;\n try {\n db = openSqliteWithRetry(driver.sqlite, databasePath, { readOnly: true }, \"inspect\", (connection) => {\n connection.exec(`PRAGMA busy_timeout = ${STORE_BUSY_TIMEOUT_MS}`);\n });\n const check = db.prepare(\"PRAGMA quick_check\").get() as\n | { quick_check?: string }\n | undefined;\n if (check?.quick_check !== \"ok\") {\n const reason = `SQLite quick_check returned ${String(check?.quick_check ?? \"no result\")}`;\n return {\n state: \"corrupt\",\n databasePath,\n schemaVersion: null,\n reason,\n issue: { code: \"corrupt\", path: databasePath, operation: \"check Store database\", retryable: false, attempts: 1, waitedMs: 0, cause: reason },\n };\n }\n const schemaVersion = readUserVersion(db);\n if (schemaVersion > CURRENT_STORE_SCHEMA_VERSION) {\n const reason = `schema version ${schemaVersion} is newer than supported version ${CURRENT_STORE_SCHEMA_VERSION}`;\n return {\n state: \"newer-unknown\",\n databasePath,\n schemaVersion,\n reason,\n issue: { code: \"schema-newer\", path: databasePath, operation: \"read schema\", retryable: false, attempts: 1, waitedMs: 0, cause: reason },\n };\n }\n if (schemaVersion !== 1 && schemaVersion !== 2 && schemaVersion !== 3 && schemaVersion !== 4 && schemaVersion !== 5 && schemaVersion !== CURRENT_STORE_SCHEMA_VERSION) {\n const reason = `schema version ${schemaVersion} is not a supported checkpoint-9 input`;\n return {\n state: \"unknown\",\n databasePath,\n schemaVersion,\n reason,\n issue: { code: \"schema-unknown\", path: databasePath, operation: \"read schema\", retryable: false, attempts: 1, waitedMs: 0, cause: reason },\n };\n }\n const expectedTables = schemaVersion === 1\n ? VERSION_ONE_TABLES\n : schemaVersion === 2\n ? VERSION_TWO_TABLES\n : schemaVersion === 3\n ? VERSION_THREE_TABLES\n : schemaVersion === 4\n ? VERSION_FOUR_TABLES\n : schemaVersion === 5\n ? VERSION_FIVE_TABLES\n : VERSION_SIX_TABLES;\n const actualTables = new Set(\n (db.prepare(\"SELECT name FROM sqlite_schema WHERE type = 'table'\").all() as Array<{ name: string }>)\n .map((row) => row.name),\n );\n const missingTables = expectedTables.filter((name) => !actualTables.has(name));\n if (missingTables.length > 0) {\n const reason = `required schema objects are missing: ${missingTables.join(\", \")}`;\n return {\n state: \"unknown\",\n databasePath,\n schemaVersion,\n reason,\n issue: { code: \"schema-unknown\", path: databasePath, operation: \"read schema\", retryable: false, attempts: 1, waitedMs: 0, cause: reason },\n };\n }\n return schemaVersion < CURRENT_STORE_SCHEMA_VERSION\n ? { state: \"supported-legacy\", databasePath, schemaVersion: schemaVersion as 1 | 2 | 3 | 4 | 5 }\n : { state: \"supported-current\", databasePath, schemaVersion: 6 };\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n const corrupt = isCorruptDatabaseMessage(reason);\n const contention = isSqliteContention(error);\n const issue = error instanceof StoreUnavailableError\n ? error.issue\n : makeStoreIssue(corrupt ? \"corrupt\" : contention ? \"contention-timeout\" : \"io-error\", databasePath, \"inspect\", error, contention ? { retryable: true, waitedMs: STORE_BUSY_TIMEOUT_MS } : {});\n return {\n state: corrupt ? \"corrupt\" : \"indeterminate\",\n databasePath,\n schemaVersion: null,\n reason,\n issue,\n };\n } finally {\n closeQuietly(db);\n }\n}\n\n/**\n * Inspects an existing Store without recovery or schema writes. Checkpoint 9\n * uses this before fresh-project and no-op install paths.\n */\nexport function inspectStoreCheckpoint9Requirement(\n storeRoot: string,\n): StoreCheckpoint9Requirement {\n const classification = classifyStoreCheckpoint9State(storeRoot);\n if (classification.state === \"absent\") return \"absent\";\n if (classification.state === \"supported-current\") return \"current\";\n if (classification.state === \"supported-legacy\") return \"migration-required\";\n throw new StoreCheckpoint9StateError(classification);\n}\n\n/**\n * The only explicit checkpoint-9 Store migration entry point. Callers invoke\n * it inside the reviewed immutable migration coordinator.\n */\nexport function migrateStoreDatabaseAtCheckpoint9(\n storeRoot: string,\n journal: StoreCheckpoint9JournalEntry,\n): StoreCheckpoint9MigrationResult {\n const classification = classifyStoreCheckpoint9State(storeRoot);\n if (\n classification.state !== \"absent\" &&\n classification.state !== \"supported-legacy\" &&\n classification.state !== \"supported-current\"\n ) {\n throw new StoreCheckpoint9StateError(classification);\n }\n assertCheckpoint9JournalEntry(journal);\n const driver = loadSqliteDriver();\n if (!driver.available) throw new StoreUnavailableError({ code: \"sqlite-unavailable\", path: getStoreDatabasePath(storeRoot), operation: \"migrate Store\", retryable: false, attempts: 1, waitedMs: 0, cause: driver.reason });\n mkdirSync(storeRoot, { recursive: true });\n const databasePath = getStoreDatabasePath(storeRoot);\n const db = connect(driver.sqlite, databasePath, classification.state !== \"absent\");\n let startingVersion: number | null = null;\n let backupPath: string | null = null;\n try {\n startingVersion = readUserVersion(db);\n if (startingVersion > 0 && startingVersion < CURRENT_STORE_SCHEMA_VERSION) {\n assertStoreBridgeInputSafe(db, startingVersion);\n backupPath = createVerifiedStoreBridgeBackup(db, databasePath, startingVersion);\n }\n db.exec(\"BEGIN IMMEDIATE\");\n assertCheckpoint9StateInsideTransaction(db, databasePath, startingVersion);\n if (startingVersion === CURRENT_STORE_SCHEMA_VERSION) {\n db.exec(\"COMMIT\");\n return {\n databasePath,\n previousSchemaVersion: startingVersion,\n schemaVersion: CURRENT_STORE_SCHEMA_VERSION,\n migrated: false,\n journal: null,\n backupPath: null,\n };\n }\n for (const migration of STORE_MIGRATIONS) {\n if (migration.version <= startingVersion) continue;\n executeStoreMigrationStatements(db, migration);\n }\n db.prepare(\n `INSERT INTO store_migration_receipts\n (receipt_id, operation, project_root_digest, source_schema_version,\n target_schema_version, snapshot_id, result, committed_at, receipt_json)\n VALUES (?, 'store.schema.migrate', ?, ?, ?, ?, 'completed', ?, ?)`,\n ).run(\n journal.receiptId,\n journal.projectRootDigest,\n startingVersion,\n CURRENT_STORE_SCHEMA_VERSION,\n journal.snapshotId,\n journal.committedAt,\n journal.receiptJson,\n );\n db.exec(`PRAGMA user_version = ${CURRENT_STORE_SCHEMA_VERSION}`);\n db.exec(\"COMMIT\");\n return {\n databasePath,\n previousSchemaVersion: classification.state === \"absent\" ? null : startingVersion,\n schemaVersion: CURRENT_STORE_SCHEMA_VERSION,\n migrated: true,\n journal,\n backupPath,\n };\n } catch (error) {\n try {\n db.exec(\"ROLLBACK\");\n } catch {\n // The transaction may already be closed.\n }\n throw error;\n } finally {\n closeQuietly(db);\n }\n}\n\nexport function readStoreCheckpoint9JournalEntry(\n storeRoot: string,\n projectRootDigest: string,\n): StoreCheckpoint9JournalEntry | null {\n const classification = classifyStoreCheckpoint9State(storeRoot);\n if (classification.state !== \"supported-current\") return null;\n const driver = loadSqliteDriver();\n if (!driver.available) throw new StoreUnavailableError({ code: \"sqlite-unavailable\", path: classification.databasePath, operation: \"read Store migration journal\", retryable: false, attempts: 1, waitedMs: 0, cause: driver.reason });\n const release = acquireStoreAccess(storeRoot);\n let db: StoreDatabase | null = null;\n try {\n db = openSqliteWithRetry(driver.sqlite, classification.databasePath, { readOnly: true }, \"read Store migration journal\", (connection) => {\n connection.exec(`PRAGMA busy_timeout = ${STORE_BUSY_TIMEOUT_MS}`);\n });\n const row = db.prepare(\n `SELECT receipt_id, checkpoint, project_root_digest, snapshot_id, committed_at, receipt_json\n FROM (\n SELECT receipt_id, 9 AS checkpoint, project_root_digest, snapshot_id, committed_at, receipt_json\n FROM store_migration_receipts\n WHERE operation = 'store.schema.migrate'\n UNION ALL\n SELECT receipt_id, checkpoint, project_root_digest, snapshot_id, committed_at, receipt_json\n FROM store_checkpoint_journal\n )\n WHERE project_root_digest = ? AND checkpoint = 9\n ORDER BY committed_at DESC, receipt_id DESC\n LIMIT 1`,\n ).get(projectRootDigest) as Record<string, unknown> | undefined;\n if (!row) return null;\n return {\n receiptId: String(row.receipt_id),\n checkpoint: 9,\n projectRootDigest: String(row.project_root_digest),\n snapshotId: String(row.snapshot_id),\n committedAt: String(row.committed_at),\n receiptJson: String(row.receipt_json),\n };\n } finally {\n closeQuietly(db);\n release();\n }\n}\n\n/**\n * Opens the store database, runs `fn`, and always closes the connection.\n * This is the standard access pattern: connections stay short-lived so no\n * process holds the write lock across user-visible waits.\n */\nexport function withStoreDatabase<T>(\n storeRoot: string,\n fn: (db: StoreDatabase, open: OpenStoreDatabaseResult) => T,\n): T {\n const open = openStoreDatabase(storeRoot);\n try {\n return fn(open.db, open);\n } finally {\n closeQuietly(open.db);\n }\n}\n\n/**\n * Applies all migrations above `fromVersion` in order, each inside a\n * `BEGIN IMMEDIATE` transaction paired with the `user_version` bump so a\n * migration either fully lands with its version or not at all (R-DB-2).\n */\nexport function applyStoreMigrations(db: StoreDatabase, fromVersion: number): number {\n const initialVersion = fromVersion;\n let version = fromVersion;\n for (const migration of STORE_MIGRATIONS) {\n if (migration.version <= version) {\n continue;\n }\n if (migration.version === 5 && initialVersion > 0) {\n assertStoreBridgeInputSafe(db, version);\n const row = db.prepare(\"PRAGMA database_list\").all() as Array<{ name: string; file: string }>;\n const databasePath = row.find((entry) => entry.name === \"main\")?.file ?? \"\";\n if (!databasePath) throw new Error(\"The Store compatibility bridge requires a file-backed database.\");\n createVerifiedStoreBridgeBackup(db, databasePath, version);\n }\n db.exec(\"BEGIN IMMEDIATE\");\n try {\n executeStoreMigrationStatements(db, migration);\n db.exec(`PRAGMA user_version = ${assertSchemaVersion(migration.version)}`);\n db.exec(\"COMMIT\");\n } catch (error) {\n try {\n db.exec(\"ROLLBACK\");\n } catch {\n // The transaction may already be rolled back.\n }\n throw error;\n }\n version = migration.version;\n }\n return version;\n}\n\nfunction assertStoreBridgeInputSafe(db: StoreDatabase, sourceVersion: number): void {\n if (sourceVersion < 3) return;\n const activeLocks = Number((db.prepare(\"SELECT COUNT(*) AS count FROM installation_locks\").get() as { count: number | bigint }).count);\n if (activeLocks > 0) {\n throw new Error(`The Store compatibility bridge found ${activeLocks} active installation lock(s). Finish the active writer and run setup again.`);\n }\n const pendingToolOperations = Number((db.prepare(\"SELECT COUNT(*) AS count FROM tool_operations WHERE status='pending'\").get() as { count: number | bigint }).count);\n if (pendingToolOperations > 0) {\n throw new Error(`The Store compatibility bridge found ${pendingToolOperations} pending tool operation(s). Recover them before schema conversion.`);\n }\n const collision = db.prepare(\n \"SELECT checkout_id FROM installation_migration_records WHERE kind='legacy-import' AND record_id IN ('w22-p5:checkout-object-numbers:v4','w22-p5:installation-ledger-projection:v4') LIMIT 1\",\n ).get() as { checkout_id: string } | undefined;\n if (collision) {\n throw new Error(`The Store compatibility bridge record already exists for checkout ${collision.checkout_id}. The source schema is unclear and was preserved.`);\n }\n const ledgers = db.prepare(\"SELECT checkout_id, manifest_json FROM installation_ledgers ORDER BY checkout_id\").all() as Array<{ checkout_id: string; manifest_json: string }>;\n for (const ledger of ledgers) {\n let value: unknown;\n try {\n value = JSON.parse(ledger.manifest_json);\n } catch {\n throw new Error(`The installation ledger for checkout ${ledger.checkout_id} is not valid JSON. The Store was preserved for review.`);\n }\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`The installation ledger for checkout ${ledger.checkout_id} has an unsupported shape. The Store was preserved for review.`);\n }\n }\n}\n\nfunction executeStoreMigrationStatements(db: StoreDatabase, migration: StoreMigration): void {\n for (const [index, statement] of migration.statements.entries()) {\n db.exec(statement);\n // The first schema-5 statement records intent. Conversion follows it and\n // stays inside the same SQLite transaction as verification and cutover.\n if (migration.version === 5 && index === 0) convertLegacyProjectionLedgerRows(db);\n }\n}\n\nfunction convertLegacyProjectionLedgerRows(db: StoreDatabase): void {\n const legacyFields = new Set([\n \"type\",\n \"resourcePath\",\n \"provenanceState\",\n \"providerPackage\",\n \"providerVersion\",\n \"providerImmutableRef\",\n \"materializationMode\",\n \"sourceDigest\",\n \"adoptionReceipt\",\n \"selectionTrigger\",\n \"operationLineage\",\n \"provenanceEvidence\",\n \"competingClaims\",\n ]);\n const rows = db.prepare(\"SELECT checkout_id, manifest_json FROM installation_ledgers ORDER BY checkout_id\").all() as Array<{ checkout_id: string; manifest_json: string }>;\n for (const row of rows) {\n const manifest = JSON.parse(row.manifest_json) as Record<string, unknown>;\n const projection = manifest.resourceProjection;\n if (!projection || typeof projection !== \"object\" || Array.isArray(projection)) continue;\n const target = structuredClone(manifest);\n const targetProjection = target.resourceProjection as Record<string, unknown>;\n let changed = false;\n for (const field of [\"selectedTypes\", \"provider\"]) {\n if (field in targetProjection) {\n delete targetProjection[field];\n changed = true;\n }\n }\n const resources = targetProjection.resources;\n if (resources && typeof resources === \"object\" && !Array.isArray(resources)) {\n for (const entry of Object.values(resources as Record<string, unknown>)) {\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) continue;\n for (const field of Object.keys(entry as Record<string, unknown>)) {\n if (!legacyFields.has(field)) continue;\n delete (entry as Record<string, unknown>)[field];\n changed = true;\n }\n }\n }\n if (!changed) continue;\n db.prepare(\n \"INSERT INTO installation_migration_records (checkout_id,kind,record_id,record_json) VALUES (?,'legacy-import','w22-p5:installation-ledger-projection:v4',?)\",\n ).run(row.checkout_id, row.manifest_json);\n db.prepare(\"UPDATE installation_ledgers SET manifest_json=?, updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE checkout_id=?\")\n .run(JSON.stringify(target), row.checkout_id);\n }\n}\n\nfunction createVerifiedStoreBridgeBackup(\n db: StoreDatabase,\n databasePath: string,\n sourceVersion: number,\n): string {\n const source = lstatSync(databasePath);\n const requiredBytes = BigInt(Math.max(source.size * 2, 1_048_576));\n const availableBytes = platform.availableBytes(path.dirname(databasePath));\n if (availableBytes < requiredBytes) {\n throw new Error(`The Store compatibility bridge needs at least ${requiredBytes} available bytes for a verified backup, but only ${availableBytes} are available.`);\n }\n const backupPath = `${databasePath}.bridge-v${sourceVersion}-to-v${CURRENT_STORE_SCHEMA_VERSION}-${randomUUID()}.backup`;\n const escaped = backupPath.replaceAll(\"'\", \"''\");\n db.exec(`VACUUM INTO '${escaped}'`);\n let backup: StoreDatabase | null = null;\n try {\n const driver = loadSqliteDriver();\n if (!driver.available) throw new Error(driver.reason);\n backup = openSqliteWithRetry(driver.sqlite, backupPath, { readOnly: true }, \"verify Store bridge backup\");\n const check = backup.prepare(\"PRAGMA quick_check\").get() as { quick_check?: string } | undefined;\n const backedUpVersion = readUserVersion(backup);\n if (check?.quick_check !== \"ok\" || backedUpVersion !== sourceVersion) {\n throw new Error(`The Store bridge backup did not verify as schema ${sourceVersion}.`);\n }\n return backupPath;\n } finally {\n closeQuietly(backup);\n }\n}\n\n/** Reads the recorded schema version (`PRAGMA user_version`). */\nexport function readUserVersion(db: StoreDatabase): number {\n const row = db.prepare(\"PRAGMA user_version\").get() as\n | { user_version?: number | bigint }\n | undefined;\n return Number(row?.user_version ?? 0);\n}\n\nfunction connect(sqlite: SqliteModule, databasePath: string, verify: boolean): StoreDatabase {\n return openSqliteWithRetry(sqlite, databasePath, {}, \"open\", (db) => {\n db.exec(`PRAGMA busy_timeout = ${STORE_BUSY_TIMEOUT_MS}`);\n db.exec(\"PRAGMA journal_mode = WAL\");\n db.exec(\"PRAGMA synchronous = NORMAL\");\n db.exec(\"PRAGMA foreign_keys = ON\");\n if (verify) {\n const check = db.prepare(\"PRAGMA quick_check\").get() as\n | { quick_check?: string }\n | undefined;\n if (check?.quick_check !== \"ok\") {\n throw new Error(\n `SQLite quick_check failed: ${String(check?.quick_check ?? \"unknown\")}`,\n );\n }\n }\n });\n}\n\nexport function isSqliteContention(error: unknown): boolean {\n const code = String((error as { code?: unknown; errcode?: unknown } | null)?.code ?? (error as { errcode?: unknown } | null)?.errcode ?? \"\");\n const message = error instanceof Error ? error.message : String(error);\n return /SQLITE_(BUSY|LOCKED|PROTOCOL)/i.test(code) || /database (?:is )?locked|database (?:is )?busy|locking protocol/i.test(message);\n}\n\nfunction openSqliteWithRetry(\n sqlite: SqliteModule,\n databasePath: string,\n options: { readOnly?: boolean },\n operation: string,\n initialize?: (db: StoreDatabase) => void,\n): StoreDatabase {\n const started = Date.now();\n const deadline = started + STORE_BUSY_TIMEOUT_MS;\n let attempt = 0;\n while (true) {\n let db: StoreDatabase | null = null;\n try {\n db = new sqlite.DatabaseSync(databasePath, options);\n initialize?.(db);\n return db;\n } catch (error) {\n closeQuietly(db);\n if (!isSqliteContention(error)) {\n if (error instanceof StoreUnavailableError) throw error;\n throw new StoreUnavailableError(makeStoreIssue(\"io-error\", databasePath, operation, error, { attempts: attempt + 1, waitedMs: Date.now() - started }));\n }\n if (Date.now() >= deadline) {\n throw new StoreUnavailableError(makeStoreIssue(\"contention-timeout\", databasePath, operation, error, { retryable: true, attempts: attempt + 1, waitedMs: Date.now() - started }));\n }\n pause(attempt++, deadline);\n }\n }\n}\n\n/** Open one SQLite connection with Store error detail and bounded contention retry. */\nexport function openStoreSqliteConnection(\n databasePath: string,\n options: { readOnly?: boolean } = {},\n operation = \"open\",\n): StoreDatabase {\n const driver = loadSqliteDriver();\n if (!driver.available) {\n throw new StoreUnavailableError({\n code: \"sqlite-unavailable\",\n path: databasePath,\n operation,\n retryable: false,\n attempts: 1,\n waitedMs: 0,\n cause: driver.reason,\n });\n }\n return openSqliteWithRetry(driver.sqlite, databasePath, options, operation, (db) => {\n db.exec(`PRAGMA busy_timeout = ${STORE_BUSY_TIMEOUT_MS}`);\n db.exec(\"PRAGMA foreign_keys = ON\");\n if (!options.readOnly) db.exec(\"PRAGMA synchronous = FULL\");\n });\n}\n\nfunction quarantineDatabase(databasePath: string): string {\n const stamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const quarantinedPath = `${databasePath}.corrupt-${stamp}`;\n platform.atomicReplace(databasePath, quarantinedPath);\n // Stale WAL/SHM sidecars must not be replayed against the fresh database.\n for (const suffix of [\"-wal\", \"-shm\"]) {\n rmSync(`${databasePath}${suffix}`, { force: true });\n }\n return quarantinedPath;\n}\n\nfunction assertSchemaVersion(version: number): number {\n if (!Number.isInteger(version) || version < 0) {\n throw new Error(`Invalid store schema version: ${String(version)}`);\n }\n return version;\n}\n\nfunction assertCheckpoint9StateInsideTransaction(\n db: StoreDatabase,\n databasePath: string,\n schemaVersion: number,\n): void {\n const check = db.prepare(\"PRAGMA quick_check\").get() as\n | { quick_check?: string }\n | undefined;\n if (check?.quick_check !== \"ok\") {\n throw new StoreCheckpoint9StateError({\n state: \"corrupt\",\n databasePath,\n schemaVersion: null,\n reason: `SQLite quick_check returned ${String(check?.quick_check ?? \"no result\")}`,\n });\n }\n if (schemaVersion > CURRENT_STORE_SCHEMA_VERSION) {\n throw new StoreCheckpoint9StateError({\n state: \"newer-unknown\",\n databasePath,\n schemaVersion,\n reason: `schema version ${schemaVersion} is newer than supported version ${CURRENT_STORE_SCHEMA_VERSION}`,\n });\n }\n if (schemaVersion !== 0 && schemaVersion !== 1 && schemaVersion !== 2 && schemaVersion !== 3 && schemaVersion !== 4 && schemaVersion !== 5 && schemaVersion !== CURRENT_STORE_SCHEMA_VERSION) {\n throw new StoreCheckpoint9StateError({\n state: \"unknown\",\n databasePath,\n schemaVersion,\n reason: `schema version ${schemaVersion} is not a supported checkpoint-9 input`,\n });\n }\n const expectedTables = schemaVersion === 1\n ? VERSION_ONE_TABLES\n : schemaVersion === 2\n ? VERSION_TWO_TABLES\n : schemaVersion === 3\n ? VERSION_THREE_TABLES\n : schemaVersion === 4\n ? VERSION_FOUR_TABLES\n : schemaVersion === 5\n ? VERSION_FIVE_TABLES\n : schemaVersion === CURRENT_STORE_SCHEMA_VERSION ? VERSION_SIX_TABLES : [];\n const actualTables = new Set(\n (db.prepare(\"SELECT name FROM sqlite_schema WHERE type = 'table'\").all() as Array<{ name: string }>)\n .map((row) => row.name),\n );\n const missingTables = expectedTables.filter((name) => !actualTables.has(name));\n if (missingTables.length > 0) {\n throw new StoreCheckpoint9StateError({\n state: \"unknown\",\n databasePath,\n schemaVersion,\n reason: `required schema objects are missing: ${missingTables.join(\", \")}`,\n });\n }\n}\n\nfunction assertCheckpoint9JournalEntry(entry: StoreCheckpoint9JournalEntry): void {\n if (\n !/^sha256:[0-9a-f]{64}$/.test(entry.receiptId) ||\n entry.checkpoint !== 9 ||\n !/^[0-9a-f]{64}$/.test(entry.projectRootDigest) ||\n !/^sha256:[0-9a-f]{64}$/.test(entry.snapshotId) ||\n entry.receiptJson.length < 2 ||\n entry.receiptJson.length > 16384\n ) {\n throw new Error(\"The checkpoint-9 journal entry is invalid or exceeds its metadata bound.\");\n }\n}\n\nfunction isCorruptDatabaseMessage(message: string): boolean {\n return /not a database|database disk image is malformed|file is not a database|malformed/i.test(message);\n}\n\nfunction closeQuietly(db: StoreDatabase | null): void {\n try {\n db?.close();\n } catch {\n // Closing an already-closed or failed connection is a no-op.\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { STORE_LEASE_RECOVERY_FILE } from \"./lease-recovery\";\nimport { platform, type FileMutationGuard } from \"../platform\";\n\nexport const GLOBAL_ASSET_LOCK_FILE = \"global-assets.lock\";\n\nexport interface GlobalAssetLock {\n storeRoot: string;\n lockPath: string;\n token: string;\n rootGuard: FileMutationGuard;\n lockGuard: FileMutationGuard;\n}\n\nconst held = new Map<string, { lock: GlobalAssetLock; depth: number }>();\n\nexport class GlobalAssetLockError extends Error {\n readonly code = \"writer-active\";\n constructor(message: string) { super(message); this.name = \"GlobalAssetLockError\"; }\n}\n\nfunction blocked(message: string): never { throw new GlobalAssetLockError(message); }\n\nfunction canonicalPath(input: string): string {\n try { return platform.describePath(input).canonicalPath; }\n catch { return blocked(\"The global asset Store path cannot be resolved.\"); }\n}\n\nfunction assertNoRemoval(root: string): void {\n for (const name of [\"removal.lock\", STORE_LEASE_RECOVERY_FILE]) {\n if (lstatSync(path.join(root, name), { throwIfNoEntry: false })) {\n blocked(\"The machine Make Docs Store is being removed or its leases need review. Global skill changes stopped.\");\n }\n }\n}\n\n/** One lock namespace for home skill targets, even when callers choose different Stores. */\nexport function acquireGlobalAssetLock(projectRoot: string): GlobalAssetLock {\n const requestedStoreRoot = path.join(platform.userDataRoot(), \".make-docs\");\n const requestedState = lstatSync(requestedStoreRoot, { throwIfNoEntry: false });\n if (requestedState && (!requestedState.isDirectory() || requestedState.isSymbolicLink()))\n blocked(\"The machine Make Docs Store must be a real directory.\");\n const storeRoot = canonicalPath(requestedStoreRoot);\n const checkout = canonicalPath(projectRoot);\n if (storeRoot === checkout || storeRoot.startsWith(`${checkout}${path.sep}`)) {\n blocked(\"The machine Make Docs Store is inside the target project. Global skill changes stopped.\");\n }\n const prior = lstatSync(storeRoot, { throwIfNoEntry: false });\n if (prior && (!prior.isDirectory() || prior.isSymbolicLink())) blocked(\"The machine Make Docs Store must be a real directory.\");\n assertNoRemoval(storeRoot);\n const existing = held.get(storeRoot);\n if (existing) { assertGlobalAssetLockActive(existing.lock); existing.depth += 1; return existing.lock; }\n mkdirSync(storeRoot, { recursive: true, mode: 0o700 });\n const rootStat = lstatSync(storeRoot);\n if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) blocked(\"The machine Make Docs Store changed before the global skill lock.\");\n const lockPath = path.join(storeRoot, GLOBAL_ASSET_LOCK_FILE);\n let fd: number;\n try { fd = openSync(lockPath, \"wx\", 0o600); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"EEXIST\") blocked(\"A global skill writer is active or needs recovery. Preserve its machine Store lease and review its owner.\");\n throw error;\n }\n const token = randomUUID();\n let lock: GlobalAssetLock | null = null;\n try {\n writeFileSync(fd, JSON.stringify({ token, pid: process.pid, hostname: platform.hostname }));\n fsyncSync(fd);\n lock = {\n storeRoot,\n lockPath,\n token,\n rootGuard: platform.captureFileGuard(rootStat, \"directory\"),\n lockGuard: platform.captureFileGuard(fstatSync(fd), \"file\"),\n };\n held.set(storeRoot, { lock, depth: 1 });\n assertGlobalAssetLockActive(lock);\n return lock;\n } catch (error) {\n held.delete(storeRoot);\n const current = lstatSync(lockPath, { throwIfNoEntry: false });\n if (current?.isFile() && !current.isSymbolicLink() &&\n (lock ? platform.matchesFileGuard(current, lock.lockGuard) : platform.sameFileObject(fstatSync(fd), current, \"file\"))) {\n unlinkSync(lockPath);\n }\n throw error;\n } finally { closeSync(fd); }\n}\n\nexport function assertGlobalAssetLockActive(lock: GlobalAssetLock): void {\n assertNoRemoval(lock.storeRoot);\n const root = lstatSync(lock.storeRoot, { throwIfNoEntry: false });\n const leaf = lstatSync(lock.lockPath, { throwIfNoEntry: false });\n if (!root?.isDirectory() || root.isSymbolicLink() || !platform.matchesFileGuard(root, lock.rootGuard) ||\n !leaf?.isFile() || leaf.isSymbolicLink() || !platform.matchesFileGuard(leaf, lock.lockGuard) || leaf.size > 16_384) {\n blocked(\"The global skill Store lease changed. Global skill changes stopped.\");\n }\n const fd = openSync(lock.lockPath, constants.O_RDONLY | constants.O_NOFOLLOW);\n try {\n const stat = fstatSync(fd);\n if (!platform.matchesFileGuard(stat, lock.lockGuard)) blocked(\"The global skill lease changed during inspection.\");\n const record = JSON.parse(readFileSync(fd, \"utf8\")) as Record<string, unknown>;\n if (record.token !== lock.token || record.pid !== process.pid || record.hostname !== platform.hostname) blocked(\"The global skill lease owner changed.\");\n } finally { closeSync(fd); }\n}\n\nexport function releaseGlobalAssetLock(lock: GlobalAssetLock): void {\n const entry = held.get(lock.storeRoot);\n if (!entry || entry.lock.token !== lock.token) return;\n if (entry.depth > 1) { entry.depth -= 1; return; }\n held.delete(lock.storeRoot);\n // Release only the exact file this process created. Preserve replacement leases.\n const root = lstatSync(lock.storeRoot, { throwIfNoEntry: false });\n if (!root?.isDirectory() || root.isSymbolicLink() || !platform.matchesFileGuard(root, lock.rootGuard)) return;\n const current = lstatSync(lock.lockPath, { throwIfNoEntry: false });\n if (current?.isFile() && !current.isSymbolicLink() && platform.matchesFileGuard(current, lock.lockGuard)) {\n try {\n const record = JSON.parse(readFileSync(lock.lockPath, \"utf8\")) as Record<string, unknown>;\n if (record.token === lock.token) unlinkSync(lock.lockPath);\n } catch { /* Preserve an unreadable or replaced lease. */ }\n }\n}\n","import { readInstallationManifest, saveInstallationManifest } from \"./store/installation-state\";\nimport { randomUUID } from \"node:crypto\";\nimport os from \"node:os\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/** Trusted bytes of the shipped contract retired by W19 R1 P8; never a current resource. */\nexport const RETIRED_PLAYBOOK_CONTRACT_PATH = \".make-docs/contracts/system/playbook-contract.md\";\nexport const RETIRED_PLAYBOOK_CONTRACT_HASH = \"3f7a1e18bedfb129ebba712a035dd08be413059b7402a6b29951417c1902ee11\";\n\nexport function hasTrustedRetiredPlaybookContractOwnership(\n entry: { hash?: string; sourceId?: string; ownershipClass?: string } | undefined,\n): boolean {\n return Boolean(entry && entry.sourceId === `file:${RETIRED_PLAYBOOK_CONTRACT_PATH}` &&\n entry.hash === RETIRED_PLAYBOOK_CONTRACT_HASH &&\n (entry.ownershipClass === undefined || entry.ownershipClass === \"managed-snapshot\"));\n}\nimport type {\n AgenticExposureMode,\n AgenticFileRole,\n AgenticOwnershipMetadata,\n AgenticPackagingProvenance,\n AgenticPathKind,\n AuditPathKind,\n AuditPathMetadata,\n Capability,\n InstallManifest,\n InstallProfile,\n InstallSelections,\n InstructionKind,\n ManifestAuditContext,\n ManifestAuditRecord,\n ManifestAdoptionReceipt,\n ManifestFileEntry,\n ManifestHashAlgorithm,\n ManifestLifecycleDisposition,\n ManifestOwnershipClass,\n ManifestProvenanceState,\n ManifestProvenanceClaim,\n SkillManifestSelectionSource,\n SkillSelectionProvenanceEntry,\n SkillExposureMetadata,\n ManifestSystemAssetEntry,\n PackageMeta,\n PluginManifestSelectionSource,\n PluginSelectionProvenanceEntry,\n PluginSourceKind,\n PluginSupportStatus,\n PluginTrustPolicy,\n PluginTrustPolicyKind,\n SystemAssetManifestState,\n SystemAssetMaterializationClass,\n SystemAssetMaterializationMode,\n SystemAssetOfflineExpectation,\n SystemAssetSelectionTrigger,\n ProjectResourceType,\n ResourceProjectionManifestState,\n RouterOwnershipManifestState,\n} from \"./types\";\nimport { classifyAgenticSkillFileRole } from \"./agentic-skill-roles\";\nimport {\n CAPABILITIES,\n HARNESSES,\n INSTRUCTION_KINDS,\n SYSTEM_ASSET_MATERIALIZATION_CLASSES,\n SYSTEM_ASSET_MATERIALIZATION_MODES,\n PROJECT_RESOURCE_TYPES,\n} from \"./types\";\nimport { parseManagedBlock } from \"./managed-block\";\nimport { resolveInstallProfile } from \"./profile\";\nimport {\n getConfiguredRouterPaths,\n getLegacyAssetsOnDemandRouterPaths,\n getLegacyIncompleteRouterPaths,\n getOnDemandRouterPaths,\n} from \"./router-paths\";\nimport { createEmptySystemAssetManifestState } from \"./system-assets\";\nimport {\n TOOL_DIRECTORY_CONFLICTS_RELATIVE_DIR,\n TOOL_DIRECTORY_MANIFEST_RELATIVE_PATH,\n TOOL_DIRECTORY_RELATIVE_PATH,\n} from \"./tool-directory\";\nimport {\n assertManagedPathHasNoSymlinks,\n hashText,\n normalizeRelativePath,\n readTextFile,\n writeTextFile,\n} from \"./utils\";\n\nexport const MANIFEST_SCHEMA_VERSION = 4;\nexport const MAKE_DOCS_STATE_RELATIVE_DIR = TOOL_DIRECTORY_RELATIVE_PATH;\nexport const MANIFEST_RELATIVE_PATH = TOOL_DIRECTORY_MANIFEST_RELATIVE_PATH;\nexport const CONFLICTS_RELATIVE_DIR = TOOL_DIRECTORY_CONFLICTS_RELATIVE_DIR;\n\nconst FIRST_PARTY_SKILL_MANIFEST_ID = \"make-docs.first-party\";\nconst FIRST_PARTY_SKILL_SELECTION_RENAMES = new Map([\n [\"software-factory\", \"factory\"],\n]);\n\nexport function getManifestPath(targetDir: string): string {\n return path.join(targetDir, MANIFEST_RELATIVE_PATH);\n}\n\n/**\n * Mints a stable project identifier (W18 R10; PRD 38 R-ID-1).\n *\n * D10 implementer decision: a random UUID (v4), minted exactly once at setup\n * and persisted in `.make-docs/manifest.json`. It is deliberately NOT derived\n * from the directory path, git remote, or any environment detail, so it is\n * stable across clones, moves, and worktrees by construction — the identifier\n * travels with the manifest file, and nothing about the machine or location\n * can change it. The full decision record lives in\n * `packages/cli/src/store/README.md` (Project identifier generation).\n *\n * Callers must never invoke this when a manifest already carries a\n * `projectId`; re-minting would orphan the project's global-store rows.\n */\nexport function mintProjectId(): string {\n return randomUUID();\n}\n\nexport function getManifestFileHash(relativePath: string, content: string | Buffer): string | null {\n if (!isInstructionManifestPath(relativePath)) {\n return hashText(content);\n }\n\n if (typeof content !== \"string\") return null;\n const parsed = parseManagedBlock(content);\n return parsed.state === \"valid\" && parsed.body !== null\n ? hashText(parsed.body)\n : null;\n}\n\nexport function getManifestFileHashForSourceSchema(\n relativePath: string,\n content: string | Buffer,\n sourceSchemaVersion: number | null,\n): string | null {\n if (!isInstructionManifestPath(relativePath)) {\n return hashText(content);\n }\n\n if (typeof content !== \"string\") return null;\n const parsed = parseManagedBlock(content);\n if (sourceSchemaVersion === 1) {\n return parsed.state === \"absent\" ? hashText(content) : null;\n }\n return parsed.state === \"valid\" && parsed.body !== null\n ? hashText(parsed.body)\n : null;\n}\n\nexport function loadManifest(targetDir: string): InstallManifest | null {\n const manifest = readInstallationManifest(targetDir);\n return manifest ? validateAndMigrateManifest(manifest, \"Make Docs Store installation ledger\") : null;\n}\n\n/** Legacy input only. Setup must verify and transfer it before managed mutation. */\nexport function loadLegacyManifest(targetDir: string): InstallManifest | null {\n assertManagedPathHasNoSymlinks(targetDir, MANIFEST_RELATIVE_PATH);\n const file = getManifestPath(targetDir);\n if (!existsSync(file)) return null;\n return validateAndMigrateManifest(JSON.parse(readTextFile(file)), file);\n}\n\nfunction migrateFirstPartySelectedSkills(\n selectedSkills: string[],\n skillManifest: SkillManifestSelectionSource | undefined,\n skillSelectionProvenance: SkillSelectionProvenanceEntry[] | undefined,\n): string[] {\n const usesBuiltInFirstPartyManifest =\n skillManifest?.manifestId === FIRST_PARTY_SKILL_MANIFEST_ID &&\n skillManifest.sourcePolicyKind === \"first-party\" &&\n skillManifest.source === \"built-in\";\n const hasFirstPartySelectionProof = skillSelectionProvenance?.some(\n (entry) =>\n entry.manifestId === FIRST_PARTY_SKILL_MANIFEST_ID &&\n entry.sourcePolicyKind === \"first-party\" &&\n entry.provenanceKind === \"first-party\" &&\n entry.skillName === \"software-factory\" &&\n entry.skillSource === \"embedded:software-factory\",\n );\n\n if (!usesBuiltInFirstPartyManifest && !hasFirstPartySelectionProof) {\n return selectedSkills;\n }\n\n return Array.from(\n new Set(\n selectedSkills.map(\n (name) => FIRST_PARTY_SKILL_SELECTION_RENAMES.get(name) ?? name,\n ),\n ),\n ).sort();\n}\n\nexport function migrateSelections(selections: unknown): InstallSelections {\n assertPlainObject(selections, \"selections\");\n assertNoRemovedAssetFields(selections, \"selections\");\n\n const legacy = selections;\n if (\"optionalSkills\" in legacy) {\n throw new Error(\"selections.optionalSkills is no longer supported\");\n }\n const skillHarnesses = legacy.skillHarnesses === undefined ? undefined : validateHarnesses(legacy.skillHarnesses);\n const skillManifest =\n \"skillManifest\" in legacy && legacy.skillManifest !== undefined\n ? validateSkillManifestSelectionSource(legacy.skillManifest)\n : undefined;\n const skillSelectionProvenance =\n \"skillSelectionProvenance\" in legacy &&\n legacy.skillSelectionProvenance !== undefined\n ? validateSkillSelectionProvenance(legacy.skillSelectionProvenance)\n : undefined;\n const selectedSkills = migrateFirstPartySelectedSkills(\n validateSelectedSkills(legacy.selectedSkills),\n skillManifest,\n skillSelectionProvenance,\n );\n const plugins =\n legacy.plugins === undefined\n ? false\n : validateBoolean(legacy.plugins, \"selections.plugins\");\n const pluginScope = validatePluginScope(legacy.pluginScope ?? \"project\");\n const selectedPlugins = validateSelectedPlugins(legacy.selectedPlugins ?? []);\n const pluginManifest =\n \"pluginManifest\" in legacy && legacy.pluginManifest !== undefined\n ? validatePluginManifestSelectionSource(legacy.pluginManifest)\n : undefined;\n const pluginSelectionProvenance =\n \"pluginSelectionProvenance\" in legacy &&\n legacy.pluginSelectionProvenance !== undefined\n ? validatePluginSelectionProvenance(legacy.pluginSelectionProvenance)\n : undefined;\n const resourceProjection =\n \"resourceProjection\" in legacy && legacy.resourceProjection !== undefined\n ? validateResourceProjectionSelection(legacy.resourceProjection)\n : undefined;\n\n if (legacy.instructionKinds && !legacy.harnesses) {\n assertPlainObject(legacy.instructionKinds, \"selections.instructionKinds\");\n const ik = legacy.instructionKinds;\n const migrated: InstallSelections = {\n capabilities: validateCapabilities(legacy.capabilities),\n harnesses: {\n \"claude-code\": validateBoolean(\n ik[\"CLAUDE.md\"] ?? false,\n \"selections.instructionKinds.CLAUDE.md\",\n ),\n codex: validateBoolean(\n ik[\"AGENTS.md\"] ?? false,\n \"selections.instructionKinds.AGENTS.md\",\n ),\n },\n skills:\n legacy.skills === undefined\n ? false\n : validateBoolean(legacy.skills, \"selections.skills\"),\n skillScope: validateSkillScope(legacy.skillScope ?? \"project\"),\n selectedSkills,\n ...(skillHarnesses === undefined ? {} : { skillHarnesses }),\n ...(skillManifest === undefined ? {} : { skillManifest }),\n ...(skillSelectionProvenance === undefined\n ? {}\n : { skillSelectionProvenance }),\n plugins,\n pluginScope,\n selectedPlugins,\n ...(pluginManifest === undefined ? {} : { pluginManifest }),\n ...(pluginSelectionProvenance === undefined\n ? {}\n : { pluginSelectionProvenance }),\n ...(resourceProjection === undefined ? {} : { resourceProjection }),\n };\n return migrated;\n }\n\n return {\n capabilities: validateCapabilities(legacy.capabilities),\n harnesses: validateHarnesses(legacy.harnesses),\n skills: validateBoolean(legacy.skills, \"selections.skills\"),\n skillScope: validateSkillScope(legacy.skillScope ?? \"project\"),\n selectedSkills,\n ...(skillHarnesses === undefined ? {} : { skillHarnesses }),\n ...(skillManifest === undefined ? {} : { skillManifest }),\n ...(skillSelectionProvenance === undefined\n ? {}\n : { skillSelectionProvenance }),\n plugins,\n pluginScope,\n selectedPlugins,\n ...(pluginManifest === undefined ? {} : { pluginManifest }),\n ...(pluginSelectionProvenance === undefined\n ? {}\n : { pluginSelectionProvenance }),\n ...(resourceProjection === undefined ? {} : { resourceProjection }),\n };\n}\n\nexport function createManifest(\n packageMeta: PackageMeta,\n profile: InstallProfile,\n files: Record<string, ManifestFileEntry>,\n skillFiles: string[],\n systemAssetMaterialization: SystemAssetManifestState,\n projectId: string,\n routerOwnership: RouterOwnershipManifestState,\n resourceProjection: ResourceProjectionManifestState,\n): InstallManifest {\n if (!routerOwnership || !resourceProjection) {\n throw new Error(\n \"Schema 4 manifests require router ownership and resource projection proof.\",\n );\n }\n return {\n schemaVersion: MANIFEST_SCHEMA_VERSION,\n projectId,\n packageName: packageMeta.name,\n packageVersion: packageMeta.version,\n updatedAt: new Date().toISOString(),\n profileId: profile.profileId,\n selections: profile.selections,\n effectiveCapabilities: profile.effectiveCapabilities,\n systemAssetMaterialization,\n routerOwnership,\n resourceProjection,\n files,\n skillFiles: Array.from(new Set(skillFiles)).sort(),\n };\n}\n\nexport function writeManifest(\n targetDir: string,\n manifest: InstallManifest,\n): string {\n return saveInstallationManifest(targetDir, manifest);\n}\n\nexport function getManifestAuditContext(\n targetDir: string,\n manifest: InstallManifest,\n homeDir = os.homedir(),\n): ManifestAuditContext {\n const managedFiles = Object.entries(manifest.files)\n .map(([managedPath, entry]) =>\n createManifestAuditRecord(\n targetDir,\n homeDir,\n managedPath,\n \"manifest-file\",\n entry,\n ),\n )\n .sort(compareAuditRecords);\n\n const skillFiles = Array.from(new Set(manifest.skillFiles))\n .map((managedPath) =>\n createManifestAuditRecord(\n targetDir,\n homeDir,\n managedPath,\n \"manifest-skill-file\",\n manifest.files[managedPath],\n ),\n )\n .sort(compareAuditRecords);\n\n return {\n manifestPath: getManifestPath(targetDir),\n managedFiles,\n skillFiles,\n priorSelections: structuredClone(manifest.selections),\n };\n}\n\nexport function createAuditPathMetadata(\n targetDir: string,\n auditPath: string,\n kind: AuditPathKind,\n homeDir = os.homedir(),\n): AuditPathMetadata {\n const normalizedTargetDir = path.resolve(targetDir);\n const absolutePath = path.isAbsolute(auditPath)\n ? path.normalize(auditPath)\n : path.resolve(normalizedTargetDir, auditPath);\n const normalizedHomeDir = path.resolve(homeDir);\n const projectRelativePath = getContainedRelativePath(\n normalizedTargetDir,\n absolutePath,\n );\n const homeRelativePath = getContainedRelativePath(\n normalizedHomeDir,\n absolutePath,\n );\n\n const pathScope =\n projectRelativePath !== null\n ? \"project\"\n : homeRelativePath !== null\n ? \"home\"\n : \"external\";\n const displayPath =\n pathScope === \"project\"\n ? normalizeRelativePath(projectRelativePath ?? auditPath)\n : normalizeRelativePath(absolutePath);\n const backupRelativePath =\n pathScope === \"project\"\n ? normalizeRelativePath(projectRelativePath ?? auditPath)\n : pathScope === \"home\"\n ? normalizeRelativePath(path.join(\"_home\", homeRelativePath ?? \"\"))\n : null;\n const depth =\n displayPath === \".\"\n ? 0\n : displayPath.split(\"/\").filter((segment) => segment.length > 0).length;\n const scopeOrder = pathScope === \"project\" ? 0 : pathScope === \"home\" ? 1 : 2;\n\n return {\n path: displayPath,\n absolutePath,\n kind,\n scope: pathScope,\n pathScope,\n backupRelativePath,\n backup: {\n scope: pathScope === \"external\" ? null : pathScope,\n relativePath: backupRelativePath,\n },\n ordering: {\n scopeOrder,\n depth,\n sortKey: `${scopeOrder}:${displayPath}`,\n pruneSortKey: `${scopeOrder}:${String(10_000 - depth).padStart(5, \"0\")}:${displayPath}`,\n },\n };\n}\n\nfunction migrateSkillFiles(skillFiles: unknown): string[] {\n if (Array.isArray(skillFiles)) {\n return skillFiles.filter(\n (value): value is string => typeof value === \"string\",\n );\n }\n\n if (isPlainObject(skillFiles)) {\n return Object.keys(skillFiles);\n }\n\n return [];\n}\n\nexport function validateAndMigrateManifest(\n value: unknown,\n manifestPath: string,\n): InstallManifest {\n try {\n assertPlainObject(value, \"manifest\");\n assertNoRemovedAssetFields(value, \"manifest\");\n\n if (!(\"skillFiles\" in value)) {\n throw new Error(\"manifest.skillFiles is required\");\n }\n\n const skillFiles = migrateSkillFiles(value.skillFiles);\n const selections = migrateSelections(value.selections);\n const files = validateManifestFiles(value.files);\n const packageName = validateString(value.packageName, \"manifest.packageName\");\n const packageVersion = validateString(value.packageVersion, \"manifest.packageVersion\");\n\n const schemaVersion = validateNumber(\n value.schemaVersion,\n \"manifest.schemaVersion\",\n );\n if (\n schemaVersion !== 1 &&\n schemaVersion !== 2 &&\n schemaVersion !== 3 &&\n schemaVersion !== MANIFEST_SCHEMA_VERSION\n ) {\n throw new Error(\n `manifest.schemaVersion must be 1, 2, 3, or ${MANIFEST_SCHEMA_VERSION}`,\n );\n }\n if (schemaVersion === MANIFEST_SCHEMA_VERSION) {\n if (!(\"routerOwnership\" in value) || value.routerOwnership === undefined) {\n throw new Error(\"manifest.routerOwnership is required for schemaVersion 4\");\n }\n if (!(\"resourceProjection\" in value) || value.resourceProjection === undefined) {\n throw new Error(\"manifest.resourceProjection is required for schemaVersion 4\");\n }\n }\n const systemAssetMaterialization =\n \"systemAssetMaterialization\" in value\n ? validateSystemAssetManifestState(value.systemAssetMaterialization)\n : createEmptySystemAssetManifestState();\n\n // Stable project identity (W18 R10; PRD 38 R-ID-1). Manifests written\n // before the identifier existed simply lack the field: they load\n // unchanged and stay fully valid — never rejected, never rewritten here.\n // The identifier is minted for them on the next install apply. A present\n // identifier is validated and preserved verbatim; it is never\n // regenerated or normalized.\n const projectId =\n \"projectId\" in value && value.projectId !== undefined\n ? validateProjectId(value.projectId)\n : undefined;\n const resourceProjection =\n \"resourceProjection\" in value && value.resourceProjection !== undefined\n ? validateResourceProjectionManifestState(\n value.resourceProjection,\n selections.resourceProjection,\n { name: packageName, version: packageVersion },\n files,\n systemAssetMaterialization,\n )\n : undefined;\n const routerOwnership =\n \"routerOwnership\" in value && value.routerOwnership !== undefined\n ? validateRouterOwnershipManifestState(\n value.routerOwnership,\n files,\n selections,\n { name: packageName, version: packageVersion },\n )\n : undefined;\n\n return {\n schemaVersion,\n ...(projectId === undefined ? {} : { projectId }),\n packageName,\n packageVersion,\n updatedAt: validateString(value.updatedAt, \"manifest.updatedAt\"),\n profileId: validateString(value.profileId, \"manifest.profileId\"),\n selections,\n effectiveCapabilities: validateEffectiveCapabilities(\n value.effectiveCapabilities,\n ),\n systemAssetMaterialization,\n ...(routerOwnership ? { routerOwnership } : {}),\n ...(resourceProjection ? { resourceProjection } : {}),\n files,\n skillFiles,\n };\n } catch (error) {\n const reason =\n error instanceof Error ? error.message : \"invalid manifest shape\";\n throw new Error(\n `Stale or malformed make-docs manifest at ${manifestPath}: ${reason}. Fix or remove the stale manifest and rerun bare \\`make-docs\\` to rebuild it.`,\n );\n }\n}\n\nfunction assertNoRemovedAssetFields(\n value: Record<string, unknown>,\n label: string,\n): void {\n for (const field of [\"prompts\", \"templatesMode\", \"referencesMode\"]) {\n if (field in value) {\n throw new Error(`${label}.${field} is no longer supported`);\n }\n }\n}\n\nfunction validateCapabilities(value: unknown): Record<Capability, boolean> {\n assertPlainObject(value, \"selections.capabilities\");\n const capabilities = {} as Record<Capability, boolean>;\n\n for (const capability of CAPABILITIES) {\n capabilities[capability] = validateBoolean(\n value[capability],\n `selections.capabilities.${capability}`,\n );\n }\n\n return capabilities;\n}\n\nfunction validateHarnesses(value: unknown): InstallSelections[\"harnesses\"] {\n assertPlainObject(value, \"selections.harnesses\");\n const harnesses = {} as InstallSelections[\"harnesses\"];\n\n for (const harness of HARNESSES) {\n harnesses[harness] = validateBoolean(\n value[harness],\n `selections.harnesses.${harness}`,\n );\n }\n\n return harnesses;\n}\n\nfunction validateSkillScope(value: unknown): InstallSelections[\"skillScope\"] {\n if (value !== \"project\" && value !== \"global\") {\n throw new Error(\"selections.skillScope must be project or global\");\n }\n\n return value;\n}\n\nfunction validatePluginScope(value: unknown): InstallSelections[\"pluginScope\"] {\n if (value !== \"project\" && value !== \"global\") {\n throw new Error(\"selections.pluginScope must be project or global\");\n }\n\n return value;\n}\n\nfunction validateManifestFiles(\n value: unknown,\n): Record<string, ManifestFileEntry> {\n assertPlainObject(value, \"manifest.files\");\n const files: Record<string, ManifestFileEntry> = {};\n\n for (const [managedPath, entry] of Object.entries(value)) {\n assertPlainObject(entry, `manifest.files.${managedPath}`);\n files[managedPath] = {\n hash: validateString(entry.hash, `manifest.files.${managedPath}.hash`),\n sourceId: validateString(\n entry.sourceId,\n `manifest.files.${managedPath}.sourceId`,\n ),\n ...(entry.ownershipClass === undefined\n ? {}\n : {\n ownershipClass: validateManifestOwnershipClass(\n entry.ownershipClass,\n `manifest.files.${managedPath}.ownershipClass`,\n ),\n }),\n ...(\"skillExposure\" in entry\n ? {\n skillExposure: validateSkillExposureMetadata(\n entry.skillExposure,\n `manifest.files.${managedPath}.skillExposure`,\n ),\n }\n : {}),\n ...(\"agenticOwnership\" in entry\n ? {\n agenticOwnership: validateAgenticOwnershipMetadata(\n entry.agenticOwnership,\n `manifest.files.${managedPath}.agenticOwnership`,\n ),\n }\n : {}),\n ...(\"systemAsset\" in entry\n ? {\n systemAsset: validateManifestSystemAssetEntry(\n entry.systemAsset,\n `manifest.files.${managedPath}.systemAsset`,\n ),\n }\n : {}),\n };\n }\n\n return files;\n}\n\nfunction validateSystemAssetManifestState(value: unknown): SystemAssetManifestState {\n assertPlainObject(value, \"manifest.systemAssetMaterialization\");\n const mode = validateSystemAssetMaterializationMode(\n value.mode,\n \"manifest.systemAssetMaterialization.mode\",\n );\n const localBootstrapPaths = validateStringArray(\n value.localBootstrapPaths,\n \"manifest.systemAssetMaterialization.localBootstrapPaths\",\n );\n const deferredSystemAssetPaths = validateStringArray(\n value.deferredSystemAssetPaths,\n \"manifest.systemAssetMaterialization.deferredSystemAssetPaths\",\n );\n const materializationClasses = validateMaterializationClasses(\n value.materializationClasses,\n );\n const assets = validateSystemAssetEntries(value.assets);\n\n return {\n mode,\n ...(\"sourcePackage\" in value\n ? {\n sourcePackage: validateString(\n value.sourcePackage,\n \"manifest.systemAssetMaterialization.sourcePackage\",\n ),\n }\n : {}),\n ...(\"sourceProvider\" in value\n ? {\n sourceProvider: validateString(\n value.sourceProvider,\n \"manifest.systemAssetMaterialization.sourceProvider\",\n ),\n }\n : {}),\n ...(\"sourceVersion\" in value\n ? {\n sourceVersion: validateString(\n value.sourceVersion,\n \"manifest.systemAssetMaterialization.sourceVersion\",\n ),\n }\n : {}),\n ...(\"sourceImmutableRef\" in value\n ? {\n sourceImmutableRef: validateString(\n value.sourceImmutableRef,\n \"manifest.systemAssetMaterialization.sourceImmutableRef\",\n ),\n }\n : {}),\n ...(\"hashAlgorithm\" in value\n ? {\n hashAlgorithm: validateHashAlgorithm(\n value.hashAlgorithm,\n \"manifest.systemAssetMaterialization.hashAlgorithm\",\n ),\n }\n : {}),\n localBootstrapPaths,\n deferredSystemAssetPaths,\n materializationClasses,\n recoveryGuidance: validateString(\n value.recoveryGuidance,\n \"manifest.systemAssetMaterialization.recoveryGuidance\",\n ),\n assets,\n };\n}\n\nfunction validateSystemAssetEntries(\n value: unknown,\n): Record<string, ManifestSystemAssetEntry> {\n assertPlainObject(value, \"manifest.systemAssetMaterialization.assets\");\n const assets: Record<string, ManifestSystemAssetEntry> = {};\n\n for (const [logicalAssetId, entry] of Object.entries(value)) {\n assets[logicalAssetId] = validateManifestSystemAssetEntry(\n entry,\n `manifest.systemAssetMaterialization.assets.${logicalAssetId}`,\n );\n }\n\n return assets;\n}\n\nfunction validateManifestSystemAssetEntry(\n value: unknown,\n label: string,\n): ManifestSystemAssetEntry {\n assertPlainObject(value, label);\n const materializationMode = validateSystemAssetMaterializationMode(\n value.materializationMode,\n `${label}.materializationMode`,\n );\n const hashAlgorithm = validateHashAlgorithm(value.hashAlgorithm, `${label}.hashAlgorithm`);\n const expectedHashes = validateStringArray(value.expectedHashes, `${label}.expectedHashes`);\n const materializationClass = validateMaterializationClass(\n value.materializationClass,\n `${label}.materializationClass`,\n );\n const offlineExpectation = validateOfflineExpectation(\n value.offlineExpectation,\n `${label}.offlineExpectation`,\n );\n const selectionTrigger = validateSelectionTrigger(\n value.selectionTrigger,\n `${label}.selectionTrigger`,\n );\n\n return {\n materializationMode,\n ...(\"sourcePackage\" in value\n ? { sourcePackage: validateString(value.sourcePackage, `${label}.sourcePackage`) }\n : {}),\n ...(\"sourceProvider\" in value\n ? { sourceProvider: validateString(value.sourceProvider, `${label}.sourceProvider`) }\n : {}),\n ...(\"sourceVersion\" in value\n ? { sourceVersion: validateString(value.sourceVersion, `${label}.sourceVersion`) }\n : {}),\n ...(\"sourceImmutableRef\" in value\n ? {\n sourceImmutableRef: validateString(\n value.sourceImmutableRef,\n `${label}.sourceImmutableRef`,\n ),\n }\n : {}),\n hashAlgorithm,\n expectedHashes,\n logicalAssetId: validateString(value.logicalAssetId, `${label}.logicalAssetId`),\n ...(\"localPath\" in value\n ? { localPath: validateString(value.localPath, `${label}.localPath`) }\n : {}),\n materializationClass,\n offlineExpectation,\n recoveryGuidance: validateString(value.recoveryGuidance, `${label}.recoveryGuidance`),\n selectionTrigger,\n };\n}\n\nfunction validateMaterializationClasses(\n value: unknown,\n): Record<string, SystemAssetMaterializationClass> {\n assertPlainObject(value, \"manifest.systemAssetMaterialization.materializationClasses\");\n const classes: Record<string, SystemAssetMaterializationClass> = {};\n\n for (const [logicalAssetId, materializationClass] of Object.entries(value)) {\n classes[logicalAssetId] = validateMaterializationClass(\n materializationClass,\n `manifest.systemAssetMaterialization.materializationClasses.${logicalAssetId}`,\n );\n }\n\n return classes;\n}\n\nfunction validateEffectiveCapabilities(value: unknown): Capability[] {\n if (!Array.isArray(value)) {\n throw new Error(\"manifest.effectiveCapabilities must be an array\");\n }\n\n return value.map((capability, index) => {\n if (\n typeof capability !== \"string\" ||\n !CAPABILITIES.includes(capability as Capability)\n ) {\n throw new Error(\n `manifest.effectiveCapabilities.${index} must be a valid capability`,\n );\n }\n return capability as Capability;\n });\n}\n\nfunction validateResourceProjectionSelection(value: unknown): ProjectResourceType[] {\n if (!Array.isArray(value)) {\n throw new Error(\"selections.resourceProjection must be an array\");\n }\n return Array.from(\n new Set(\n value.map((item, index) => {\n if (\n typeof item !== \"string\" ||\n !PROJECT_RESOURCE_TYPES.includes(item as ProjectResourceType)\n ) {\n throw new Error(\n `selections.resourceProjection.${index} must be contract, prompt, reference, or template`,\n );\n }\n return item as ProjectResourceType;\n }),\n ),\n ).sort();\n}\n\nfunction validateManifestOwnershipClass(\n value: unknown,\n label: string,\n): ManifestOwnershipClass {\n if (\n value !== \"managed-snapshot\" &&\n value !== \"managed-block\" &&\n value !== \"project-owned\" &&\n value !== \"runtime-state\" &&\n value !== \"selected-skill\" &&\n value !== \"installed-provider\" &&\n value !== \"managed-projection\" &&\n value !== \"project-override\"\n ) {\n throw new Error(`${label} must be a valid ownership class`);\n }\n return value;\n}\n\nfunction validateManifestProvenanceState(\n value: unknown,\n label: string,\n): ManifestProvenanceState {\n if (\n value !== \"verified\" &&\n value !== \"incomplete\" &&\n value !== \"ambiguous\" &&\n value !== \"contradictory\"\n ) {\n throw new Error(`${label} must be a valid provenance state`);\n }\n return value;\n}\n\nfunction validateLocalOwnershipProof(\n value: Record<string, unknown>,\n options: {\n label: string;\n packageMeta: PackageMeta;\n ownershipClass: \"managed-snapshot\" | \"project-owned\";\n expectedMaterializationMode: \"managed-block\";\n },\n) {\n const sourcePackage = validateString(value.sourcePackage, `${options.label}.sourcePackage`);\n const sourceVersion = validateString(value.sourceVersion, `${options.label}.sourceVersion`);\n const sourceImmutableRef = validateString(\n value.sourceImmutableRef,\n `${options.label}.sourceImmutableRef`,\n );\n if (\n sourcePackage !== options.packageMeta.name ||\n sourceVersion !== options.packageMeta.version ||\n sourceImmutableRef !== `package:${options.packageMeta.name}@${options.packageMeta.version}`\n ) {\n throw new Error(`${options.label} source identity must equal the manifest package`);\n }\n const provenanceState = validateManifestProvenanceState(\n value.provenanceState,\n `${options.label}.provenanceState`,\n );\n return {\n sourcePackage,\n sourceVersion,\n sourceImmutableRef,\n materializationMode: validateExactString(\n value.materializationMode,\n options.expectedMaterializationMode,\n `${options.label}.materializationMode`,\n ),\n provenanceState,\n provenanceEvidence: validateNonEmptyStringArray(\n value.provenanceEvidence,\n `${options.label}.provenanceEvidence`,\n ),\n competingClaims: validateProvenanceClaims(\n value.competingClaims,\n `${options.label}.competingClaims`,\n provenanceState,\n ),\n hashAlgorithm: validateExactString(\n value.hashAlgorithm,\n \"sha256\",\n `${options.label}.hashAlgorithm`,\n ),\n expectedSourceHash: validateSha256Digest(\n value.expectedSourceHash,\n `${options.label}.expectedSourceHash`,\n ),\n installedHash: validateSha256Digest(\n value.installedHash,\n `${options.label}.installedHash`,\n ),\n lastVerifiedAt: validateIsoTimestamp(\n value.lastVerifiedAt,\n `${options.label}.lastVerifiedAt`,\n ),\n lifecycleDisposition: validateLifecycleDisposition(\n value.lifecycleDisposition,\n `${options.label}.lifecycleDisposition`,\n ),\n adoptionReceipt: validateAdoptionReceipt(\n value.adoptionReceipt,\n `${options.label}.adoptionReceipt`,\n options.ownershipClass,\n ),\n };\n}\n\nfunction validateProvenanceClaims(\n value: unknown,\n label: string,\n state: ManifestProvenanceState,\n): ManifestProvenanceClaim[] {\n if (!Array.isArray(value)) {\n throw new Error(`${label} must be an array`);\n }\n const claims = value.map((claim, index) => {\n const claimLabel = `${label}.${index}`;\n assertPlainObject(claim, claimLabel);\n return {\n sourcePackage: validateString(claim.sourcePackage, `${claimLabel}.sourcePackage`),\n sourceVersion: validateString(claim.sourceVersion, `${claimLabel}.sourceVersion`),\n sourceImmutableRef: validateString(\n claim.sourceImmutableRef,\n `${claimLabel}.sourceImmutableRef`,\n ),\n evidenceRefs: validateNonEmptyStringArray(\n claim.evidenceRefs,\n `${claimLabel}.evidenceRefs`,\n ),\n };\n });\n const expectsClaims = state === \"ambiguous\" || state === \"contradictory\";\n if (expectsClaims && claims.length < 2) {\n throw new Error(`${label} must retain at least two evidenced source claims for ${state} provenance`);\n }\n if (!expectsClaims && claims.length !== 0) {\n throw new Error(`${label} must be empty unless provenance is ambiguous or contradictory`);\n }\n return claims;\n}\n\nfunction validateAdoptionReceipt(\n value: unknown,\n label: string,\n ownershipClass: \"managed-snapshot\" | \"project-owned\",\n): ManifestAdoptionReceipt | null {\n if (ownershipClass === \"managed-snapshot\") {\n if (value !== null) {\n throw new Error(`${label} must be null for managed-snapshot ownership`);\n }\n return null;\n }\n assertPlainObject(value, label);\n if (value.priorOwnershipClass !== \"managed-snapshot\") {\n throw new Error(`${label}.priorOwnershipClass must be managed-snapshot`);\n }\n return {\n receiptId: validateString(value.receiptId, `${label}.receiptId`),\n adoptedAt: validateIsoTimestamp(value.adoptedAt, `${label}.adoptedAt`),\n priorOwnershipClass: \"managed-snapshot\",\n evidenceRefs: validateNonEmptyStringArray(value.evidenceRefs, `${label}.evidenceRefs`),\n };\n}\n\nfunction validateNonEmptyStringArray(value: unknown, label: string): string[] {\n const values = validateStringArray(value, label);\n if (values.length === 0) {\n throw new Error(`${label} must not be empty`);\n }\n return values;\n}\n\nfunction validateExactString<T extends string>(value: unknown, expected: T, label: string): T {\n if (value !== expected) {\n throw new Error(`${label} must be ${expected}`);\n }\n return expected;\n}\n\nfunction validateIsoTimestamp(value: unknown, label: string): string {\n const timestamp = validateString(value, label);\n if (!/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{3})?Z$/.test(timestamp) || Number.isNaN(Date.parse(timestamp))) {\n throw new Error(`${label} must be an ISO 8601 UTC timestamp`);\n }\n return timestamp;\n}\n\nfunction validateLifecycleDisposition(value: unknown, label: string): ManifestLifecycleDisposition {\n if (\n value !== \"active\" &&\n value !== \"preserved-export\" &&\n value !== \"superseded-managed\" &&\n value !== \"conflict\"\n ) {\n throw new Error(`${label} must be a valid lifecycle disposition`);\n }\n return value;\n}\n\nfunction validateRouterOwnershipManifestState(\n value: unknown,\n files: Record<string, ManifestFileEntry>,\n selections: InstallSelections,\n packageMeta: PackageMeta,\n): RouterOwnershipManifestState {\n assertPlainObject(value, \"manifest.routerOwnership\");\n if (value.operationLineage !== \"W19 R1 P4\") {\n throw new Error(\"manifest.routerOwnership.operationLineage must be W19 R1 P4\");\n }\n const configuredHarnesses = validateStringArray(\n value.configuredHarnesses,\n \"manifest.routerOwnership.configuredHarnesses\",\n ).map((harness, index) => {\n if (!HARNESSES.includes(harness as (typeof HARNESSES)[number])) {\n throw new Error(\n `manifest.routerOwnership.configuredHarnesses.${index} must be a valid harness`,\n );\n }\n return harness as (typeof HARNESSES)[number];\n });\n if (new Set(configuredHarnesses).size !== configuredHarnesses.length) {\n throw new Error(\"manifest.routerOwnership.configuredHarnesses must not contain duplicates\");\n }\n const expectedHarnesses = configuredHarnesses.slice().sort();\n const selectedHarnesses = Object.entries(selections.harnesses)\n .filter(([, selected]) => selected)\n .map(([harness]) => harness as (typeof HARNESSES)[number])\n .sort();\n if (JSON.stringify(expectedHarnesses) !== JSON.stringify(selectedHarnesses)) {\n throw new Error(\n \"manifest.routerOwnership.configuredHarnesses must exactly equal selections.harnesses\",\n );\n }\n const profile = resolveInstallProfile(selections);\n assertPlainObject(value.routers, \"manifest.routerOwnership.routers\");\n const routers: RouterOwnershipManifestState[\"routers\"] = {};\n for (const [relativePath, rawEntry] of Object.entries(value.routers)) {\n assertPlainObject(rawEntry, `manifest.routerOwnership.routers.${relativePath}`);\n const entryPath = validateString(\n rawEntry.relativePath,\n `manifest.routerOwnership.routers.${relativePath}.relativePath`,\n );\n if (entryPath !== relativePath || normalizeRelativePath(entryPath) !== entryPath) {\n throw new Error(\n `manifest.routerOwnership.routers.${relativePath}.relativePath must equal its canonical map key`,\n );\n }\n const harness = validateString(\n rawEntry.harness,\n `manifest.routerOwnership.routers.${relativePath}.harness`,\n ) as (typeof HARNESSES)[number];\n if (!HARNESSES.includes(harness) || !expectedHarnesses.includes(harness)) {\n throw new Error(\n `manifest.routerOwnership.routers.${relativePath}.harness must be configured`,\n );\n }\n const instructionKind = validateString(\n rawEntry.instructionKind,\n `manifest.routerOwnership.routers.${relativePath}.instructionKind`,\n ) as InstructionKind;\n if (!INSTRUCTION_KINDS.includes(instructionKind)) {\n throw new Error(\n `manifest.routerOwnership.routers.${relativePath}.instructionKind must be valid`,\n );\n }\n const expectedInstruction =\n harness === \"codex\" ? \"AGENTS.md\" : \"CLAUDE.md\";\n if (instructionKind !== expectedInstruction) {\n throw new Error(\n `manifest.routerOwnership.routers.${relativePath}.instructionKind must match its harness`,\n );\n }\n if (rawEntry.ownershipClass !== \"managed-snapshot\" && rawEntry.ownershipClass !== \"project-owned\") {\n throw new Error(\n `manifest.routerOwnership.routers.${relativePath}.ownershipClass must be managed-snapshot or project-owned`,\n );\n }\n const routerClass = rawEntry.routerClass;\n if (routerClass !== \"bootstrap\" && routerClass !== \"on-demand-surface\") {\n throw new Error(\n `manifest.routerOwnership.routers.${relativePath}.routerClass must be bootstrap or on-demand-surface`,\n );\n }\n const allowedPaths = routerClass === \"bootstrap\"\n ? getConfiguredRouterPaths(profile, instructionKind)\n : getOnDemandRouterPaths(instructionKind);\n const isLegacyAssetsBootstrapPath = routerClass === \"bootstrap\" && relativePath === `docs/assets/${instructionKind}`;\n const isLegacyArtifactsPath = routerClass === \"on-demand-surface\" && relativePath === `docs/artifacts/${instructionKind}`;\n if (!allowedPaths.includes(relativePath) && !isLegacyAssetsBootstrapPath && !isLegacyArtifactsPath) {\n throw new Error(\n `manifest.routerOwnership.routers.${relativePath} is not an allowed ${routerClass} router path`,\n );\n }\n const sourceId = validateString(\n rawEntry.sourceId,\n `manifest.routerOwnership.routers.${relativePath}.sourceId`,\n );\n if (sourceId !== `router:${harness}:${relativePath}`) {\n throw new Error(\n `manifest.routerOwnership.routers.${relativePath}.sourceId must match its harness and path`,\n );\n }\n const expectedFileOwnership = rawEntry.ownershipClass === \"managed-snapshot\"\n ? \"managed-block\"\n : \"project-owned\";\n if (\n files[relativePath]?.sourceId !== sourceId ||\n files[relativePath]?.ownershipClass !== expectedFileOwnership\n ) {\n throw new Error(\n `manifest.routerOwnership.routers.${relativePath} must match manifest.files ownership`,\n );\n }\n const proof = validateLocalOwnershipProof(rawEntry, {\n label: `manifest.routerOwnership.routers.${relativePath}`,\n packageMeta,\n ownershipClass: rawEntry.ownershipClass,\n expectedMaterializationMode: \"managed-block\",\n });\n if (\n proof.expectedSourceHash !== files[relativePath]?.hash ||\n proof.installedHash !== files[relativePath]?.hash\n ) {\n throw new Error(\n `manifest.routerOwnership.routers.${relativePath} hashes must match manifest.files`,\n );\n }\n routers[relativePath] = {\n relativePath,\n harness,\n instructionKind,\n ownershipClass: rawEntry.ownershipClass,\n routerClass,\n sourceId,\n ...proof,\n };\n }\n const bootstrapPaths = Object.values(routers)\n .filter((router) => router.routerClass === \"bootstrap\")\n .map((router) => router.relativePath)\n .sort();\n const legacyBootstrapPaths = expectedHarnesses.flatMap((harness) => {\n const instructionKind = harness === \"codex\" ? \"AGENTS.md\" : \"CLAUDE.md\";\n return getLegacyIncompleteRouterPaths(instructionKind);\n }).sort();\n const isExactLegacyIncompleteInput =\n JSON.stringify(bootstrapPaths) === JSON.stringify(legacyBootstrapPaths);\n if (!isExactLegacyIncompleteInput) {\n for (const harness of expectedHarnesses) {\n const instructionKind = harness === \"codex\" ? \"AGENTS.md\" : \"CLAUDE.md\";\n for (const relativePath of getConfiguredRouterPaths(profile, instructionKind)) {\n if (!routers[relativePath]) {\n throw new Error(\n `manifest.routerOwnership.routers must include bootstrap router ${relativePath}`,\n );\n }\n }\n }\n }\n for (const [relativePath, file] of Object.entries(files)) {\n if (!file.sourceId.startsWith(\"router:\")) {\n continue;\n }\n const router = routers[relativePath];\n if (!router || router.sourceId !== file.sourceId) {\n throw new Error(\n `manifest.routerOwnership.routers must include managed router ${relativePath}`,\n );\n }\n }\n return {\n configuredHarnesses: expectedHarnesses,\n operationLineage: \"W19 R1 P4\",\n routers,\n };\n}\n\nfunction validateResourceProjectionManifestState(\n value: unknown,\n selectedResourceTypes: ProjectResourceType[] | undefined,\n packageMeta: PackageMeta,\n files: Record<string, ManifestFileEntry>,\n systemAssetMaterialization: SystemAssetManifestState,\n): ResourceProjectionManifestState {\n assertPlainObject(value, \"manifest.resourceProjection\");\n assertPlainObject(value.resources, \"manifest.resourceProjection.resources\");\n const legacy = \"selectedTypes\" in value || \"provider\" in value;\n if (legacy) {\n return validateLegacyResourceProjectionManifestState(\n value,\n selectedResourceTypes,\n packageMeta,\n files,\n systemAssetMaterialization,\n );\n }\n\n const selectedTypes = selectedResourceTypes ?? [];\n const resources: ResourceProjectionManifestState[\"resources\"] = {};\n const allowedFields = new Set([\n \"uri\",\n \"managedDestination\",\n \"ownershipClass\",\n \"installedDigest\",\n \"hashAlgorithm\",\n \"lastVerifiedAt\",\n \"lifecycleDisposition\",\n ]);\n for (const [uri, rawEntry] of Object.entries(value.resources)) {\n assertPlainObject(rawEntry, `manifest.resourceProjection.resources.${uri}`);\n const duplicateField = Object.keys(rawEntry).find((field) => !allowedFields.has(field));\n if (duplicateField) {\n throw new Error(\n `manifest.resourceProjection.resources.${uri}.${duplicateField} duplicates config or provider authority`,\n );\n }\n const entryUri = validateString(\n rawEntry.uri,\n `manifest.resourceProjection.resources.${uri}.uri`,\n );\n if (entryUri !== uri) {\n throw new Error(`manifest.resourceProjection.resources.${uri}.uri must equal its map key`);\n }\n const match = /^make-docs:\\/\\/system\\/(contract|prompt|reference|template)\\/(.+)$/.exec(uri);\n if (!match) {\n throw new Error(`manifest.resourceProjection.resources.${uri} must use a canonical system URI`);\n }\n const type = match[1] as ProjectResourceType;\n const resourcePath = validateCanonicalResourcePath(\n match[2],\n `manifest.resourceProjection.resources.${uri}.uri`,\n );\n if (!selectedTypes.includes(type)) {\n throw new Error(`manifest.resourceProjection.resources.${uri} must be selected by project config`);\n }\n const typeDirectory = {\n contract: \"contracts\",\n prompt: \"prompts\",\n reference: \"references\",\n template: \"templates\",\n }[type];\n const managedDestination = validateString(\n rawEntry.managedDestination,\n `manifest.resourceProjection.resources.${uri}.managedDestination`,\n );\n const canonicalDestination = `.make-docs/system/${typeDirectory}/${resourcePath}`;\n if (managedDestination !== canonicalDestination) {\n throw new Error(\n `manifest.resourceProjection.resources.${uri}.managedDestination must be ${canonicalDestination}`,\n );\n }\n const ownershipClass = rawEntry.ownershipClass;\n if (ownershipClass !== \"managed-snapshot\" && ownershipClass !== \"project-owned\") {\n throw new Error(\n `manifest.resourceProjection.resources.${uri}.ownershipClass must be managed-snapshot or project-owned`,\n );\n }\n const installedDigest = validateSha256Digest(\n rawEntry.installedDigest,\n `manifest.resourceProjection.resources.${uri}.installedDigest`,\n );\n if (rawEntry.hashAlgorithm !== \"sha256\") {\n throw new Error(`manifest.resourceProjection.resources.${uri}.hashAlgorithm must be sha256`);\n }\n const fileEntry = files[managedDestination];\n const expectedFileOwnership = ownershipClass === \"managed-snapshot\"\n ? \"managed-projection\"\n : \"project-owned\";\n if (\n fileEntry?.sourceId !== `resource:${uri}` ||\n fileEntry.ownershipClass !== expectedFileOwnership ||\n fileEntry.hash !== installedDigest\n ) {\n throw new Error(\n `manifest.resourceProjection.resources.${uri} must match managed manifest.files ownership`,\n );\n }\n resources[uri] = {\n uri: entryUri,\n managedDestination,\n ownershipClass,\n installedDigest,\n hashAlgorithm: \"sha256\",\n lastVerifiedAt: validateIsoTimestamp(\n rawEntry.lastVerifiedAt,\n `manifest.resourceProjection.resources.${uri}.lastVerifiedAt`,\n ),\n lifecycleDisposition: validateLifecycleDisposition(\n rawEntry.lifecycleDisposition,\n `manifest.resourceProjection.resources.${uri}.lifecycleDisposition`,\n ),\n };\n }\n assertCompleteResourceProjection(resources, selectedTypes, files, systemAssetMaterialization);\n return { resources };\n}\n\nfunction validateLegacyResourceProjectionManifestState(\n value: Record<string, unknown>,\n selectedResourceTypes: ProjectResourceType[] | undefined,\n packageMeta: PackageMeta,\n files: Record<string, ManifestFileEntry>,\n systemAssetMaterialization: SystemAssetManifestState,\n): ResourceProjectionManifestState {\n assertPlainObject(value, \"manifest.resourceProjection\");\n const selectedTypes = validateResourceProjectionSelection(value.selectedTypes);\n if (\n JSON.stringify(selectedTypes) !== JSON.stringify(selectedResourceTypes ?? [])\n ) {\n throw new Error(\n \"manifest.resourceProjection.selectedTypes must equal selections.resourceProjection\",\n );\n }\n assertPlainObject(value.provider, \"manifest.resourceProjection.provider\");\n assertPlainObject(value.resources, \"manifest.resourceProjection.resources\");\n if (\n value.provider.ownershipClass !== \"installed-provider\" ||\n value.provider.provenanceState !== \"verified\"\n ) {\n throw new Error(\n \"manifest.resourceProjection.provider must have installed-provider ownership and verified provenance\",\n );\n }\n const provider = {\n ownershipClass: \"installed-provider\" as const,\n provenanceState: \"verified\" as const,\n packageName: validateString(\n value.provider.packageName,\n \"manifest.resourceProjection.provider.packageName\",\n ),\n version: validateString(\n value.provider.version,\n \"manifest.resourceProjection.provider.version\",\n ),\n immutableRef: validateString(\n value.provider.immutableRef,\n \"manifest.resourceProjection.provider.immutableRef\",\n ),\n inventoryDigest: validateSha256Digest(\n value.provider.inventoryDigest,\n \"manifest.resourceProjection.provider.inventoryDigest\",\n ),\n };\n const resources: ResourceProjectionManifestState[\"resources\"] = {};\n for (const [uri, rawEntry] of Object.entries(value.resources)) {\n assertPlainObject(rawEntry, `manifest.resourceProjection.resources.${uri}`);\n const type = validateResourceProjectionSelection([rawEntry.type])[0];\n if (!type) {\n throw new Error(`manifest.resourceProjection.resources.${uri}.type is required`);\n }\n const entryUri = validateString(\n rawEntry.uri,\n `manifest.resourceProjection.resources.${uri}.uri`,\n );\n if (entryUri !== uri) {\n throw new Error(\n `manifest.resourceProjection.resources.${uri}.uri must equal its map key`,\n );\n }\n if (!selectedTypes.includes(type)) {\n throw new Error(\n `manifest.resourceProjection.resources.${uri}.type must be selected`,\n );\n }\n const resourcePath = validateCanonicalResourcePath(\n rawEntry.resourcePath,\n `manifest.resourceProjection.resources.${uri}.resourcePath`,\n );\n const managedDestination = validateString(\n rawEntry.managedDestination,\n `manifest.resourceProjection.resources.${uri}.managedDestination`,\n );\n const typeDirectory = {\n contract: \"contracts\",\n prompt: \"prompts\",\n reference: \"references\",\n template: \"templates\",\n }[type];\n const canonicalDestination = `.make-docs/system/${typeDirectory}/${resourcePath}`;\n const canonicalUri = `make-docs://system/${type}/${resourcePath}`;\n if (uri !== canonicalUri || entryUri !== canonicalUri) {\n throw new Error(\n `manifest.resourceProjection.resources.${uri} must use canonical URI ${canonicalUri}`,\n );\n }\n if (managedDestination !== canonicalDestination) {\n throw new Error(\n `manifest.resourceProjection.resources.${uri}.managedDestination must be ${canonicalDestination}`,\n );\n }\n const ownershipClass = rawEntry.ownershipClass;\n if (ownershipClass !== \"managed-snapshot\" && ownershipClass !== \"project-owned\") {\n throw new Error(\n `manifest.resourceProjection.resources.${uri}.ownershipClass must be managed-snapshot or project-owned`,\n );\n }\n const selectionTrigger = rawEntry.selectionTrigger;\n if (selectionTrigger !== \"setup-selection\" && selectionTrigger !== \"reconfigure-selection\") {\n throw new Error(\n `manifest.resourceProjection.resources.${uri}.selectionTrigger must be setup-selection or reconfigure-selection`,\n );\n }\n if (rawEntry.operationLineage !== \"W19 R1 P4\") {\n throw new Error(\n `manifest.resourceProjection.resources.${uri}.operationLineage must be W19 R1 P4`,\n );\n }\n if (rawEntry.hashAlgorithm !== \"sha256\") {\n throw new Error(\n `manifest.resourceProjection.resources.${uri}.hashAlgorithm must be sha256`,\n );\n }\n const providerPackage = validateString(\n rawEntry.providerPackage,\n `manifest.resourceProjection.resources.${uri}.providerPackage`,\n );\n const providerVersion = validateString(\n rawEntry.providerVersion,\n `manifest.resourceProjection.resources.${uri}.providerVersion`,\n );\n const providerImmutableRef = validateString(\n rawEntry.providerImmutableRef,\n `manifest.resourceProjection.resources.${uri}.providerImmutableRef`,\n );\n if (\n providerPackage !== provider.packageName ||\n providerVersion !== provider.version ||\n providerImmutableRef !== provider.immutableRef\n ) {\n throw new Error(\n `manifest.resourceProjection.resources.${uri} provider identity must equal manifest.resourceProjection.provider`,\n );\n }\n if (\n providerPackage !== packageMeta.name ||\n providerVersion !== packageMeta.version\n ) {\n throw new Error(\n `manifest.resourceProjection.resources.${uri} provider identity must equal the manifest package`,\n );\n }\n const provenanceState = validateManifestProvenanceState(\n rawEntry.provenanceState,\n `manifest.resourceProjection.resources.${uri}.provenanceState`,\n );\n const provenanceEvidence = validateNonEmptyStringArray(\n rawEntry.provenanceEvidence,\n `manifest.resourceProjection.resources.${uri}.provenanceEvidence`,\n );\n const competingClaims = validateProvenanceClaims(\n rawEntry.competingClaims,\n `manifest.resourceProjection.resources.${uri}.competingClaims`,\n provenanceState,\n );\n const adoptionReceipt = validateAdoptionReceipt(\n rawEntry.adoptionReceipt,\n `manifest.resourceProjection.resources.${uri}.adoptionReceipt`,\n ownershipClass,\n );\n const sourceDigest = validateSha256Digest(\n rawEntry.sourceDigest,\n `manifest.resourceProjection.resources.${uri}.sourceDigest`,\n );\n const installedDigest = validateSha256Digest(\n rawEntry.installedDigest,\n `manifest.resourceProjection.resources.${uri}.installedDigest`,\n );\n const fileEntry = files[managedDestination];\n const expectedFileOwnership = ownershipClass === \"managed-snapshot\"\n ? \"managed-projection\"\n : \"project-owned\";\n if (\n fileEntry?.sourceId !== `resource:${uri}` ||\n fileEntry.ownershipClass !== expectedFileOwnership ||\n fileEntry.hash !== installedDigest\n ) {\n throw new Error(\n `manifest.resourceProjection.resources.${uri} must match managed manifest.files ownership`,\n );\n }\n resources[uri] = {\n uri: entryUri,\n type,\n resourcePath,\n managedDestination,\n ownershipClass,\n provenanceState,\n providerPackage,\n providerVersion,\n providerImmutableRef,\n materializationMode: validateExactString(\n rawEntry.materializationMode,\n \"provider-backed-copy\",\n `manifest.resourceProjection.resources.${uri}.materializationMode`,\n ),\n sourceDigest,\n installedDigest,\n hashAlgorithm: \"sha256\",\n lastVerifiedAt: validateIsoTimestamp(\n rawEntry.lastVerifiedAt,\n `manifest.resourceProjection.resources.${uri}.lastVerifiedAt`,\n ),\n lifecycleDisposition: validateLifecycleDisposition(\n rawEntry.lifecycleDisposition,\n `manifest.resourceProjection.resources.${uri}.lifecycleDisposition`,\n ),\n adoptionReceipt,\n selectionTrigger,\n operationLineage: \"W19 R1 P4\",\n provenanceEvidence,\n competingClaims,\n };\n }\n const requiredResources = new Map<string, string>();\n const selectedDirectories = new Set(\n selectedTypes.map((type) => ({\n contract: \"contracts\",\n prompt: \"prompts\",\n reference: \"references\",\n template: \"templates\",\n })[type]),\n );\n for (const asset of Object.values(systemAssetMaterialization.assets)) {\n const localPath = asset.localPath;\n if (\n !localPath ||\n asset.materializationClass !== \"deferred-system-asset\" ||\n asset.selectionTrigger !== \"internal-materialization-mode\"\n ) {\n continue;\n }\n const match = /^\\.make-docs\\/system\\/(contracts|prompts|references|templates)\\/(.+)$/.exec(localPath);\n if (!match || !selectedDirectories.has(match[1])) {\n continue;\n }\n const type = ({\n contracts: \"contract\",\n prompts: \"prompt\",\n references: \"reference\",\n templates: \"template\",\n } as const)[match[1] as \"contracts\" | \"prompts\" | \"references\" | \"templates\"];\n requiredResources.set(`make-docs://system/${type}/${match[2]}`, localPath);\n }\n for (const [relativePath, file] of Object.entries(files)) {\n if (!file.sourceId.startsWith(\"resource:\")) {\n continue;\n }\n const uri = file.sourceId.slice(\"resource:\".length);\n if (!resources[uri] || resources[uri].managedDestination !== relativePath) {\n throw new Error(\n `manifest.resourceProjection.resources must include managed resource ${uri}`,\n );\n }\n }\n for (const [uri, localPath] of requiredResources) {\n if (!resources[uri] || resources[uri].managedDestination !== localPath) {\n throw new Error(\n `manifest.resourceProjection.resources must include selected provider resource ${uri}`,\n );\n }\n }\n for (const uri of Object.keys(resources)) {\n if (!requiredResources.has(uri)) {\n throw new Error(\n `manifest.resourceProjection.resources contains unselected or unmaterialized resource ${uri}`,\n );\n }\n }\n return {\n selectedTypes,\n provider,\n resources,\n };\n}\n\nfunction assertCompleteResourceProjection(\n resources: ResourceProjectionManifestState[\"resources\"],\n selectedTypes: ProjectResourceType[],\n files: Record<string, ManifestFileEntry>,\n systemAssetMaterialization: SystemAssetManifestState,\n): void {\n const requiredResources = new Map<string, string>();\n const selectedDirectories = new Set(\n selectedTypes.map((type) => ({\n contract: \"contracts\",\n prompt: \"prompts\",\n reference: \"references\",\n template: \"templates\",\n })[type]),\n );\n for (const asset of Object.values(systemAssetMaterialization.assets)) {\n const localPath = asset.localPath;\n if (\n !localPath ||\n asset.materializationClass !== \"deferred-system-asset\" ||\n asset.selectionTrigger !== \"internal-materialization-mode\"\n ) {\n continue;\n }\n const match = /^\\.make-docs\\/system\\/(contracts|prompts|references|templates)\\/(.+)$/.exec(localPath);\n if (!match || !selectedDirectories.has(match[1])) continue;\n const type = ({\n contracts: \"contract\",\n prompts: \"prompt\",\n references: \"reference\",\n templates: \"template\",\n } as const)[match[1] as \"contracts\" | \"prompts\" | \"references\" | \"templates\"];\n requiredResources.set(`make-docs://system/${type}/${match[2]}`, localPath);\n }\n for (const [relativePath, file] of Object.entries(files)) {\n if (!file.sourceId.startsWith(\"resource:\")) continue;\n const uri = file.sourceId.slice(\"resource:\".length);\n if (!resources[uri] || resources[uri].managedDestination !== relativePath) {\n throw new Error(\n `manifest.resourceProjection.resources must include managed resource ${uri}`,\n );\n }\n }\n for (const [uri, localPath] of requiredResources) {\n if (!resources[uri] || resources[uri].managedDestination !== localPath) {\n throw new Error(\n `manifest.resourceProjection.resources must include selected provider resource ${uri}`,\n );\n }\n }\n for (const uri of Object.keys(resources)) {\n if (!requiredResources.has(uri)) {\n throw new Error(\n `manifest.resourceProjection.resources contains unselected or unmaterialized resource ${uri}`,\n );\n }\n }\n}\n\nfunction validateCanonicalResourcePath(value: unknown, label: string): string {\n const resourcePath = validateString(value, label);\n const segments = resourcePath.split(\"/\");\n if (\n resourcePath.startsWith(\"/\") ||\n resourcePath.includes(\"\\\\\") ||\n segments.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\")\n ) {\n throw new Error(`${label} must be a canonical relative resource path`);\n }\n return resourcePath;\n}\n\nfunction validateSha256Digest(value: unknown, label: string): string {\n const digest = validateString(value, label);\n if (!/^[a-f0-9]{64}$/.test(digest)) {\n throw new Error(`${label} must be a lowercase sha256 digest`);\n }\n return digest;\n}\n\nfunction validateSystemAssetMaterializationMode(\n value: unknown,\n label: string,\n): SystemAssetMaterializationMode {\n if (\n typeof value !== \"string\" ||\n !SYSTEM_ASSET_MATERIALIZATION_MODES.includes(\n value as SystemAssetMaterializationMode,\n )\n ) {\n throw new Error(`${label} must be a valid system asset materialization mode`);\n }\n\n return value as SystemAssetMaterializationMode;\n}\n\nfunction validateMaterializationClass(\n value: unknown,\n label: string,\n): SystemAssetMaterializationClass {\n if (\n typeof value !== \"string\" ||\n !SYSTEM_ASSET_MATERIALIZATION_CLASSES.includes(\n value as SystemAssetMaterializationClass,\n )\n ) {\n throw new Error(`${label} must be a valid system asset materialization class`);\n }\n\n return value as SystemAssetMaterializationClass;\n}\n\nfunction validateHashAlgorithm(value: unknown, label: string): ManifestHashAlgorithm {\n if (value !== \"sha256\") {\n throw new Error(`${label} must be sha256`);\n }\n\n return value;\n}\n\nfunction validateOfflineExpectation(\n value: unknown,\n label: string,\n): SystemAssetOfflineExpectation {\n if (\n value !== \"local\" &&\n value !== \"cache-or-provider\" &&\n value !== \"reviewed-full-snapshot-fallback\"\n ) {\n throw new Error(`${label} must be a valid offline expectation`);\n }\n\n return value;\n}\n\nfunction validateSelectionTrigger(\n value: unknown,\n label: string,\n): SystemAssetSelectionTrigger {\n if (\n value !== \"local-bootstrap\" &&\n value !== \"profile-selection\" &&\n value !== \"internal-materialization-mode\"\n ) {\n throw new Error(`${label} must be a valid selection trigger`);\n }\n\n return value;\n}\n\nfunction validateStringArray(value: unknown, label: string): string[] {\n if (!Array.isArray(value)) {\n throw new Error(`${label} must be an array`);\n }\n\n return value.map((item, index) => validateString(item, `${label}.${index}`));\n}\n\nfunction validateProjectId(value: unknown): string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new Error(\n \"manifest.projectId must be a non-empty string (the stable project identifier minted at setup)\",\n );\n }\n\n return value;\n}\n\nfunction validateString(value: unknown, label: string): string {\n if (typeof value !== \"string\") {\n throw new Error(`${label} must be a string`);\n }\n\n return value;\n}\n\nfunction validateNumber(value: unknown, label: string): number {\n if (typeof value !== \"number\") {\n throw new Error(`${label} must be a number`);\n }\n\n return value;\n}\n\nfunction validateBoolean(value: unknown, label: string): boolean {\n if (typeof value !== \"boolean\") {\n throw new Error(`${label} must be a boolean`);\n }\n\n return value;\n}\n\nfunction assertPlainObject(\n value: unknown,\n label: string,\n): asserts value is Record<string, unknown> {\n if (!isPlainObject(value)) {\n throw new Error(`${label} must be an object`);\n }\n}\n\nfunction validateSelectedSkills(value: unknown): string[] {\n if (!Array.isArray(value)) {\n throw new Error(\"selections.selectedSkills must be an array\");\n }\n\n return Array.from(\n new Set(\n value.map((skill, index) =>\n validateString(skill, `selections.selectedSkills.${index}`),\n ),\n ),\n ).sort();\n}\n\nfunction validateSelectedPlugins(value: unknown): string[] {\n if (!Array.isArray(value)) {\n throw new Error(\"selections.selectedPlugins must be an array\");\n }\n\n return Array.from(\n new Set(\n value.map((pluginId, index) =>\n validateString(pluginId, `selections.selectedPlugins.${index}`),\n ),\n ),\n ).sort();\n}\n\nfunction validateSkillManifestSelectionSource(\n value: unknown,\n): SkillManifestSelectionSource {\n assertPlainObject(value, \"selections.skillManifest\");\n const source = validateString(value.source, \"selections.skillManifest.source\");\n if (\n source !== \"built-in\" &&\n source !== \"file\" &&\n source !== \"remote-pinned\"\n ) {\n throw new Error(\n \"selections.skillManifest.source must be built-in, file, or remote-pinned\",\n );\n }\n\n const sourcePolicyKind = validateString(\n value.sourcePolicyKind,\n \"selections.skillManifest.sourcePolicyKind\",\n );\n if (\n sourcePolicyKind !== \"first-party\" &&\n sourcePolicyKind !== \"local\" &&\n sourcePolicyKind !== \"remote-pinned\"\n ) {\n throw new Error(\n \"selections.skillManifest.sourcePolicyKind must be first-party, local, or remote-pinned\",\n );\n }\n\n return {\n manifestId: validateString(\n value.manifestId,\n \"selections.skillManifest.manifestId\",\n ),\n displayName: validateString(\n value.displayName,\n \"selections.skillManifest.displayName\",\n ),\n sourcePolicyKind,\n source,\n ...(\"path\" in value\n ? { path: validateString(value.path, \"selections.skillManifest.path\") }\n : {}),\n ...(\"digest\" in value\n ? {\n digest: validateString(\n value.digest,\n \"selections.skillManifest.digest\",\n ),\n }\n : {}),\n };\n}\n\nfunction validateSkillSelectionProvenance(\n value: unknown,\n): SkillSelectionProvenanceEntry[] {\n if (!Array.isArray(value)) {\n throw new Error(\"selections.skillSelectionProvenance must be an array\");\n }\n\n return value.map((entry, index) => {\n assertPlainObject(entry, `selections.skillSelectionProvenance.${index}`);\n const sourcePolicyKind = validateString(\n entry.sourcePolicyKind,\n `selections.skillSelectionProvenance.${index}.sourcePolicyKind`,\n );\n if (\n sourcePolicyKind !== \"first-party\" &&\n sourcePolicyKind !== \"local\" &&\n sourcePolicyKind !== \"remote-pinned\"\n ) {\n throw new Error(\n `selections.skillSelectionProvenance.${index}.sourcePolicyKind must be first-party, local, or remote-pinned`,\n );\n }\n\n const provenanceKind = validateString(\n entry.provenanceKind,\n `selections.skillSelectionProvenance.${index}.provenanceKind`,\n );\n if (\n provenanceKind !== \"first-party\" &&\n provenanceKind !== \"local\" &&\n provenanceKind !== \"remote-pinned\" &&\n provenanceKind !== \"third-party\"\n ) {\n throw new Error(\n `selections.skillSelectionProvenance.${index}.provenanceKind must be first-party, local, remote-pinned, or third-party`,\n );\n }\n\n const supportedHarnesses = validateStringArray(\n entry.supportedHarnesses,\n `selections.skillSelectionProvenance.${index}.supportedHarnesses`,\n ).map((harness) => {\n if (harness !== \"claude-code\" && harness !== \"codex\") {\n throw new Error(\n `selections.skillSelectionProvenance.${index}.supportedHarnesses contains unsupported harness ${harness}`,\n );\n }\n return harness;\n });\n\n return {\n skillName: validateString(\n entry.skillName,\n `selections.skillSelectionProvenance.${index}.skillName`,\n ),\n displayName: validateString(\n entry.displayName,\n `selections.skillSelectionProvenance.${index}.displayName`,\n ),\n manifestId: validateString(\n entry.manifestId,\n `selections.skillSelectionProvenance.${index}.manifestId`,\n ),\n manifestDisplayName: validateString(\n entry.manifestDisplayName,\n `selections.skillSelectionProvenance.${index}.manifestDisplayName`,\n ),\n sourcePolicyKind,\n purposeIds: validateStringArray(\n entry.purposeIds,\n `selections.skillSelectionProvenance.${index}.purposeIds`,\n ),\n purposeLabels: validateStringArray(\n entry.purposeLabels,\n `selections.skillSelectionProvenance.${index}.purposeLabels`,\n ),\n supportedHarnesses,\n skillSource: validateString(\n entry.skillSource,\n `selections.skillSelectionProvenance.${index}.skillSource`,\n ),\n provenanceKind,\n provenanceLabel: validateString(\n entry.provenanceLabel,\n `selections.skillSelectionProvenance.${index}.provenanceLabel`,\n ),\n ...(\"repository\" in entry\n ? {\n repository: validateString(\n entry.repository,\n `selections.skillSelectionProvenance.${index}.repository`,\n ),\n }\n : {}),\n ...(\"ref\" in entry\n ? {\n ref: validateString(\n entry.ref,\n `selections.skillSelectionProvenance.${index}.ref`,\n ),\n }\n : {}),\n ...(\"digest\" in entry\n ? {\n digest: validateString(\n entry.digest,\n `selections.skillSelectionProvenance.${index}.digest`,\n ),\n }\n : {}),\n };\n });\n}\n\nfunction validatePluginManifestSelectionSource(\n value: unknown,\n): PluginManifestSelectionSource {\n assertPlainObject(value, \"selections.pluginManifest\");\n const source = validatePluginSourceKind(\n value.source,\n \"selections.pluginManifest.source\",\n );\n const sourcePolicyKind = validatePluginTrustPolicyKind(\n value.sourcePolicyKind,\n \"selections.pluginManifest.sourcePolicyKind\",\n );\n\n return {\n manifestId: validateString(\n value.manifestId,\n \"selections.pluginManifest.manifestId\",\n ),\n displayName: validateString(\n value.displayName,\n \"selections.pluginManifest.displayName\",\n ),\n sourcePolicyKind,\n source,\n ...(\"path\" in value\n ? { path: validateString(value.path, \"selections.pluginManifest.path\") }\n : {}),\n ...(\"digest\" in value\n ? {\n digest: validateString(\n value.digest,\n \"selections.pluginManifest.digest\",\n ),\n }\n : {}),\n };\n}\n\nfunction validatePluginSelectionProvenance(\n value: unknown,\n): PluginSelectionProvenanceEntry[] {\n if (!Array.isArray(value)) {\n throw new Error(\"selections.pluginSelectionProvenance must be an array\");\n }\n\n return value.map((entry, index) => {\n assertPlainObject(entry, `selections.pluginSelectionProvenance.${index}`);\n const sourcePolicyKind = validatePluginTrustPolicyKind(\n entry.sourcePolicyKind,\n `selections.pluginSelectionProvenance.${index}.sourcePolicyKind`,\n );\n const provenanceKind = validatePluginTrustPolicyKind(\n entry.provenanceKind,\n `selections.pluginSelectionProvenance.${index}.provenanceKind`,\n );\n const supportedHarnesses = validateStringArray(\n entry.supportedHarnesses,\n `selections.pluginSelectionProvenance.${index}.supportedHarnesses`,\n ).map((harness) => {\n if (harness !== \"claude-code\" && harness !== \"codex\") {\n throw new Error(\n `selections.pluginSelectionProvenance.${index}.supportedHarnesses contains unsupported harness ${harness}`,\n );\n }\n return harness;\n });\n\n return {\n pluginId: validateString(\n entry.pluginId,\n `selections.pluginSelectionProvenance.${index}.pluginId`,\n ),\n title: validateString(\n entry.title,\n `selections.pluginSelectionProvenance.${index}.title`,\n ),\n manifestId: validateString(\n entry.manifestId,\n `selections.pluginSelectionProvenance.${index}.manifestId`,\n ),\n manifestDisplayName: validateString(\n entry.manifestDisplayName,\n `selections.pluginSelectionProvenance.${index}.manifestDisplayName`,\n ),\n sourcePolicyKind,\n supportedHarnesses,\n pluginSource: validatePluginSourceKind(\n entry.pluginSource,\n `selections.pluginSelectionProvenance.${index}.pluginSource`,\n ),\n provenanceKind,\n provenanceLabel: validateString(\n entry.provenanceLabel,\n `selections.pluginSelectionProvenance.${index}.provenanceLabel`,\n ),\n supportStatus: validatePluginSupportStatus(\n entry.supportStatus,\n `selections.pluginSelectionProvenance.${index}.supportStatus`,\n ),\n ...(\"repository\" in entry\n ? {\n repository: validateString(\n entry.repository,\n `selections.pluginSelectionProvenance.${index}.repository`,\n ),\n }\n : {}),\n ...(\"ref\" in entry\n ? {\n ref: validateString(\n entry.ref,\n `selections.pluginSelectionProvenance.${index}.ref`,\n ),\n }\n : {}),\n ...(\"digest\" in entry\n ? {\n digest: validateString(\n entry.digest,\n `selections.pluginSelectionProvenance.${index}.digest`,\n ),\n }\n : {}),\n };\n });\n}\n\nfunction validateSkillExposureMetadata(\n value: unknown,\n label: string,\n): SkillExposureMetadata {\n assertPlainObject(value, label);\n const harness = validateHarnessValue(value.harness, `${label}.harness`);\n const scope = validateSkillScope(value.scope);\n const preferredMode = validateString(value.preferredMode, `${label}.preferredMode`);\n if (preferredMode !== \"symlink\") {\n throw new Error(`${label}.preferredMode must be symlink`);\n }\n\n return {\n skillName: validateString(value.skillName, `${label}.skillName`),\n installName: validateString(value.installName, `${label}.installName`),\n harness,\n scope,\n canonicalPayloadPath: validateString(\n value.canonicalPayloadPath,\n `${label}.canonicalPayloadPath`,\n ),\n exposurePath: validateString(value.exposurePath, `${label}.exposurePath`),\n symlinkTarget: validateString(value.symlinkTarget, `${label}.symlinkTarget`),\n preferredMode,\n ...(\"mode\" in value\n ? { mode: validateSkillExposureMode(value.mode, `${label}.mode`) }\n : {}),\n ...(\"copyMirrorSource\" in value\n ? {\n copyMirrorSource: validateString(\n value.copyMirrorSource,\n `${label}.copyMirrorSource`,\n ),\n }\n : {}),\n ...(\"fallbackReason\" in value\n ? {\n fallbackReason: validateString(\n value.fallbackReason,\n `${label}.fallbackReason`,\n ),\n }\n : {}),\n ...(\"legacyStub\" in value\n ? { legacyStub: validateBoolean(value.legacyStub, `${label}.legacyStub`) }\n : {}),\n };\n}\n\nfunction validateHarnessValue(value: unknown, label: string): SkillExposureMetadata[\"harness\"] {\n if (!HARNESSES.includes(value as SkillExposureMetadata[\"harness\"])) {\n throw new Error(`${label} must be a supported harness`);\n }\n return value as SkillExposureMetadata[\"harness\"];\n}\n\nfunction validateSkillExposureMode(\n value: unknown,\n label: string,\n): NonNullable<SkillExposureMetadata[\"mode\"]> {\n if (value !== \"symlink\" && value !== \"copy-mirror\") {\n throw new Error(`${label} must be symlink or copy-mirror`);\n }\n return value;\n}\n\nfunction validateAgenticOwnershipMetadata(\n value: unknown,\n label: string,\n): AgenticOwnershipMetadata {\n assertPlainObject(value, label);\n const artifactKind = validateAgenticArtifactKind(\n value.artifactKind,\n `${label}.artifactKind`,\n );\n const role = validateAgenticFileRole(value.role, `${label}.role`);\n if (artifactKind === \"skill\" && !isSkillAgenticRole(role)) {\n throw new Error(`${label}.role must be a skill ownership role`);\n }\n if (artifactKind === \"plugin\" && !isPluginAgenticRole(role)) {\n throw new Error(`${label}.role must be a plugin ownership role`);\n }\n\n return {\n artifactKind,\n role,\n id: validateString(value.id, `${label}.id`),\n pathKind: validateAgenticPathKind(value.pathKind, `${label}.pathKind`),\n ...(\"scope\" in value\n ? { scope: validateSkillScope(value.scope) }\n : {}),\n ...(\"harness\" in value\n ? { harness: validateHarnessValue(value.harness, `${label}.harness`) }\n : {}),\n ...(\"canonicalPayloadPath\" in value\n ? {\n canonicalPayloadPath: validateString(\n value.canonicalPayloadPath,\n `${label}.canonicalPayloadPath`,\n ),\n }\n : {}),\n ...(\"exposurePath\" in value\n ? {\n exposurePath: validateString(value.exposurePath, `${label}.exposurePath`),\n }\n : {}),\n ...(\"exposureMode\" in value\n ? {\n exposureMode: validateAgenticExposureMode(\n value.exposureMode,\n `${label}.exposureMode`,\n ),\n }\n : {}),\n ...(\"sourceManifest\" in value\n ? {\n sourceManifest: validateString(\n value.sourceManifest,\n `${label}.sourceManifest`,\n ),\n }\n : {}),\n ...(\"ref\" in value ? { ref: validateString(value.ref, `${label}.ref`) } : {}),\n ...(\"version\" in value\n ? { version: validateString(value.version, `${label}.version`) }\n : {}),\n ...(\"digest\" in value\n ? { digest: validateString(value.digest, `${label}.digest`) }\n : {}),\n ...(\"provenance\" in value\n ? {\n provenance: validateString(value.provenance, `${label}.provenance`),\n }\n : {}),\n ...(\"trustPolicy\" in value\n ? {\n trustPolicy: validatePluginTrustPolicy(\n value.trustPolicy,\n `${label}.trustPolicy`,\n ),\n }\n : {}),\n ...(\"supportStatus\" in value\n ? {\n supportStatus: validatePluginSupportStatus(\n value.supportStatus,\n `${label}.supportStatus`,\n ),\n }\n : {}),\n ...(\"packaging\" in value\n ? {\n packaging: validateAgenticPackagingProvenance(\n value.packaging,\n `${label}.packaging`,\n ),\n }\n : {}),\n };\n}\n\n/**\n * Per-artifact Playbook-packaging provenance (W18 R8 P4, R-PROV-1): source\n * refs and digests, package profile, adapter id, output kind, generated file,\n * category, and generation tier ride on the manifest ownership record so the\n * manifest and audit surfaces stay the queryable provenance carriers.\n */\nfunction validateAgenticPackagingProvenance(\n value: unknown,\n label: string,\n): AgenticPackagingProvenance {\n assertPlainObject(value, label);\n const profile = value.profile;\n if (profile !== \"native\" && profile !== \"portable\") {\n throw new Error(`${label}.profile must be native or portable`);\n }\n const outputKind = value.outputKind;\n if (outputKind !== \"plugin\" && outputKind !== \"skills-bundle\") {\n throw new Error(`${label}.outputKind must be plugin or skills-bundle`);\n }\n const generationTier = value.generationTier;\n if (\n generationTier !== undefined &&\n generationTier !== \"deterministic\" &&\n generationTier !== \"agent-proposed\"\n ) {\n throw new Error(`${label}.generationTier must be deterministic or agent-proposed`);\n }\n if (value.ownershipStatus !== \"make-docs-managed\") {\n throw new Error(`${label}.ownershipStatus must be make-docs-managed`);\n }\n return {\n packageId: validateString(value.packageId, `${label}.packageId`),\n profile,\n adapterId: validateString(value.adapterId, `${label}.adapterId`),\n outputKind,\n sourceRefs: validateStringArray(value.sourceRefs, `${label}.sourceRefs`),\n sourceDigests: validateStringArray(value.sourceDigests, `${label}.sourceDigests`),\n generatedFile: validateString(value.generatedFile, `${label}.generatedFile`),\n category: validateString(value.category, `${label}.category`),\n ...(generationTier !== undefined ? { generationTier } : {}),\n ownershipStatus: \"make-docs-managed\",\n };\n}\n\nfunction validateAgenticArtifactKind(value: unknown, label: string): \"skill\" | \"plugin\" {\n if (value !== \"skill\" && value !== \"plugin\") {\n throw new Error(`${label} must be skill or plugin`);\n }\n return value;\n}\n\nfunction validateAgenticFileRole(value: unknown, label: string): AgenticFileRole {\n if (\n value !== \"shared-payload\" &&\n value !== \"native-exposure\" &&\n value !== \"copy-mirror\" &&\n value !== \"generated-stub\" &&\n value !== \"legacy-duplicated-payload\" &&\n value !== \"plugin-payload\" &&\n value !== \"plugin-native-exposure\" &&\n value !== \"plugin-copy-mirror\" &&\n value !== \"plugin-generated-adapter\" &&\n value !== \"plugin-legacy-generated-output\"\n ) {\n throw new Error(`${label} must be a supported agentic ownership role`);\n }\n return value;\n}\n\nfunction isSkillAgenticRole(role: AgenticFileRole): boolean {\n return (\n role === \"shared-payload\" ||\n role === \"native-exposure\" ||\n role === \"copy-mirror\" ||\n role === \"generated-stub\" ||\n role === \"legacy-duplicated-payload\"\n );\n}\n\nfunction isPluginAgenticRole(role: AgenticFileRole): boolean {\n return (\n role === \"plugin-payload\" ||\n role === \"plugin-native-exposure\" ||\n role === \"plugin-copy-mirror\" ||\n role === \"plugin-generated-adapter\" ||\n role === \"plugin-legacy-generated-output\"\n );\n}\n\nfunction validateAgenticPathKind(value: unknown, label: string): AgenticPathKind {\n if (value !== \"file\" && value !== \"directory\") {\n throw new Error(`${label} must be file or directory`);\n }\n return value;\n}\n\nfunction validateAgenticExposureMode(\n value: unknown,\n label: string,\n): AgenticExposureMode {\n if (\n value !== \"symlink\" &&\n value !== \"copy-mirror\" &&\n value !== \"generated-adapter\"\n ) {\n throw new Error(`${label} must be symlink, copy-mirror, or generated-adapter`);\n }\n return value;\n}\n\nfunction validatePluginTrustPolicy(value: unknown, label: string): PluginTrustPolicy {\n assertPlainObject(value, label);\n const kind = validatePluginTrustPolicyKind(value.kind, `${label}.kind`);\n return {\n kind,\n ...(\"description\" in value\n ? { description: validateString(value.description, `${label}.description`) }\n : {}),\n };\n}\n\nfunction validatePluginTrustPolicyKind(\n value: unknown,\n label: string,\n): PluginTrustPolicyKind {\n if (\n value !== \"first-party\" &&\n value !== \"local-reviewed\" &&\n value !== \"remote-pinned\" &&\n value !== \"manual-review-required\"\n ) {\n throw new Error(`${label} must be a supported trust policy`);\n }\n return value;\n}\n\nfunction validatePluginSourceKind(value: unknown, label: string): PluginSourceKind {\n if (value !== \"built-in\" && value !== \"file\" && value !== \"remote-pinned\") {\n throw new Error(`${label} must be built-in, file, or remote-pinned`);\n }\n return value;\n}\n\nfunction validatePluginSupportStatus(\n value: unknown,\n label: string,\n): PluginSupportStatus {\n if (\n value !== \"provisional\" &&\n value !== \"implementation-validated\" &&\n value !== \"conformance-validated\" &&\n value !== \"unsupported\"\n ) {\n throw new Error(`${label} must be a supported plugin support status`);\n }\n return value;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction createManifestAuditRecord(\n targetDir: string,\n homeDir: string,\n managedPath: string,\n ownershipSource: ManifestAuditRecord[\"ownershipSource\"],\n manifestEntry?: ManifestFileEntry,\n): ManifestAuditRecord {\n const agenticRole = classifyAgenticSkillFileRole({\n relativePath: managedPath,\n sourceId: manifestEntry?.sourceId,\n });\n const kind =\n manifestEntry?.agenticOwnership?.pathKind ??\n (manifestEntry?.skillExposure ? \"directory\" : \"file\");\n\n return {\n ...createAuditPathMetadata(targetDir, managedPath, kind, homeDir),\n ownershipSource,\n sourceId: manifestEntry?.sourceId,\n manifestHash: manifestEntry?.hash,\n skillExposure: manifestEntry?.skillExposure,\n agenticOwnership: manifestEntry?.agenticOwnership,\n ...(manifestEntry?.agenticOwnership?.role\n ? { agenticRole: manifestEntry.agenticOwnership.role }\n : agenticRole\n ? { agenticRole }\n : {}),\n };\n}\n\nfunction compareAuditRecords(\n left: ManifestAuditRecord,\n right: ManifestAuditRecord,\n): number {\n return left.ordering.sortKey.localeCompare(right.ordering.sortKey);\n}\n\nexport function isInstructionManifestPath(relativePath: string): boolean {\n const normalized = normalizeRelativePath(relativePath);\n // A Skill may carry a plain file with a harness-instruction filename.\n // Its ownership covers all bytes, not a Make Docs managed router block.\n if (/(?:^|\\/)(?:\\.make-docs\\/agentics|\\.agents|\\.claude|\\.codex)\\/skills\\//.test(normalized)) return false;\n const basename = path.posix.basename(normalized);\n return INSTRUCTION_KINDS.includes(basename as InstructionKind);\n}\n\nfunction getContainedRelativePath(\n root: string,\n candidate: string,\n): string | null {\n const relative = path.relative(root, candidate);\n if (relative === \"\") {\n return \".\";\n }\n\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n return null;\n }\n\n return relative;\n}\n","import type { AgenticFileRole } from \"./types\";\n\nconst CANONICAL_SKILL_DIRS = [\".agents/skills\", \".claude/skills\"] as const;\nconst LEGACY_SHARED_SKILL_DIR = \".make-docs/agentics/skills\";\nconst SHARED_AGENTICS_PLUGIN_DIR = \".make-docs/agentics/plugins\";\nconst HARNESS_SKILL_DIRS = [\".claude/skills\", \".agents/skills\", \".codex/skills\"] as const;\n\nexport function classifyAgenticSkillFileRole(options: {\n relativePath: string;\n sourceId?: string;\n}): AgenticFileRole | undefined {\n return classifyAgenticFileRole(options);\n}\n\nexport function classifyAgenticFileRole(options: {\n relativePath: string;\n sourceId?: string;\n}): AgenticFileRole | undefined {\n const normalizedPath = normalizePath(options.relativePath);\n const sourceId = options.sourceId ?? \"\";\n\n if (\n sourceId.startsWith(\"skill:shared:\") ||\n sourceId.startsWith(\"skill-shared-asset:\")\n ) {\n return \"shared-payload\";\n }\n\n if (\n sourceId.startsWith(\"plugin:payload:\") ||\n sourceId.startsWith(\"plugin-payload-asset:\") ||\n isSharedAgenticsPluginPath(normalizedPath)\n ) {\n return \"plugin-payload\";\n }\n\n if (sourceId.startsWith(\"skill-exposure:\")) {\n return \"native-exposure\";\n }\n\n if (sourceId.startsWith(\"plugin-exposure:\")) {\n return \"plugin-native-exposure\";\n }\n\n if (sourceId.startsWith(\"skill-copy-mirror-asset:\")) {\n return \"copy-mirror\";\n }\n\n if (sourceId.startsWith(\"plugin-copy-mirror-asset:\")) {\n return \"plugin-copy-mirror\";\n }\n\n if (sourceId.startsWith(\"plugin-generated-adapter:\")) {\n return \"plugin-generated-adapter\";\n }\n\n if (sourceId.startsWith(\"plugin-legacy-generated-output:\")) {\n return \"plugin-legacy-generated-output\";\n }\n\n if (isLegacyDuplicatedSkillSource(sourceId)) {\n return \"legacy-duplicated-payload\";\n }\n\n if (sourceId.startsWith(\"skill-stub:\")) {\n return \"generated-stub\";\n }\n\n if (isSharedAgenticsSkillPath(normalizedPath)) return \"shared-payload\";\n\n if (isHarnessSkillPath(normalizedPath)) {\n return \"legacy-duplicated-payload\";\n }\n\n return undefined;\n}\n\nexport function formatAgenticSkillFileRole(\n role: AgenticFileRole | undefined,\n): string | undefined {\n return formatAgenticFileRole(role);\n}\n\nexport function formatAgenticFileRole(\n role: AgenticFileRole | undefined,\n): string | undefined {\n switch (role) {\n case \"shared-payload\":\n return \"Skill files\";\n case \"native-exposure\":\n return \"native harness exposure\";\n case \"copy-mirror\":\n return \"managed copy mirror\";\n case \"generated-stub\":\n return \"generated harness stub\";\n case \"legacy-duplicated-payload\":\n return \"legacy duplicated payload\";\n case \"plugin-payload\":\n return \"plugin payload\";\n case \"plugin-native-exposure\":\n return \"plugin native harness exposure\";\n case \"plugin-copy-mirror\":\n return \"plugin managed copy mirror\";\n case \"plugin-generated-adapter\":\n return \"plugin generated adapter\";\n case \"plugin-legacy-generated-output\":\n return \"plugin legacy generated output\";\n case undefined:\n return undefined;\n }\n}\n\nexport function isSharedAgenticsSkillPath(relativePath: string): boolean {\n return [...CANONICAL_SKILL_DIRS, LEGACY_SHARED_SKILL_DIR].some(root => matchesKnownRoot(normalizePath(relativePath), root));\n}\n\nexport function isHarnessSkillPath(relativePath: string): boolean {\n const normalizedPath = normalizePath(relativePath);\n return HARNESS_SKILL_DIRS.some((root) => matchesKnownRoot(normalizedPath, root));\n}\n\nexport function isSharedAgenticsPluginPath(relativePath: string): boolean {\n return matchesKnownRoot(normalizePath(relativePath), SHARED_AGENTICS_PLUGIN_DIR);\n}\n\nfunction isLegacyDuplicatedSkillSource(sourceId: string): boolean {\n return (\n sourceId.startsWith(\"skill-asset:\") ||\n sourceId.startsWith(\"retired-skill-asset:\") ||\n (sourceId.startsWith(\"skill:\") &&\n !sourceId.startsWith(\"skill:shared:\") &&\n !sourceId.startsWith(\"skill-stub:\"))\n );\n}\n\nfunction matchesKnownRoot(relativePath: string, root: string): boolean {\n return relativePath === root || relativePath.startsWith(`${root}/`) || relativePath.includes(`/${root}/`);\n}\n\nfunction normalizePath(relativePath: string): string {\n return relativePath.replace(/\\\\/g, \"/\");\n}\n","export const CAPABILITIES = [\"designs\", \"plans\", \"prd\", \"work\"] as const;\n\nexport type Capability = (typeof CAPABILITIES)[number];\n\nexport const INSTRUCTION_KINDS = [\"AGENTS.md\", \"CLAUDE.md\"] as const;\n\nexport type InstructionKind = (typeof INSTRUCTION_KINDS)[number];\n\nexport const HARNESSES = [\"claude-code\", \"codex\"] as const;\n\nexport type Harness = (typeof HARNESSES)[number];\n\nexport const PROJECT_RESOURCE_TYPES = [\n \"contract\",\n \"prompt\",\n \"reference\",\n \"template\",\n] as const;\n\nexport type ProjectResourceType = (typeof PROJECT_RESOURCE_TYPES)[number];\n\nexport const INSTRUCTION_KIND_TO_HARNESS: Record<InstructionKind, Harness> = {\n \"AGENTS.md\": \"codex\",\n \"CLAUDE.md\": \"claude-code\",\n};\n\nexport const HARNESS_TO_INSTRUCTION: Record<Harness, InstructionKind> = {\n \"claude-code\": \"CLAUDE.md\",\n codex: \"AGENTS.md\",\n};\n\nexport type ManagedFileConflictResolution = \"overwrite\" | \"skip\";\nexport type ManagedFileConflictResolutions = Partial<\n Record<string, ManagedFileConflictResolution>\n>;\nexport type ManagedFileConflictGroup =\n | \"agent-instructions\"\n | \"managed-files\"\n | \"prompts\"\n | \"references\"\n | \"skills\"\n | \"templates\";\nexport type ActionType =\n | \"create\"\n | \"noop\"\n | \"skip\"\n | \"update\"\n | \"update-conflict\"\n | \"skip-conflict\"\n | \"strip-managed-block\"\n | \"remove-managed\"\n | \"generate\";\n\nexport const SYSTEM_ASSET_MATERIALIZATION_MODES = [\n \"full-snapshot\",\n \"provider-backed\",\n \"hybrid-pinned-cache\",\n] as const;\n\nexport type SystemAssetMaterializationMode =\n (typeof SYSTEM_ASSET_MATERIALIZATION_MODES)[number];\n\nexport const DEFAULT_SYSTEM_ASSET_MATERIALIZATION_MODE =\n \"full-snapshot\" satisfies SystemAssetMaterializationMode;\n\nexport const SYSTEM_ASSET_MATERIALIZATION_CLASSES = [\n \"always-local-bootstrap\",\n \"materialized-system-asset\",\n \"deferred-system-asset\",\n] as const;\n\nexport type SystemAssetMaterializationClass =\n (typeof SYSTEM_ASSET_MATERIALIZATION_CLASSES)[number];\n\nexport type ManifestHashAlgorithm = \"sha256\";\n\nexport type SystemAssetOfflineExpectation =\n | \"local\"\n | \"cache-or-provider\"\n | \"reviewed-full-snapshot-fallback\";\n\nexport type SystemAssetSelectionTrigger =\n | \"local-bootstrap\"\n | \"profile-selection\"\n | \"internal-materialization-mode\";\n\nexport interface SystemAssetMaterializationPlan {\n mode: SystemAssetMaterializationMode;\n localBootstrapPaths: string[];\n deferredSystemAssetPaths: string[];\n materializationClasses: Record<string, SystemAssetMaterializationClass>;\n}\n\nexport interface ManifestSystemAssetEntry {\n materializationMode: SystemAssetMaterializationMode;\n sourcePackage?: string;\n sourceProvider?: string;\n sourceVersion?: string;\n sourceImmutableRef?: string;\n hashAlgorithm: ManifestHashAlgorithm;\n expectedHashes: string[];\n logicalAssetId: string;\n localPath?: string;\n materializationClass: SystemAssetMaterializationClass;\n offlineExpectation: SystemAssetOfflineExpectation;\n recoveryGuidance: string;\n selectionTrigger: SystemAssetSelectionTrigger;\n}\n\nexport interface SystemAssetManifestState extends SystemAssetMaterializationPlan {\n sourcePackage?: string;\n sourceProvider?: string;\n sourceVersion?: string;\n sourceImmutableRef?: string;\n hashAlgorithm?: ManifestHashAlgorithm;\n recoveryGuidance: string;\n assets: Record<string, ManifestSystemAssetEntry>;\n}\n\nexport interface InstallSelections {\n /** Native Skill tools can differ from the project router tool set. */\n skillHarnesses?: Record<Harness, boolean>;\n capabilities: Record<Capability, boolean>;\n harnesses: Record<Harness, boolean>;\n skills: boolean;\n skillScope: \"project\" | \"global\";\n selectedSkills: string[];\n skillManifest?: SkillManifestSelectionSource;\n skillSelectionProvenance?: SkillSelectionProvenanceEntry[];\n plugins: boolean;\n pluginScope: AgenticScope;\n selectedPlugins: string[];\n pluginManifest?: PluginManifestSelectionSource;\n pluginSelectionProvenance?: PluginSelectionProvenanceEntry[];\n /**\n * Explicit project-local system-resource projection. An empty array means\n * provider-only operation. Absence is reserved for pre-P4 manifests so\n * compatibility code can fail closed instead of inventing past intent.\n */\n resourceProjection?: ProjectResourceType[];\n}\n\nexport interface SkillManifestSelectionSource {\n manifestId: string;\n displayName: string;\n sourcePolicyKind: \"first-party\" | \"local\" | \"remote-pinned\";\n source: \"built-in\" | \"file\" | \"remote-pinned\";\n path?: string;\n digest?: string;\n}\n\nexport interface SkillSelectionProvenanceEntry {\n skillName: string;\n displayName: string;\n manifestId: string;\n manifestDisplayName: string;\n sourcePolicyKind: \"first-party\" | \"local\" | \"remote-pinned\";\n purposeIds: string[];\n purposeLabels: string[];\n supportedHarnesses: Harness[];\n skillSource: string;\n provenanceKind: \"first-party\" | \"local\" | \"remote-pinned\" | \"third-party\";\n provenanceLabel: string;\n repository?: string;\n ref?: string;\n digest?: string;\n}\n\nexport function getActiveInstructionKinds(\n selections: Pick<InstallSelections, \"harnesses\">,\n): Set<InstructionKind> {\n const active = new Set<InstructionKind>();\n for (const harness of HARNESSES) {\n if (selections.harnesses[harness]) {\n active.add(HARNESS_TO_INSTRUCTION[harness]);\n }\n }\n return active;\n}\n\nexport interface CapabilityState {\n explicitSelection: boolean;\n effectiveSelection: boolean;\n missingPrerequisites: Capability[];\n disabledReason?: string;\n}\n\nexport interface InstallProfile {\n selections: InstallSelections;\n capabilityState: Record<Capability, CapabilityState>;\n effectiveCapabilities: Capability[];\n profileId: string;\n}\n\nexport type FileContent = string | Buffer;\n\nexport interface ResolvedAsset<Content extends FileContent = string> {\n kind?: \"file\";\n relativePath: string;\n assetClass: \"static\" | \"scoped-static\";\n sourceId: string;\n content: Content;\n}\n\nexport type ResolvedFileAsset = ResolvedAsset<FileContent>;\n\nexport interface ResolvedSkillExposureAsset {\n kind: \"skill-exposure\";\n relativePath: string;\n assetClass: \"static\" | \"scoped-static\";\n sourceId: string;\n skillExposure: SkillExposureMetadata;\n copyMirrorAssets: ResolvedFileAsset[];\n}\n\nexport interface ResolvedPluginPayloadAsset {\n kind: \"plugin-payload\";\n relativePath: string;\n assetClass: \"static\" | \"scoped-static\";\n sourceId: string;\n content: string;\n pluginArtifact: PluginArtifactMetadata;\n agenticOwnership: AgenticOwnershipMetadata;\n}\n\nexport interface ResolvedPluginExposureAsset {\n kind: \"plugin-exposure\";\n relativePath: string;\n assetClass: \"static\" | \"scoped-static\";\n sourceId: string;\n pluginArtifact: PluginArtifactMetadata;\n agenticOwnership: AgenticOwnershipMetadata;\n pluginExposure: PluginExposureMetadata;\n copyMirrorAssets: ResolvedPluginPayloadAsset[];\n generatedAdapterAsset?: ResolvedPluginPayloadAsset;\n}\n\nexport type ResolvedInstallAsset =\n | ResolvedFileAsset\n | ResolvedSkillExposureAsset;\n\nexport type SkillExposureMode = \"symlink\" | \"copy-mirror\";\n\nexport interface SkillExposureMetadata {\n skillName: string;\n installName: string;\n harness: Harness;\n scope: \"project\" | \"global\";\n canonicalPayloadPath: string;\n exposurePath: string;\n symlinkTarget: string;\n preferredMode: \"symlink\";\n mode?: SkillExposureMode;\n copyMirrorSource?: string;\n fallbackReason?: string;\n legacyStub?: boolean;\n}\n\nexport interface ManifestFileEntry {\n hash: string;\n sourceId: string;\n ownershipClass?: ManifestOwnershipClass;\n systemAsset?: ManifestSystemAssetEntry;\n skillExposure?: SkillExposureMetadata;\n agenticOwnership?: AgenticOwnershipMetadata;\n}\n\nexport type ManifestOwnershipClass =\n | \"installed-provider\"\n | \"managed-projection\"\n | \"project-override\"\n | \"managed-snapshot\"\n | \"managed-block\"\n | \"project-owned\"\n | \"runtime-state\"\n | \"selected-skill\";\n\nexport type ManifestProvenanceState =\n | \"verified\"\n | \"incomplete\"\n | \"ambiguous\"\n | \"contradictory\";\n\nexport interface ManifestProvenanceClaim {\n sourcePackage: string;\n sourceVersion: string;\n sourceImmutableRef: string;\n evidenceRefs: string[];\n}\n\nexport interface ManifestAdoptionReceipt {\n receiptId: string;\n adoptedAt: string;\n priorOwnershipClass: \"managed-snapshot\";\n evidenceRefs: string[];\n}\n\nexport type ManifestLifecycleDisposition =\n | \"active\"\n | \"preserved-export\"\n | \"superseded-managed\"\n | \"conflict\";\n\nexport interface ManifestResourceProjectionEntry {\n uri: string;\n managedDestination: string;\n ownershipClass: \"managed-snapshot\" | \"project-owned\";\n installedDigest: string;\n hashAlgorithm: \"sha256\";\n lastVerifiedAt: string;\n lifecycleDisposition: ManifestLifecycleDisposition;\n /** Legacy schema-4 mirrors. New manifests do not write these provider facts. */\n type?: ProjectResourceType;\n resourcePath?: string;\n provenanceState?: ManifestProvenanceState;\n providerPackage?: string;\n providerVersion?: string;\n providerImmutableRef?: string;\n materializationMode?: \"provider-backed-copy\";\n sourceDigest?: string;\n adoptionReceipt?: ManifestAdoptionReceipt | null;\n selectionTrigger?: \"setup-selection\" | \"reconfigure-selection\";\n operationLineage?: \"W19 R1 P4\";\n provenanceEvidence?: string[];\n competingClaims?: ManifestProvenanceClaim[];\n}\n\nexport interface ResourceProjectionManifestState {\n /** Legacy schema-4 mirrors. Desired selection now comes only from config. */\n selectedTypes?: ProjectResourceType[];\n /** Legacy schema-4 mirror. Provider identity now comes only from the provider. */\n provider?: {\n ownershipClass: \"installed-provider\";\n provenanceState: \"verified\";\n packageName: string;\n version: string;\n immutableRef: string;\n inventoryDigest: string;\n };\n resources: Record<string, ManifestResourceProjectionEntry>;\n}\n\nexport interface ManifestRouterOwnershipEntry {\n relativePath: string;\n harness: Harness;\n instructionKind: InstructionKind;\n ownershipClass: \"managed-snapshot\" | \"project-owned\";\n routerClass: \"bootstrap\" | \"on-demand-surface\";\n sourceId: string;\n sourcePackage: string;\n sourceVersion: string;\n sourceImmutableRef: string;\n materializationMode: \"managed-block\";\n provenanceState: ManifestProvenanceState;\n provenanceEvidence: string[];\n competingClaims: ManifestProvenanceClaim[];\n hashAlgorithm: \"sha256\";\n expectedSourceHash: string;\n installedHash: string;\n lastVerifiedAt: string;\n lifecycleDisposition: ManifestLifecycleDisposition;\n adoptionReceipt: ManifestAdoptionReceipt | null;\n}\n\nexport interface RouterOwnershipManifestState {\n configuredHarnesses: Harness[];\n operationLineage: \"W19 R1 P4\";\n routers: Record<string, ManifestRouterOwnershipEntry>;\n}\n\nexport type LifecyclePlanDisposition =\n | \"create\"\n | \"update\"\n | \"preserve\"\n | \"conflict\"\n | \"skip\"\n | \"remove\"\n | \"stop\";\n\nexport interface LifecyclePlanSnapshotEntry {\n relativePath: string;\n state: \"missing\" | \"file\" | \"directory\" | \"symlink\" | \"other\";\n digest?: string;\n}\n\nexport interface LifecyclePlanSnapshot {\n id: string;\n entries: LifecyclePlanSnapshotEntry[];\n}\n\nexport interface LifecycleMutationReceipt {\n schemaVersion: 1;\n receiptId: string;\n operation: string;\n projectId: string;\n manifestSchemaVersion: number;\n profileId: string;\n selectedResourceTypes: ProjectResourceType[];\n outcomes: Record<LifecyclePlanDisposition, number>;\n conflicts: string[];\n backupReferences: string[];\n committedAt: string;\n claims: {\n validated: false;\n accepted: false;\n published: false;\n released: false;\n };\n}\n\nexport type AgenticSkillFileRole =\n | \"shared-payload\"\n | \"native-exposure\"\n | \"copy-mirror\"\n | \"generated-stub\"\n | \"legacy-duplicated-payload\";\n\nexport type AgenticPluginFileRole =\n | \"plugin-payload\"\n | \"plugin-native-exposure\"\n | \"plugin-copy-mirror\"\n | \"plugin-generated-adapter\"\n | \"plugin-legacy-generated-output\";\n\nexport type AgenticFileRole = AgenticSkillFileRole | AgenticPluginFileRole;\n\nexport type AgenticArtifactKind = \"skill\" | \"plugin\";\nexport type AgenticPathKind = \"file\" | \"directory\";\nexport type AgenticScope = \"project\" | \"global\";\nexport type AgenticExposureMode = \"symlink\" | \"copy-mirror\" | \"generated-adapter\";\n\nexport type PluginArtifactStatus = \"provisional\" | \"active\" | \"deprecated\";\nexport type PluginSupportStatus =\n | \"provisional\"\n | \"implementation-validated\"\n | \"conformance-validated\"\n | \"unsupported\";\nexport type PluginTrustPolicyKind =\n | \"first-party\"\n | \"local-reviewed\"\n | \"remote-pinned\"\n | \"manual-review-required\";\nexport type PluginSourceKind = \"built-in\" | \"file\" | \"remote-pinned\";\n\nexport interface PluginTrustPolicy {\n kind: PluginTrustPolicyKind;\n description?: string;\n}\n\nexport interface PluginManifestSelectionSource {\n manifestId: string;\n displayName: string;\n sourcePolicyKind: PluginTrustPolicyKind;\n source: PluginSourceKind;\n path?: string;\n digest?: string;\n}\n\nexport interface PluginSelectionProvenanceEntry {\n pluginId: string;\n title: string;\n manifestId: string;\n manifestDisplayName: string;\n sourcePolicyKind: PluginTrustPolicyKind;\n supportedHarnesses: Harness[];\n pluginSource: PluginSourceKind;\n provenanceKind: PluginTrustPolicyKind;\n provenanceLabel: string;\n supportStatus: PluginSupportStatus;\n repository?: string;\n ref?: string;\n digest?: string;\n}\n\nexport interface PluginSourceManifestMetadata {\n manifestId: string;\n displayName: string;\n source: PluginSourceKind;\n path?: string;\n}\n\nexport interface PluginArtifactMetadata {\n pluginId: string;\n title: string;\n summary: string;\n status: PluginArtifactStatus;\n sourceManifest: PluginSourceManifestMetadata;\n ref?: string;\n version?: string;\n digest: string;\n provenance: string;\n trustPolicy: PluginTrustPolicy;\n supportedHarnesses: Harness[];\n scope: AgenticScope;\n supportStatus: PluginSupportStatus;\n /** Opaque historical metadata. Current code does not interpret these fields. */\n workflowBundles?: unknown[];\n packageBoundary?: unknown;\n}\n\nexport interface PluginExposureMetadata {\n pluginId: string;\n harness: Harness;\n scope: AgenticScope;\n canonicalPayloadPath: string;\n exposurePath: string;\n preferredMode: \"symlink\";\n mode?: AgenticExposureMode;\n symlinkTarget?: string;\n copyMirrorSource?: string;\n generatedAdapterSourceId?: string;\n generatedAdapterDigest?: string;\n fallbackReason?: string;\n}\n\n/**\n * Playbook-packaging provenance carried on manifest ownership records (W18 R8\n * P4, R-PROV-1): every generated artifact stays traceable to its source\n * Playbook refs and digests, package profile, adapter id, output kind, and\n * the concrete generated file — queryable through the manifest and the audit\n * records that embed it, not only through the in-tree\n * `.make-docs/provenance.json`. `adapterId` is the free-form harness adapter\n * identifier, so provenance survives adapters (like `pi`) that are not\n * first-class {@link Harness} values.\n */\nexport interface AgenticPackagingProvenance {\n packageId: string;\n profile: \"native\" | \"portable\";\n adapterId: string;\n outputKind: \"plugin\" | \"skills-bundle\";\n sourceRefs: string[];\n sourceDigests: string[];\n /** Container-relative generated file this entry tracks; \".\" for the exposure root. */\n generatedFile: string;\n /** Compiler inventory category (skill, harness-manifest, ...); \"exposure\" for exposure entries. */\n category: string;\n /** R-GEN-1 generation tier of the file's semantic content; absent on exposure entries. */\n generationTier?: \"deterministic\" | \"agent-proposed\";\n ownershipStatus: \"make-docs-managed\";\n}\n\nexport interface AgenticOwnershipMetadata {\n artifactKind: AgenticArtifactKind;\n role: AgenticFileRole;\n id: string;\n pathKind: AgenticPathKind;\n scope?: AgenticScope;\n harness?: Harness;\n canonicalPayloadPath?: string;\n exposurePath?: string;\n exposureMode?: AgenticExposureMode;\n sourceManifest?: string;\n ref?: string;\n version?: string;\n digest?: string;\n provenance?: string;\n trustPolicy?: PluginTrustPolicy;\n supportStatus?: PluginSupportStatus;\n /** Per-artifact Playbook-packaging provenance (W18 R8 P4, R-PROV-1). */\n packaging?: AgenticPackagingProvenance;\n}\n\nexport interface InstallManifest {\n schemaVersion: number;\n /**\n * Stable project identifier minted once at setup (W18 R10; PRD 38 R-ID-1).\n * Keys every project-scoped row in the machine-level global store and never\n * changes for the lifetime of the install — clones, moves, and worktrees\n * carry it with the manifest. Absent on pre-identifier manifests (installs\n * written before W18 R10); such manifests remain fully valid and the\n * identifier is minted on the next `make-docs` apply.\n */\n projectId?: string;\n packageName: string;\n packageVersion: string;\n updatedAt: string;\n profileId: string;\n selections: InstallSelections;\n effectiveCapabilities: Capability[];\n systemAssetMaterialization: SystemAssetManifestState;\n routerOwnership?: RouterOwnershipManifestState;\n resourceProjection?: ResourceProjectionManifestState;\n files: Record<string, ManifestFileEntry>;\n skillFiles: string[];\n}\n\nexport interface ReviewableManagedFileConflict {\n relativePath: string;\n group: ManagedFileConflictGroup;\n sourceId: string;\n reason: string;\n instructionKind?: InstructionKind;\n scope?: \"file\" | \"managed-block\";\n}\n\nexport interface PlannedAction {\n type: ActionType;\n relativePath: string;\n sourceId?: string;\n /** Explicit user decision that resolved a managed-file ownership conflict. */\n reviewedConflictResolution?: ManagedFileConflictResolution;\n agenticRole?: AgenticFileRole;\n agenticOwnership?: AgenticOwnershipMetadata;\n skillExposure?: SkillExposureMetadata;\n copyMirrorAssets?: ResolvedFileAsset[];\n content?: FileContent;\n contentHash?: string;\n reason?: string;\n disposition?: LifecyclePlanDisposition;\n}\n\nexport interface InstallPlan {\n packageName: string;\n packageVersion: string;\n profile: InstallProfile;\n systemAssetMaterialization: SystemAssetManifestState;\n actions: PlannedAction[];\n desiredFiles: Record<string, ManifestFileEntry>;\n desiredSkillFiles: string[];\n conflictsRunId?: string;\n operation?: \"setup\" | \"setup.reconfigure\" | \"setup.sync\";\n routerOwnership?: RouterOwnershipManifestState;\n resourceProjection?: ResourceProjectionManifestState;\n classificationSnapshot?: LifecyclePlanSnapshot;\n stops?: string[];\n /** Internal staged-migration control. It never comes from CLI or MCP input. */\n forceManifestWrite?: boolean;\n}\n\nexport interface PackageMeta {\n name: string;\n version: string;\n}\n\nexport interface ApplyResult {\n manifest: InstallManifest;\n appliedActions: PlannedAction[];\n conflictFiles: string[];\n receipt?: LifecycleMutationReceipt;\n mutationApplied: boolean;\n}\n\nexport type AuditMode = \"manifest-present\" | \"manifest-missing\";\nexport type CompatibilitySourceState =\n | \"clean-v1\"\n | \"clean-v2-full-snapshot\"\n | \"clean-v2-provider-backed\"\n | \"clean-v2-hybrid-pinned-cache\"\n | \"modified-v1\"\n | \"partial-install\"\n | \"malformed-manifest\"\n | \"missing-manifest-recognizable\"\n | \"unknown-shape\";\nexport type CompatibilityDisposition =\n | \"sync\"\n | \"migrate\"\n | \"migrate-with-review\"\n | \"backup-and-reinstall\"\n | \"manual-review-required\";\nexport type AuditPathKind = \"file\" | \"directory\";\nexport type AuditPathScope = \"project\" | \"home\" | \"external\";\nexport type AuditOwnershipSource =\n | \"manifest-file\"\n | \"manifest-skill-file\"\n | \"managed-state\"\n | \"project-config\"\n | \"fallback\";\nexport type AuditSkippedStatus = \"already-absent\" | \"excluded\";\nexport type AuditReasonCode =\n | \"instruction-content-match\"\n | \"managed-file-hash-match\"\n | \"managed-skill-file-content-match\"\n | \"managed-skill-exposure-symlink-match\"\n | \"managed-skill-exposure-copy-mirror-match\"\n | \"managed-plugin-file-content-match\"\n | \"managed-plugin-exposure-symlink-match\"\n | \"managed-plugin-exposure-copy-mirror-match\"\n | \"managed-state-file\"\n | \"fallback-canonical-content-match\"\n | \"fallback-root-fingerprint-match\"\n | \"directory-eligible-for-prune\"\n | \"already-absent\"\n | \"inside-backup-root\"\n | \"outside-supported-roots\"\n | \"instruction-user-content-preserved\"\n | \"instruction-content-mismatch\"\n | \"managed-file-modified\"\n | \"manifest-skill-file-without-metadata\"\n | \"manifest-skill-file-content-mismatch\"\n | \"manifest-skill-exposure-mismatch\"\n | \"manifest-plugin-file-content-mismatch\"\n | \"manifest-plugin-exposure-mismatch\"\n | \"fallback-root-fingerprint-mismatch\"\n | \"fallback-ambiguous\"\n | \"project-config-preserved\"\n | \"directory-contains-unmanaged-descendants\"\n | \"directory-contains-preserved-descendants\";\n\nexport interface AuditReason {\n code: AuditReasonCode;\n message: string;\n}\n\nexport interface AuditBackupPath {\n scope: Exclude<AuditPathScope, \"external\"> | null;\n relativePath: string | null;\n}\n\nexport interface AuditOrderingMetadata {\n scopeOrder: number;\n depth: number;\n sortKey: string;\n pruneSortKey: string;\n}\n\nexport interface AuditPathMetadata {\n path: string;\n absolutePath: string;\n kind: AuditPathKind;\n scope: AuditPathScope;\n pathScope: AuditPathScope;\n backupRelativePath: string | null;\n backup: AuditBackupPath;\n ordering: AuditOrderingMetadata;\n}\n\nexport interface AuditManagedPathMetadata extends AuditPathMetadata {\n ownershipSource: AuditOwnershipSource;\n sourceId?: string;\n agenticRole?: AgenticFileRole;\n agenticOwnership?: AgenticOwnershipMetadata;\n skillExposure?: SkillExposureMetadata;\n}\n\nexport interface AuditCandidateMetadata extends AuditPathMetadata {\n ownershipSource?: AuditOwnershipSource;\n sourceId?: string;\n agenticRole?: AgenticFileRole;\n agenticOwnership?: AgenticOwnershipMetadata;\n skillExposure?: SkillExposureMetadata;\n}\n\nexport interface ManifestAuditRecord extends AuditManagedPathMetadata {\n manifestHash?: string;\n}\n\nexport interface ManifestAuditContext {\n manifestPath: string;\n managedFiles: ManifestAuditRecord[];\n skillFiles: ManifestAuditRecord[];\n priorSelections: InstallSelections;\n}\n\nexport interface AuditRemovableFile extends AuditManagedPathMetadata {\n kind: \"file\" | \"directory\";\n reason: string;\n reasonCode: AuditReasonCode;\n expectedHash?: string;\n currentHash?: string;\n}\n\nexport interface AuditPrunableDirectory extends AuditPathMetadata {\n kind: \"directory\";\n reason: string;\n reasonCode: AuditReasonCode;\n removableDescendantPaths: string[];\n preservedDescendantPaths: string[];\n}\n\nexport interface AuditPreservedPath extends AuditCandidateMetadata {\n reason: string;\n reasonCode: AuditReasonCode;\n preservedDescendantPaths?: string[];\n}\n\nexport interface AuditSkippedPath extends AuditCandidateMetadata {\n reason: string;\n reasonCode: AuditReasonCode;\n status: AuditSkippedStatus;\n}\n\nexport interface AuditSkillSelectionReview {\n skillsEnabled: boolean;\n skillScope: InstallSelections[\"skillScope\"];\n selectedSkills: string[];\n skillManifest?: SkillManifestSelectionSource;\n skillSelectionProvenance: SkillSelectionProvenanceEntry[];\n}\n\nexport interface AuditPluginSelectionReview {\n pluginsEnabled: boolean;\n pluginScope: InstallSelections[\"pluginScope\"];\n selectedPlugins: string[];\n pluginManifest?: PluginManifestSelectionSource;\n pluginSelectionProvenance: PluginSelectionProvenanceEntry[];\n}\n\nexport interface AuditReport {\n mode: AuditMode;\n targetDir: string;\n manifestPath: string;\n skillSelectionReview?: AuditSkillSelectionReview;\n pluginSelectionReview?: AuditPluginSelectionReview;\n removableFiles: AuditRemovableFile[];\n prunableDirectories: AuditPrunableDirectory[];\n preservedPaths: AuditPreservedPath[];\n skippedPaths: AuditSkippedPath[];\n}\n\nexport type LifecyclePermissionsMode = \"confirm\" | \"allow-all\";\n\nexport interface BackupDestinationPlan {\n backupRoot: string;\n dateStamp: string;\n directoryName: string;\n destinationDir: string;\n promotion?: {\n from: string;\n to: string;\n };\n}\n\nexport interface BackupCommandOptions {\n targetDir: string;\n permissions: LifecyclePermissionsMode;\n homeDir?: string;\n now?: Date;\n}\n\nexport interface BackupExecutionResult {\n status: \"completed\" | \"cancelled\" | \"noop\";\n targetDir: string;\n destinationDir: string | null;\n auditReport: AuditReport;\n copiedFiles: string[];\n materializedDirectories: string[];\n}\n","export const MANAGED_BLOCK_BEGIN = \"<!-- make-docs:begin -->\";\nexport const MANAGED_BLOCK_END = \"<!-- make-docs:end -->\";\n\nexport type ManagedBlockMarkers = {\n begin: string;\n end: string;\n};\n\nexport type ManagedBlockState = \"absent\" | \"valid\" | \"malformed\";\n\nexport type ManagedBlockAction = \"inserted\" | \"updated\" | \"reasserted\" | \"noop\";\n\nexport type ManagedBlockInsertPosition = \"append\" | \"prepend\";\n\nexport type ParsedManagedBlock = {\n state: ManagedBlockState;\n body: string | null;\n prefix: string;\n suffix: string;\n};\n\nexport type UpsertManagedBlockOptions = {\n markers?: ManagedBlockMarkers;\n insertPosition?: ManagedBlockInsertPosition;\n};\n\nexport type UpsertManagedBlockResult = {\n content: string;\n action: ManagedBlockAction;\n changed: boolean;\n previousState: ManagedBlockState;\n previousBody: string | null;\n};\n\ntype MarkerSpan = {\n end: number;\n start: number;\n};\n\nconst DEFAULT_MARKERS: ManagedBlockMarkers = {\n begin: MANAGED_BLOCK_BEGIN,\n end: MANAGED_BLOCK_END,\n};\n\nexport function renderManagedBlock(\n body: string,\n markers: ManagedBlockMarkers = DEFAULT_MARKERS,\n): string {\n return `${markers.begin}\\n${normalizeManagedBlockBody(body)}${markers.end}`;\n}\n\nexport function parseManagedBlock(\n content: string,\n markers: ManagedBlockMarkers = DEFAULT_MARKERS,\n): ParsedManagedBlock {\n const beginSpans = findMarkerSpans(content, markers.begin);\n const endSpans = findMarkerSpans(content, markers.end);\n\n if (beginSpans.length === 0 && endSpans.length === 0) {\n return {\n body: null,\n prefix: content,\n state: \"absent\",\n suffix: \"\",\n };\n }\n\n const hasSingleValidPair =\n beginSpans.length === 1 &&\n endSpans.length === 1 &&\n beginSpans[0].start < endSpans[0].start;\n\n if (hasSingleValidPair) {\n const beginSpan = beginSpans[0];\n const endSpan = endSpans[0];\n\n return {\n body: stripOpeningLineBreak(content.slice(beginSpan.end, endSpan.start)),\n prefix: content.slice(0, beginSpan.start),\n state: \"valid\",\n suffix: content.slice(endSpan.end),\n };\n }\n\n const markerSpans = [...beginSpans, ...endSpans].sort(\n (left, right) => left.start - right.start || left.end - right.end,\n );\n const firstMarker = markerSpans[0];\n const lastMarker = markerSpans[markerSpans.length - 1];\n const suffixStart =\n beginSpans.length > 0 && endSpans.length === 0 ? content.length : lastMarker.end;\n\n return {\n body: null,\n prefix: content.slice(0, firstMarker.start),\n state: \"malformed\",\n suffix: content.slice(suffixStart),\n };\n}\n\nexport function upsertManagedBlock(\n content: string,\n body: string,\n options: UpsertManagedBlockOptions = {},\n): UpsertManagedBlockResult {\n const markers = options.markers ?? DEFAULT_MARKERS;\n const insertPosition = options.insertPosition ?? \"append\";\n const parsed = parseManagedBlock(content, markers);\n const nextBlock = renderManagedBlock(body, markers);\n\n if (parsed.state === \"absent\") {\n const nextContent = insertManagedBlock(content, nextBlock, insertPosition);\n\n return {\n action: \"inserted\",\n changed: true,\n content: nextContent,\n previousBody: null,\n previousState: parsed.state,\n };\n }\n\n const nextContent = `${parsed.prefix}${nextBlock}${parsed.suffix}`;\n\n if (nextContent === content) {\n return {\n action: \"noop\",\n changed: false,\n content,\n previousBody: parsed.body,\n previousState: parsed.state,\n };\n }\n\n return {\n action: parsed.state === \"malformed\" ? \"reasserted\" : \"updated\",\n changed: true,\n content: nextContent,\n previousBody: parsed.body,\n previousState: parsed.state,\n };\n}\n\nfunction findMarkerSpans(content: string, marker: string): MarkerSpan[] {\n if (marker.length === 0) {\n throw new Error(\"Managed block markers must not be empty.\");\n }\n\n const spans: MarkerSpan[] = [];\n let searchStart = 0;\n\n while (searchStart <= content.length) {\n const start = content.indexOf(marker, searchStart);\n\n if (start === -1) {\n break;\n }\n\n const end = start + marker.length;\n spans.push({ end, start });\n searchStart = end;\n }\n\n return spans;\n}\n\nfunction insertManagedBlock(\n content: string,\n block: string,\n position: ManagedBlockInsertPosition,\n): string {\n if (content.length === 0) {\n return `${block}\\n`;\n }\n\n if (position === \"prepend\") {\n return `${block}\\n${content}`;\n }\n\n return content.endsWith(\"\\n\") ? `${content}${block}\\n` : `${content}\\n${block}\\n`;\n}\n\nfunction normalizeManagedBlockBody(body: string): string {\n if (body.length === 0 || body.endsWith(\"\\n\")) {\n return body;\n }\n\n return `${body}\\n`;\n}\n\nfunction stripOpeningLineBreak(body: string): string {\n if (body.startsWith(\"\\r\\n\")) {\n return body.slice(2);\n }\n\n if (body.startsWith(\"\\n\")) {\n return body.slice(1);\n }\n\n return body;\n}\n","import { createHash } from \"node:crypto\";\nimport {\n existsSync,\n mkdirSync,\n lstatSync,\n readFileSync,\n readdirSync,\n rmdirSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nexport const PACKAGE_ROOT = findPackageRoot(import.meta.url);\nexport const TEMPLATE_ROOT = resolveTemplateRoot(PACKAGE_ROOT);\n\nexport function findPackageRoot(fromUrl: string): string {\n let current = path.dirname(fileURLToPath(fromUrl));\n\n while (!existsSync(path.join(current, \"package.json\"))) {\n const parent = path.dirname(current);\n if (parent === current) {\n throw new Error(\"Could not locate package.json from current module.\");\n }\n\n current = parent;\n }\n\n return current;\n}\n\nexport function resolveTemplateRoot(packageRoot: string): string {\n const sibling = path.resolve(packageRoot, \"..\", \"docs\", \"template\");\n if (existsSync(sibling)) {\n return sibling;\n }\n\n const bundled = path.join(packageRoot, \"template\");\n if (existsSync(bundled)) {\n return bundled;\n }\n\n throw new Error(\n `Could not locate template root. Tried ${sibling} and ${bundled}.`,\n );\n}\n\nexport function readPackageFile(relativePath: string): string {\n if (relativePath === \"package.json\") {\n return readTextFile(path.join(PACKAGE_ROOT, relativePath));\n }\n\n return readTextFile(path.join(TEMPLATE_ROOT, relativePath));\n}\n\nexport function readTextFile(filePath: string): string {\n return readFileSync(filePath, \"utf8\");\n}\n\nexport function writeTextFile(filePath: string, content: string): void {\n ensureParentDir(filePath);\n writeFileSync(filePath, content, \"utf8\");\n}\n\nexport function writeContentFile(filePath: string, content: string | Uint8Array): void {\n ensureParentDir(filePath);\n writeFileSync(filePath, content);\n}\n\nexport function contentEquals(left: string | Uint8Array, right: string | Uint8Array): boolean {\n return Buffer.from(left).equals(Buffer.from(right));\n}\n\nexport function ensureParentDir(filePath: string): void {\n mkdirSync(path.dirname(filePath), { recursive: true });\n}\n\nexport function normalizeRelativePath(relativePath: string): string {\n return relativePath.split(path.sep).join(\"/\");\n}\n\nexport function hashText(content: string | Uint8Array): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\nexport function readPackageMeta(): { name: string; version: string } {\n const raw = JSON.parse(readPackageFile(\"package.json\")) as {\n name: string;\n version: string;\n };\n\n return { name: raw.name, version: raw.version };\n}\n\nexport function createRunId(now = new Date()): string {\n return now.toISOString().replace(/[:.]/g, \"-\");\n}\n\nexport function pruneEmptyDirectories(startDir: string, stopDir: string): void {\n let current = startDir;\n const boundary = path.resolve(stopDir);\n\n while (current.startsWith(boundary) && current !== boundary) {\n if (!existsSync(current)) {\n current = path.dirname(current);\n continue;\n }\n\n const entries = readdirSync(current);\n if (entries.length > 0) {\n break;\n }\n\n rmSync(current, { recursive: true, force: true });\n current = path.dirname(current);\n }\n}\n\nexport function removeFileIfPresent(filePath: string): boolean {\n let stats;\n try {\n stats = lstatSync(filePath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n throw error;\n }\n if (!stats.isFile() && !stats.isSymbolicLink()) {\n throw new Error(`Expected a regular file at ${filePath}, but found a different entry type.`);\n }\n\n rmSync(filePath, { force: false });\n return true;\n}\n\nexport function removeManagedPathIfPresent(filePath: string): boolean {\n try {\n lstatSync(filePath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n throw error;\n }\n rmSync(filePath, { recursive: true, force: false });\n return true;\n}\n\nexport function pruneDirectoryIfEmpty(directoryPath: string): boolean {\n if (!existsSync(directoryPath)) {\n return false;\n }\n\n const stats = lstatSync(directoryPath);\n if (!stats.isDirectory()) {\n throw new Error(`Expected a directory at ${directoryPath}, but found a different entry type.`);\n }\n\n if (readdirSync(directoryPath).length > 0) {\n return false;\n }\n\n rmdirSync(directoryPath);\n return true;\n}\n\nexport function formatInlineList(items: string[]): string {\n if (items.length === 0) {\n return \"\";\n }\n\n if (items.length === 1) {\n return items[0];\n }\n\n if (items.length === 2) {\n return `${items[0]} and ${items[1]}`;\n }\n\n return `${items.slice(0, -1).join(\", \")}, and ${items.at(-1)}`;\n}\n\nexport function relativePathToTarget(targetDir: string, relativePath: string): string {\n return path.isAbsolute(relativePath) ? path.normalize(relativePath) : path.join(targetDir, relativePath);\n}\n\nexport function assertManagedPathHasNoSymlinks(\n targetDir: string,\n relativePath: string,\n): void {\n const boundary = path.resolve(targetDir);\n const destination = path.resolve(boundary, relativePath);\n const relativeDestination = path.relative(boundary, destination);\n if (\n relativeDestination === \"..\" ||\n relativeDestination.startsWith(`..${path.sep}`) ||\n path.isAbsolute(relativeDestination)\n ) {\n throw new Error(`Managed path escapes the project target: ${relativePath}.`);\n }\n\n let current = boundary;\n for (const segment of [\"\", ...relativeDestination.split(path.sep).filter(Boolean)]) {\n if (segment) current = path.join(current, segment);\n try {\n if (lstatSync(current).isSymbolicLink()) {\n const displayedPath = segment ? path.relative(boundary, current) : \".\";\n throw new Error(\n `Managed path uses a symbolic link at ${displayedPath}: ${relativePath}.`,\n );\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw error;\n }\n }\n}\n\nexport function exists(filePath: string): boolean {\n return existsSync(filePath);\n}\n","import { hashText, formatInlineList } from \"./utils\";\nimport {\n CAPABILITIES,\n type Capability,\n type CapabilityState,\n type InstallProfile,\n type InstallSelections,\n} from \"./types\";\n\nexport const CAPABILITY_DEPENDENCIES: Record<Capability, Capability[]> = {\n designs: [],\n plans: [],\n prd: [\"plans\"],\n work: [\"plans\", \"prd\"],\n};\n\nexport function defaultSelections(): InstallSelections {\n return {\n capabilities: {\n designs: true,\n plans: true,\n prd: true,\n work: true,\n },\n harnesses: {\n \"claude-code\": true,\n codex: true,\n },\n skills: false,\n skillScope: \"project\",\n selectedSkills: [],\n plugins: false,\n pluginScope: \"project\",\n selectedPlugins: [],\n };\n}\n\nexport function cloneSelections(\n selections: InstallSelections,\n): InstallSelections {\n return structuredClone(selections);\n}\n\nexport function resolveCapabilityState(\n selections: InstallSelections,\n): Record<Capability, CapabilityState> {\n const state = {} as Record<Capability, CapabilityState>;\n\n for (const capability of CAPABILITIES) {\n const missingPrerequisites = CAPABILITY_DEPENDENCIES[capability].filter(\n (dependency) => !state[dependency]?.effectiveSelection,\n );\n const explicitSelection = selections.capabilities[capability];\n const effectiveSelection =\n explicitSelection && missingPrerequisites.length === 0;\n\n state[capability] = {\n explicitSelection,\n effectiveSelection,\n missingPrerequisites,\n disabledReason:\n missingPrerequisites.length > 0\n ? `${capability} requires ${formatInlineList(missingPrerequisites)}`\n : undefined,\n };\n }\n\n return state;\n}\n\nexport function resolveInstallProfile(\n selections: InstallSelections,\n): InstallProfile {\n const capabilityState = resolveCapabilityState(selections);\n const effectiveCapabilities = CAPABILITIES.filter(\n (capability) => capabilityState[capability].effectiveSelection,\n );\n\n const profileId = hashText(\n JSON.stringify({\n capabilities: capabilityState,\n harnesses: selections.harnesses,\n ...(selections.skillHarnesses ? {skillHarnesses:selections.skillHarnesses} : {}),\n skills: selections.skills,\n skillScope: selections.skillScope,\n selectedSkills: [...selections.selectedSkills].sort(),\n skillManifest: selections.skillManifest,\n skillSelectionProvenance: selections.skillSelectionProvenance ?? [],\n plugins: selections.plugins,\n pluginScope: selections.pluginScope,\n selectedPlugins: [...selections.selectedPlugins].sort(),\n pluginManifest: selections.pluginManifest,\n pluginSelectionProvenance: selections.pluginSelectionProvenance ?? [],\n resourceProjection: [...(selections.resourceProjection ?? [])].sort(),\n }),\n ).slice(0, 16);\n\n return {\n selections,\n capabilityState,\n effectiveCapabilities,\n profileId,\n };\n}\n\nexport function hasEffectiveCapabilities(profile: InstallProfile): boolean {\n return profile.effectiveCapabilities.length > 0;\n}\n","import type { Capability, InstallProfile, InstructionKind } from \"./types\";\nimport { INSTRUCTION_KINDS } from \"./types\";\n\nconst FOUNDATION_ROUTER_DIRECTORIES = [\n \"\",\n \"docs\",\n \".make-docs\",\n \".make-docs/system\",\n \".make-docs/system/contracts\",\n \".make-docs/system/prompts\",\n \".make-docs/system/references\",\n \".make-docs/system/templates\",\n] as const;\n\nconst LEGACY_INCOMPLETE_FOUNDATION_DIRECTORIES = FOUNDATION_ROUTER_DIRECTORIES;\n\nconst CAPABILITY_ROUTER_DIRECTORIES: ReadonlyArray<readonly [Capability, string]> = [\n [\"designs\", \"docs/designs\"],\n [\"plans\", \"docs/plans\"],\n [\"prd\", \"docs/prd\"],\n [\"work\", \"docs/work\"],\n];\n\nconst ON_DEMAND_ROUTER_DIRECTORIES = [\n \".make-docs/archive\",\n \"docs/assets\",\n] as const;\n\nconst RETIRED_TEMPLATE_CHILD_ROUTER_DIRECTORIES = [\n \"docs/assets/archive\",\n \"docs/assets/artifacts\",\n \"docs/assets/library\",\n \"docs/assets/playbooks\",\n] as const;\n\nexport function getFoundationRouterPaths(instructionKind: InstructionKind): string[] {\n return FOUNDATION_ROUTER_DIRECTORIES.map((directory) =>\n directory === \"\" ? instructionKind : `${directory}/${instructionKind}`\n );\n}\n\nexport function getConfiguredRouterPaths(\n profile: InstallProfile,\n instructionKind: InstructionKind,\n): string[] {\n const paths = getFoundationRouterPaths(instructionKind);\n for (const [capability, directory] of CAPABILITY_ROUTER_DIRECTORIES) {\n if (profile.capabilityState[capability].effectiveSelection) {\n paths.push(`${directory}/${instructionKind}`);\n }\n }\n return paths;\n}\n\nexport function getLegacyIncompleteRouterPaths(\n instructionKind: InstructionKind,\n): string[] {\n return LEGACY_INCOMPLETE_FOUNDATION_DIRECTORIES.map((directory) =>\n directory === \"\" ? instructionKind : `${directory}/${instructionKind}`\n );\n}\n\nexport function getLegacyAssetsOnDemandRouterPaths(\n instructionKind: InstructionKind,\n): string[] {\n return [`docs/assets/${instructionKind}`];\n}\n\nexport function getOnDemandRouterPaths(instructionKind: InstructionKind): string[] {\n return ON_DEMAND_ROUTER_DIRECTORIES.map((directory) =>\n `${directory}/${instructionKind}`\n );\n}\n\nexport function isRetiredTemplateOwnedChildRouterPath(relativePath: string): boolean {\n return RETIRED_TEMPLATE_CHILD_ROUTER_DIRECTORIES.some((directory) =>\n INSTRUCTION_KINDS.some((instructionKind) =>\n relativePath === `${directory}/${instructionKind}`\n )\n );\n}\n\nexport function isConfiguredRouterPath(\n profile: InstallProfile,\n relativePath: string,\n instructionKind: InstructionKind,\n): boolean {\n return getConfiguredRouterPaths(profile, instructionKind).includes(relativePath);\n}\n\n/** Static source variants keep the declared harness set readable without the CLI. */\nexport function getRouterTemplateSourcePath(profile: InstallProfile, relativePath: string): string {\n if (relativePath === \"docs/AGENTS.md\" && profile.selections.harnesses.codex && !profile.selections.harnesses[\"claude-code\"]) return \"docs/AGENTS.codex-only.md\";\n if (relativePath === \"docs/CLAUDE.md\" && profile.selections.harnesses[\"claude-code\"] && !profile.selections.harnesses.codex) return \"docs/CLAUDE.claude-only.md\";\n return relativePath;\n}\n","import type {\n ManifestHashAlgorithm,\n ManifestSystemAssetEntry,\n SystemAssetMaterializationClass,\n SystemAssetMaterializationMode,\n SystemAssetManifestState,\n SystemAssetSelectionTrigger,\n} from \"./types\";\nimport { DEFAULT_SYSTEM_ASSET_MATERIALIZATION_MODE } from \"./types\";\n\nconst DEFAULT_RECOVERY_GUIDANCE =\n \"Rerun make-docs to refresh local system asset provenance from the installed package. If provider-backed resolution is enabled internally, use a reviewed full-snapshot materialization path when provider or cache pins cannot be verified.\";\n\nexport function createEmptySystemAssetManifestState(): SystemAssetManifestState {\n return {\n mode: DEFAULT_SYSTEM_ASSET_MATERIALIZATION_MODE,\n localBootstrapPaths: [],\n deferredSystemAssetPaths: [],\n materializationClasses: {},\n recoveryGuidance: DEFAULT_RECOVERY_GUIDANCE,\n assets: {},\n };\n}\n\nexport function createSystemAssetManifestState(options: {\n mode: SystemAssetMaterializationMode;\n sourcePackage: string;\n sourceVersion: string;\n localBootstrapPaths: string[];\n deferredSystemAssetPaths: string[];\n materializationClasses: Record<string, SystemAssetMaterializationClass>;\n expectedFiles: Record<string, { hash: string; sourceId: string }>;\n materializedFiles: Record<string, { hash: string; sourceId: string }>;\n}): SystemAssetManifestState {\n const sourceProvider = \"package\";\n const sourceImmutableRef = `package:${options.sourcePackage}@${options.sourceVersion}`;\n const assets = Object.fromEntries(\n Object.entries(options.materializationClasses).flatMap(\n ([logicalAssetId, materializationClass]) => {\n const expectedFile = options.expectedFiles[logicalAssetId];\n const materializedFile = options.materializedFiles[logicalAssetId];\n if (!expectedFile && !materializedFile) {\n return [];\n }\n\n return [\n [\n logicalAssetId,\n createManifestSystemAssetEntry({\n mode: options.mode,\n sourcePackage: options.sourcePackage,\n sourceProvider,\n sourceVersion: options.sourceVersion,\n sourceImmutableRef,\n logicalAssetId,\n materializationClass,\n expectedHash: expectedFile?.hash,\n localPath: materializedFile ? logicalAssetId : undefined,\n }),\n ],\n ];\n },\n ),\n );\n\n return {\n mode: options.mode,\n sourcePackage: options.sourcePackage,\n sourceProvider,\n sourceVersion: options.sourceVersion,\n sourceImmutableRef,\n hashAlgorithm: \"sha256\",\n localBootstrapPaths: [...options.localBootstrapPaths],\n deferredSystemAssetPaths: [...options.deferredSystemAssetPaths],\n materializationClasses: { ...options.materializationClasses },\n recoveryGuidance: DEFAULT_RECOVERY_GUIDANCE,\n assets,\n };\n}\n\nexport function createManifestSystemAssetEntry(options: {\n mode: SystemAssetMaterializationMode;\n sourcePackage: string;\n sourceProvider: string;\n sourceVersion: string;\n sourceImmutableRef: string;\n logicalAssetId: string;\n materializationClass: SystemAssetMaterializationClass;\n expectedHash?: string;\n localPath?: string;\n}): ManifestSystemAssetEntry {\n return {\n materializationMode: options.mode,\n sourcePackage: options.sourcePackage,\n sourceProvider: options.sourceProvider,\n sourceVersion: options.sourceVersion,\n sourceImmutableRef: options.sourceImmutableRef,\n hashAlgorithm: \"sha256\",\n expectedHashes: options.expectedHash ? [options.expectedHash] : [],\n logicalAssetId: options.logicalAssetId,\n ...(options.localPath ? { localPath: options.localPath } : {}),\n materializationClass: options.materializationClass,\n offlineExpectation: getOfflineExpectation(options.materializationClass),\n recoveryGuidance: DEFAULT_RECOVERY_GUIDANCE,\n selectionTrigger: getSelectionTrigger(options.materializationClass, options.mode),\n };\n}\n\nexport function resolveSystemAssetMaterializationSafety(options: {\n logicalAssetId: string;\n materializationMode: SystemAssetMaterializationMode;\n sourceProvider?: string;\n sourceVersion?: string;\n sourceImmutableRef?: string;\n hashAlgorithm: ManifestHashAlgorithm;\n expectedHashes: string[];\n actualHash?: string;\n providerAvailable: boolean;\n cacheHit: boolean;\n reviewedFallbackAllowed: boolean;\n}): { status: \"provider-approved\" | \"reviewed-full-snapshot-fallback\"; recoveryGuidance: string } {\n assertProviderPin(options);\n\n if (!options.providerAvailable || !options.cacheHit) {\n if (options.reviewedFallbackAllowed) {\n return {\n status: \"reviewed-full-snapshot-fallback\",\n recoveryGuidance: `Provider/cache state for ${options.logicalAssetId} is unavailable. Use the reviewed full-snapshot materialization path before writing files.`,\n };\n }\n\n throw new Error(\n `Provider/cache state for ${options.logicalAssetId} is unavailable. Failing closed; use a reviewed full-snapshot materialization path before writing files.`,\n );\n }\n\n if (!options.actualHash || !options.expectedHashes.includes(options.actualHash)) {\n throw new Error(\n `Provider/cache state for ${options.logicalAssetId} resolved a different asset version. Expected one of ${options.expectedHashes.join(\", \")}; got ${options.actualHash ?? \"missing hash\"}. Use a reviewed full-snapshot materialization path before writing files.`,\n );\n }\n\n return {\n status: \"provider-approved\",\n recoveryGuidance: `Provider/cache pins for ${options.logicalAssetId} matched the expected sha256 hash set.`,\n };\n}\n\nfunction assertProviderPin(options: {\n logicalAssetId: string;\n sourceProvider?: string;\n sourceVersion?: string;\n sourceImmutableRef?: string;\n hashAlgorithm: ManifestHashAlgorithm;\n expectedHashes: string[];\n}): void {\n if (!options.sourceProvider) {\n throw new Error(`Provider-backed system asset ${options.logicalAssetId} is missing a provider identity.`);\n }\n\n if (!options.sourceVersion && !options.sourceImmutableRef) {\n throw new Error(\n `Provider-backed system asset ${options.logicalAssetId} is missing a provider version or immutable ref.`,\n );\n }\n\n if (options.hashAlgorithm !== \"sha256\") {\n throw new Error(\n `Provider-backed system asset ${options.logicalAssetId} must use sha256 provenance hashes.`,\n );\n }\n\n if (options.expectedHashes.length === 0) {\n throw new Error(\n `Provider-backed system asset ${options.logicalAssetId} is missing an expected hash set.`,\n );\n }\n}\n\nfunction getOfflineExpectation(\n materializationClass: SystemAssetMaterializationClass,\n): ManifestSystemAssetEntry[\"offlineExpectation\"] {\n return materializationClass === \"deferred-system-asset\"\n ? \"reviewed-full-snapshot-fallback\"\n : \"local\";\n}\n\nfunction getSelectionTrigger(\n materializationClass: SystemAssetMaterializationClass,\n mode: SystemAssetMaterializationMode,\n): SystemAssetSelectionTrigger {\n if (materializationClass === \"always-local-bootstrap\") {\n return \"local-bootstrap\";\n }\n\n return mode === DEFAULT_SYSTEM_ASSET_MATERIALIZATION_MODE\n ? \"profile-selection\"\n : \"internal-materialization-mode\";\n}\n","import {\n SYSTEM_ASSET_MATERIALIZATION_MODES,\n type SystemAssetMaterializationMode,\n} from \"./types\";\nimport { normalizeRelativePath } from \"./utils\";\n\nexport const TOOL_DIRECTORY_RELATIVE_PATH = \".make-docs\";\nexport const TOOL_DIRECTORY_MANIFEST_RELATIVE_PATH = `${TOOL_DIRECTORY_RELATIVE_PATH}/manifest.json`;\nexport const TOOL_DIRECTORY_CONFLICTS_RELATIVE_DIR = `${TOOL_DIRECTORY_RELATIVE_PATH}/conflicts`;\nexport const TOOL_DIRECTORY_RUNS_RELATIVE_DIR = `${TOOL_DIRECTORY_RELATIVE_PATH}/runs`;\nexport const TOOL_DIRECTORY_CONFIG_RELATIVE_PATH = `${TOOL_DIRECTORY_RELATIVE_PATH}/config.yaml`;\nexport const TOOL_DIRECTORY_SYSTEM_RELATIVE_PATH = `${TOOL_DIRECTORY_RELATIVE_PATH}/system`;\n\nexport const TOOL_RESOURCE_FAMILIES = [\n \"contracts\",\n \"prompts\",\n \"references\",\n \"templates\",\n] as const;\n\nexport type ToolResourceFamily = (typeof TOOL_RESOURCE_FAMILIES)[number];\n\n/** Retired product layout. These names support read-only inventory and reviewed removal only. */\nexport const RESERVED_AGENTICS_FAMILIES = [\"skills\", \"plugins\"] as const;\n\nexport type ReservedAgenticsFamily = (typeof RESERVED_AGENTICS_FAMILIES)[number];\n\n/** Legacy input locations only. Current operations keep their state in the Store. */\nexport const TOOL_DIRECTORY_RUNTIME_STATE_PATHS = [\n TOOL_DIRECTORY_MANIFEST_RELATIVE_PATH,\n TOOL_DIRECTORY_CONFLICTS_RELATIVE_DIR,\n TOOL_DIRECTORY_RUNS_RELATIVE_DIR,\n] as const;\n\nexport const TOOL_DIRECTORY_LOCAL_BOOTSTRAP_PATHS = [\n TOOL_DIRECTORY_CONFIG_RELATIVE_PATH,\n] as const;\n\nexport const TOOL_RESOURCE_MATERIALIZATION_MODES =\n SYSTEM_ASSET_MATERIALIZATION_MODES;\n\nexport type ToolResourceMaterializationMode = SystemAssetMaterializationMode;\n\nexport const LEGACY_TOOL_RESOURCE_FAMILIES = [\n \"contracts\",\n \"prompts\",\n \"references\",\n \"templates\",\n] as const;\n\nexport type LegacyToolResourceFamily =\n (typeof LEGACY_TOOL_RESOURCE_FAMILIES)[number];\n\nexport const LEGACY_TOOL_RESOURCE_ROOTS = {\n contracts: \".make-docs/contracts/system\",\n prompts: \".make-docs/prompts/system\",\n references: \".make-docs/references/system\",\n templates: \".make-docs/templates/system\",\n} as const satisfies Record<LegacyToolResourceFamily, string>;\n\nconst EARLIER_LEGACY_TOOL_RESOURCE_ROOTS = {\n prompts: \"docs/assets/prompts\",\n references: \"docs/assets/references\",\n templates: \"docs/assets/templates\",\n} as const;\n\nconst LEGACY_REFERENCE_CONTRACT_FILES = new Set([\n \"commit-message-convention.md\",\n \"coverage-pass-contract.md\",\n \"design-contract.md\",\n \"guide-contract.md\",\n \"history-record-contract.md\",\n \"output-contract.md\",\n]);\n\nexport type SystemToolResourceMigrationFixture = {\n currentPath: string;\n family: LegacyToolResourceFamily;\n targetPath: string;\n tier: \"system\";\n};\n\nexport function getToolResourcePath(family: ToolResourceFamily): string {\n return `${TOOL_DIRECTORY_SYSTEM_RELATIVE_PATH}/${family}`;\n}\n\nexport function getToolResourcePaths(): string[] {\n return TOOL_RESOURCE_FAMILIES.map(getToolResourcePath);\n}\n\n/** Legacy input path; never a current installation destination. */\nexport function getReservedAgenticsPath(family: ReservedAgenticsFamily): string {\n return `${TOOL_DIRECTORY_RELATIVE_PATH}/agentics/${family}`;\n}\n\nexport function isToolDirectorySystemResourcePath(relativePath: string): boolean {\n const normalized = normalizeRelativePath(relativePath);\n return TOOL_RESOURCE_FAMILIES.some((family) =>\n pathContainsOrEquals(normalized, getToolResourcePath(family)),\n );\n}\n\nexport function isReservedAgenticsPath(relativePath: string): boolean {\n const normalized = normalizeRelativePath(relativePath);\n return RESERVED_AGENTICS_FAMILIES.some((family) =>\n pathContainsOrEquals(normalized, getReservedAgenticsPath(family)),\n );\n}\n\nexport function isToolDirectoryRuntimeStatePath(relativePath: string): boolean {\n const normalized = normalizeRelativePath(relativePath);\n return TOOL_DIRECTORY_RUNTIME_STATE_PATHS.some((runtimePath) =>\n pathContainsOrEquals(normalized, runtimePath),\n );\n}\n\nexport function isToolDirectoryLocalBootstrapPath(\n relativePath: string,\n): boolean {\n const normalized = normalizeRelativePath(relativePath);\n return TOOL_DIRECTORY_LOCAL_BOOTSTRAP_PATHS.some(\n (bootstrapPath) => normalized === bootstrapPath,\n );\n}\n\nexport function getLocalBootstrapPathsForMaterializationMode(\n _mode: ToolResourceMaterializationMode,\n): string[] {\n return [...TOOL_DIRECTORY_LOCAL_BOOTSTRAP_PATHS];\n}\n\nexport function getLegacyToolResourceFamily(\n relativePath: string,\n): LegacyToolResourceFamily | null {\n const normalized = normalizeRelativePath(relativePath);\n\n for (const family of LEGACY_TOOL_RESOURCE_FAMILIES) {\n if (pathContainsOrEquals(normalized, LEGACY_TOOL_RESOURCE_ROOTS[family])) {\n return family;\n }\n }\n\n for (const [family, root] of Object.entries(EARLIER_LEGACY_TOOL_RESOURCE_ROOTS)) {\n if (pathContainsOrEquals(normalized, root)) {\n return family as LegacyToolResourceFamily;\n }\n }\n\n return null;\n}\n\nexport function getSystemToolResourceMigrationTarget(\n relativePath: string,\n): string | null {\n const normalized = normalizeRelativePath(relativePath);\n\n for (const family of LEGACY_TOOL_RESOURCE_FAMILIES) {\n const root = LEGACY_TOOL_RESOURCE_ROOTS[family];\n const resourcePath = getContainedRelativePath(root, normalized);\n if (resourcePath !== null) {\n return resourcePath === \"\"\n ? getToolResourcePath(family)\n : `${getToolResourcePath(family)}/${resourcePath}`;\n }\n }\n\n for (const [legacyFamily, root] of Object.entries(EARLIER_LEGACY_TOOL_RESOURCE_ROOTS)) {\n const resourcePath = getContainedRelativePath(root, normalized);\n if (resourcePath === null) {\n continue;\n }\n const family =\n legacyFamily === \"references\" && LEGACY_REFERENCE_CONTRACT_FILES.has(resourcePath)\n ? \"contracts\"\n : legacyFamily;\n return resourcePath === \"\"\n ? getToolResourcePath(family as ToolResourceFamily)\n : `${getToolResourcePath(family as ToolResourceFamily)}/${resourcePath}`;\n }\n\n return null;\n}\n\nexport function createSystemToolResourceMigrationFixture(\n relativePath: string,\n): SystemToolResourceMigrationFixture | null {\n const normalized = normalizeRelativePath(relativePath);\n const family = getLegacyToolResourceFamily(normalized);\n const targetPath = getSystemToolResourceMigrationTarget(normalized);\n\n if (family === null || targetPath === null) {\n return null;\n }\n\n return {\n currentPath: normalized,\n family,\n targetPath,\n tier: \"system\",\n };\n}\n\nexport function createSystemToolResourceMigrationFixtures(\n relativePaths: readonly string[],\n): SystemToolResourceMigrationFixture[] {\n return relativePaths\n .map(createSystemToolResourceMigrationFixture)\n .filter(\n (fixture): fixture is SystemToolResourceMigrationFixture =>\n fixture !== null,\n )\n .sort((left, right) => left.currentPath.localeCompare(right.currentPath));\n}\n\nfunction pathContainsOrEquals(candidate: string, prefix: string): boolean {\n return candidate === prefix || candidate.startsWith(`${prefix}/`);\n}\n\nfunction getContainedRelativePath(\n root: string,\n candidate: string,\n): string | null {\n if (candidate === root) {\n return \"\";\n }\n\n if (!candidate.startsWith(`${root}/`)) {\n return null;\n }\n\n return candidate.slice(root.length + 1);\n}\n","import * as os from \"node:os\";\nimport path from \"node:path\";\nimport type { Harness, InstallSelections } from \"./types\";\n\nconst HARNESS_SKILL_DIRS: Record<Harness, string> = { \"claude-code\": \".claude/skills\", codex: \".agents/skills\" };\n\nexport function getCanonicalSkillDirectory(selections: InstallSelections): string {\n const tools = selections.skillHarnesses ?? selections.harnesses;\n return selections.skillScope === \"project\" && !tools.codex && tools[\"claude-code\"]\n ? \".claude/skills\" : \".agents/skills\";\n}\n\nexport function getHarnessSkillDirectory(harness: Harness, scope: InstallSelections[\"skillScope\"], homeDir = os.homedir()): string {\n if (scope === \"project\") return HARNESS_SKILL_DIRS[harness];\n const configuredHome = harness === \"codex\" ? process.env.CODEX_HOME : process.env.CLAUDE_CONFIG_DIR;\n return path.join(configuredHome ? path.resolve(configuredHome) : path.join(homeDir, harness === \"codex\" ? \".codex\" : \".claude\"), \"skills\");\n}\n","import path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { readTextFile } from \"./utils\";\n\nexport type SkillManifestSourcePolicyKind =\n | \"first-party\"\n | \"local\"\n | \"remote-pinned\";\n\nexport type SkillProvenanceKind =\n | SkillManifestSourcePolicyKind\n | \"third-party\";\n\nexport type SkillSupportedHarness = \"claude-code\" | \"codex\";\n\nexport interface SkillAssetEntry {\n source: string;\n installPath: string;\n}\n\nexport interface SkillProvenance {\n kind: SkillProvenanceKind;\n label: string;\n manifestId?: string;\n repository?: string;\n ref?: string;\n digest?: string;\n}\n\nexport interface SkillPurpose {\n id: string;\n label: string;\n description: string;\n order?: number;\n provenance: SkillProvenance;\n}\n\nexport interface SkillManifestSourcePolicy {\n kind: SkillManifestSourcePolicyKind;\n label: string;\n allowRemoteSkillSources?: boolean;\n}\n\nexport interface SkillRegistryEntry {\n name: string;\n displayName: string;\n source: string;\n entryPoint: string;\n installName: string;\n description: string;\n purposes: string[];\n supportedHarnesses: SkillSupportedHarness[];\n provenance: SkillProvenance;\n defaultForPurposes?: string[];\n assets: SkillAssetEntry[];\n}\n\nexport interface SkillRegistry {\n schemaVersion: number;\n manifestId: string;\n displayName: string;\n description?: string;\n sourcePolicy: SkillManifestSourcePolicy;\n purposes: SkillPurpose[];\n skills: SkillRegistryEntry[];\n}\n\nexport interface EffectiveSkillRegistry {\n registry: SkillRegistry;\n source: EffectiveSkillRegistrySource;\n}\n\nexport type EffectiveSkillRegistrySource =\n | { kind: \"built-in\" }\n | { kind: \"file\"; path: string }\n | { kind: \"remote-pinned\"; reference: string; digest: string };\n\nconst REGISTRY_FILENAME = \"skill-registry.json\";\nconst FIRST_PARTY_MANIFEST_ID = \"make-docs.first-party\";\nconst EMBEDDED_SOURCE_PREFIX = \"embedded:\";\nconst FIRST_PARTY_PURPOSE_IDS = new Set([\n \"archive-management\",\n \"backlog-review\",\n \"codebase-decomposition\",\n \"documentation-maintenance\",\n \"lifecycle-closeout\",\n \"workflow-execution\",\n \"naive-uat\",\n \"plan-creation\",\n \"migration-support\",\n]);\nconst SOURCE_POLICY_KINDS = new Set<SkillManifestSourcePolicyKind>([\n \"first-party\",\n \"local\",\n \"remote-pinned\",\n]);\nconst PROVENANCE_KINDS = new Set<SkillProvenanceKind>([\n \"first-party\",\n \"local\",\n \"remote-pinned\",\n \"third-party\",\n]);\nconst SUPPORTED_HARNESSES = new Set<SkillSupportedHarness>([\n \"claude-code\",\n \"codex\",\n]);\n\nexport function loadSkillRegistry(packageRoot: string): SkillRegistry {\n const registryPath = path.join(packageRoot, REGISTRY_FILENAME);\n return loadSkillRegistryFromPath(registryPath);\n}\n\nexport function loadEffectiveSkillRegistry(options: {\n packageRoot: string;\n manifestReference?: string;\n}): EffectiveSkillRegistry {\n if (!options.manifestReference) {\n return {\n registry: loadSkillRegistry(options.packageRoot),\n source: { kind: \"built-in\" },\n };\n }\n\n if (isRemoteSource(options.manifestReference)) {\n throw new Error(\n \"Remote skills manifests require an immutable reference plus digest before install. Use a local file manifest for now or provide a future remote-pinned manifest input.\",\n );\n }\n\n const registryPath = path.resolve(options.manifestReference);\n const registry = loadSkillRegistryFromPath(registryPath);\n if (registry.sourcePolicy.kind === \"first-party\") {\n throw new Error(\"An alternate skills manifest cannot claim the built-in first-party source policy.\");\n }\n return {\n registry,\n source: { kind: \"file\", path: registryPath },\n };\n}\n\nexport function loadSkillRegistryFromPath(registryPath: string): SkillRegistry {\n let raw: string;\n try {\n raw = readTextFile(registryPath);\n } catch (cause) {\n throw new Error(`Skill registry not found at ${registryPath}`, { cause });\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n throw new Error(`Skill registry at ${registryPath} is not valid JSON`, {\n cause,\n });\n }\n\n return normalizeLocalSkillSources(\n validateSkillRegistryManifest(parsed, registryPath),\n registryPath,\n );\n}\n\nexport function validateSkillRegistryManifest(\n parsed: unknown,\n registryPath = \"skill-registry.json\",\n): SkillRegistry {\n const errors: string[] = [];\n\n if (!isPlainObject(parsed)) {\n throw new Error(`Skill registry at ${registryPath} must be an object`);\n }\n\n const schemaVersion = readRequiredNumber(\n parsed,\n \"schemaVersion\",\n \"manifest\",\n errors,\n );\n const manifestId = readRequiredString(\n parsed,\n \"manifestId\",\n \"manifest\",\n errors,\n );\n const displayName = readRequiredString(\n parsed,\n \"displayName\",\n \"manifest\",\n errors,\n );\n const description = readOptionalString(parsed, \"description\", \"manifest\", errors);\n const sourcePolicy = validateSourcePolicy(parsed.sourcePolicy, errors);\n if (\n sourcePolicy.kind === \"first-party\" &&\n manifestId !== null &&\n manifestId !== FIRST_PARTY_MANIFEST_ID\n ) {\n errors.push(\n `first-party source policy is reserved for manifest \\`${FIRST_PARTY_MANIFEST_ID}\\``,\n );\n }\n const purposes = validatePurposes(\n Array.isArray(parsed.purposes) ? parsed.purposes : null,\n sourcePolicy,\n manifestId,\n errors,\n );\n if (!Array.isArray(parsed.purposes)) {\n errors.push(\"manifest is missing required `purposes` array\");\n }\n if (!Array.isArray(parsed.skills)) {\n errors.push(\"manifest is missing required `skills` array\");\n }\n\n const skills: SkillRegistryEntry[] = [];\n if (Array.isArray(parsed.skills)) {\n const purposeIds = new Set(purposes.map((purpose) => purpose.id));\n for (const [index, entry] of parsed.skills.entries()) {\n const validated = validateEntry(\n entry,\n index,\n sourcePolicy,\n purposeIds,\n errors,\n );\n if (!validated) {\n continue;\n }\n skills.push(validated);\n }\n }\n\n if (errors.length > 0) {\n throw new Error(\n `Skill registry at ${registryPath} is invalid:\\n- ${errors.join(\"\\n- \")}`,\n );\n }\n\n return {\n schemaVersion: schemaVersion ?? 1,\n manifestId: manifestId ?? \"\",\n displayName: displayName ?? \"\",\n ...(description === undefined ? {} : { description }),\n sourcePolicy,\n purposes,\n skills,\n };\n}\n\nexport function getSkillRegistryNames(registry: SkillRegistry): string[] {\n return registry.skills.map((skill) => skill.name).sort();\n}\n\nfunction validateEntry(\n entry: unknown,\n index: number,\n sourcePolicy: SkillManifestSourcePolicy,\n purposeIds: Set<string>,\n errors: string[],\n): SkillRegistryEntry | null {\n if (!isPlainObject(entry)) {\n errors.push(`skill at index ${index} must be an object`);\n return null;\n }\n\n const name = readRequiredString(entry, \"name\", `skill at index ${index}`, errors);\n if (name === null) return null;\n\n const displayName =\n readRequiredString(entry, \"displayName\", `skill \\`${name}\\``, errors) ??\n name;\n const source = readRequiredString(entry, \"source\", `skill \\`${name}\\``, errors);\n const entryPoint = readRequiredString(\n entry,\n \"entryPoint\",\n `skill \\`${name}\\``,\n errors,\n );\n const installName = readRequiredString(\n entry,\n \"installName\",\n `skill \\`${name}\\``,\n errors,\n );\n if (source === null || entryPoint === null || installName === null)\n return null;\n\n if (sourcePolicy.kind === \"first-party\") {\n if (source !== `${EMBEDDED_SOURCE_PREFIX}${name}`) {\n errors.push(`skill \\`${name}\\` must use its embedded first-party source`);\n }\n } else if (source.startsWith(EMBEDDED_SOURCE_PREFIX)) {\n errors.push(`skill \\`${name}\\` embedded sources are reserved for the first-party registry`);\n } else if (sourcePolicy.kind !== \"local\" && !isRemoteSource(source)) {\n errors.push(`skill \\`${name}\\` must use a remote source URL unless the manifest source policy is local`);\n }\n\n const description = readRequiredString(\n entry,\n \"description\",\n `skill \\`${name}\\``,\n errors,\n );\n const purposes = validateStringArray(\n entry.purposes,\n `skill \\`${name}\\` purposes`,\n errors,\n { minItems: 1 },\n );\n for (const purposeId of purposes) {\n if (!purposeIds.has(purposeId)) {\n errors.push(`skill \\`${name}\\` references missing purpose \\`${purposeId}\\``);\n }\n }\n const supportedHarnesses = validateSupportedHarnesses(\n entry.supportedHarnesses,\n name,\n errors,\n );\n const provenance = validateProvenance(\n entry.provenance,\n `skill \\`${name}\\` provenance`,\n errors,\n );\n if (\n isRemoteSource(source) &&\n sourcePolicy.kind !== \"first-party\" &&\n !hasRemotePinnedProvenance(provenance)\n ) {\n errors.push(\n `skill \\`${name}\\` remote source requires remote-pinned provenance with immutable ref and digest`,\n );\n }\n const defaultForPurposes =\n entry.defaultForPurposes === undefined\n ? undefined\n : validateStringArray(\n entry.defaultForPurposes,\n `skill \\`${name}\\` defaultForPurposes`,\n errors,\n );\n if (defaultForPurposes) {\n for (const purposeId of defaultForPurposes) {\n if (!purposes.includes(purposeId)) {\n errors.push(\n `skill \\`${name}\\` default purpose \\`${purposeId}\\` must also appear in its purposes`,\n );\n }\n }\n }\n\n if (!Array.isArray(entry.assets)) {\n errors.push(`skill \\`${name}\\` is missing required \\`assets\\` array`);\n return null;\n }\n\n const assets: SkillAssetEntry[] = [];\n for (const [assetIndex, asset] of entry.assets.entries()) {\n if (\n !isPlainObject(asset) ||\n typeof asset.source !== \"string\" ||\n typeof asset.installPath !== \"string\"\n ) {\n errors.push(\n `skill \\`${name}\\` asset at index ${assetIndex} must include string source and installPath`,\n );\n continue;\n }\n assets.push({ source: asset.source, installPath: asset.installPath });\n }\n\n return {\n name,\n displayName,\n source,\n entryPoint,\n installName,\n description: description ?? \"\",\n purposes,\n supportedHarnesses,\n provenance,\n ...(defaultForPurposes === undefined ? {} : { defaultForPurposes }),\n assets,\n };\n}\n\nfunction validateSourcePolicy(\n value: unknown,\n errors: string[],\n): SkillManifestSourcePolicy {\n if (!isPlainObject(value)) {\n errors.push(\"manifest is missing required `sourcePolicy` metadata\");\n return { kind: \"local\", label: \"\" };\n }\n\n const kind = readRequiredString(value, \"kind\", \"sourcePolicy\", errors);\n const label = readRequiredString(value, \"label\", \"sourcePolicy\", errors);\n const allowRemoteSkillSources =\n value.allowRemoteSkillSources === undefined\n ? undefined\n : readRequiredBoolean(\n value,\n \"allowRemoteSkillSources\",\n \"sourcePolicy\",\n errors,\n );\n\n if (kind !== null && !SOURCE_POLICY_KINDS.has(kind as SkillManifestSourcePolicyKind)) {\n errors.push(\n \"sourcePolicy.kind must be one of first-party, local, or remote-pinned\",\n );\n }\n\n return {\n kind: SOURCE_POLICY_KINDS.has(kind as SkillManifestSourcePolicyKind)\n ? (kind as SkillManifestSourcePolicyKind)\n : \"local\",\n label: label ?? \"\",\n ...(allowRemoteSkillSources === undefined ? {} : { allowRemoteSkillSources }),\n };\n}\n\nfunction validatePurposes(\n values: unknown[] | null,\n sourcePolicy: SkillManifestSourcePolicy,\n manifestId: string | null,\n errors: string[],\n): SkillPurpose[] {\n if (!values) {\n return [];\n }\n\n const purposes: SkillPurpose[] = [];\n const seenPurposeIds = new Set<string>();\n for (const [index, value] of values.entries()) {\n if (!isPlainObject(value)) {\n errors.push(`purpose at index ${index} must be an object`);\n continue;\n }\n\n const id = readRequiredString(value, \"id\", `purpose at index ${index}`, errors);\n if (id === null) {\n continue;\n }\n if (seenPurposeIds.has(id)) {\n errors.push(`duplicate purpose id \\`${id}\\``);\n }\n seenPurposeIds.add(id);\n\n const provenance = validateProvenance(\n value.provenance,\n `purpose \\`${id}\\` provenance`,\n errors,\n );\n const firstPartyPurpose = FIRST_PARTY_PURPOSE_IDS.has(id);\n const firstPartyDefinition =\n provenance.kind === \"first-party\" &&\n provenance.manifestId === FIRST_PARTY_MANIFEST_ID;\n if (\n firstPartyPurpose &&\n sourcePolicy.kind !== \"first-party\" &&\n !firstPartyDefinition\n ) {\n errors.push(\n `purpose \\`${id}\\` collides with a first-party purpose id without first-party provenance`,\n );\n }\n if (!firstPartyPurpose && !isNamespacedPurposeId(id)) {\n errors.push(`third-party purpose id \\`${id}\\` must be namespaced`);\n }\n if (\n sourcePolicy.kind === \"first-party\" &&\n manifestId === FIRST_PARTY_MANIFEST_ID &&\n !firstPartyPurpose\n ) {\n errors.push(\n `first-party manifest purpose \\`${id}\\` must be a canonical make-docs purpose id`,\n );\n }\n\n const label = readRequiredString(value, \"label\", `purpose \\`${id}\\``, errors);\n const description = readRequiredString(\n value,\n \"description\",\n `purpose \\`${id}\\``,\n errors,\n );\n const order =\n value.order === undefined\n ? undefined\n : readRequiredNumber(value, \"order\", `purpose \\`${id}\\``, errors);\n\n purposes.push({\n id,\n label: label ?? \"\",\n description: description ?? \"\",\n ...(order === undefined || order === null ? {} : { order }),\n provenance,\n });\n }\n\n return purposes;\n}\n\nfunction validateProvenance(\n value: unknown,\n context: string,\n errors: string[],\n): SkillProvenance {\n if (!isPlainObject(value)) {\n errors.push(`${context} is missing required provenance metadata`);\n return { kind: \"local\", label: \"\" };\n }\n\n const kind = readRequiredString(value, \"kind\", context, errors);\n const label = readRequiredString(value, \"label\", context, errors);\n const manifestId = readOptionalString(value, \"manifestId\", context, errors);\n const repository = readOptionalString(value, \"repository\", context, errors);\n const ref = readOptionalString(value, \"ref\", context, errors);\n const digest = readOptionalString(value, \"digest\", context, errors);\n\n if (kind !== null && !PROVENANCE_KINDS.has(kind as SkillProvenanceKind)) {\n errors.push(\n `${context}.kind must be one of first-party, local, remote-pinned, or third-party`,\n );\n }\n\n return {\n kind: PROVENANCE_KINDS.has(kind as SkillProvenanceKind)\n ? (kind as SkillProvenanceKind)\n : \"local\",\n label: label ?? \"\",\n ...(manifestId === undefined ? {} : { manifestId }),\n ...(repository === undefined ? {} : { repository }),\n ...(ref === undefined ? {} : { ref }),\n ...(digest === undefined ? {} : { digest }),\n };\n}\n\nfunction validateSupportedHarnesses(\n value: unknown,\n skillName: string,\n errors: string[],\n): SkillSupportedHarness[] {\n const harnesses = validateStringArray(\n value,\n `skill \\`${skillName}\\` supportedHarnesses`,\n errors,\n { minItems: 1 },\n );\n const unique = Array.from(new Set(harnesses));\n if (unique.length !== harnesses.length) {\n errors.push(`skill \\`${skillName}\\` supportedHarnesses must be unique`);\n }\n for (const harness of unique) {\n if (!SUPPORTED_HARNESSES.has(harness as SkillSupportedHarness)) {\n errors.push(\n `skill \\`${skillName}\\` supportedHarnesses contains unsupported harness \\`${harness}\\``,\n );\n }\n }\n\n return unique.filter((harness): harness is SkillSupportedHarness =>\n SUPPORTED_HARNESSES.has(harness as SkillSupportedHarness),\n );\n}\n\nfunction validateStringArray(\n value: unknown,\n context: string,\n errors: string[],\n options: { minItems?: number } = {},\n): string[] {\n if (!Array.isArray(value)) {\n errors.push(`${context} must be an array`);\n return [];\n }\n\n const strings: string[] = [];\n for (const [index, entry] of value.entries()) {\n if (typeof entry !== \"string\" || entry.length === 0) {\n errors.push(`${context}.${index} must be a non-empty string`);\n continue;\n }\n strings.push(entry);\n }\n\n if (options.minItems && strings.length < options.minItems) {\n errors.push(`${context} must contain at least ${options.minItems} item`);\n }\n\n return strings;\n}\n\nfunction readRequiredString(\n entry: Record<string, unknown>,\n field: string,\n context: string,\n errors: string[],\n): string | null {\n const value = entry[field];\n if (typeof value !== \"string\" || value.length === 0) {\n errors.push(`${context} is missing required string field \\`${field}\\``);\n return null;\n }\n return value;\n}\n\nfunction readOptionalString(\n entry: Record<string, unknown>,\n field: string,\n context: string,\n errors: string[],\n): string | undefined {\n const value = entry[field];\n if (value === undefined) {\n return undefined;\n }\n if (typeof value !== \"string\" || value.length === 0) {\n errors.push(`${context} field \\`${field}\\` must be a non-empty string`);\n return undefined;\n }\n return value;\n}\n\nfunction readRequiredNumber(\n entry: Record<string, unknown>,\n field: string,\n context: string,\n errors: string[],\n): number | null {\n const value = entry[field];\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n errors.push(`${context} is missing required integer field \\`${field}\\``);\n return null;\n }\n return value;\n}\n\nfunction readRequiredBoolean(\n entry: Record<string, unknown>,\n field: string,\n context: string,\n errors: string[],\n): boolean | undefined {\n const value = entry[field];\n if (typeof value !== \"boolean\") {\n errors.push(`${context} field \\`${field}\\` must be a boolean`);\n return undefined;\n }\n return value;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNamespacedPurposeId(id: string): boolean {\n return /^[a-z0-9][a-z0-9-]*\\.[a-z0-9][a-z0-9-]*$/.test(id);\n}\n\nfunction hasRemotePinnedProvenance(provenance: SkillProvenance): boolean {\n return (\n provenance.kind === \"remote-pinned\" &&\n typeof provenance.ref === \"string\" &&\n provenance.ref.length > 0 &&\n typeof provenance.digest === \"string\" &&\n provenance.digest.length > 0\n );\n}\n\nfunction normalizeLocalSkillSources(\n registry: SkillRegistry,\n registryPath: string,\n): SkillRegistry {\n if (registry.sourcePolicy.kind !== \"local\") {\n return registry;\n }\n\n const baseDir = path.dirname(path.resolve(registryPath));\n return {\n ...registry,\n skills: registry.skills.map((skill) => ({\n ...skill,\n source: isRemoteSource(skill.source)\n ? skill.source\n : normalizeLocalSource(skill.source, baseDir),\n })),\n };\n}\n\nfunction normalizeLocalSource(source: string, baseDir: string): string {\n if (source.startsWith(\"file:\")) {\n return source;\n }\n\n const rawSource = source.startsWith(\"local:\")\n ? source.slice(\"local:\".length)\n : source;\n return pathToFileURL(path.resolve(baseDir, rawSource)).href;\n}\n\nfunction isRemoteSource(source: string): boolean {\n return (\n source.startsWith(\"https://\") ||\n source.startsWith(\"http://\") ||\n source.startsWith(\"github:\") ||\n source.startsWith(\"url:\")\n );\n}\n","import * as os from \"node:os\";\nimport path from \"node:path\";\nimport { resolveSkillSource } from \"./skill-resolver\";\nimport {\n loadSkillRegistry,\n type EffectiveSkillRegistry,\n type SkillRegistry,\n type SkillRegistryEntry,\n} from \"./skill-registry\";\nimport {\n HARNESSES,\n type Harness,\n type InstallSelections,\n type ResolvedFileAsset,\n type ResolvedInstallAsset,\n type ResolvedSkillExposureAsset,\n type SkillManifestSelectionSource,\n type SkillSelectionProvenanceEntry,\n} from \"./types\";\nimport { PACKAGE_ROOT } from \"./utils\";\n\nimport { getCanonicalSkillDirectory, getHarnessSkillDirectory } from \"./skill-paths\";\nexport { getCanonicalSkillDirectory, getHarnessSkillDirectory } from \"./skill-paths\";\n\n// No registry skill currently carries retired managed assets. The map stays\n// as the seam for future skill-asset retirements; the four withdrawn\n// lifecycle skills (closeout-commit, closeout-phase, work-on-phase,\n// work-on-wave) were pulled from the registry entirely (D-020 stopgap), so\n// their retired-script cleanup now flows through the generic stale-skill\n// removal path instead of per-skill retirement entries.\nconst RETIRED_MANAGED_SKILL_ASSETS: Record<string, string[]> = {};\n\nexport interface WizardSkillChoice {\n name: string;\n displayName: string;\n description: string;\n purposes: Array<{ id: string; label: string; description: string }>;\n source: string;\n sourcePolicyKind: SkillRegistry[\"sourcePolicy\"][\"kind\"];\n supportedHarnesses: Harness[];\n provenanceLabel: string;\n provenanceKind: SkillRegistryEntry[\"provenance\"][\"kind\"];\n}\n\nexport async function getDesiredSkillAssets(\n selections: InstallSelections,\n registry = loadSkillRegistry(PACKAGE_ROOT),\n): Promise<ResolvedInstallAsset[]> {\n if (!selections.skills) {\n return [];\n }\n\n const selectedSkills = new Set(selections.selectedSkills);\n const selectedEntries = registry.skills.filter((entry) =>\n selectedSkills.has(entry.name),\n );\n\n if (selectedEntries.length === 0) {\n return [];\n }\n\n const installRoot = selections.skillScope === \"project\" ? \".\" : os.homedir();\n const desiredAssets = (\n await Promise.all(\n selectedEntries.map(async (entry) => {\n const selectedTools = selections.skillHarnesses ?? selections.harnesses;\n const supportedTools = Object.fromEntries(HARNESSES.map(harness => [harness, selectedTools[harness] && entry.supportedHarnesses.includes(harness)])) as Record<Harness, boolean>;\n if (!HARNESSES.some(harness => supportedTools[harness])) return [];\n const canonicalDirectory = getCanonicalSkillDirectory({ ...selections, skillHarnesses: supportedTools });\n const canonicalRoot = getInstallPath(installRoot, canonicalDirectory);\n const nativeRoots = HARNESSES.filter(harness => supportedTools[harness]).map(harness => getInstallPath(installRoot, getHarnessSkillDirectory(harness, selections.skillScope)));\n if (nativeRoots.some((root,index) => root !== canonicalRoot && nativeRoots.indexOf(root) !== index)) throw new Error(`Selected tools share the same noncanonical Skill directory: ${nativeRoots.join(\", \")}. Use distinct CODEX_HOME and CLAUDE_CONFIG_DIR values, or select one tool, then run a fresh review.`);\n const sharedAssets = await buildSharedSkillAssets(entry, installRoot, canonicalDirectory);\n const exposureAssets = HARNESSES.flatMap((harness) => {\n if (\n !(selections.skillHarnesses ?? selections.harnesses)[harness] ||\n !entry.supportedHarnesses.includes(harness) ||\n getInstallPath(installRoot, getHarnessSkillDirectory(harness, selections.skillScope)) === getInstallPath(installRoot, canonicalDirectory)\n ) {\n return [];\n }\n\n return [\n buildHarnessSkillExposureAsset(\n entry,\n harness,\n installRoot,\n sharedAssets,\n canonicalDirectory,\n getHarnessSkillDirectory(harness, selections.skillScope),\n ),\n ];\n });\n\n return [...sharedAssets, ...exposureAssets];\n }),\n )\n ).flat();\n\n return desiredAssets.sort((left, right) =>\n left.relativePath.localeCompare(right.relativePath),\n );\n}\n\nexport async function getRetiredManagedSkillAssets(\n selections: InstallSelections,\n registry = loadSkillRegistry(PACKAGE_ROOT),\n): Promise<ResolvedFileAsset[]> {\n if (!selections.skills) {\n return [];\n }\n\n const selectedSkills = new Set(selections.selectedSkills);\n const selectedEntries = registry.skills.filter((entry) =>\n selectedSkills.has(entry.name),\n );\n\n if (selectedEntries.length === 0) {\n return [];\n }\n\n const installRoot = selections.skillScope === \"project\" ? \".\" : os.homedir();\n const retiredAssets = (\n await Promise.all(\n HARNESSES.flatMap((harness) => {\n if (!(selections.skillHarnesses ?? selections.harnesses)[harness]) {\n return [];\n }\n\n return selectedEntries.map(async (entry) => {\n if (!entry.supportedHarnesses.includes(harness)) {\n return [];\n }\n\n const [duplicatedPayloadAssets, retiredSupportAssets] =\n await Promise.all([\n buildRetiredDuplicatedSkillPayloadAssets(\n entry,\n harness,\n installRoot,\n ),\n buildRetiredManagedSkillAssets(entry, harness, installRoot),\n ]);\n\n return [...duplicatedPayloadAssets, ...retiredSupportAssets];\n });\n }),\n )\n ).flat(2);\n\n return retiredAssets.sort((left, right) =>\n left.relativePath.localeCompare(right.relativePath),\n );\n}\n\nexport function getRecommendedSkillChoices(\n registry = loadSkillRegistry(PACKAGE_ROOT),\n): WizardSkillChoice[] {\n const purposeById = new Map(\n registry.purposes.map((purpose) => [purpose.id, purpose]),\n );\n const purposeOrder = new Map(\n registry.purposes.map((purpose, index) => [\n purpose.id,\n purpose.order ?? index,\n ]),\n );\n\n const toChoice = (entry: SkillRegistryEntry): WizardSkillChoice => ({\n name: entry.name,\n displayName: entry.displayName,\n description: entry.description,\n purposes: entry.purposes.map((purposeId) => {\n const purpose = purposeById.get(purposeId);\n return {\n id: purposeId,\n label: purpose?.label ?? purposeId,\n description: purpose?.description ?? \"\",\n };\n }),\n source: entry.source,\n sourcePolicyKind: registry.sourcePolicy.kind,\n supportedHarnesses: [...entry.supportedHarnesses],\n provenanceLabel: entry.provenance.label,\n provenanceKind: entry.provenance.kind,\n });\n\n return registry.skills\n .map(toChoice)\n .sort((left, right) => {\n const leftPurposeOrder = Math.min(\n ...left.purposes.map((purpose) => purposeOrder.get(purpose.id) ?? 10_000),\n );\n const rightPurposeOrder = Math.min(\n ...right.purposes.map((purpose) => purposeOrder.get(purpose.id) ?? 10_000),\n );\n if (leftPurposeOrder !== rightPurposeOrder) {\n return leftPurposeOrder - rightPurposeOrder;\n }\n return left.name.localeCompare(right.name);\n });\n}\n\nexport function applySkillRegistrySelectionMetadata(\n selections: InstallSelections,\n effectiveRegistry: EffectiveSkillRegistry,\n): InstallSelections {\n const next = structuredClone(selections);\n if (!next.skills) {\n delete next.skillManifest;\n delete next.skillSelectionProvenance;\n return next;\n }\n\n next.skillManifest = createSkillManifestSelectionSource(effectiveRegistry);\n next.skillSelectionProvenance = createSkillSelectionProvenance(\n effectiveRegistry.registry,\n next.selectedSkills,\n );\n return next;\n}\n\nfunction createSkillManifestSelectionSource(\n effectiveRegistry: EffectiveSkillRegistry,\n): SkillManifestSelectionSource {\n const { registry, source } = effectiveRegistry;\n\n return {\n manifestId: registry.manifestId,\n displayName: registry.displayName,\n sourcePolicyKind: registry.sourcePolicy.kind,\n source:\n source.kind === \"built-in\"\n ? \"built-in\"\n : source.kind === \"file\"\n ? \"file\"\n : \"remote-pinned\",\n ...(source.kind === \"file\" ? { path: source.path } : {}),\n ...(source.kind === \"remote-pinned\" ? { digest: source.digest } : {}),\n };\n}\n\nfunction createSkillSelectionProvenance(\n registry: SkillRegistry,\n selectedSkills: string[],\n): SkillSelectionProvenanceEntry[] {\n const purposeById = new Map(\n registry.purposes.map((purpose) => [purpose.id, purpose]),\n );\n const selectedSkillSet = new Set(selectedSkills);\n\n return registry.skills\n .filter((skill) => selectedSkillSet.has(skill.name))\n .map((skill) => ({\n skillName: skill.name,\n displayName: skill.displayName,\n manifestId: registry.manifestId,\n manifestDisplayName: registry.displayName,\n sourcePolicyKind: registry.sourcePolicy.kind,\n purposeIds: [...skill.purposes],\n purposeLabels: skill.purposes.map(\n (purposeId) => purposeById.get(purposeId)?.label ?? purposeId,\n ),\n supportedHarnesses: [...skill.supportedHarnesses],\n skillSource: skill.source,\n provenanceKind: skill.provenance.kind,\n provenanceLabel: skill.provenance.label,\n ...(skill.provenance.repository\n ? { repository: skill.provenance.repository }\n : {}),\n ...(skill.provenance.ref ? { ref: skill.provenance.ref } : {}),\n ...(skill.provenance.digest ? { digest: skill.provenance.digest } : {}),\n }))\n .sort((left, right) => left.skillName.localeCompare(right.skillName));\n}\n\nasync function buildSharedSkillAssets(\n entry: SkillRegistryEntry,\n installRoot: string,\n canonicalDirectory: string,\n): Promise<ResolvedFileAsset[]> {\n const resolvedSkill = await resolveSkillSource(\n entry.source,\n entry.entryPoint,\n entry.assets,\n );\n const skillInstallRoot = getInstallPath(\n installRoot,\n canonicalDirectory,\n entry.installName,\n );\n\n const desiredAssets: ResolvedFileAsset[] = [\n {\n relativePath: getInstallPath(skillInstallRoot, entry.entryPoint),\n assetClass: \"static\",\n sourceId: getSharedSkillSourceId(entry),\n content: resolvedSkill.entryPointContent,\n },\n ];\n\n resolvedSkill.assets.forEach((asset) => {\n desiredAssets.push({\n relativePath: getInstallPath(skillInstallRoot, asset.installPath),\n assetClass: \"static\",\n sourceId: getSharedSkillAssetSourceId(entry.name, asset.installPath),\n content: asset.content,\n });\n });\n\n return desiredAssets;\n}\n\nfunction buildHarnessSkillExposureAsset(\n entry: SkillRegistryEntry,\n harness: Harness,\n installRoot: string,\n sharedAssets: ResolvedFileAsset[],\n canonicalDirectory: string,\n harnessDirectory: string,\n): ResolvedSkillExposureAsset {\n const exposureRoot = getInstallPath(\n installRoot,\n harnessDirectory,\n entry.installName,\n );\n const canonicalPayloadPath = getInstallPath(\n installRoot,\n canonicalDirectory,\n entry.installName,\n );\n const copyMirrorAssets = sharedAssets.map((asset) => {\n const skillRelativePath = path.relative(canonicalPayloadPath, asset.relativePath);\n\n return {\n ...asset,\n relativePath: getInstallPath(exposureRoot, skillRelativePath),\n sourceId: getCopyMirrorSkillAssetSourceId(\n harness,\n entry.name,\n skillRelativePath,\n ),\n };\n });\n\n return {\n kind: \"skill-exposure\",\n relativePath: exposureRoot,\n assetClass: \"static\",\n sourceId: getSkillExposureSourceId(entry, harness),\n copyMirrorAssets,\n skillExposure: {\n skillName: entry.name,\n installName: entry.installName,\n harness,\n scope: installRoot === \".\" ? \"project\" : \"global\",\n canonicalPayloadPath,\n exposurePath: exposureRoot,\n symlinkTarget: path.relative(path.dirname(exposureRoot), canonicalPayloadPath),\n preferredMode: \"symlink\",\n copyMirrorSource: canonicalPayloadPath,\n },\n };\n}\n\nasync function buildRetiredManagedSkillAssets(\n entry: SkillRegistryEntry,\n harness: Harness,\n installRoot: string,\n): Promise<ResolvedFileAsset[]> {\n const retiredAssetPaths = RETIRED_MANAGED_SKILL_ASSETS[entry.name] ?? [];\n if (retiredAssetPaths.length === 0) return [];\n const resolvedSkill = await resolveSkillSource(\n entry.source,\n entry.entryPoint,\n retiredAssetPaths.map((assetPath) => ({\n source: assetPath,\n installPath: assetPath,\n })),\n );\n const skillInstallRoot = getInstallPath(\n installRoot,\n getHarnessSkillDirectory(harness, \"project\"),\n entry.installName,\n );\n\n return resolvedSkill.assets.map((asset) => ({\n relativePath: getInstallPath(skillInstallRoot, asset.installPath),\n assetClass: \"static\",\n sourceId: getRetiredSkillAssetSourceId(harness, entry.name, asset.installPath),\n content: asset.content,\n }));\n}\n\nasync function buildRetiredDuplicatedSkillPayloadAssets(\n entry: SkillRegistryEntry,\n harness: Harness,\n installRoot: string,\n): Promise<ResolvedFileAsset[]> {\n const resolvedSkill = await resolveSkillSource(\n entry.source,\n entry.entryPoint,\n entry.assets,\n );\n const skillInstallRoot = getInstallPath(\n installRoot,\n getHarnessSkillDirectory(harness, \"project\"),\n entry.installName,\n );\n\n const retiredAssets: ResolvedFileAsset[] = [\n {\n relativePath: getInstallPath(skillInstallRoot, entry.entryPoint),\n assetClass: \"static\",\n sourceId: getLegacyDuplicatedSkillSourceId(entry, harness),\n content: resolvedSkill.entryPointContent,\n },\n ];\n\n resolvedSkill.assets.forEach((asset) => {\n retiredAssets.push({\n relativePath: getInstallPath(skillInstallRoot, asset.installPath),\n assetClass: \"static\",\n sourceId: getLegacyDuplicatedSkillAssetSourceId(\n harness,\n entry.name,\n asset.installPath,\n ),\n content: asset.content,\n });\n });\n\n return retiredAssets;\n}\n\nfunction getInstallPath(...segments: string[]): string {\n const installPath = segments.length > 1 && path.isAbsolute(segments[1])\n ? path.join(...segments.slice(1)) : path.join(...segments);\n return path.isAbsolute(installPath)\n ? installPath\n : installPath.split(path.sep).join(path.posix.sep);\n}\n\nfunction getSharedSkillSourceId(entry: SkillRegistryEntry): string {\n return `skill:shared:${entry.name}`;\n}\n\nfunction getSharedSkillAssetSourceId(\n skillName: string,\n installPath: string,\n): string {\n return `skill-shared-asset:${skillName}:${installPath}`;\n}\n\nfunction getSkillExposureSourceId(\n entry: SkillRegistryEntry,\n harness: Harness,\n): string {\n return `skill-exposure:${harness}:${entry.name}`;\n}\n\nfunction getCopyMirrorSkillAssetSourceId(\n harness: Harness,\n skillName: string,\n installPath: string,\n): string {\n return `skill-copy-mirror-asset:${harness}:${skillName}:${installPath}`;\n}\n\nfunction getRetiredSkillAssetSourceId(\n harness: Harness,\n skillName: string,\n installPath: string,\n): string {\n return `retired-skill-asset:${harness}:${skillName}:${installPath}`;\n}\n\nfunction getLegacyDuplicatedSkillSourceId(\n entry: SkillRegistryEntry,\n harness: Harness,\n): string {\n return `skill:${harness}:${entry.name}`;\n}\n\nfunction getLegacyDuplicatedSkillAssetSourceId(\n harness: Harness,\n skillName: string,\n installPath: string,\n): string {\n return `skill-asset:${harness}:${skillName}:${installPath}`;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { lstatSync, readFileSync, readdirSync } from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { SkillAssetEntry } from \"./skill-registry\";\nimport type { EmbeddedSkillBundle } from \"./embedded-skill-types\";\nimport { PACKAGE_ROOT } from \"./utils\";\n\nconst URL_PROTOCOL = \"url:\";\nconst GITHUB_PROTOCOL = \"github:\";\nconst DEFAULT_GITHUB_REF = \"main\";\nconst RAW_GITHUB_HOST = \"raw.githubusercontent.com\";\n\ninterface ResolvedDirectory {\n location: string;\n virtualPath: string;\n}\n\ninterface ResolvedFile {\n location: string;\n virtualPath: string;\n}\n\nconst remoteTextCache = new Map<string, Promise<string>>();\nconst remoteBinaryCache = new Map<string, Promise<Buffer>>();\n\nexport interface ResolvedSkillAsset {\n installPath: string;\n content: string | Buffer;\n sourcePath: string;\n}\n\nexport interface ResolvedSkill {\n entryPointContent: string;\n assets: ResolvedSkillAsset[];\n}\n\nexport class UnsupportedProtocolError extends Error {\n constructor(public readonly protocol: string) {\n super(`Unsupported skill source protocol: \\`${protocol}\\``);\n this.name = \"UnsupportedProtocolError\";\n }\n}\n\nexport async function resolveSkillSource(\n source: string,\n entryPoint: string,\n assets: SkillAssetEntry[],\n): Promise<ResolvedSkill> {\n if (source.startsWith(\"embedded:\")) {\n return resolveEmbeddedSkill(source, entryPoint, assets);\n }\n const sourceDir = resolveSourceDirectory(source);\n const entryPointFile = resolveRelativeFile(entryPoint, sourceDir);\n const entryPointContent = await readSourceText(entryPointFile);\n\n const resolvedAssets = await Promise.all(\n assets.map(async (asset) => {\n const file = resolveSourceFile(asset.source, sourceDir);\n return {\n installPath: asset.installPath,\n content: isMarkdownPath(file.virtualPath)\n ? await readSourceText(file)\n : await readSourceBinary(file),\n sourcePath: file.virtualPath,\n };\n }),\n );\n\n return {\n entryPointContent,\n assets: resolvedAssets,\n };\n}\n\nconst sha256 = (value: string | Buffer) => createHash(\"sha256\").update(value).digest(\"hex\");\n\nexport function validateEmbeddedSkillBundle(candidate: unknown): asserts candidate is EmbeddedSkillBundle {\n const invalid = () => { throw new Error(\"The embedded first-party Skill bundle is missing or corrupt. Reinstall the CLI package.\"); };\n const object = (value: unknown): value is Record<string, any> => !!value && typeof value === \"object\" && !Array.isArray(value);\n const digest = (value: unknown) => typeof value === \"string\" && /^[a-f0-9]{64}$/.test(value);\n const filePath = (value: unknown): value is string => typeof value === \"string\" && !!value &&\n !/[\\\\:\\x00-\\x1f]/.test(value) && value.split(\"/\").every((part) => !!part && !part.startsWith(\".\"));\n if (!object(candidate) || candidate.schemaVersion !== 1 || !object(candidate.payloads) ||\n !digest(candidate.packageDigest) || !digest(candidate.registryDigest) || !digest(candidate.digest)) return invalid();\n if (sha256(JSON.stringify({ packageDigest: candidate.packageDigest, registryDigest: candidate.registryDigest, payloads: candidate.payloads })) !== candidate.digest) return invalid();\n for (const [name, payload] of Object.entries(candidate.payloads)) {\n if (!/^[a-z0-9][a-z0-9-]*$/.test(name) || !object(payload) || !filePath(payload.entryPoint) ||\n !Array.isArray(payload.assets) || !object(payload.files)) return invalid();\n const expected = new Set<string>([payload.entryPoint]);\n const destinations = new Set<string>([payload.entryPoint.toLowerCase()]);\n for (const asset of payload.assets) {\n if (!object(asset) || !filePath(asset.source) || !filePath(asset.installPath) || destinations.has(asset.installPath.toLowerCase())) return invalid();\n destinations.add(asset.installPath.toLowerCase());\n expected.add(asset.source);\n }\n if (Object.keys(payload.files).length !== expected.size) return invalid();\n for (const source of expected) {\n const file = Object.hasOwn(payload.files, source) ? payload.files[source] : undefined;\n if (!object(file) || typeof file.base64 !== \"string\" || !digest(file.sha256)) return invalid();\n const bytes = Buffer.from(file.base64, \"base64\");\n if (bytes.toString(\"base64\") !== file.base64 || sha256(bytes) !== file.sha256 ||\n (source === payload.entryPoint && !Buffer.from(bytes.toString(\"utf8\")).equals(bytes))) return invalid();\n }\n }\n}\n\nasync function loadEmbeddedSkillBundle(): Promise<EmbeddedSkillBundle> {\n try {\n const { bundle, sourceTestAdapter } = await import(\"virtual:make-docs-first-party-skills\");\n validateEmbeddedSkillBundle(bundle);\n const [registryBytes, packageBytes] = await Promise.all([\n readFile(path.join(PACKAGE_ROOT, \"skill-registry.json\")),\n readFile(path.join(PACKAGE_ROOT, \"package.json\")),\n ]);\n if (sha256(registryBytes) !== bundle.registryDigest || sha256(packageBytes) !== bundle.packageDigest) {\n throw new Error(\"The embedded Skill bundle does not match this CLI package and registry.\");\n }\n loadedEmbeddedBundle = bundle;\n loadedSourceTestAdapter = sourceTestAdapter === true;\n return bundle;\n } catch (cause) {\n throw new Error(\"Cannot load the embedded first-party Skills. Rebuild or reinstall the CLI package; no source fallback is used.\", { cause });\n }\n}\n\nlet loadedEmbeddedBundle: EmbeddedSkillBundle | undefined;\nlet loadedSourceTestAdapter = false;\n\n/** Bind the complete installed runtime, including file names and raw bytes. */\nexport function readSkillRuntimeDigest(packageRoot: string, sourceTestAdapter = false): string {\n const runtimeRoot = path.join(packageRoot, \"dist\");\n const runtimeStat = lstatSync(runtimeRoot, { throwIfNoEntry: false });\n if (!runtimeStat && sourceTestAdapter) return sha256(\"explicit-source-test-adapter:no-dist\");\n if (!runtimeStat?.isDirectory() || runtimeStat.isSymbolicLink()) {\n throw new Error(\"The reviewed CLI runtime is missing or unsafe. Rebuild or reinstall the CLI package.\");\n }\n const files: Array<[string, string]> = [];\n const visit = (directory: string) => {\n for (const name of readdirSync(directory).sort()) {\n const file = path.join(directory, name);\n const stat = lstatSync(file);\n if (stat.isDirectory() && !stat.isSymbolicLink()) visit(file);\n else if (stat.isFile() && !stat.isSymbolicLink()) files.push([path.relative(runtimeRoot, file).split(path.sep).join(\"/\"), sha256(readFileSync(file))]);\n else throw new Error(\"The reviewed CLI runtime contains an unsafe file. Reinstall the CLI package.\");\n }\n };\n visit(runtimeRoot);\n if (!files.some(([name]) => name === \"index.js\")) throw new Error(\"The reviewed CLI runtime entry point is missing. Rebuild or reinstall the CLI package.\");\n return sha256(JSON.stringify(files));\n}\n\nfunction reviewedPackageDigest(bundle: EmbeddedSkillBundle): string {\n return sha256(JSON.stringify({ bundleDigest: bundle.digest, runtimeDigest: readSkillRuntimeDigest(PACKAGE_ROOT, loadedSourceTestAdapter) }));\n}\n\n/** Recheck the exact loaded payload and package inputs inside a writer's lock. */\nexport function assertEmbeddedSkillPackageDigest(expectedDigest: string): void {\n const bundle = loadedEmbeddedBundle;\n if (!bundle || reviewedPackageDigest(bundle) !== expectedDigest) {\n throw new Error(\"The reviewed embedded Skill package is not loaded or has changed.\");\n }\n validateEmbeddedSkillBundle(bundle);\n if (sha256(readFileSync(path.join(PACKAGE_ROOT, \"skill-registry.json\"))) !== bundle.registryDigest ||\n sha256(readFileSync(path.join(PACKAGE_ROOT, \"package.json\"))) !== bundle.packageDigest) {\n throw new Error(\"The reviewed Skill package or registry has changed. Preview the operation again.\");\n }\n}\n\nexport async function getEmbeddedSkillPackageDigest(): Promise<string> {\n return reviewedPackageDigest(await loadEmbeddedSkillBundle());\n}\n\nasync function resolveEmbeddedSkill(source: string, entryPoint: string, assets: SkillAssetEntry[]): Promise<ResolvedSkill> {\n const bundle = await loadEmbeddedSkillBundle();\n const name = source.slice(\"embedded:\".length);\n const payload = Object.hasOwn(bundle.payloads, name) ? bundle.payloads[name] : undefined;\n if (!payload || payload.entryPoint !== entryPoint || JSON.stringify(payload.assets) !== JSON.stringify(assets)) {\n throw new Error(`Embedded first-party Skill inventory does not match ${source}. Reinstall the CLI package.`);\n }\n const read = (filePath: string) => {\n const file = Object.hasOwn(payload.files, filePath) ? payload.files[filePath] : undefined;\n if (!file) throw new Error(`Embedded first-party Skill file is missing: ${source}/${filePath}`);\n return Buffer.from(file.base64, \"base64\");\n };\n return {\n entryPointContent: read(entryPoint).toString(\"utf8\"),\n assets: assets.map((asset) => {\n const bytes = read(asset.source);\n const text = bytes.toString(\"utf8\");\n return {\n installPath: asset.installPath,\n content: isMarkdownPath(asset.source) && Buffer.from(text).equals(bytes) ? text : bytes,\n sourcePath: `${source}/${asset.source}`,\n };\n }),\n };\n}\n\nfunction resolveSourceDirectory(source: string): ResolvedDirectory {\n if (isFileSource(source)) {\n const location = normalizeFileSource(source, { directory: true });\n return {\n location,\n virtualPath: toFileVirtualPath(location),\n };\n }\n\n if (!isRemoteSource(source)) {\n throw new UnsupportedProtocolError(extractProtocol(source));\n }\n\n const location = normalizeRemoteSource(source, { directory: true });\n return {\n location,\n virtualPath: toRemoteVirtualPath(location),\n };\n}\n\nfunction resolveSourceFile(source: string, baseDir: ResolvedDirectory): ResolvedFile {\n if (isFileSource(source)) {\n const location = normalizeFileSource(source, { directory: false });\n return {\n location,\n virtualPath: toFileVirtualPath(location),\n };\n }\n\n if (isRemoteSource(source)) {\n const location = normalizeRemoteSource(source, { directory: false });\n return {\n location,\n virtualPath: toRemoteVirtualPath(location),\n };\n }\n\n return resolveRelativeFile(source, baseDir);\n}\n\nfunction resolveRelativeFile(relativePath: string, baseDir: ResolvedDirectory): ResolvedFile {\n const nextUrl = new URL(relativePath, ensureTrailingSlash(baseDir.location)).href;\n const location = isFileSource(nextUrl)\n ? normalizeFileSource(nextUrl, { directory: false })\n : normalizeRemoteSource(nextUrl, { directory: false });\n return {\n location,\n virtualPath: isFileSource(location)\n ? toFileVirtualPath(location)\n : toRemoteVirtualPath(location),\n };\n}\n\nasync function readSourceText(file: ResolvedFile): Promise<string> {\n if (isFileSource(file.location)) {\n return readFile(fileURLToPath(file.location), \"utf8\");\n }\n\n return fetchRemoteText(file.location);\n}\n\nasync function readSourceBinary(file: ResolvedFile): Promise<Buffer> {\n if (isFileSource(file.location)) {\n return readFile(fileURLToPath(file.location));\n }\n\n return fetchRemoteBinary(file.location);\n}\n\nfunction isFileSource(source: string): boolean {\n return source.startsWith(\"file:\");\n}\n\nfunction isRemoteSource(source: string): boolean {\n return (\n source.startsWith(URL_PROTOCOL) ||\n source.startsWith(GITHUB_PROTOCOL) ||\n source.startsWith(\"https://\") ||\n source.startsWith(\"http://\")\n );\n}\n\nfunction normalizeRemoteSource(source: string, options: { directory: boolean }): string {\n if (source.startsWith(GITHUB_PROTOCOL)) {\n return normalizeGithubProtocol(source, options);\n }\n\n const rawSource = source.startsWith(URL_PROTOCOL)\n ? source.slice(URL_PROTOCOL.length)\n : source;\n const url = new URL(rawSource);\n\n if (url.hostname === \"github.com\") {\n return normalizeGithubUrl(url, options);\n }\n\n if (url.hostname === RAW_GITHUB_HOST) {\n return options.directory ? ensureTrailingSlash(url.href) : stripTrailingSlash(url.href);\n }\n\n return options.directory ? ensureTrailingSlash(url.href) : stripTrailingSlash(url.href);\n}\n\nfunction normalizeFileSource(source: string, options: { directory: boolean }): string {\n const url = new URL(source);\n return options.directory ? ensureTrailingSlash(url.href) : stripTrailingSlash(url.href);\n}\n\nfunction normalizeGithubProtocol(\n source: string,\n options: { directory: boolean },\n): string {\n const rawSource = source.slice(GITHUB_PROTOCOL.length);\n const atIndex = rawSource.lastIndexOf(\"@\");\n const withoutRef = atIndex === -1 ? rawSource : rawSource.slice(0, atIndex);\n const ref = atIndex === -1 ? DEFAULT_GITHUB_REF : rawSource.slice(atIndex + 1);\n const segments = withoutRef.split(\"/\").filter(Boolean);\n\n if (segments.length < 3) {\n throw new Error(\n `GitHub skill source \\`${source}\\` must use github:<owner>/<repo>/<path>[@<ref>]`,\n );\n }\n\n const [owner, repo, ...pathSegments] = segments;\n return buildGithubRawUrl(owner, repo, ref, pathSegments, options.directory);\n}\n\nfunction normalizeGithubUrl(url: URL, options: { directory: boolean }): string {\n const segments = url.pathname.split(\"/\").filter(Boolean);\n\n if (segments.length < 4) {\n throw new Error(\n `GitHub skill source \\`${url.href}\\` must point to a tree or blob URL.`,\n );\n }\n\n const [owner, repo, mode, ref, ...pathSegments] = segments;\n if (mode !== \"tree\" && mode !== \"blob\") {\n throw new Error(\n `GitHub skill source \\`${url.href}\\` must use /tree/ or /blob/ paths.`,\n );\n }\n\n return buildGithubRawUrl(owner, repo, ref, pathSegments, options.directory || mode === \"tree\");\n}\n\nfunction buildGithubRawUrl(\n owner: string,\n repo: string,\n ref: string,\n pathSegments: string[],\n directory: boolean,\n): string {\n const pathname = pathSegments.join(\"/\");\n const base = `https://${RAW_GITHUB_HOST}/${owner}/${repo}/${ref}/${pathname}`;\n return directory ? ensureTrailingSlash(base) : stripTrailingSlash(base);\n}\n\nfunction ensureTrailingSlash(value: string): string {\n return value.endsWith(\"/\") ? value : `${value}/`;\n}\n\nfunction stripTrailingSlash(value: string): string {\n return value.endsWith(\"/\") ? value.slice(0, -1) : value;\n}\n\nfunction toRemoteVirtualPath(source: string): string {\n const url = new URL(source);\n const joined = path.posix.join(\"/\", url.host, url.pathname);\n return joined.endsWith(\"/\") ? joined.slice(0, -1) : joined;\n}\n\nfunction toFileVirtualPath(source: string): string {\n return fileURLToPath(source);\n}\n\nasync function fetchRemoteText(url: string): Promise<string> {\n const cached = remoteTextCache.get(url);\n if (cached) {\n return cached;\n }\n\n const request = fetchRemote(url, \"text\") as Promise<string>;\n remoteTextCache.set(url, request);\n return request;\n}\n\nasync function fetchRemoteBinary(url: string): Promise<Buffer> {\n const cached = remoteBinaryCache.get(url);\n if (cached) {\n return cached;\n }\n\n const request = fetchRemote(url, \"binary\") as Promise<Buffer>;\n remoteBinaryCache.set(url, request);\n return request;\n}\n\nasync function fetchRemote(url: string, mode: \"text\" | \"binary\"): Promise<string | Buffer> {\n const response = await fetch(url, {\n headers: {\n \"User-Agent\": \"make-docs-cli\",\n },\n });\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch skill source \\`${url}\\`: ${response.status} ${response.statusText}`,\n );\n }\n\n if (mode === \"text\") {\n return response.text();\n }\n\n return Buffer.from(await response.arrayBuffer());\n}\n\nfunction isMarkdownPath(filePath: string): boolean {\n return path.posix.extname(filePath).toLowerCase() === \".md\";\n}\n\nfunction extractProtocol(uri: string): string {\n if (/^https?:\\/\\//.test(uri)) {\n const url = new URL(uri);\n return `${url.protocol}//`;\n }\n\n const colon = uri.indexOf(\":\");\n return colon === -1 ? uri : uri.slice(0, colon + 1);\n}\n","import type { Capability, InstallProfile } from \"./types\";\n\nexport interface PromptRule {\n relativePath: string;\n requires: Capability[];\n}\n\nexport const PROMPT_RULES: PromptRule[] = [\n {\n relativePath: \".make-docs/system/prompts/docs-path-hygiene-cleanup.prompt.md\",\n requires: [],\n },\n {\n relativePath: \".make-docs/system/prompts/performance-coverage.prompt.md\",\n requires: [],\n },\n {\n relativePath: \".make-docs/system/prompts/request-to-design.prompt.md\",\n requires: [\"designs\"],\n },\n {\n relativePath: \".make-docs/system/prompts/designs-to-plan.prompt.md\",\n requires: [\"designs\", \"plans\"],\n },\n {\n relativePath: \".make-docs/system/prompts/designs-to-plan-change.prompt.md\",\n requires: [\"designs\", \"plans\"],\n },\n {\n relativePath: \".make-docs/system/prompts/plan-to-prd-change.prompt.md\",\n requires: [\"plans\", \"prd\"],\n },\n {\n relativePath: \".make-docs/system/prompts/plan-to-prd-green-field.prompt.md\",\n requires: [\"plans\", \"prd\"],\n },\n {\n relativePath: \".make-docs/system/prompts/prd-change-to-work.prompt.md\",\n requires: [\"prd\", \"work\"],\n },\n {\n relativePath: \".make-docs/system/prompts/prd-to-work-full-prd.prompt.md\",\n requires: [\"prd\", \"work\"],\n },\n {\n relativePath: \".make-docs/system/prompts/prd-to-work-prd-feature.prompt.md\",\n requires: [\"prd\", \"work\"],\n },\n {\n relativePath: \".make-docs/system/prompts/coverage-pass-maintainer-guide.prompt.md\",\n requires: [\"work\"],\n },\n {\n relativePath: \".make-docs/system/prompts/coverage-pass-user-guide.prompt.md\",\n requires: [\"work\"],\n },\n {\n relativePath: \".make-docs/system/prompts/coverage-pass-prd-reconciliation.prompt.md\",\n requires: [\"work\"],\n },\n {\n relativePath: \".make-docs/system/prompts/coverage-pass-testing-uat.prompt.md\",\n requires: [\"work\"],\n },\n {\n relativePath: \".make-docs/system/prompts/naive-uat-facilitator.prompt.md\",\n requires: [\"work\"],\n },\n {\n relativePath: \".make-docs/system/prompts/naive-uat-tester.prompt.md\",\n requires: [\"work\"],\n },\n {\n relativePath: \".make-docs/system/prompts/work-to-guides.prompt.md\",\n requires: [\"work\"],\n },\n {\n relativePath: \".make-docs/system/prompts/update-readme-green-field.prompt.md\",\n requires: [\"designs\", \"plans\"],\n },\n {\n relativePath: \".make-docs/system/prompts/session-to-history-record.prompt.md\",\n requires: [],\n },\n {\n relativePath: \".make-docs/system/prompts/work-to-commit-message.prompt.md\",\n requires: [],\n },\n];\n\nconst PLAN_TEMPLATE_PATHS = [\n \".make-docs/system/templates/plan-overview.md\",\n \".make-docs/system/templates/plan-prd.md\",\n \".make-docs/system/templates/plan-prd-decompose.md\",\n \".make-docs/system/templates/plan-prd-change.md\",\n];\n\nconst PRD_TEMPLATE_PATHS = [\n \".make-docs/system/templates/prd-architecture.md\",\n \".make-docs/system/templates/prd-glossary.md\",\n \".make-docs/system/templates/prd-index.md\",\n \".make-docs/system/templates/prd-overview.md\",\n \".make-docs/system/templates/prd-reference.md\",\n \".make-docs/system/templates/prd-risk-register.md\",\n \".make-docs/system/templates/prd-subsystem.md\",\n];\n\nconst WORK_TEMPLATE_PATHS = [\n \".make-docs/system/templates/work-index.md\",\n \".make-docs/system/templates/work-phase.md\",\n];\n\nconst ALWAYS_TEMPLATE_PATHS = [\n \".make-docs/system/templates/guide-maintainer.md\",\n \".make-docs/system/templates/guide-user.md\",\n \".make-docs/system/templates/history-record.md\",\n \".make-docs/system/templates/naive-uat-scenario.md\",\n \".make-docs/system/templates/performance-evidence-profile.md\",\n];\n\nconst REQUIRED_REFERENCE_PATHS = {\n designs: [\n \".make-docs/system/references/design-workflow.md\",\n \".make-docs/system/contracts/design-contract.md\",\n ],\n plans: [\n \".make-docs/system/references/planning-workflow.md\",\n \".make-docs/system/contracts/output-contract.md\",\n \".make-docs/system/references/prd-change-management.md\",\n ],\n prd: [\n \".make-docs/system/references/execution-workflow.md\",\n \".make-docs/system/contracts/output-contract.md\",\n \".make-docs/system/references/prd-change-management.md\",\n ],\n work: [\n \".make-docs/system/references/execution-workflow.md\",\n \".make-docs/system/contracts/output-contract.md\",\n \".make-docs/system/references/prd-change-management.md\",\n ],\n} as const;\n\nconst ALWAYS_REFERENCE_PATHS = [\n \".make-docs/system/contracts/human-experience-contract.md\",\n \".make-docs/system/references/human-experience.md\",\n \".make-docs/system/contracts/performance-evidence-governance.md\",\n \".make-docs/system/references/performance-evidence.md\",\n \".make-docs/system/contracts/guide-contract.md\",\n \".make-docs/system/contracts/deferred-obligation-contract.md\",\n \".make-docs/system/contracts/naive-uat-contract.md\",\n \".make-docs/system/references/wave-model.md\",\n \".make-docs/system/references/lifecycle.md\",\n \".make-docs/system/contracts/coverage-pass-contract.md\",\n \".make-docs/system/contracts/history-record-contract.md\",\n \".make-docs/system/contracts/commit-message-convention.md\",\n \".make-docs/system/contracts/system-resource-contract.md\",\n \".make-docs/system/references/path-and-link-hygiene.md\",\n \".make-docs/system/references/naive-uat-workflow.md\",\n \".make-docs/system/references/naive-uat-validation.md\",\n \".make-docs/system-resources.catalog.json\",\n \".make-docs/system-resources.schema.json\",\n];\n\nconst ALWAYS_SCRIPT_PATHS: string[] = [];\n\nexport function profileHasCapabilities(\n profile: InstallProfile,\n capabilities: Capability[],\n): boolean {\n return capabilities.every(\n (capability) => profile.capabilityState[capability].effectiveSelection,\n );\n}\n\nexport function getPromptPaths(profile: InstallProfile): string[] {\n return PROMPT_RULES.filter((rule) => profileHasCapabilities(profile, rule.requires)).map(\n (rule) => rule.relativePath,\n );\n}\n\nexport function getScriptPaths(_profile: InstallProfile): string[] {\n return [...ALWAYS_SCRIPT_PATHS];\n}\n\nexport function getTemplatePaths(profile: InstallProfile): string[] {\n const paths = new Set<string>();\n\n for (const templatePath of ALWAYS_TEMPLATE_PATHS) {\n paths.add(templatePath);\n }\n\n if (profile.capabilityState.designs.effectiveSelection) {\n paths.add(\".make-docs/system/templates/design.md\");\n }\n\n if (profile.capabilityState.plans.effectiveSelection) {\n for (const templatePath of PLAN_TEMPLATE_PATHS) {\n paths.add(templatePath);\n }\n }\n\n if (profile.capabilityState.prd.effectiveSelection) {\n for (const templatePath of PRD_TEMPLATE_PATHS) {\n paths.add(templatePath);\n }\n }\n\n if (profile.capabilityState.work.effectiveSelection) {\n for (const templatePath of WORK_TEMPLATE_PATHS) {\n paths.add(templatePath);\n }\n }\n\n return Array.from(paths).sort();\n}\n\nexport function getReferencePaths(profile: InstallProfile): string[] {\n const paths = new Set<string>();\n\n for (const referencePath of ALWAYS_REFERENCE_PATHS) {\n paths.add(referencePath);\n }\n\n for (const capability of Object.keys(REQUIRED_REFERENCE_PATHS) as Capability[]) {\n if (profile.capabilityState[capability].effectiveSelection) {\n for (const referencePath of REQUIRED_REFERENCE_PATHS[capability]) {\n paths.add(referencePath);\n }\n }\n }\n\n if (profile.effectiveCapabilities.length > 0) {\n paths.add(\".make-docs/system/references/harness-capability-matrix.md\");\n }\n\n return Array.from(paths).sort();\n}\n\nexport function getReferenceDirInstalled(profile: InstallProfile): boolean {\n return getReferencePaths(profile).length > 0;\n}\n\nexport function getTemplateDirInstalled(profile: InstallProfile): boolean {\n return getTemplatePaths(profile).length > 0;\n}\n\nexport function getPromptsDirInstalled(profile: InstallProfile): boolean {\n return getPromptPaths(profile).length > 0;\n}\n","import {\n getPromptPaths,\n getReferencePaths,\n getScriptPaths,\n getTemplatePaths,\n} from \"./rules\";\nimport {\n getLocalBootstrapPathsForMaterializationMode,\n} from \"./tool-directory\";\nimport type {\n InstallProfile,\n InstructionKind,\n ResolvedAsset,\n SystemAssetMaterializationMode,\n SystemAssetMaterializationPlan,\n} from \"./types\";\nimport { DEFAULT_SYSTEM_ASSET_MATERIALIZATION_MODE } from \"./types\";\nimport { getActiveInstructionKinds } from \"./types\";\nimport { getConfiguredRouterPaths, getRouterTemplateSourcePath } from \"./router-paths\";\nimport { readPackageFile } from \"./utils\";\n\nfunction getPackageSourcePath(relativePath: string): string {\n return relativePath;\n}\n\nfunction buildAsset(relativePath: string, profile: InstallProfile): ResolvedAsset {\n const sourcePath = getRouterTemplateSourcePath(profile, getPackageSourcePath(relativePath));\n return {\n relativePath,\n assetClass: \"scoped-static\",\n sourceId: `file:${sourcePath}`,\n content: readPackageFile(sourcePath),\n };\n}\n\nfunction addInstructionAssets(\n profile: InstallProfile,\n activeInstructionKind: InstructionKind,\n relativePaths: Set<string>,\n): void {\n for (const relativePath of getConfiguredRouterPaths(profile, activeInstructionKind)) {\n relativePaths.add(relativePath);\n }\n}\n\nexport function getDesiredAssets(profile: InstallProfile): ResolvedAsset[] {\n return getDesiredAssetsForMaterializationMode(\n profile,\n DEFAULT_SYSTEM_ASSET_MATERIALIZATION_MODE,\n );\n}\n\nexport function getDesiredAssetsForMaterializationMode(\n profile: InstallProfile,\n mode: SystemAssetMaterializationMode,\n): ResolvedAsset[] {\n const relativePaths = getDesiredSystemAssetPaths(profile);\n const materializedPaths =\n mode === DEFAULT_SYSTEM_ASSET_MATERIALIZATION_MODE\n ? relativePaths\n : filterMaterializedLocalBootstrapAssetPaths(profile, mode, relativePaths);\n\n return Array.from(materializedPaths)\n .sort()\n .map((relativePath) => buildAsset(relativePath, profile));\n}\n\nexport function getSystemAssetMaterializationPlan(\n profile: InstallProfile,\n mode: SystemAssetMaterializationMode = DEFAULT_SYSTEM_ASSET_MATERIALIZATION_MODE,\n): SystemAssetMaterializationPlan {\n const allSystemAssetPaths = Array.from(getDesiredSystemAssetPaths(profile)).sort();\n const localBootstrapPaths = getLocalBootstrapSystemAssetPaths(profile, mode);\n const localBootstrapPathSet = new Set(localBootstrapPaths);\n const deferredSystemAssetPaths =\n mode === DEFAULT_SYSTEM_ASSET_MATERIALIZATION_MODE\n ? []\n : allSystemAssetPaths.filter((relativePath) => !localBootstrapPathSet.has(relativePath));\n const materializationClasses = Object.fromEntries([\n ...localBootstrapPaths.map((relativePath) => [\n relativePath,\n \"always-local-bootstrap\" as const,\n ]),\n ...allSystemAssetPaths\n .filter((relativePath) => !localBootstrapPathSet.has(relativePath))\n .map((relativePath) => [\n relativePath,\n mode === DEFAULT_SYSTEM_ASSET_MATERIALIZATION_MODE\n ? (\"materialized-system-asset\" as const)\n : (\"deferred-system-asset\" as const),\n ]),\n ]);\n\n return {\n mode,\n localBootstrapPaths,\n deferredSystemAssetPaths,\n materializationClasses,\n };\n}\n\nexport function getLocalBootstrapSystemAssetPaths(\n profile: InstallProfile,\n mode: SystemAssetMaterializationMode,\n): string[] {\n return Array.from(\n new Set([\n ...getLocalBootstrapPathsForMaterializationMode(mode),\n ...getLocalBootstrapInstructionRouterPaths(profile),\n ]),\n ).sort();\n}\n\nfunction getDesiredSystemAssetPaths(profile: InstallProfile): Set<string> {\n const relativePaths = new Set<string>();\n\n for (const referencePath of getReferencePaths(profile)) {\n relativePaths.add(referencePath);\n }\n\n for (const templatePath of getTemplatePaths(profile)) {\n relativePaths.add(templatePath);\n }\n\n for (const promptPath of getPromptPaths(profile)) {\n relativePaths.add(promptPath);\n }\n\n for (const scriptPath of getScriptPaths(profile)) {\n relativePaths.add(scriptPath);\n }\n\n for (const instructionKind of getActiveInstructionKinds(profile.selections)) {\n addInstructionAssets(profile, instructionKind, relativePaths);\n }\n\n return relativePaths;\n}\n\nfunction filterMaterializedLocalBootstrapAssetPaths(\n profile: InstallProfile,\n mode: SystemAssetMaterializationMode,\n relativePaths: Set<string>,\n): Set<string> {\n const localBootstrapPaths = new Set(getLocalBootstrapSystemAssetPaths(profile, mode));\n return new Set(\n Array.from(relativePaths).filter((relativePath) =>\n localBootstrapPaths.has(relativePath),\n ),\n );\n}\n\nfunction getLocalBootstrapInstructionRouterPaths(profile: InstallProfile): string[] {\n const relativePaths = new Set<string>();\n\n for (const instructionKind of getActiveInstructionKinds(profile.selections)) {\n for (const relativePath of getConfiguredRouterPaths(profile, instructionKind)) {\n relativePaths.add(relativePath);\n }\n }\n\n return Array.from(relativePaths).sort();\n}\n"],"mappings":";;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,OAAO,QAAQ;AACf,OAAO,UAAU;AAiDV,IAAM,yBAAN,cAAqC,MAAM;AAAA,EAChD,YACW,MAMT,SACS,OACT;AACA,UAAM,OAAO;AATJ;AAOA;AAGT,SAAK,OAAO;AAAA,EACd;AACF;AAEA,SAAS,aAAa,OAAsC;AAC1D,MAAI,UAAU,WAAW,UAAU,YAAY,UAAU,QAAS,QAAO;AACzE,QAAM,IAAI;AAAA,IACR;AAAA,IACA,iDAAiD,KAAK;AAAA,EACxD;AACF;AAEA,SAAS,QAAQ,MAA2D;AAC1E,SAAO,SAAS,UAAU,KAAK,QAAQ,KAAK;AAC9C;AAGO,SAAS,oBACd,OACA,MACA,MAAM,SAAS,UAAU,SAAS,KAC1B;AACR,MAAI,CAAC,MAAM,KAAK,GAAG;AACjB,UAAM,IAAI,uBAAuB,eAAe,yBAAyB;AAAA,EAC3E;AACA,QAAM,MAAM,QAAQ,IAAI;AACxB,QAAM,aAAa,IAAI,WAAW,KAAK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","mkdirSync","readFileSync","writeFileSync","openSync","closeSync","fsyncSync","unlinkSync","readdirSync","rmdirSync","fstatSync","path","path","res","res","map","schema","node","schema","path","i","end","isBlock","map","value","map","schema","stringify","comment","str","schema","map","map","schema","schema","seq","seq","schema","intIdentify","schema","seq","schema","pairs","map","schema","pairs","omap","seq","floatNaN","floatExp","float","intIdentify","intResolve","n","intStringify","intOct","int","intHex","schema","set","map","res","schema","intOct","int","intHex","floatNaN","floatExp","float","schema","tags","merge","schema","path","res","composeNode","composeEmptyNode","map","composeNode","composeEmptyNode","seq","composeNode","composeEmptyNode","isMap","map","CN","value","end","schema","tag","BREAK","SKIP","REMOVE","visit","path","SCALAR","SCALAR","i","ch","SCALAR","map","start","seq","stringify","randomUUID","closeSync","constants","fstatSync","lstatSync","openSync","readFileSync","unlinkSync","path","closeSync","constants","fstatSync","fsyncSync","lstatSync","openSync","readdirSync","path","require","lstatSync","targetPath","openSync","constants","fstatSync","closeSync","path","fsyncSync","readdirSync","active","stat","lstatSync","path","sameFile","lstatSync","path","openSync","constants","fstatSync","readFileSync","closeSync","randomUUID","unlinkSync","randomUUID","closeSync","constants","fstatSync","fsyncSync","lstatSync","mkdirSync","openSync","readFileSync","unlinkSync","writeFileSync","path","blocked","lstatSync","path","checkout","mkdirSync","openSync","randomUUID","writeFileSync","fsyncSync","fstatSync","unlinkSync","closeSync","constants","readFileSync","randomUUID","os","existsSync","path","active","nextContent","createHash","mkdirSync","lstatSync","readFileSync","readdirSync","rmdirSync","rmSync","writeFileSync","path","now","lstatSync","readdirSync","rmdirSync","path","path","randomUUID","os","path","getContainedRelativePath","timestamp","os","path","HARNESS_SKILL_DIRS","held","createHash","path","canonicalPath","selected","lstatSync","randomUUID","mkdirSync","rows","readFileSync","unlinkSync","existsSync","matches","row","owner","target","openSync","writeFileSync","fsyncSync","closeSync","readdirSync","fstatSync","rmdirSync","state","ordered","conflicts","remaining","existsSync","readFileSync","mkdirSync","path","writeFileSync","held","path","path","isPlainObject","validateStringArray","os","path","lstatSync","readFileSync","readdirSync","createHash","path","fileURLToPath","createHash","path","lstatSync","visit","readdirSync","readFileSync","location","isRemoteSource","fileURLToPath","path"]}