@brucewaynedecoy/make-docs 1.0.0-rc.1 → 2.0.3

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 (187) hide show
  1. package/LICENSE +21 -201
  2. package/README.md +31 -67
  3. package/dist/backup-GCM64IPN.js +20 -0
  4. package/dist/backup-GCM64IPN.js.map +1 -0
  5. package/dist/chunk-2HNJCJJE.js +1291 -0
  6. package/dist/chunk-2HNJCJJE.js.map +1 -0
  7. package/dist/chunk-4LLSMDWJ.js +24674 -0
  8. package/dist/chunk-4LLSMDWJ.js.map +1 -0
  9. package/dist/chunk-57GN6ALR.js +204 -0
  10. package/dist/chunk-57GN6ALR.js.map +1 -0
  11. package/dist/chunk-C2IBRVUA.js +4136 -0
  12. package/dist/chunk-C2IBRVUA.js.map +1 -0
  13. package/dist/chunk-D4HDZEJT.js +37 -0
  14. package/dist/chunk-D4HDZEJT.js.map +1 -0
  15. package/dist/chunk-DFQJENNL.js +2340 -0
  16. package/dist/chunk-DFQJENNL.js.map +1 -0
  17. package/dist/chunk-DNDM7DUQ.js +39 -0
  18. package/dist/chunk-DNDM7DUQ.js.map +1 -0
  19. package/dist/chunk-GPVKIBFC.js +875 -0
  20. package/dist/chunk-GPVKIBFC.js.map +1 -0
  21. package/dist/chunk-IHMZ2OCS.js +1575 -0
  22. package/dist/chunk-IHMZ2OCS.js.map +1 -0
  23. package/dist/chunk-O2UZ35PV.js +523 -0
  24. package/dist/chunk-O2UZ35PV.js.map +1 -0
  25. package/dist/chunk-U25GFKNZ.js +13995 -0
  26. package/dist/chunk-U25GFKNZ.js.map +1 -0
  27. package/dist/chunk-Z5K4FHYP.js +922 -0
  28. package/dist/chunk-Z5K4FHYP.js.map +1 -0
  29. package/dist/index.js +3798 -250
  30. package/dist/index.js.map +1 -1
  31. package/dist/self-UHPM4A2U.js +653 -0
  32. package/dist/self-UHPM4A2U.js.map +1 -0
  33. package/dist/server-N7XAAV3X.js +512 -0
  34. package/dist/server-N7XAAV3X.js.map +1 -0
  35. package/dist/setup-system-JUHGDZJW.js +544 -0
  36. package/dist/setup-system-JUHGDZJW.js.map +1 -0
  37. package/dist/{skills-command-3ESCZ75U.js → skills-command-W3SE3OFP.js} +190 -32
  38. package/dist/skills-command-W3SE3OFP.js.map +1 -0
  39. package/dist/uninstall-BGMJ6KCI.js +223 -0
  40. package/dist/uninstall-BGMJ6KCI.js.map +1 -0
  41. package/dist/virtual_make-docs-first-party-skills-VXSUUHTL.js +11 -0
  42. package/dist/virtual_make-docs-first-party-skills-VXSUUHTL.js.map +1 -0
  43. package/package.json +9 -6
  44. package/skill-registry.json +328 -125
  45. package/skill-registry.schema.json +221 -45
  46. package/template/.make-docs/AGENTS.md +18 -0
  47. package/template/.make-docs/CLAUDE.md +18 -0
  48. package/template/.make-docs/archive/AGENTS.md +11 -0
  49. package/template/.make-docs/archive/CLAUDE.md +11 -0
  50. package/template/.make-docs/system/AGENTS.md +12 -0
  51. package/template/.make-docs/system/CLAUDE.md +12 -0
  52. package/template/.make-docs/system/contracts/AGENTS.md +13 -0
  53. package/template/.make-docs/system/contracts/CLAUDE.md +13 -0
  54. package/template/{docs/assets/references → .make-docs/system/contracts}/commit-message-convention.md +4 -4
  55. package/template/.make-docs/system/contracts/coverage-pass-contract.md +198 -0
  56. package/template/.make-docs/system/contracts/deferred-obligation-contract.md +128 -0
  57. package/template/{docs/assets/references → .make-docs/system/contracts}/design-contract.md +7 -2
  58. package/template/{docs/assets/references → .make-docs/system/contracts}/guide-contract.md +21 -19
  59. package/template/{docs/assets/references → .make-docs/system/contracts}/history-record-contract.md +17 -11
  60. package/template/.make-docs/system/contracts/human-experience-contract.md +134 -0
  61. package/template/.make-docs/system/contracts/naive-uat-contract.md +231 -0
  62. package/template/.make-docs/system/contracts/output-contract.md +277 -0
  63. package/template/.make-docs/system/contracts/performance-evidence-governance.md +257 -0
  64. package/template/.make-docs/system/contracts/system-resource-contract.md +93 -0
  65. package/template/.make-docs/system/prompts/AGENTS.md +12 -0
  66. package/template/.make-docs/system/prompts/CLAUDE.md +12 -0
  67. package/template/.make-docs/system/prompts/coverage-pass-maintainer-guide.prompt.md +20 -0
  68. package/template/.make-docs/system/prompts/coverage-pass-prd-reconciliation.prompt.md +18 -0
  69. package/template/.make-docs/system/prompts/coverage-pass-testing-uat.prompt.md +46 -0
  70. package/template/.make-docs/system/prompts/coverage-pass-user-guide.prompt.md +20 -0
  71. package/template/.make-docs/system/prompts/designs-to-plan-change.prompt.md +18 -0
  72. package/template/.make-docs/system/prompts/designs-to-plan.prompt.md +14 -0
  73. package/template/.make-docs/system/prompts/docs-path-hygiene-cleanup.prompt.md +29 -0
  74. package/template/.make-docs/system/prompts/naive-uat-facilitator.prompt.md +28 -0
  75. package/template/.make-docs/system/prompts/naive-uat-tester.prompt.md +20 -0
  76. package/template/.make-docs/system/prompts/performance-coverage.prompt.md +63 -0
  77. package/template/.make-docs/system/prompts/plan-to-prd-change.prompt.md +12 -0
  78. package/template/.make-docs/system/prompts/plan-to-prd-green-field.prompt.md +10 -0
  79. package/template/.make-docs/system/prompts/prd-change-to-work.prompt.md +14 -0
  80. package/template/.make-docs/system/prompts/prd-to-work-full-prd.prompt.md +10 -0
  81. package/template/.make-docs/system/prompts/prd-to-work-prd-feature.prompt.md +10 -0
  82. package/template/.make-docs/system/prompts/request-to-design.prompt.md +20 -0
  83. package/template/.make-docs/system/prompts/session-to-history-record.prompt.md +23 -0
  84. package/template/{docs/assets → .make-docs/system}/prompts/work-to-commit-message.prompt.md +2 -2
  85. package/template/.make-docs/system/prompts/work-to-guides.prompt.md +22 -0
  86. package/template/.make-docs/system/references/AGENTS.md +14 -0
  87. package/template/.make-docs/system/references/CLAUDE.md +14 -0
  88. package/template/{docs/assets → .make-docs/system}/references/design-workflow.md +15 -2
  89. package/template/.make-docs/system/references/execution-workflow.md +189 -0
  90. package/template/.make-docs/system/references/human-experience.md +138 -0
  91. package/template/.make-docs/system/references/lifecycle.md +153 -0
  92. package/template/.make-docs/system/references/naive-uat-validation.md +65 -0
  93. package/template/.make-docs/system/references/naive-uat-workflow.md +64 -0
  94. package/template/.make-docs/system/references/path-and-link-hygiene.md +101 -0
  95. package/template/.make-docs/system/references/performance-evidence.md +114 -0
  96. package/template/.make-docs/system/references/planning-workflow.md +209 -0
  97. package/template/.make-docs/system/references/prd-change-management.md +165 -0
  98. package/template/{docs/assets → .make-docs/system}/references/wave-model.md +10 -8
  99. package/template/.make-docs/system/templates/AGENTS.md +12 -0
  100. package/template/.make-docs/system/templates/CLAUDE.md +12 -0
  101. package/template/.make-docs/system/templates/design.md +79 -0
  102. package/template/{docs/assets/templates/guide-developer.md → .make-docs/system/templates/guide-maintainer.md} +7 -3
  103. package/template/{docs/assets → .make-docs/system}/templates/guide-user.md +6 -2
  104. package/template/{docs/assets → .make-docs/system}/templates/history-record.md +6 -3
  105. package/template/.make-docs/system/templates/naive-uat-scenario.md +91 -0
  106. package/template/.make-docs/system/templates/performance-evidence-profile.md +252 -0
  107. package/template/.make-docs/system/templates/plan-overview.md +76 -0
  108. package/template/.make-docs/system/templates/plan-prd-change.md +155 -0
  109. package/template/{docs/assets → .make-docs/system}/templates/plan-prd-decompose.md +10 -0
  110. package/template/{docs/assets → .make-docs/system}/templates/plan-prd.md +28 -2
  111. package/template/{docs/assets → .make-docs/system}/templates/prd-architecture.md +13 -0
  112. package/template/.make-docs/system/templates/prd-glossary.md +28 -0
  113. package/template/.make-docs/system/templates/prd-index.md +70 -0
  114. package/template/{docs/assets → .make-docs/system}/templates/prd-overview.md +13 -0
  115. package/template/.make-docs/system/templates/prd-reference.md +30 -0
  116. package/template/{docs/assets → .make-docs/system}/templates/prd-risk-register.md +16 -1
  117. package/template/{docs/assets → .make-docs/system}/templates/prd-subsystem.md +15 -0
  118. package/template/.make-docs/system/templates/work-index.md +58 -0
  119. package/template/.make-docs/system/templates/work-phase.md +107 -0
  120. package/template/.make-docs/system-resources.catalog.json +91 -0
  121. package/template/.make-docs/system-resources.schema.json +204 -0
  122. package/template/AGENTS.md +8 -1
  123. package/template/CLAUDE.md +8 -1
  124. package/template/docs/AGENTS.codex-only.md +22 -0
  125. package/template/docs/AGENTS.md +21 -13
  126. package/template/docs/CLAUDE.claude-only.md +22 -0
  127. package/template/docs/CLAUDE.md +21 -13
  128. package/template/docs/assets/AGENTS.md +11 -7
  129. package/template/docs/assets/CLAUDE.md +11 -7
  130. package/template/docs/designs/AGENTS.md +8 -3
  131. package/template/docs/designs/CLAUDE.md +8 -3
  132. package/template/docs/plans/AGENTS.md +10 -3
  133. package/template/docs/plans/CLAUDE.md +10 -3
  134. package/template/docs/prd/AGENTS.md +14 -4
  135. package/template/docs/prd/CLAUDE.md +14 -4
  136. package/template/docs/work/AGENTS.md +10 -3
  137. package/template/docs/work/CLAUDE.md +10 -3
  138. package/dist/chunk-HP3HBG7F.js +0 -626
  139. package/dist/chunk-HP3HBG7F.js.map +0 -1
  140. package/dist/chunk-QRFH4J6H.js +0 -1194
  141. package/dist/chunk-QRFH4J6H.js.map +0 -1
  142. package/dist/chunk-WM3OXYTW.js +0 -2630
  143. package/dist/chunk-WM3OXYTW.js.map +0 -1
  144. package/dist/skills-command-3ESCZ75U.js.map +0 -1
  145. package/dist/uninstall-GQE4SJF2.js +0 -150
  146. package/dist/uninstall-GQE4SJF2.js.map +0 -1
  147. package/template/.make-docs/scripts/check_path_hygiene.py +0 -435
  148. package/template/docs/assets/archive/AGENTS.md +0 -20
  149. package/template/docs/assets/archive/CLAUDE.md +0 -20
  150. package/template/docs/assets/history/AGENTS.md +0 -12
  151. package/template/docs/assets/history/CLAUDE.md +0 -12
  152. package/template/docs/assets/prompts/AGENTS.md +0 -8
  153. package/template/docs/assets/prompts/CLAUDE.md +0 -8
  154. package/template/docs/assets/prompts/designs-to-plan-change.prompt.md +0 -14
  155. package/template/docs/assets/prompts/designs-to-plan.prompt.md +0 -10
  156. package/template/docs/assets/prompts/docs-path-hygiene-cleanup.prompt.md +0 -27
  157. package/template/docs/assets/prompts/plan-to-prd-change.prompt.md +0 -8
  158. package/template/docs/assets/prompts/plan-to-prd-green-field.prompt.md +0 -6
  159. package/template/docs/assets/prompts/prd-change-to-work.prompt.md +0 -10
  160. package/template/docs/assets/prompts/prd-to-work-full-prd.prompt.md +0 -6
  161. package/template/docs/assets/prompts/prd-to-work-prd-feature.prompt.md +0 -6
  162. package/template/docs/assets/prompts/request-to-design.prompt.md +0 -16
  163. package/template/docs/assets/prompts/session-to-history-record.prompt.md +0 -19
  164. package/template/docs/assets/prompts/work-to-guides.prompt.md +0 -18
  165. package/template/docs/assets/references/AGENTS.md +0 -9
  166. package/template/docs/assets/references/CLAUDE.md +0 -9
  167. package/template/docs/assets/references/execution-workflow.md +0 -157
  168. package/template/docs/assets/references/output-contract.md +0 -221
  169. package/template/docs/assets/references/path-and-link-hygiene.md +0 -49
  170. package/template/docs/assets/references/planning-workflow.md +0 -160
  171. package/template/docs/assets/references/prd-change-management.md +0 -129
  172. package/template/docs/assets/templates/AGENTS.md +0 -8
  173. package/template/docs/assets/templates/CLAUDE.md +0 -8
  174. package/template/docs/assets/templates/design.md +0 -30
  175. package/template/docs/assets/templates/plan-overview.md +0 -32
  176. package/template/docs/assets/templates/plan-prd-change.md +0 -99
  177. package/template/docs/assets/templates/prd-change-addition.md +0 -45
  178. package/template/docs/assets/templates/prd-change-revision.md +0 -45
  179. package/template/docs/assets/templates/prd-glossary.md +0 -15
  180. package/template/docs/assets/templates/prd-index.md +0 -45
  181. package/template/docs/assets/templates/prd-reference.md +0 -17
  182. package/template/docs/assets/templates/work-index.md +0 -21
  183. package/template/docs/assets/templates/work-phase.md +0 -34
  184. package/template/docs/guides/AGENTS.md +0 -15
  185. package/template/docs/guides/CLAUDE.md +0 -15
  186. /package/template/{docs/assets → .make-docs/system}/prompts/update-readme-green-field.prompt.md +0 -0
  187. /package/template/{docs/assets → .make-docs/system}/references/harness-capability-matrix.md +0 -0
@@ -0,0 +1,4136 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ annotateLifecycleActions,
4
+ assertLifecyclePlanSnapshotCurrent,
5
+ createLifecycleMutationReceipt,
6
+ createLifecyclePlanSnapshot,
7
+ prepareInstallationRemoval,
8
+ pruneInstallationParents,
9
+ removeInstallationPath
10
+ } from "./chunk-57GN6ALR.js";
11
+ import {
12
+ NO_ACCESS,
13
+ getFirstPartyHarnessAdapter,
14
+ validateHarnessMethodSelection
15
+ } from "./chunk-DFQJENNL.js";
16
+ import {
17
+ CONFLICTS_RELATIVE_DIR,
18
+ DEFAULT_SYSTEM_ASSET_MATERIALIZATION_MODE,
19
+ HARNESS_TO_INSTRUCTION,
20
+ INSTRUCTION_KINDS,
21
+ MANIFEST_RELATIVE_PATH,
22
+ RETIRED_PLAYBOOK_CONTRACT_HASH,
23
+ RETIRED_PLAYBOOK_CONTRACT_PATH,
24
+ TEMPLATE_ROOT,
25
+ TOOL_DIRECTORY_CONFIG_RELATIVE_PATH,
26
+ assertEmbeddedSkillPackageDigest,
27
+ assertManagedPathHasNoSymlinks,
28
+ canonicalInstallationPath,
29
+ classifyAgenticSkillFileRole,
30
+ contentEquals,
31
+ createManifest,
32
+ createRunId,
33
+ createSystemAssetManifestState,
34
+ ensureParentDir,
35
+ getConfiguredRouterPaths,
36
+ getDesiredAssetsForMaterializationMode,
37
+ getDesiredSkillAssets,
38
+ getEmbeddedSkillPackageDigest,
39
+ getHarnessSkillDirectory,
40
+ getInstallationProjectId,
41
+ getManifestFileHash,
42
+ getManifestFileHashForSourceSchema,
43
+ getRetiredManagedSkillAssets,
44
+ getRouterTemplateSourcePath,
45
+ getSystemAssetMaterializationPlan,
46
+ getSystemToolResourceMigrationTarget,
47
+ hasTrustedRetiredPlaybookContractOwnership,
48
+ hashText,
49
+ isConfiguredRouterPath,
50
+ isMap,
51
+ isRetiredTemplateOwnedChildRouterPath,
52
+ isScalar,
53
+ isSeq,
54
+ isToolDirectorySystemResourcePath,
55
+ loadManifest,
56
+ mintProjectId,
57
+ parse,
58
+ parseDocument,
59
+ parseManagedBlock,
60
+ prepareDetachedInstallationOperation,
61
+ preparePlannedFileChange,
62
+ readInstallationPathClaims,
63
+ readInstallationStatus,
64
+ readPackageFile,
65
+ readPackageMeta,
66
+ readTextFile,
67
+ recordPlannedFileChange,
68
+ recoverInstallationOperation,
69
+ registerDetachedInstallationOperation,
70
+ relativePathToTarget,
71
+ resolveInstallProfile,
72
+ sealInstallationOperation,
73
+ stringify,
74
+ upsertManagedBlock,
75
+ withInstallationOperation,
76
+ writeContentFile,
77
+ writeManifest
78
+ } from "./chunk-U25GFKNZ.js";
79
+
80
+ // src/config.ts
81
+ import { existsSync, readFileSync } from "fs";
82
+ import path from "path";
83
+ var PERSONA_PRIMITIVES = ["user", "maintainer"];
84
+ var RESERVED_PERSONA_SLUGS = /* @__PURE__ */ new Set(["project", "archive", "artifacts", "library", "playbooks"]);
85
+ var PERSONA_SLUG_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
86
+ var LIFECYCLE_LABEL_KEYS = [
87
+ "design",
88
+ "plan",
89
+ "prd",
90
+ "work",
91
+ "implementation",
92
+ "history",
93
+ "guide"
94
+ ];
95
+ var DOCUMENT_KIND_LABEL_KEYS = [
96
+ "design",
97
+ "plan",
98
+ "prd",
99
+ "work",
100
+ "history",
101
+ "guide"
102
+ ];
103
+ var COORDINATE_LABEL_KEYS = ["wave", "revision", "phase"];
104
+ var HARNESS_CAPABILITY_IDS = [
105
+ "goal_managed_execution",
106
+ "long_running_runs",
107
+ "resume_after_interrupt",
108
+ "subagent_delegation",
109
+ "user_gate_prompts"
110
+ ];
111
+ var TOP_LEVEL_KEYS = /* @__PURE__ */ new Set([
112
+ "projectId",
113
+ "labels",
114
+ "personas",
115
+ "generatedProse",
116
+ "harnessCapabilities",
117
+ "harnessIntegrations"
118
+ ]);
119
+ var LABEL_GROUP_KEYS = /* @__PURE__ */ new Set(["lifecycle", "documentKinds", "coordinates"]);
120
+ var PERSONA_KEYS = /* @__PURE__ */ new Set(["slug", "label", "description", "primitive"]);
121
+ var HARNESS_CAPABILITY_RECORD_KEYS = /* @__PURE__ */ new Set([
122
+ "harness",
123
+ "reviewStatus",
124
+ "capabilities",
125
+ "source",
126
+ "caveats"
127
+ ]);
128
+ var HARNESS_INTEGRATION_RECORD_KEYS = /* @__PURE__ */ new Set(["harness", "mode", "method", "accessCeiling"]);
129
+ var RETIRED_OPAQUE_CONFIG_KEYS = /* @__PURE__ */ new Set([
130
+ "packaging",
131
+ "labels.lifecycle.playbook",
132
+ "labels.documentKinds.protocol"
133
+ ]);
134
+ var STRUCTURAL_RENAME_KEYS = /* @__PURE__ */ new Set([
135
+ "contractName",
136
+ "contractNames",
137
+ "coordinate",
138
+ "coordinateModel",
139
+ "coordinates",
140
+ "directory",
141
+ "directories",
142
+ "field",
143
+ "fields",
144
+ "frontmatter",
145
+ "frontmatterField",
146
+ "frontmatterFields",
147
+ "harnessName",
148
+ "harnessNames",
149
+ "kind",
150
+ "kindValue",
151
+ "kindValues",
152
+ "kinds",
153
+ "lifecycleSlug",
154
+ "lifecycleSlugs",
155
+ "manifest",
156
+ "manifestKey",
157
+ "manifestKeys",
158
+ "metadata",
159
+ "metadataKey",
160
+ "metadataKeys",
161
+ "path",
162
+ "paths",
163
+ "persona",
164
+ "primitive",
165
+ "primitiveValue",
166
+ "primitiveValues",
167
+ "promptPath",
168
+ "promptPaths",
169
+ "route",
170
+ "routeId",
171
+ "routeIds",
172
+ "routes",
173
+ "schemaKey",
174
+ "schemaKeys",
175
+ "skillName",
176
+ "skillNames",
177
+ "sourceType",
178
+ "sourceTypes"
179
+ ]);
180
+ function getMakeDocsConfigPath(targetDir) {
181
+ return path.join(targetDir, TOOL_DIRECTORY_CONFIG_RELATIVE_PATH);
182
+ }
183
+ function createDefaultMakeDocsConfig() {
184
+ return {
185
+ labels: {
186
+ lifecycle: {
187
+ design: "design",
188
+ plan: "plan",
189
+ prd: "PRD",
190
+ work: "work",
191
+ implementation: "implementation",
192
+ history: "history",
193
+ guide: "guide"
194
+ },
195
+ documentKinds: {
196
+ design: "design",
197
+ plan: "plan",
198
+ prd: "PRD",
199
+ work: "work",
200
+ history: "history",
201
+ guide: "guide"
202
+ },
203
+ coordinates: {
204
+ wave: "Wave",
205
+ revision: "Revision",
206
+ phase: "Phase"
207
+ }
208
+ },
209
+ generatedProse: {},
210
+ harnessCapabilities: [],
211
+ harnessIntegrations: [],
212
+ personas: [
213
+ {
214
+ slug: "user",
215
+ label: "User",
216
+ description: "People or agents that use the project.",
217
+ primitive: "user"
218
+ },
219
+ {
220
+ slug: "maintainer",
221
+ label: "Maintainer",
222
+ description: "People or agents that build, operate, maintain, or extend the project.",
223
+ primitive: "maintainer"
224
+ }
225
+ ]
226
+ };
227
+ }
228
+ function getConfigRenderingLabels(config = createDefaultMakeDocsConfig()) {
229
+ return {
230
+ documentKinds: formatLabelEntries(config.labels.documentKinds),
231
+ lifecycle: formatLabelEntries(config.labels.lifecycle),
232
+ coordinates: formatLabelEntries(config.labels.coordinates),
233
+ personas: config.personas.map((persona) => `${persona.slug}=${persona.label}`).join(", ")
234
+ };
235
+ }
236
+ function getDocumentKindLabel(config, key) {
237
+ return config.labels.documentKinds[key];
238
+ }
239
+ function loadMakeDocsConfig(targetDir) {
240
+ assertManagedPathHasNoSymlinks(targetDir, TOOL_DIRECTORY_CONFIG_RELATIVE_PATH);
241
+ const configPath = getMakeDocsConfigPath(targetDir);
242
+ const defaults = createDefaultMakeDocsConfig();
243
+ if (!existsSync(configPath)) {
244
+ return {
245
+ config: defaults,
246
+ configuredPersonaSlugs: [],
247
+ personaDisplaySources: getPersonaDisplaySources(defaults, []),
248
+ configPath,
249
+ diagnostics: [],
250
+ present: false,
251
+ valid: true
252
+ };
253
+ }
254
+ const diagnostics = [];
255
+ const raw = readTextFile(configPath);
256
+ const document = parseDocument(raw);
257
+ for (const error of document.errors) {
258
+ diagnostics.push({
259
+ code: "parse-error",
260
+ filePath: configPath,
261
+ keyPath: "<root>",
262
+ message: `Invalid YAML in ${configPath} at <root>: ${error.message}`
263
+ });
264
+ }
265
+ if (diagnostics.length > 0) {
266
+ return invalidConfigResult(configPath, diagnostics);
267
+ }
268
+ const parsed = document.toJSON();
269
+ if ((parsed === null || parsed === void 0) && document.contents === null) {
270
+ return {
271
+ config: defaults,
272
+ configuredPersonaSlugs: [],
273
+ personaDisplaySources: getPersonaDisplaySources(defaults, []),
274
+ configPath,
275
+ diagnostics: [],
276
+ present: true,
277
+ valid: true
278
+ };
279
+ }
280
+ if (!isPlainObject(parsed)) {
281
+ diagnostics.push({
282
+ code: "invalid-type",
283
+ filePath: configPath,
284
+ keyPath: "<root>",
285
+ message: `Invalid make-docs config at ${configPath} (<root>): expected an object.`
286
+ });
287
+ return invalidConfigResult(configPath, diagnostics);
288
+ }
289
+ const config = createDefaultMakeDocsConfig();
290
+ validateKeys({
291
+ allowedKeys: TOP_LEVEL_KEYS,
292
+ diagnostics,
293
+ filePath: configPath,
294
+ keyPath: "",
295
+ value: parsed
296
+ });
297
+ applyLabels(parsed.labels, config, configPath, diagnostics);
298
+ applyGeneratedProse(parsed.generatedProse, config, configPath, diagnostics);
299
+ applyPersonas(parsed.personas, config, configPath, diagnostics);
300
+ applyHarnessCapabilities(parsed.harnessCapabilities, config, configPath, diagnostics);
301
+ applyHarnessIntegrations(parsed.harnessIntegrations, config, configPath, diagnostics);
302
+ if (diagnostics.length > 0) {
303
+ return invalidConfigResult(configPath, diagnostics);
304
+ }
305
+ return {
306
+ config,
307
+ configuredPersonaSlugs: Array.isArray(parsed.personas) ? parsed.personas.map((entry) => entry.slug.trim()) : [],
308
+ personaDisplaySources: getPersonaDisplaySources(config, parsed.personas),
309
+ configPath,
310
+ diagnostics: [],
311
+ present: true,
312
+ valid: true
313
+ };
314
+ }
315
+ function loadMakeDocsConfigOrThrow(targetDir) {
316
+ const loaded = loadMakeDocsConfig(targetDir);
317
+ if (!loaded.valid) {
318
+ throw new Error(formatMakeDocsConfigDiagnostics(loaded));
319
+ }
320
+ return loaded;
321
+ }
322
+ function planProjectHarnessIntegrationWrite(input) {
323
+ const configPath = getMakeDocsConfigPath(input.targetDir);
324
+ const beforeContent = existsSync(configPath) ? readFileSync(configPath, "utf8") : null;
325
+ const updated = updateProjectHarnessIntegrationsYaml(
326
+ beforeContent ?? input.contentWhenMissing,
327
+ input.reviewed
328
+ );
329
+ return {
330
+ configPath,
331
+ beforeContent,
332
+ content: updated.content,
333
+ changed: beforeContent === null || updated.content !== beforeContent,
334
+ reviewed: input.reviewed.map((record) => ({
335
+ ...record,
336
+ ...record.accessCeiling ? { accessCeiling: { ...record.accessCeiling } } : {}
337
+ }))
338
+ };
339
+ }
340
+ function updateProjectHarnessIntegrationsYaml(raw, reviewed) {
341
+ const document = parseDocument(raw);
342
+ if (document.errors.length > 0) {
343
+ throw new Error(`Invalid make-docs config YAML: ${document.errors.map((error) => error.message).join("; ")}`);
344
+ }
345
+ const seen = /* @__PURE__ */ new Set();
346
+ for (const record of reviewed) {
347
+ if (seen.has(record.harness)) throw new Error(`Duplicate reviewed harness entry '${record.harness}'.`);
348
+ seen.add(record.harness);
349
+ if (record.mode !== "narrow" && record.mode !== "disable") {
350
+ throw new Error("Setup can write only explicit narrow or disable harness intent.");
351
+ }
352
+ if (record.mode === "narrow" && (!record.method || !record.accessCeiling)) {
353
+ throw new Error(`Narrow harness entry '${record.harness}' requires a method and access ceiling.`);
354
+ }
355
+ if (record.mode === "disable" && (record.method || record.accessCeiling)) {
356
+ throw new Error(`Disabled harness entry '${record.harness}' cannot include a method or access ceiling.`);
357
+ }
358
+ }
359
+ if (document.contents === null) {
360
+ document.contents = document.createNode({});
361
+ }
362
+ if (!isMap(document.contents)) throw new Error("The make-docs config root must be a YAML map.");
363
+ let sequence = getYamlMapValueNode(document.contents, "harnessIntegrations");
364
+ if (sequence === void 0 || sequence === null) {
365
+ document.set("harnessIntegrations", document.createNode([]));
366
+ sequence = getYamlMapValueNode(document.contents, "harnessIntegrations");
367
+ }
368
+ if (!isSeq(sequence)) throw new Error("harnessIntegrations must be a YAML sequence.");
369
+ for (const record of reviewed) {
370
+ const matches = sequence.items.filter((item) => isMap(item) && item.get("harness") === record.harness);
371
+ if (matches.length > 1) throw new Error(`Duplicate harness integration record '${record.harness}'.`);
372
+ let map = matches[0];
373
+ if (!map || !isMap(map)) {
374
+ const created = document.createNode({ harness: record.harness, mode: record.mode });
375
+ if (!isMap(created)) throw new Error("Could not create a harness integration YAML map.");
376
+ sequence.add(created);
377
+ map = created;
378
+ }
379
+ if (!isMap(map)) throw new Error("The harness integration entry is not a YAML map.");
380
+ setYamlScalar(map, "harness", record.harness);
381
+ setYamlScalar(map, "mode", record.mode);
382
+ if (record.mode === "disable") {
383
+ map.delete("method");
384
+ map.delete("accessCeiling");
385
+ continue;
386
+ }
387
+ setYamlScalar(map, "method", record.method);
388
+ let access = getYamlMapValueNode(map, "accessCeiling");
389
+ if (!isMap(access)) {
390
+ map.set("accessCeiling", document.createNode({}));
391
+ access = getYamlMapValueNode(map, "accessCeiling");
392
+ }
393
+ if (!isMap(access)) throw new Error("Could not create the harness access ceiling YAML map.");
394
+ setYamlScalar(access, "store", record.accessCeiling.store);
395
+ setYamlScalar(access, "project", record.accessCeiling.project);
396
+ setYamlScalar(access, "hostConfig", record.accessCeiling.hostConfig);
397
+ }
398
+ const content = document.toString();
399
+ return { content, changed: content !== raw };
400
+ }
401
+ function getYamlMapValueNode(map, key) {
402
+ return map.items.find(
403
+ (item) => isScalar(item.key) && item.key.value === key || item.key === key
404
+ )?.value;
405
+ }
406
+ function setYamlScalar(map, key, value) {
407
+ const node = map.get(key, true);
408
+ if (isScalar(node)) {
409
+ node.value = value;
410
+ return;
411
+ }
412
+ map.set(key, value);
413
+ }
414
+ function formatMakeDocsConfigDiagnostics(loaded) {
415
+ const detailLines = loaded.diagnostics.map(
416
+ (diagnostic) => `- ${diagnostic.keyPath}: ${diagnostic.message}`
417
+ );
418
+ return [
419
+ `Invalid make-docs config: ${loaded.configPath}`,
420
+ ...detailLines
421
+ ].join("\n");
422
+ }
423
+ function invalidConfigResult(configPath, diagnostics) {
424
+ return {
425
+ config: createDefaultMakeDocsConfig(),
426
+ configuredPersonaSlugs: [],
427
+ personaDisplaySources: getPersonaDisplaySources(createDefaultMakeDocsConfig(), []),
428
+ configPath,
429
+ diagnostics,
430
+ present: true,
431
+ valid: false
432
+ };
433
+ }
434
+ function applyLabels(value, config, filePath, diagnostics) {
435
+ if (value === void 0) {
436
+ return;
437
+ }
438
+ if (!isPlainObject(value)) {
439
+ addInvalidTypeDiagnostic(diagnostics, filePath, "labels", "an object");
440
+ return;
441
+ }
442
+ validateKeys({
443
+ allowedKeys: LABEL_GROUP_KEYS,
444
+ diagnostics,
445
+ filePath,
446
+ keyPath: "labels",
447
+ value
448
+ });
449
+ applyLabelGroup({
450
+ allowedKeys: new Set(LIFECYCLE_LABEL_KEYS),
451
+ diagnostics,
452
+ filePath,
453
+ group: config.labels.lifecycle,
454
+ keyPath: "labels.lifecycle",
455
+ value: value.lifecycle
456
+ });
457
+ applyLabelGroup({
458
+ allowedKeys: new Set(DOCUMENT_KIND_LABEL_KEYS),
459
+ diagnostics,
460
+ filePath,
461
+ group: config.labels.documentKinds,
462
+ keyPath: "labels.documentKinds",
463
+ value: value.documentKinds
464
+ });
465
+ applyLabelGroup({
466
+ allowedKeys: new Set(COORDINATE_LABEL_KEYS),
467
+ diagnostics,
468
+ filePath,
469
+ group: config.labels.coordinates,
470
+ keyPath: "labels.coordinates",
471
+ value: value.coordinates
472
+ });
473
+ }
474
+ function applyLabelGroup(options) {
475
+ const { allowedKeys, diagnostics, filePath, group, keyPath, value } = options;
476
+ if (value === void 0) {
477
+ return;
478
+ }
479
+ if (!isPlainObject(value)) {
480
+ addInvalidTypeDiagnostic(diagnostics, filePath, keyPath, "an object");
481
+ return;
482
+ }
483
+ validateKeys({ allowedKeys, diagnostics, filePath, keyPath, value });
484
+ for (const [key, label] of Object.entries(value)) {
485
+ if (!allowedKeys.has(key)) {
486
+ continue;
487
+ }
488
+ if (!isNonEmptyString(label)) {
489
+ addInvalidTypeDiagnostic(diagnostics, filePath, joinKeyPath(keyPath, key), "a non-empty string");
490
+ continue;
491
+ }
492
+ group[key] = label.trim();
493
+ }
494
+ }
495
+ function applyGeneratedProse(value, config, filePath, diagnostics) {
496
+ if (value === void 0) {
497
+ return;
498
+ }
499
+ if (!isPlainObject(value)) {
500
+ addInvalidTypeDiagnostic(diagnostics, filePath, "generatedProse", "an object");
501
+ return;
502
+ }
503
+ for (const [key, label] of Object.entries(value)) {
504
+ const keyPath = joinKeyPath("generatedProse", key);
505
+ if (isStructuralRenameKey(key)) {
506
+ addStructuralRenameDiagnostic(diagnostics, filePath, keyPath);
507
+ continue;
508
+ }
509
+ if (!isNonEmptyString(label)) {
510
+ addInvalidTypeDiagnostic(diagnostics, filePath, keyPath, "a non-empty string");
511
+ continue;
512
+ }
513
+ config.generatedProse[key] = label.trim();
514
+ }
515
+ }
516
+ function getPersonaDisplaySources(config, value) {
517
+ const entries = Array.isArray(value) ? value : [];
518
+ return Object.fromEntries(config.personas.map((persona) => {
519
+ const configured = entries.find((entry) => isPlainObject(entry) && typeof entry.slug === "string" && entry.slug.trim() === persona.slug);
520
+ const builtin = persona.slug === "user" || persona.slug === "maintainer";
521
+ return [persona.slug, {
522
+ label: !builtin || configured && Object.hasOwn(configured, "label") ? "configured" : "shipped",
523
+ description: !builtin || configured && Object.hasOwn(configured, "description") ? "configured" : "shipped"
524
+ }];
525
+ }));
526
+ }
527
+ function applyPersonas(value, config, filePath, diagnostics) {
528
+ if (value === void 0) return;
529
+ if (!Array.isArray(value)) {
530
+ addInvalidTypeDiagnostic(diagnostics, filePath, "personas", "an array");
531
+ return;
532
+ }
533
+ const personasBySlug = new Map(config.personas.map((persona) => [persona.slug, persona]));
534
+ const configuredSlugs = /* @__PURE__ */ new Set();
535
+ for (const [index, entry] of value.entries()) {
536
+ const entryPath = `personas[${index}]`;
537
+ if (!isPlainObject(entry)) {
538
+ addInvalidTypeDiagnostic(diagnostics, filePath, entryPath, "an object");
539
+ continue;
540
+ }
541
+ validateKeys({ allowedKeys: PERSONA_KEYS, diagnostics, filePath, keyPath: entryPath, value: entry });
542
+ const slug = getRequiredString(entry, "slug", entryPath, filePath, diagnostics);
543
+ if (!slug) continue;
544
+ if (!PERSONA_SLUG_PATTERN.test(slug)) {
545
+ addInvalidTypeDiagnostic(diagnostics, filePath, `${entryPath}.slug`, "a lowercase kebab-case slug");
546
+ continue;
547
+ }
548
+ if (configuredSlugs.has(slug)) {
549
+ diagnostics.push({ code: "duplicate-persona-slug", filePath, keyPath: `${entryPath}.slug`, message: `Duplicate persona slug '${slug}'.` });
550
+ continue;
551
+ }
552
+ configuredSlugs.add(slug);
553
+ if (RESERVED_PERSONA_SLUGS.has(slug)) {
554
+ diagnostics.push({ code: "reserved-persona-slug", filePath, keyPath: `${entryPath}.slug`, message: `Persona slug '${slug}' is reserved for project structure. Review a new slug and retained-content destination; no content was moved.` });
555
+ continue;
556
+ }
557
+ const builtin = slug === "user" || slug === "maintainer" ? personasBySlug.get(slug) : void 0;
558
+ const field = (key) => builtin && !Object.hasOwn(entry, key) ? builtin[key] : getRequiredString(entry, key, entryPath, filePath, diagnostics);
559
+ const label = field("label");
560
+ const description = field("description");
561
+ const primitive = field("primitive");
562
+ if (!label || !description || !primitive) continue;
563
+ if (!PERSONA_PRIMITIVES.includes(primitive)) {
564
+ diagnostics.push({ code: "invalid-primitive", filePath, keyPath: `${entryPath}.primitive`, message: `Persona primitive must be one of ${PERSONA_PRIMITIVES.join(", ")}; actor technology does not define an audience.` });
565
+ continue;
566
+ }
567
+ if (builtin && primitive !== builtin.primitive) {
568
+ diagnostics.push({ code: "fixed-persona-primitive", filePath, keyPath: `${entryPath}.primitive`, message: `Built-in persona '${slug}' must retain primitive '${builtin.primitive}'.` });
569
+ continue;
570
+ }
571
+ personasBySlug.set(slug, { slug, label, description, primitive });
572
+ }
573
+ config.personas = [...personasBySlug.values()];
574
+ }
575
+ function applyHarnessIntegrations(value, config, filePath, diagnostics) {
576
+ if (value === void 0) {
577
+ return;
578
+ }
579
+ if (!Array.isArray(value)) {
580
+ addInvalidTypeDiagnostic(diagnostics, filePath, "harnessIntegrations", "an array");
581
+ return;
582
+ }
583
+ const records = [];
584
+ const harnesses = /* @__PURE__ */ new Set();
585
+ for (const [index, entry] of value.entries()) {
586
+ const entryPath = `harnessIntegrations[${index}]`;
587
+ if (!isPlainObject(entry)) {
588
+ addInvalidTypeDiagnostic(diagnostics, filePath, entryPath, "an object");
589
+ continue;
590
+ }
591
+ validateKeys({
592
+ allowedKeys: HARNESS_INTEGRATION_RECORD_KEYS,
593
+ diagnostics,
594
+ filePath,
595
+ keyPath: entryPath,
596
+ value: entry
597
+ });
598
+ const harness = getRequiredString(entry, "harness", entryPath, filePath, diagnostics);
599
+ const mode = getRequiredString(entry, "mode", entryPath, filePath, diagnostics);
600
+ const method = getOptionalString(entry, "method", entryPath, filePath, diagnostics);
601
+ const accessCeiling = getHarnessAccessCeiling(
602
+ entry.accessCeiling,
603
+ `${entryPath}.accessCeiling`,
604
+ filePath,
605
+ diagnostics
606
+ );
607
+ if (!harness || !mode) {
608
+ continue;
609
+ }
610
+ if (!PERSONA_SLUG_PATTERN.test(harness)) {
611
+ diagnostics.push({
612
+ code: "invalid-harness-identifier",
613
+ filePath,
614
+ keyPath: `${entryPath}.harness`,
615
+ message: `Invalid make-docs config at ${filePath} (${entryPath}.harness): use a lowercase harness identifier.`
616
+ });
617
+ continue;
618
+ }
619
+ if (harnesses.has(harness)) {
620
+ diagnostics.push({
621
+ code: "duplicate-harness-integration-record",
622
+ filePath,
623
+ keyPath: `${entryPath}.harness`,
624
+ message: `Invalid make-docs config at ${filePath} (${entryPath}.harness): duplicate harness integration record '${harness}'.`
625
+ });
626
+ continue;
627
+ }
628
+ harnesses.add(harness);
629
+ if (mode !== "inherit" && mode !== "narrow" && mode !== "disable") {
630
+ diagnostics.push({
631
+ code: "invalid-harness-integration-mode",
632
+ filePath,
633
+ keyPath: `${entryPath}.mode`,
634
+ message: `Invalid make-docs config at ${filePath} (${entryPath}.mode): mode must be inherit, narrow, or disable.`
635
+ });
636
+ continue;
637
+ }
638
+ if (method !== void 0 && !PERSONA_SLUG_PATTERN.test(method)) {
639
+ diagnostics.push({
640
+ code: "invalid-harness-method",
641
+ filePath,
642
+ keyPath: `${entryPath}.method`,
643
+ message: `Invalid make-docs config at ${filePath} (${entryPath}.method): use a lowercase connection method identifier.`
644
+ });
645
+ continue;
646
+ }
647
+ if (method !== void 0 && getFirstPartyHarnessAdapter(harness)) {
648
+ try {
649
+ validateHarnessMethodSelection({ harnessId: harness, method, scope: "project" });
650
+ } catch (error) {
651
+ diagnostics.push({
652
+ code: "invalid-harness-method",
653
+ filePath,
654
+ keyPath: `${entryPath}.method`,
655
+ message: `Invalid make-docs config at ${filePath} (${entryPath}.method): ${error instanceof Error ? error.message : String(error)}`
656
+ });
657
+ continue;
658
+ }
659
+ }
660
+ const hasNarrowing = method !== void 0 || accessCeiling !== void 0;
661
+ if (mode === "narrow" !== hasNarrowing) {
662
+ diagnostics.push({
663
+ code: "invalid-harness-integration-combination",
664
+ filePath,
665
+ keyPath: entryPath,
666
+ message: `Invalid make-docs config at ${filePath} (${entryPath}): narrow requires a method or accessCeiling, while inherit and disable forbid them.`
667
+ });
668
+ continue;
669
+ }
670
+ records.push({
671
+ harness,
672
+ mode,
673
+ ...method ? { method } : {},
674
+ ...accessCeiling ? { accessCeiling } : {}
675
+ });
676
+ }
677
+ config.harnessIntegrations = records;
678
+ }
679
+ function resolveEffectiveHarnessIntegration(project, machine, harnessId) {
680
+ assertHarnessAccessCeiling(machine.accessCeiling, "Machine harness access ceiling");
681
+ if (project && project.harness !== harnessId) {
682
+ throw new Error(`Project harness '${project.harness}' does not match '${harnessId}'.`);
683
+ }
684
+ if (project?.mode === "narrow" && !project.method && !project.accessCeiling) {
685
+ throw new Error("Project narrow mode needs a narrower method or accessCeiling.");
686
+ }
687
+ if (project && project.mode !== "narrow" && (project.method !== void 0 || project.accessCeiling !== void 0)) {
688
+ throw new Error(`Project ${project.mode} mode cannot declare a method or accessCeiling.`);
689
+ }
690
+ if (machine.maximumMethod === null || machine.maximumMethod === "none") {
691
+ if (machine.selected) {
692
+ throw new Error(`Selected harness '${harnessId}' must have an approved connection method.`);
693
+ }
694
+ return { enabled: false, method: null, access: { ...NO_ACCESS }, source: "machine" };
695
+ }
696
+ if (!machine.selected) {
697
+ return { enabled: false, method: null, access: { ...NO_ACCESS }, source: "machine" };
698
+ }
699
+ validateHarnessMethodSelection({ harnessId, method: machine.maximumMethod });
700
+ if (!project || project.mode === "inherit") {
701
+ return {
702
+ enabled: true,
703
+ method: machine.maximumMethod,
704
+ access: { ...machine.accessCeiling },
705
+ source: "machine"
706
+ };
707
+ }
708
+ if (project.mode === "disable") {
709
+ return { enabled: false, method: null, access: { ...NO_ACCESS }, source: "project-disable" };
710
+ }
711
+ const projectMethod = project.method ?? machine.maximumMethod;
712
+ validateHarnessMethodSelection({ harnessId, method: projectMethod, scope: "project" });
713
+ if (machine.maximumMethod !== "mcp" && projectMethod !== machine.maximumMethod) {
714
+ throw new Error(
715
+ `Project method '${projectMethod}' is broader than machine-approved method '${machine.maximumMethod}'.`
716
+ );
717
+ }
718
+ const projectAccess = project.accessCeiling ?? machine.accessCeiling;
719
+ assertHarnessAccessCeiling(projectAccess, "Project harness access ceiling");
720
+ if (!accessAtMost(projectAccess, machine.accessCeiling)) {
721
+ throw new Error("Project accessCeiling is broader than the machine-approved access ceiling.");
722
+ }
723
+ return {
724
+ enabled: true,
725
+ method: projectMethod,
726
+ access: { ...projectAccess },
727
+ source: "project-narrow"
728
+ };
729
+ }
730
+ function getHarnessAccessCeiling(value, keyPath, filePath, diagnostics) {
731
+ if (value === void 0) return void 0;
732
+ if (!isPlainObject(value)) {
733
+ diagnostics.push({
734
+ code: "invalid-harness-access",
735
+ filePath,
736
+ keyPath,
737
+ message: `Invalid make-docs config at ${filePath} (${keyPath}): expected store, project, and hostConfig access.`
738
+ });
739
+ return void 0;
740
+ }
741
+ const keys = Object.keys(value).sort();
742
+ if (keys.join(",") !== "hostConfig,project,store" || !isAccessLevel(value.store) || !isAccessLevel(value.project) || value.hostConfig !== "none" && value.hostConfig !== "write") {
743
+ diagnostics.push({
744
+ code: "invalid-harness-access",
745
+ filePath,
746
+ keyPath,
747
+ message: `Invalid make-docs config at ${filePath} (${keyPath}): accessCeiling must declare only store, project, and hostConfig with supported access values.`
748
+ });
749
+ return void 0;
750
+ }
751
+ return {
752
+ store: value.store,
753
+ project: value.project,
754
+ hostConfig: value.hostConfig
755
+ };
756
+ }
757
+ function assertHarnessAccessCeiling(value, label) {
758
+ if (!value || !isAccessLevel(value.store) || !isAccessLevel(value.project) || value.hostConfig !== "none") {
759
+ throw new Error(`${label} must be complete and cannot grant host-configuration writes.`);
760
+ }
761
+ }
762
+ function accessAtMost(candidate, ceiling) {
763
+ const rank = { none: 0, read: 1, write: 2 };
764
+ return rank[candidate.store] <= rank[ceiling.store] && rank[candidate.project] <= rank[ceiling.project] && candidate.hostConfig === "none";
765
+ }
766
+ function isAccessLevel(value) {
767
+ return value === "none" || value === "read" || value === "write";
768
+ }
769
+ function applyHarnessCapabilities(value, config, filePath, diagnostics) {
770
+ if (value === void 0) {
771
+ return;
772
+ }
773
+ if (!Array.isArray(value)) {
774
+ addInvalidTypeDiagnostic(diagnostics, filePath, "harnessCapabilities", "an array");
775
+ return;
776
+ }
777
+ const records = [];
778
+ const harnesses = /* @__PURE__ */ new Set();
779
+ for (const [index, entry] of value.entries()) {
780
+ const entryPath = `harnessCapabilities[${index}]`;
781
+ if (!isPlainObject(entry)) {
782
+ addInvalidTypeDiagnostic(diagnostics, filePath, entryPath, "an object");
783
+ continue;
784
+ }
785
+ validateKeys({
786
+ allowedKeys: HARNESS_CAPABILITY_RECORD_KEYS,
787
+ diagnostics,
788
+ filePath,
789
+ keyPath: entryPath,
790
+ value: entry
791
+ });
792
+ const harness = getRequiredString(entry, "harness", entryPath, filePath, diagnostics);
793
+ const reviewStatus = getRequiredString(entry, "reviewStatus", entryPath, filePath, diagnostics);
794
+ const capabilities = parseHarnessCapabilityMap(
795
+ entry.capabilities,
796
+ joinKeyPath(entryPath, "capabilities"),
797
+ filePath,
798
+ diagnostics
799
+ );
800
+ const source = getOptionalString(entry, "source", entryPath, filePath, diagnostics);
801
+ const caveats = getOptionalStringArray(entry, "caveats", entryPath, filePath, diagnostics);
802
+ if (!harness || !reviewStatus || capabilities === null || caveats === null) {
803
+ continue;
804
+ }
805
+ if (harnesses.has(harness)) {
806
+ diagnostics.push({
807
+ code: "duplicate-harness-capability-record",
808
+ filePath,
809
+ keyPath: joinKeyPath(entryPath, "harness"),
810
+ message: `Invalid make-docs config at ${filePath} (${joinKeyPath(entryPath, "harness")}): duplicate harness capability record '${harness}'.`
811
+ });
812
+ continue;
813
+ }
814
+ harnesses.add(harness);
815
+ if (reviewStatus !== "reviewed" && reviewStatus !== "unreviewed") {
816
+ diagnostics.push({
817
+ code: "invalid-review-status",
818
+ filePath,
819
+ keyPath: joinKeyPath(entryPath, "reviewStatus"),
820
+ message: `Invalid make-docs config at ${filePath} (${joinKeyPath(entryPath, "reviewStatus")}): reviewStatus must be reviewed or unreviewed.`
821
+ });
822
+ continue;
823
+ }
824
+ records.push({
825
+ harness,
826
+ reviewStatus,
827
+ capabilities,
828
+ ...source ? { source } : {},
829
+ caveats
830
+ });
831
+ }
832
+ config.harnessCapabilities = records;
833
+ }
834
+ function parseHarnessCapabilityMap(value, keyPath, filePath, diagnostics) {
835
+ if (value === void 0) {
836
+ diagnostics.push({
837
+ code: "missing-required-key",
838
+ filePath,
839
+ keyPath,
840
+ message: `Invalid make-docs config at ${filePath} (${keyPath}): missing required key 'capabilities'.`
841
+ });
842
+ return null;
843
+ }
844
+ if (!isPlainObject(value)) {
845
+ addInvalidTypeDiagnostic(diagnostics, filePath, keyPath, "an object");
846
+ return null;
847
+ }
848
+ const capabilities = {};
849
+ for (const [key, enabled] of Object.entries(value)) {
850
+ if (key === "parallel_playbook_runs") continue;
851
+ const capabilityPath = joinKeyPath(keyPath, key);
852
+ if (!HARNESS_CAPABILITY_IDS.includes(key)) {
853
+ diagnostics.push({
854
+ code: "invalid-harness-capability-id",
855
+ filePath,
856
+ keyPath: capabilityPath,
857
+ message: `Invalid make-docs config at ${filePath} (${capabilityPath}): unknown harness capability id '${key}'.`
858
+ });
859
+ continue;
860
+ }
861
+ if (typeof enabled !== "boolean") {
862
+ addInvalidTypeDiagnostic(diagnostics, filePath, capabilityPath, "a boolean");
863
+ continue;
864
+ }
865
+ capabilities[key] = enabled;
866
+ }
867
+ return capabilities;
868
+ }
869
+ function validateKeys(options) {
870
+ for (const key of Object.keys(options.value)) {
871
+ if (options.allowedKeys.has(key)) continue;
872
+ const keyPath = joinKeyPath(options.keyPath, key);
873
+ if (RETIRED_OPAQUE_CONFIG_KEYS.has(keyPath)) continue;
874
+ if (isStructuralRenameKey(key)) {
875
+ addStructuralRenameDiagnostic(options.diagnostics, options.filePath, keyPath);
876
+ continue;
877
+ }
878
+ options.diagnostics.push({
879
+ code: "unknown-key",
880
+ filePath: options.filePath,
881
+ keyPath,
882
+ message: `Invalid make-docs config at ${options.filePath} (${keyPath}): unknown key '${key}'.`
883
+ });
884
+ }
885
+ }
886
+ function getRequiredString(value, key, parentKeyPath, filePath, diagnostics) {
887
+ const keyPath = joinKeyPath(parentKeyPath, key);
888
+ if (!(key in value)) {
889
+ diagnostics.push({
890
+ code: "missing-required-key",
891
+ filePath,
892
+ keyPath,
893
+ message: `Invalid make-docs config at ${filePath} (${keyPath}): missing required key '${key}'.`
894
+ });
895
+ return null;
896
+ }
897
+ const candidate = value[key];
898
+ if (!isNonEmptyString(candidate)) {
899
+ addInvalidTypeDiagnostic(diagnostics, filePath, keyPath, "a non-empty string");
900
+ return null;
901
+ }
902
+ return candidate.trim();
903
+ }
904
+ function getOptionalString(value, key, parentKeyPath, filePath, diagnostics) {
905
+ if (!(key in value)) {
906
+ return void 0;
907
+ }
908
+ const candidate = value[key];
909
+ if (!isNonEmptyString(candidate)) {
910
+ addInvalidTypeDiagnostic(diagnostics, filePath, joinKeyPath(parentKeyPath, key), "a non-empty string");
911
+ return void 0;
912
+ }
913
+ return candidate.trim();
914
+ }
915
+ function getOptionalStringArray(value, key, parentKeyPath, filePath, diagnostics) {
916
+ if (!(key in value)) {
917
+ return [];
918
+ }
919
+ const candidate = value[key];
920
+ const keyPath = joinKeyPath(parentKeyPath, key);
921
+ if (!Array.isArray(candidate)) {
922
+ addInvalidTypeDiagnostic(diagnostics, filePath, keyPath, "an array of strings");
923
+ return null;
924
+ }
925
+ const items = [];
926
+ for (const [index, item] of candidate.entries()) {
927
+ if (!isNonEmptyString(item)) {
928
+ addInvalidTypeDiagnostic(diagnostics, filePath, `${keyPath}[${index}]`, "a non-empty string");
929
+ continue;
930
+ }
931
+ items.push(item.trim());
932
+ }
933
+ return items;
934
+ }
935
+ function addInvalidTypeDiagnostic(diagnostics, filePath, keyPath, expected) {
936
+ diagnostics.push({
937
+ code: "invalid-type",
938
+ filePath,
939
+ keyPath,
940
+ message: `Invalid make-docs config at ${filePath} (${keyPath}): expected ${expected}.`
941
+ });
942
+ }
943
+ function addStructuralRenameDiagnostic(diagnostics, filePath, keyPath) {
944
+ diagnostics.push({
945
+ code: "structural-rename-attempt",
946
+ filePath,
947
+ keyPath,
948
+ message: `Invalid make-docs config at ${filePath} (${keyPath}): structural paths, metadata fields, kind values, route identifiers, primitive values, and schema keys are canonical and cannot be renamed by config.`
949
+ });
950
+ }
951
+ function isPlainObject(value) {
952
+ return typeof value === "object" && value !== null && !Array.isArray(value);
953
+ }
954
+ function isNonEmptyString(value) {
955
+ return typeof value === "string" && value.trim().length > 0;
956
+ }
957
+ function isStructuralRenameKey(key) {
958
+ return STRUCTURAL_RENAME_KEYS.has(key);
959
+ }
960
+ function joinKeyPath(parent, key) {
961
+ return parent ? `${parent}.${key}` : key;
962
+ }
963
+ function formatLabelEntries(labels) {
964
+ return Object.entries(labels).map(([key, value]) => `${key}=${value}`).join(", ");
965
+ }
966
+
967
+ // src/install.ts
968
+ import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
969
+ import { existsSync as existsSync5, mkdirSync, readFileSync as readFileSync5, symlinkSync } from "fs";
970
+ import path6 from "path";
971
+
972
+ // src/retired-path-helper.ts
973
+ import { existsSync as existsSync2, lstatSync, readdirSync, readFileSync as readFileSync2 } from "fs";
974
+ import path2 from "path";
975
+ var RETIRED_PATH_HELPER = ".make-docs/scripts/check_path_hygiene.py";
976
+ var TRUSTED_HASHES = /* @__PURE__ */ new Set([
977
+ "be2eac13966e77a10d5743b97fc38c6cb60822f0629158007dbe8ab1629f3db4",
978
+ "77c66f924a14118f124a4d9b321b6a9f68f194ecfbf97f18e21fc801e2a88b4c"
979
+ ]);
980
+ function planRetiredPathHelper(targetDir, manifest, actions) {
981
+ const entry = manifest?.files[RETIRED_PATH_HELPER];
982
+ const absolute = path2.join(targetDir, RETIRED_PATH_HELPER);
983
+ const base = { relativePath: RETIRED_PATH_HELPER, sourceId: entry?.sourceId ?? "file:" + RETIRED_PATH_HELPER };
984
+ const preserve = (reason) => ({ ...base, type: "skip", reason: "Path helper cleanup incomplete: " + reason });
985
+ try {
986
+ assertManagedPathHasNoSymlinks(targetDir, RETIRED_PATH_HELPER);
987
+ if (!existsSync2(absolute)) {
988
+ if (!entry) return null;
989
+ if (entry.sourceId !== "file:" + RETIRED_PATH_HELPER || entry.ownershipClass === "project-owned" || !TRUSTED_HASHES.has(entry.hash)) {
990
+ return preserve("the missing path does not have trusted managed ownership.");
991
+ }
992
+ return { ...base, type: "remove-managed", reason: "Forget the missing retired path helper." };
993
+ }
994
+ if (!lstatSync(absolute).isFile()) return preserve("the path is not a regular file.");
995
+ if (!entry || entry.sourceId !== "file:" + RETIRED_PATH_HELPER || entry.ownershipClass === "project-owned" || !TRUSTED_HASHES.has(entry.hash) || hashText(readFileSync2(absolute, "utf8")) !== entry.hash) {
996
+ return preserve("managed ownership or unchanged shipped bytes are not proved.");
997
+ }
998
+ const files = /* @__PURE__ */ new Set();
999
+ const visit = (relative) => {
1000
+ const full = path2.join(targetDir, relative);
1001
+ if (!existsSync2(full)) return;
1002
+ assertManagedPathHasNoSymlinks(targetDir, relative);
1003
+ const stat = lstatSync(full);
1004
+ if (stat.isDirectory()) {
1005
+ for (const name of readdirSync(full)) visit(relative + "/" + name);
1006
+ } else if (/\.(md|txt|rst)$/.test(relative)) files.add(relative);
1007
+ };
1008
+ for (const root of ["README.md", "AGENTS.md", "CLAUDE.md", ".make-docs/system", ".make-docs/prompts", ".make-docs/references"]) visit(root);
1009
+ for (const action of actions) if (action.relativePath.startsWith(".make-docs/system/")) files.add(action.relativePath);
1010
+ for (const file2 of files) {
1011
+ const action = actions.find((item) => item.relativePath === file2);
1012
+ if (action?.type === "remove-managed") continue;
1013
+ const replacement = action && ["create", "update", "generate", "strip-managed-block"].includes(action.type) ? action.content : void 0;
1014
+ const contents = replacement ?? (existsSync2(path2.join(targetDir, file2)) ? readFileSync2(path2.join(targetDir, file2), "utf8") : "");
1015
+ if (typeof contents === "string" && contents.includes("check_path_hygiene.py")) return preserve("a live instruction still uses Python: " + file2);
1016
+ }
1017
+ return { ...base, type: "remove-managed", reason: "Remove the trusted Python path helper after CLI instructions are updated; prune its directory only if empty." };
1018
+ } catch (error) {
1019
+ return preserve(error instanceof Error ? error.message : String(error));
1020
+ }
1021
+ }
1022
+
1023
+ // src/planner.ts
1024
+ import { isDeepStrictEqual } from "util";
1025
+
1026
+ // src/retired-resource-paths.ts
1027
+ var REPLACEMENTS = {
1028
+ ".make-docs/system/templates/guide-developer.md": ".make-docs/system/templates/guide-maintainer.md",
1029
+ ".make-docs/system/prompts/coverage-pass-developer-guide.prompt.md": ".make-docs/system/prompts/coverage-pass-maintainer-guide.prompt.md"
1030
+ };
1031
+ function getRetiredResourceReplacement(relativePath) {
1032
+ return REPLACEMENTS[relativePath];
1033
+ }
1034
+
1035
+ // src/planner.ts
1036
+ import { existsSync as existsSync4, lstatSync as lstatSync3, readFileSync as readFileSync4, readdirSync as readdirSync3, readlinkSync, statSync as statSync2 } from "fs";
1037
+ import path5 from "path";
1038
+ import { homedir } from "os";
1039
+
1040
+ // src/project-projection.ts
1041
+ import { Buffer as Buffer2 } from "buffer";
1042
+
1043
+ // src/operations/resource/provider.ts
1044
+ import { createHash } from "crypto";
1045
+ import {
1046
+ existsSync as existsSync3,
1047
+ lstatSync as lstatSync2,
1048
+ readdirSync as readdirSync2,
1049
+ readFileSync as readFileSync3,
1050
+ realpathSync,
1051
+ statSync
1052
+ } from "fs";
1053
+ import path4 from "path";
1054
+
1055
+ // src/operations/resource/identity.ts
1056
+ import path3 from "path";
1057
+
1058
+ // src/operations/resource/types.ts
1059
+ var SYSTEM_RESOURCE_TYPES = [
1060
+ "contract",
1061
+ "prompt",
1062
+ "reference",
1063
+ "template"
1064
+ ];
1065
+ var SYSTEM_RESOURCE_TYPE_DIRECTORIES = {
1066
+ contract: "contracts",
1067
+ prompt: "prompts",
1068
+ reference: "references",
1069
+ template: "templates"
1070
+ };
1071
+ var SYSTEM_RESOURCE_ORIGINS = ["effective", "local", "installed"];
1072
+ var SYSTEM_RESOURCE_ENSURE_APPROVAL = "resource-projection-write";
1073
+
1074
+ // src/operations/resource/identity.ts
1075
+ var RESOURCE_URI_PREFIX = "make-docs://system/";
1076
+ var WINDOWS_DRIVE_PATH = /^[A-Za-z]:/;
1077
+ var ENCODED_OCTET = /%[0-9A-Fa-f]{2}/;
1078
+ var CONTROL_CHARACTER = /[\u0000-\u001f\u007f]/;
1079
+ function isSystemResourceType(value) {
1080
+ return typeof value === "string" && SYSTEM_RESOURCE_TYPES.includes(value);
1081
+ }
1082
+ function createSystemResourceIdentity(type, resourcePath) {
1083
+ if (!isSystemResourceType(type)) {
1084
+ return {
1085
+ ok: false,
1086
+ error: {
1087
+ code: "invalid-resource-type",
1088
+ message: `Unknown system-resource type: ${String(type)}.`,
1089
+ recovery: `Use one of: ${SYSTEM_RESOURCE_TYPES.join(", ")}.`
1090
+ }
1091
+ };
1092
+ }
1093
+ const normalized2 = canonicalSystemResourcePath(resourcePath);
1094
+ if (!normalized2.ok) {
1095
+ return normalized2;
1096
+ }
1097
+ return {
1098
+ ok: true,
1099
+ value: {
1100
+ type,
1101
+ path: normalized2.value,
1102
+ uri: `${RESOURCE_URI_PREFIX}${type}/${normalized2.value}`
1103
+ }
1104
+ };
1105
+ }
1106
+ function parseSystemResourceUri(uri) {
1107
+ if (typeof uri !== "string" || !uri.startsWith(RESOURCE_URI_PREFIX)) {
1108
+ return invalidUri(uri, "The URI must start with make-docs://system/.");
1109
+ }
1110
+ if (uri.includes("?") || uri.includes("#")) {
1111
+ return invalidUri(uri, "Query and fragment parts are not permitted.");
1112
+ }
1113
+ const remainder = uri.slice(RESOURCE_URI_PREFIX.length);
1114
+ const slash = remainder.indexOf("/");
1115
+ if (slash <= 0) {
1116
+ return invalidUri(uri, "The URI must contain a type and a relative path.");
1117
+ }
1118
+ const result = createSystemResourceIdentity(remainder.slice(0, slash), remainder.slice(slash + 1));
1119
+ if (!result.ok) {
1120
+ return {
1121
+ ok: false,
1122
+ error: {
1123
+ ...result.error,
1124
+ code: result.error.code === "invalid-resource-type" ? result.error.code : "invalid-resource-uri",
1125
+ uri
1126
+ }
1127
+ };
1128
+ }
1129
+ if (result.value.uri !== uri) {
1130
+ return invalidUri(uri, "The URI is not in canonical form.");
1131
+ }
1132
+ return result;
1133
+ }
1134
+ function canonicalSystemResourcePath(value) {
1135
+ if (typeof value !== "string" || value.length === 0) {
1136
+ return invalidPath(value, "The path must be a non-empty string.");
1137
+ }
1138
+ if (CONTROL_CHARACTER.test(value)) {
1139
+ return invalidPath(value, "Control characters are not permitted.");
1140
+ }
1141
+ if (value.includes("\\")) {
1142
+ return invalidPath(value, "Backslashes are ambiguous and are not permitted.");
1143
+ }
1144
+ if (ENCODED_OCTET.test(value)) {
1145
+ return invalidPath(value, "Percent-encoded octets are not permitted.");
1146
+ }
1147
+ if (path3.posix.isAbsolute(value) || WINDOWS_DRIVE_PATH.test(value)) {
1148
+ return invalidPath(value, "Absolute and Windows drive paths are not permitted.");
1149
+ }
1150
+ const segments = value.split("/");
1151
+ if (segments.some((segment) => segment.length === 0)) {
1152
+ return invalidPath(value, "Empty path segments are not permitted.");
1153
+ }
1154
+ if (segments.some((segment) => segment === "." || segment === "..")) {
1155
+ return invalidPath(value, "Dot and traversal segments are not permitted.");
1156
+ }
1157
+ if (path3.posix.normalize(value) !== value) {
1158
+ return invalidPath(value, "The path is not in canonical POSIX form.");
1159
+ }
1160
+ return { ok: true, value };
1161
+ }
1162
+ function invalidPath(value, message) {
1163
+ return {
1164
+ ok: false,
1165
+ error: {
1166
+ code: "invalid-resource-path",
1167
+ message,
1168
+ recovery: "Use a case-sensitive POSIX-relative path with non-empty ordinary segments.",
1169
+ path: typeof value === "string" ? value : void 0
1170
+ }
1171
+ };
1172
+ }
1173
+ function invalidUri(value, message) {
1174
+ return {
1175
+ ok: false,
1176
+ error: {
1177
+ code: "invalid-resource-uri",
1178
+ message,
1179
+ recovery: "Use make-docs://system/<type>/<posix-relative-path>.",
1180
+ uri: typeof value === "string" ? value : void 0
1181
+ }
1182
+ };
1183
+ }
1184
+
1185
+ // src/operations/resource/provider.ts
1186
+ var DEFAULT_CATALOG_PATH = ".make-docs/system-resources.catalog.json";
1187
+ function loadSystemResourceProvider(input) {
1188
+ const root = inspectRoot(input.root, "provider");
1189
+ if (!root.ok) {
1190
+ return root;
1191
+ }
1192
+ const catalogRelativePath = input.catalogRelativePath ?? DEFAULT_CATALOG_PATH;
1193
+ const catalogPath = resolveExistingSafePath(root.value, catalogRelativePath, "file");
1194
+ if (!catalogPath.ok) {
1195
+ return withCode(catalogPath.error, "provider-catalog-invalid", catalogRelativePath);
1196
+ }
1197
+ let catalog;
1198
+ try {
1199
+ catalog = JSON.parse(readFileSync3(catalogPath.value, "utf8"));
1200
+ } catch (error) {
1201
+ return failure(
1202
+ "provider-catalog-invalid",
1203
+ `Could not parse the system-resource catalog: ${errorMessage(error)}.`,
1204
+ "Restore a valid shipped system-resource catalog.",
1205
+ void 0,
1206
+ catalogPath.value
1207
+ );
1208
+ }
1209
+ const catalogTypes = validateCatalog(catalog);
1210
+ if (!catalogTypes.ok) {
1211
+ return catalogTypes;
1212
+ }
1213
+ const resources = [];
1214
+ const seen = /* @__PURE__ */ new Set();
1215
+ for (const catalogType of catalogTypes.value.resourceTypes) {
1216
+ const sourceRoot = resolveExistingSafePath(root.value, catalogType.sourceRoot, "directory");
1217
+ if (!sourceRoot.ok) {
1218
+ return withCode(sourceRoot.error, "provider-unavailable", catalogType.sourceRoot);
1219
+ }
1220
+ const files = listSafeFiles(root.value, sourceRoot.value);
1221
+ if (!files.ok) {
1222
+ return files;
1223
+ }
1224
+ for (const filePath of files.value) {
1225
+ const relativePath = toPosix(path4.relative(sourceRoot.value, filePath));
1226
+ if (!matchesAny(relativePath, catalogType.include) || matchesAny(relativePath, catalogType.exclude)) {
1227
+ continue;
1228
+ }
1229
+ const identity = createSystemResourceIdentity(catalogType.type, relativePath);
1230
+ if (!identity.ok) {
1231
+ return identity;
1232
+ }
1233
+ if (seen.has(identity.value.uri)) {
1234
+ return failure(
1235
+ "duplicate-resource-identity",
1236
+ `The provider contains duplicate logical identity ${identity.value.uri}.`,
1237
+ "Remove the duplicate catalog mapping or provider file.",
1238
+ identity.value.uri,
1239
+ filePath
1240
+ );
1241
+ }
1242
+ seen.add(identity.value.uri);
1243
+ let content;
1244
+ try {
1245
+ content = readFileSync3(filePath);
1246
+ } catch (error) {
1247
+ return failure(
1248
+ "filesystem-error",
1249
+ `Could not read provider resource ${identity.value.uri}: ${errorMessage(error)}.`,
1250
+ "Repair the installed provider and retry.",
1251
+ identity.value.uri,
1252
+ filePath
1253
+ );
1254
+ }
1255
+ const storedContent = Uint8Array.from(content);
1256
+ resources.push(Object.freeze({
1257
+ identity: Object.freeze(identity.value),
1258
+ mediaType: catalogTypes.value.mediaType,
1259
+ digest: sha256(storedContent),
1260
+ byteLength: storedContent.byteLength,
1261
+ sourcePath: filePath,
1262
+ readContent: () => Uint8Array.from(storedContent)
1263
+ }));
1264
+ }
1265
+ }
1266
+ resources.sort((left, right) => compareCodeUnits(left.identity.uri, right.identity.uri));
1267
+ const inventoryDigest = sha256(
1268
+ Buffer.from(resources.map((entry) => `${entry.identity.uri}\0${entry.digest}`).join("\n"))
1269
+ );
1270
+ const immutableRef = input.immutableRef ?? `sha256:${inventoryDigest}`;
1271
+ const providerIdentity = Object.freeze({
1272
+ packageName: input.packageName,
1273
+ version: input.version,
1274
+ immutableRef,
1275
+ source: input.source
1276
+ });
1277
+ const providerMetadata = Object.freeze({
1278
+ identity: providerIdentity,
1279
+ root: root.value,
1280
+ catalogPath: catalogPath.value,
1281
+ catalogRules: Object.freeze(catalogTypes.value.resourceTypes.map((entry) => Object.freeze({
1282
+ type: entry.type,
1283
+ include: Object.freeze([...entry.include]),
1284
+ exclude: Object.freeze([...entry.exclude])
1285
+ }))),
1286
+ inventoryDigest
1287
+ });
1288
+ const inventory = Object.freeze({
1289
+ provider: providerMetadata,
1290
+ resources: Object.freeze([...resources])
1291
+ });
1292
+ return {
1293
+ ok: true,
1294
+ value: inventory
1295
+ };
1296
+ }
1297
+ function loadInstalledSystemResourceProvider() {
1298
+ try {
1299
+ const packageMeta = readPackageMeta();
1300
+ const source = path4.basename(path4.dirname(TEMPLATE_ROOT)) === "docs" ? "development" : "packed";
1301
+ return loadSystemResourceProvider({
1302
+ root: TEMPLATE_ROOT,
1303
+ packageName: packageMeta.name,
1304
+ version: packageMeta.version,
1305
+ immutableRef: `package:${packageMeta.name}@${packageMeta.version}`,
1306
+ source
1307
+ });
1308
+ } catch (error) {
1309
+ return failure(
1310
+ "provider-unavailable",
1311
+ `Could not identify the installed provider: ${errorMessage(error)}.`,
1312
+ "Repair the installed package metadata and retry.",
1313
+ void 0,
1314
+ TEMPLATE_ROOT
1315
+ );
1316
+ }
1317
+ }
1318
+ function matchesSystemResourceCatalogPath(provider, type, resourcePath) {
1319
+ const rules = provider?.provider?.catalogRules;
1320
+ if (!Array.isArray(rules) || rules.length !== SYSTEM_RESOURCE_TYPES.length || !SYSTEM_RESOURCE_TYPES.every(
1321
+ (expectedType) => rules.filter((rule2) => rule2?.type === expectedType).length === 1
1322
+ )) {
1323
+ return invalidCatalogType("Provider inventory catalog rules are incomplete or duplicated.");
1324
+ }
1325
+ const rule = rules.find((candidate) => candidate.type === type);
1326
+ if (!rule || !isStringArray(rule.include) || rule.include.length === 0 || !isStringArray(rule.exclude)) {
1327
+ return invalidCatalogType(`Provider inventory catalog rules for ${type} are invalid.`);
1328
+ }
1329
+ return {
1330
+ ok: true,
1331
+ value: matchesAny(resourcePath, rule.include) && !matchesAny(resourcePath, rule.exclude)
1332
+ };
1333
+ }
1334
+ function validateCatalog(catalog) {
1335
+ if (catalog.schemaVersion !== 1 || catalog.pathBase !== "template-root" || catalog.identityTemplate !== "make-docs://system/{type}/{path}" || typeof catalog.defaultMediaType !== "string" || catalog.defaultMediaType.length === 0 || !Array.isArray(catalog.resourceTypes)) {
1336
+ return failure(
1337
+ "provider-catalog-invalid",
1338
+ "The system-resource catalog header is invalid.",
1339
+ "Restore the shipped schema version 1 catalog."
1340
+ );
1341
+ }
1342
+ const result = [];
1343
+ const seenTypes = /* @__PURE__ */ new Set();
1344
+ for (const raw of catalog.resourceTypes) {
1345
+ if (!isPlainObject2(raw)) {
1346
+ return invalidCatalogType("Each resourceTypes entry must be an object.");
1347
+ }
1348
+ const entry = raw;
1349
+ if (!isSystemResourceType(entry.type)) {
1350
+ return invalidCatalogType(`Unknown catalog resource type: ${String(entry.type)}.`);
1351
+ }
1352
+ if (seenTypes.has(entry.type)) {
1353
+ return failure(
1354
+ "duplicate-resource-identity",
1355
+ `The catalog repeats resource type ${entry.type}.`,
1356
+ "Keep exactly one catalog entry for each peer resource type."
1357
+ );
1358
+ }
1359
+ seenTypes.add(entry.type);
1360
+ const expectedRoot = `.make-docs/system/${SYSTEM_RESOURCE_TYPE_DIRECTORIES[entry.type]}`;
1361
+ if (entry.sourceRoot !== expectedRoot) {
1362
+ return invalidCatalogType(
1363
+ `Catalog type ${entry.type} must use provider root ${expectedRoot}.`
1364
+ );
1365
+ }
1366
+ const sourceRoot = canonicalSystemResourcePath(entry.sourceRoot);
1367
+ if (!sourceRoot.ok) {
1368
+ return withCode(sourceRoot.error, "provider-catalog-invalid", String(entry.sourceRoot));
1369
+ }
1370
+ if (!isStringArray(entry.include) || entry.include.length === 0 || !isStringArray(entry.exclude)) {
1371
+ return invalidCatalogType(`Catalog patterns for ${entry.type} are invalid.`);
1372
+ }
1373
+ result.push({
1374
+ ...entry,
1375
+ type: entry.type,
1376
+ sourceRoot: sourceRoot.value,
1377
+ include: [...entry.include],
1378
+ exclude: [...entry.exclude]
1379
+ });
1380
+ }
1381
+ if (result.length !== SYSTEM_RESOURCE_TYPES.length || SYSTEM_RESOURCE_TYPES.some((type) => !seenTypes.has(type))) {
1382
+ return invalidCatalogType("The catalog must contain exactly the four peer resource types.");
1383
+ }
1384
+ result.sort((left, right) => compareCodeUnits(left.type, right.type));
1385
+ return {
1386
+ ok: true,
1387
+ value: { mediaType: catalog.defaultMediaType, resourceTypes: result }
1388
+ };
1389
+ }
1390
+ function inspectRoot(rootInput, label) {
1391
+ const absolute = path4.resolve(rootInput);
1392
+ try {
1393
+ if (!existsSync3(absolute)) {
1394
+ return failure(
1395
+ "provider-unavailable",
1396
+ `The ${label} root does not exist.`,
1397
+ `Restore the ${label} root and retry.`,
1398
+ void 0,
1399
+ absolute
1400
+ );
1401
+ }
1402
+ if (lstatSync2(absolute).isSymbolicLink()) {
1403
+ return failure(
1404
+ "symlink-not-allowed",
1405
+ `The ${label} root is a symbolic link.`,
1406
+ `Use a real ${label} directory.`,
1407
+ void 0,
1408
+ absolute
1409
+ );
1410
+ }
1411
+ const real = realpathSync(absolute);
1412
+ if (!statSync(real).isDirectory()) {
1413
+ return failure(
1414
+ "unsafe-root",
1415
+ `The ${label} root is not a directory.`,
1416
+ `Use a real ${label} directory.`,
1417
+ void 0,
1418
+ absolute
1419
+ );
1420
+ }
1421
+ return { ok: true, value: real };
1422
+ } catch (error) {
1423
+ return failure(
1424
+ "filesystem-error",
1425
+ `Could not inspect the ${label} root: ${errorMessage(error)}.`,
1426
+ `Repair the ${label} root and retry.`,
1427
+ void 0,
1428
+ absolute
1429
+ );
1430
+ }
1431
+ }
1432
+ function resolveExistingSafePath(root, relativeInput, kind) {
1433
+ const relative = canonicalSystemResourcePath(relativeInput);
1434
+ if (!relative.ok) {
1435
+ return relative;
1436
+ }
1437
+ const segments = relative.value.split("/");
1438
+ let current = root;
1439
+ try {
1440
+ for (const segment of segments) {
1441
+ const candidate = path4.join(current, segment);
1442
+ const entries = readdirSync2(current);
1443
+ if (!entries.includes(segment)) {
1444
+ if (existsSync3(candidate)) {
1445
+ return failure(
1446
+ "provider-unavailable",
1447
+ `Provider path case does not match the catalog: ${relative.value}.`,
1448
+ "Restore the exact provider path case.",
1449
+ void 0,
1450
+ candidate
1451
+ );
1452
+ }
1453
+ return failure(
1454
+ "provider-unavailable",
1455
+ `Required provider path is missing: ${relative.value}.`,
1456
+ "Repair the installed provider and retry.",
1457
+ void 0,
1458
+ candidate
1459
+ );
1460
+ }
1461
+ current = candidate;
1462
+ if (lstatSync2(current).isSymbolicLink()) {
1463
+ return failure(
1464
+ "symlink-not-allowed",
1465
+ `Provider path contains a symbolic link: ${relative.value}.`,
1466
+ "Replace the link with provider-owned content.",
1467
+ void 0,
1468
+ current
1469
+ );
1470
+ }
1471
+ }
1472
+ const real = realpathSync(current);
1473
+ if (!isWithinRoot(root, real)) {
1474
+ return failure(
1475
+ "root-escape",
1476
+ `Provider path escapes its approved root: ${relative.value}.`,
1477
+ "Restore the provider path beneath its approved root.",
1478
+ void 0,
1479
+ real
1480
+ );
1481
+ }
1482
+ const stats = statSync(real);
1483
+ if (kind === "file" && !stats.isFile() || kind === "directory" && !stats.isDirectory()) {
1484
+ return failure(
1485
+ "provider-unavailable",
1486
+ `Provider path is not a ${kind}: ${relative.value}.`,
1487
+ "Repair the installed provider and retry.",
1488
+ void 0,
1489
+ real
1490
+ );
1491
+ }
1492
+ return { ok: true, value: real };
1493
+ } catch (error) {
1494
+ return failure(
1495
+ "filesystem-error",
1496
+ `Could not inspect provider path ${relative.value}: ${errorMessage(error)}.`,
1497
+ "Repair the installed provider and retry.",
1498
+ void 0,
1499
+ current
1500
+ );
1501
+ }
1502
+ }
1503
+ function listSafeFiles(root, directory) {
1504
+ const files = [];
1505
+ const visit = (current) => {
1506
+ try {
1507
+ for (const entry of readdirSync2(current).sort(compareCodeUnits)) {
1508
+ const candidate = path4.join(current, entry);
1509
+ const stats = lstatSync2(candidate);
1510
+ if (stats.isSymbolicLink()) {
1511
+ return {
1512
+ code: "symlink-not-allowed",
1513
+ message: `Provider inventory contains a symbolic link: ${candidate}.`,
1514
+ recovery: "Replace the link with provider-owned content.",
1515
+ path: candidate
1516
+ };
1517
+ }
1518
+ const real = realpathSync(candidate);
1519
+ if (!isWithinRoot(root, real)) {
1520
+ return {
1521
+ code: "root-escape",
1522
+ message: `Provider inventory path escapes its approved root: ${candidate}.`,
1523
+ recovery: "Restore the resource beneath the provider root.",
1524
+ path: candidate
1525
+ };
1526
+ }
1527
+ if (stats.isDirectory()) {
1528
+ const error2 = visit(real);
1529
+ if (error2) return error2;
1530
+ } else if (stats.isFile()) {
1531
+ files.push(real);
1532
+ }
1533
+ }
1534
+ return null;
1535
+ } catch (error2) {
1536
+ return {
1537
+ code: "filesystem-error",
1538
+ message: `Could not inventory provider directory ${current}: ${errorMessage(error2)}.`,
1539
+ recovery: "Repair the installed provider and retry.",
1540
+ path: current
1541
+ };
1542
+ }
1543
+ };
1544
+ const error = visit(directory);
1545
+ return error ? { ok: false, error } : { ok: true, value: files };
1546
+ }
1547
+ function matchesAny(value, patterns) {
1548
+ return patterns.some((pattern) => globPattern(pattern).test(value));
1549
+ }
1550
+ function globPattern(pattern) {
1551
+ let source = "^";
1552
+ for (let index = 0; index < pattern.length; index += 1) {
1553
+ const character = pattern[index];
1554
+ if (character === "*" && pattern[index + 1] === "*") {
1555
+ source += ".*";
1556
+ index += 1;
1557
+ } else if (character === "*") {
1558
+ source += "[^/]*";
1559
+ } else if (character === "?") {
1560
+ source += "[^/]";
1561
+ } else {
1562
+ source += character.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
1563
+ }
1564
+ }
1565
+ return new RegExp(`${source}$`);
1566
+ }
1567
+ function isWithinRoot(root, candidate) {
1568
+ const relative = path4.relative(root, candidate);
1569
+ return relative === "" || !relative.startsWith(`..${path4.sep}`) && relative !== ".." && !path4.isAbsolute(relative);
1570
+ }
1571
+ function compareCodeUnits(left, right) {
1572
+ return left < right ? -1 : left > right ? 1 : 0;
1573
+ }
1574
+ function sha256(content) {
1575
+ return createHash("sha256").update(content).digest("hex");
1576
+ }
1577
+ function toPosix(value) {
1578
+ return value.split(path4.sep).join("/");
1579
+ }
1580
+ function isPlainObject2(value) {
1581
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1582
+ }
1583
+ function isStringArray(value) {
1584
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string" && entry.length > 0);
1585
+ }
1586
+ function invalidCatalogType(message) {
1587
+ return failure(
1588
+ "provider-catalog-invalid",
1589
+ message,
1590
+ "Restore a catalog with exactly one valid entry for each peer resource type."
1591
+ );
1592
+ }
1593
+ function withCode(error, code, resourcePath) {
1594
+ return { ok: false, error: { ...error, code, path: error.path ?? resourcePath } };
1595
+ }
1596
+ function failure(code, message, recovery, uri, resourcePath) {
1597
+ return { ok: false, error: { code, message, recovery, uri, path: resourcePath } };
1598
+ }
1599
+ function errorMessage(error) {
1600
+ return error instanceof Error ? error.message : String(error);
1601
+ }
1602
+
1603
+ // src/project-projection.ts
1604
+ var P4_OPERATION_LINEAGE = "W19 R1 P4";
1605
+ var RESOURCE_PROJECTION_AUTHORITIES = Object.freeze({
1606
+ desiredSelection: "project-config",
1607
+ sourceIdentity: "installed-provider",
1608
+ liveBytes: "project-files",
1609
+ appliedOwnership: "store-installation-ledger"
1610
+ });
1611
+ function normalizeProjectResourceSelection(values) {
1612
+ return Array.from(new Set(values)).sort(compareCodeUnits2);
1613
+ }
1614
+ function buildSelectedResourceProjection(options) {
1615
+ const selectedTypes = normalizeProjectResourceSelection(
1616
+ options.profile.selections.resourceProjection ?? []
1617
+ );
1618
+ const provider = options.provider ?? unwrapProvider(loadInstalledSystemResourceProvider());
1619
+ const verifiedAt = options.verifiedAt ?? (/* @__PURE__ */ new Date()).toISOString();
1620
+ const selectedSet = new Set(selectedTypes);
1621
+ const selectedResources = provider.resources.filter((resource) => selectedSet.has(resource.identity.type)).sort((left, right) => compareCodeUnits2(left.identity.uri, right.identity.uri));
1622
+ const assets = selectedResources.map((resource) => {
1623
+ const managedDestination = projectionPath(
1624
+ resource.identity.type,
1625
+ resource.identity.path
1626
+ );
1627
+ return {
1628
+ relativePath: managedDestination,
1629
+ assetClass: "scoped-static",
1630
+ sourceId: `resource:${resource.identity.uri}`,
1631
+ content: Buffer2.from(resource.readContent()).toString("utf8")
1632
+ };
1633
+ });
1634
+ const resources = Object.fromEntries(
1635
+ selectedResources.map((resource) => {
1636
+ const managedDestination = projectionPath(
1637
+ resource.identity.type,
1638
+ resource.identity.path
1639
+ );
1640
+ const previous = options.existingState?.resources[resource.identity.uri];
1641
+ const lastVerifiedAt = previous?.ownershipClass === "managed-snapshot" && previous.installedDigest === resource.digest ? previous.lastVerifiedAt : verifiedAt;
1642
+ return [
1643
+ resource.identity.uri,
1644
+ {
1645
+ uri: resource.identity.uri,
1646
+ managedDestination,
1647
+ ownershipClass: "managed-snapshot",
1648
+ installedDigest: resource.digest,
1649
+ hashAlgorithm: "sha256",
1650
+ lastVerifiedAt,
1651
+ lifecycleDisposition: "active"
1652
+ }
1653
+ ];
1654
+ })
1655
+ );
1656
+ return {
1657
+ assets,
1658
+ state: {
1659
+ resources
1660
+ }
1661
+ };
1662
+ }
1663
+ function createThinRouterAssets(profile) {
1664
+ const assets = [];
1665
+ for (const [harness, instructionKind] of Object.entries(HARNESS_TO_INSTRUCTION)) {
1666
+ if (!profile.selections.harnesses[harness]) {
1667
+ continue;
1668
+ }
1669
+ for (const relativePath of getConfiguredRouterPaths(profile, instructionKind)) {
1670
+ assets.push({
1671
+ relativePath,
1672
+ assetClass: "scoped-static",
1673
+ sourceId: `router:${harness}:${relativePath}`,
1674
+ content: readThinRouterContent(relativePath, profile)
1675
+ });
1676
+ }
1677
+ }
1678
+ return assets.sort((left, right) => compareCodeUnits2(left.relativePath, right.relativePath));
1679
+ }
1680
+ function createRouterOwnershipManifestState(profile, assets, options) {
1681
+ const configuredHarnesses = Object.entries(profile.selections.harnesses).filter(([, selected]) => selected).map(([harness]) => harness).sort(compareCodeUnits2);
1682
+ const routers = Object.fromEntries(
1683
+ assets.map((asset) => {
1684
+ const match = /^router:([^:]+):(.+)$/.exec(asset.sourceId);
1685
+ if (!match) {
1686
+ throw new Error(`Router asset ${asset.relativePath} has an invalid source identity.`);
1687
+ }
1688
+ const harness = match[1];
1689
+ const instructionKind = HARNESS_TO_INSTRUCTION[harness];
1690
+ if (!instructionKind || instructionKind !== routerInstructionKind(asset.relativePath)) {
1691
+ throw new Error(`Router asset ${asset.relativePath} does not match harness ${harness}.`);
1692
+ }
1693
+ return [asset.relativePath, createRouterOwnershipManifestEntry({
1694
+ asset,
1695
+ harness,
1696
+ instructionKind,
1697
+ profile,
1698
+ packageMeta: options.packageMeta,
1699
+ verifiedAt: options.verifiedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1700
+ previous: options.existingState?.routers[asset.relativePath]
1701
+ })];
1702
+ })
1703
+ );
1704
+ return {
1705
+ configuredHarnesses,
1706
+ operationLineage: P4_OPERATION_LINEAGE,
1707
+ routers
1708
+ };
1709
+ }
1710
+ function createRouterOwnershipManifestEntry(options) {
1711
+ const expectedSourceHash = getRouterContentHash(options.asset);
1712
+ const sourceImmutableRef = `package:${options.packageMeta.name}@${options.packageMeta.version}`;
1713
+ const routerClass = isConfiguredRouterPath(
1714
+ options.profile,
1715
+ options.asset.relativePath,
1716
+ options.instructionKind
1717
+ ) ? "bootstrap" : "on-demand-surface";
1718
+ const previous = options.previous;
1719
+ const lastVerifiedAt = previous?.provenanceState === "verified" && previous.sourceId === options.asset.sourceId && previous.sourcePackage === options.packageMeta.name && previous.sourceVersion === options.packageMeta.version && previous.sourceImmutableRef === sourceImmutableRef && previous.expectedSourceHash === expectedSourceHash && previous.installedHash === expectedSourceHash ? previous.lastVerifiedAt : options.verifiedAt;
1720
+ return {
1721
+ relativePath: options.asset.relativePath,
1722
+ harness: options.harness,
1723
+ instructionKind: options.instructionKind,
1724
+ ownershipClass: "managed-snapshot",
1725
+ routerClass,
1726
+ sourceId: options.asset.sourceId,
1727
+ sourcePackage: options.packageMeta.name,
1728
+ sourceVersion: options.packageMeta.version,
1729
+ sourceImmutableRef,
1730
+ materializationMode: "managed-block",
1731
+ provenanceState: "verified",
1732
+ provenanceEvidence: [
1733
+ `package:${options.packageMeta.name}@${options.packageMeta.version}`,
1734
+ `managed-source:${options.asset.sourceId}`
1735
+ ],
1736
+ competingClaims: [],
1737
+ hashAlgorithm: "sha256",
1738
+ expectedSourceHash,
1739
+ installedHash: expectedSourceHash,
1740
+ lastVerifiedAt,
1741
+ lifecycleDisposition: "active",
1742
+ adoptionReceipt: null
1743
+ };
1744
+ }
1745
+ function createProjectSurfaceRouterAssets(profile, surface) {
1746
+ const directory = {
1747
+ archive: ".make-docs/archive",
1748
+ artifacts: "docs/assets",
1749
+ assets: "docs/assets"
1750
+ }[surface];
1751
+ return Object.entries(HARNESS_TO_INSTRUCTION).filter(([harness]) => profile.selections.harnesses[harness]).map(([harness, instructionKind]) => {
1752
+ const relativePath = `${directory}/${instructionKind}`;
1753
+ return {
1754
+ relativePath,
1755
+ assetClass: "scoped-static",
1756
+ sourceId: `router:${harness}:${relativePath}`,
1757
+ content: readThinRouterContent(relativePath, profile)
1758
+ };
1759
+ }).sort((left, right) => compareCodeUnits2(left.relativePath, right.relativePath));
1760
+ }
1761
+ function applyP4ManifestOwnership(relativePath, entry) {
1762
+ if (relativePath === "AGENTS.md" || relativePath === "CLAUDE.md" || /\/AGENTS\.md$|\/CLAUDE\.md$/.test(relativePath)) {
1763
+ return { ...entry, ownershipClass: "managed-block" };
1764
+ }
1765
+ if (entry.skillExposure || entry.agenticOwnership) {
1766
+ return { ...entry, ownershipClass: "selected-skill" };
1767
+ }
1768
+ if (entry.sourceId.startsWith("resource:")) {
1769
+ return { ...entry, ownershipClass: "managed-projection" };
1770
+ }
1771
+ return { ...entry, ownershipClass: "managed-snapshot" };
1772
+ }
1773
+ function resourceProjectionStops(actions) {
1774
+ return actions.filter(
1775
+ (action) => action.sourceId?.startsWith("resource:") && (action.type === "skip-conflict" || action.type === "update-conflict")
1776
+ ).map((action) => action.relativePath).sort(compareCodeUnits2);
1777
+ }
1778
+ function getThinRouterManagedBody(relativePath, profile) {
1779
+ const parsed = parseManagedBlock(readThinRouterContent(relativePath, profile));
1780
+ if (parsed.state !== "valid" || parsed.body === null) {
1781
+ throw new Error(`Upstream thin router is malformed: ${relativePath}.`);
1782
+ }
1783
+ return parsed.body;
1784
+ }
1785
+ function readThinRouterContent(relativePath, profile) {
1786
+ const content = readPackageFile(profile ? getRouterTemplateSourcePath(profile, relativePath) : relativePath);
1787
+ const parsed = parseManagedBlock(content);
1788
+ if (parsed.state !== "valid" || parsed.prefix.trim() !== "" || parsed.suffix.trim() !== "") {
1789
+ throw new Error(`Upstream thin router must contain one managed block: ${relativePath}.`);
1790
+ }
1791
+ return content;
1792
+ }
1793
+ function routerInstructionKind(relativePath) {
1794
+ const fileName = relativePath.split("/").at(-1);
1795
+ return fileName === "AGENTS.md" || fileName === "CLAUDE.md" ? fileName : null;
1796
+ }
1797
+ function getRouterContentHash(asset) {
1798
+ const digest = getManifestFileHash(asset.relativePath, asset.content);
1799
+ if (digest === null) {
1800
+ throw new Error(`Router asset ${asset.relativePath} has a malformed managed block.`);
1801
+ }
1802
+ return digest;
1803
+ }
1804
+ function projectionPath(type, resourcePath) {
1805
+ return `.make-docs/system/${SYSTEM_RESOURCE_TYPE_DIRECTORIES[type]}/${resourcePath}`;
1806
+ }
1807
+ function unwrapProvider(result) {
1808
+ if (!result.ok) {
1809
+ throw new Error(
1810
+ `Installed system-resource provider is unavailable: ${result.error.message}`
1811
+ );
1812
+ }
1813
+ return result.value;
1814
+ }
1815
+ function compareCodeUnits2(left, right) {
1816
+ return left < right ? -1 : left > right ? 1 : 0;
1817
+ }
1818
+
1819
+ // src/planner.ts
1820
+ async function createInstallPlan(options) {
1821
+ const {
1822
+ targetDir,
1823
+ packageMeta,
1824
+ profile,
1825
+ existingManifest,
1826
+ managedFileConflictResolutions,
1827
+ systemAssetMaterializationMode = DEFAULT_SYSTEM_ASSET_MATERIALIZATION_MODE,
1828
+ skillRegistry,
1829
+ operation = existingManifest ? "setup.sync" : "setup"
1830
+ } = options;
1831
+ if (!options.reviewedSkillAdoption) assertStandardSkillLayout(existingManifest, targetDir, profile.selections);
1832
+ const p4ProjectionSelected = profile.selections.resourceProjection !== void 0;
1833
+ if (p4ProjectionSelected) {
1834
+ assertManagedPathHasNoSymlinks(targetDir, MANIFEST_RELATIVE_PATH);
1835
+ }
1836
+ const effectiveMaterializationMode = p4ProjectionSelected ? "provider-backed" : systemAssetMaterializationMode;
1837
+ const systemAssetMaterialization = getSystemAssetMaterializationPlan(
1838
+ profile,
1839
+ effectiveMaterializationMode
1840
+ );
1841
+ let desiredAssets = getDesiredAssetsForMaterializationMode(
1842
+ profile,
1843
+ effectiveMaterializationMode
1844
+ );
1845
+ const verifiedAt = (/* @__PURE__ */ new Date()).toISOString();
1846
+ const selectedProjection = buildSelectedResourceProjection({
1847
+ profile,
1848
+ selectionTrigger: operation === "setup.reconfigure" ? "reconfigure-selection" : "setup-selection",
1849
+ verifiedAt,
1850
+ existingState: existingManifest?.resourceProjection
1851
+ });
1852
+ const thinRouterAssets = createThinRouterAssets(profile);
1853
+ const carriedOnDemandRouterAssets = getCarriedOnDemandRouterAssets({
1854
+ targetDir,
1855
+ profile,
1856
+ existingManifest,
1857
+ completedRemovalHandoff: options.completedRemovalHandoff
1858
+ });
1859
+ const routerAssets = [...thinRouterAssets, ...carriedOnDemandRouterAssets];
1860
+ const thinRouterPaths = new Set(
1861
+ thinRouterAssets.map((asset) => asset.relativePath)
1862
+ );
1863
+ const fullSnapshotAssets = getDesiredAssetsForMaterializationMode(
1864
+ profile,
1865
+ DEFAULT_SYSTEM_ASSET_MATERIALIZATION_MODE
1866
+ );
1867
+ const preserveManagedSnapshotAssets = p4ProjectionSelected && existingManifest !== null;
1868
+ const preservedFullSnapshotAssets = preserveManagedSnapshotAssets ? fullSnapshotAssets.filter(
1869
+ (asset) => existingManifest.files[asset.relativePath]?.systemAsset?.localPath === asset.relativePath && existingManifest.files[asset.relativePath]?.systemAsset?.expectedHashes.includes(
1870
+ existingManifest.files[asset.relativePath].hash
1871
+ ) === true && !(isToolDirectorySystemResourcePath(asset.relativePath) && !isInstructionPath(asset.relativePath))
1872
+ ) : [];
1873
+ desiredAssets = [
1874
+ ...desiredAssets.filter((asset) => !thinRouterPaths.has(asset.relativePath)),
1875
+ ...preservedFullSnapshotAssets.filter((asset) => !thinRouterPaths.has(asset.relativePath)),
1876
+ ...thinRouterAssets,
1877
+ ...carriedOnDemandRouterAssets,
1878
+ ...selectedProjection?.assets ?? []
1879
+ ].filter(
1880
+ (asset, index, assets) => assets.findIndex((candidate) => candidate.relativePath === asset.relativePath) === index
1881
+ ).sort((left, right) => left.relativePath.localeCompare(right.relativePath));
1882
+ const preserveExistingSkills = Boolean(options.preserveExistingSkills && existingManifest);
1883
+ const desiredSkillAssets = preserveExistingSkills ? [] : await getDesiredSkillAssets(profile.selections, skillRegistry);
1884
+ if (!options.reviewedSkillAdoption) assertStandardSkillDestinations(existingManifest, desiredSkillAssets);
1885
+ const desiredSkillFiles = preserveExistingSkills ? [...existingManifest?.skillFiles ?? []] : desiredSkillAssets.map((asset) => asset.relativePath);
1886
+ const desiredSkillFileSet = new Set(desiredSkillFiles);
1887
+ const previousSkillContent = await getPreviousSkillContentByPath(existingManifest);
1888
+ const allDesiredAssets = [
1889
+ ...desiredAssets,
1890
+ ...desiredSkillAssets
1891
+ ];
1892
+ const preservedSkillFiles = preserveExistingSkills ? Object.fromEntries(
1893
+ Object.entries(existingManifest?.files ?? {}).filter(
1894
+ ([relativePath, entry]) => desiredSkillFileSet.has(relativePath) || Boolean(entry.skillExposure) || entry.sourceId.startsWith("skill")
1895
+ ).map(([relativePath, entry]) => [relativePath, { ...entry }])
1896
+ ) : {};
1897
+ const baseDesiredFiles = {
1898
+ ...Object.fromEntries(
1899
+ allDesiredAssets.map((asset) => [
1900
+ asset.relativePath,
1901
+ {
1902
+ hash: getManifestHashForAsset(asset),
1903
+ sourceId: asset.sourceId,
1904
+ ...isSkillExposureAsset(asset) ? { skillExposure: asset.skillExposure } : {}
1905
+ }
1906
+ ])
1907
+ ),
1908
+ ...preservedSkillFiles
1909
+ };
1910
+ const systemAssetManifestState = createSystemAssetManifestState({
1911
+ mode: systemAssetMaterialization.mode,
1912
+ sourcePackage: packageMeta.name,
1913
+ sourceVersion: packageMeta.version,
1914
+ localBootstrapPaths: systemAssetMaterialization.localBootstrapPaths,
1915
+ deferredSystemAssetPaths: systemAssetMaterialization.deferredSystemAssetPaths,
1916
+ materializationClasses: systemAssetMaterialization.materializationClasses,
1917
+ expectedFiles: Object.fromEntries(
1918
+ fullSnapshotAssets.map((asset) => [
1919
+ asset.relativePath,
1920
+ {
1921
+ hash: getManifestHashForAsset(asset),
1922
+ sourceId: asset.sourceId
1923
+ }
1924
+ ])
1925
+ ),
1926
+ materializedFiles: baseDesiredFiles
1927
+ });
1928
+ const desiredFiles = Object.fromEntries(
1929
+ Object.entries(baseDesiredFiles).map(([relativePath, entry]) => [
1930
+ relativePath,
1931
+ applyP4ManifestOwnership(
1932
+ relativePath,
1933
+ systemAssetManifestState.assets[relativePath] ? {
1934
+ ...entry,
1935
+ systemAsset: systemAssetManifestState.assets[relativePath]
1936
+ } : entry
1937
+ )
1938
+ ])
1939
+ );
1940
+ let forceManifestWrite = existingManifest !== null && Object.entries(desiredFiles).some(
1941
+ ([relativePath, entry]) => !isDeepStrictEqual(existingManifest.files[relativePath] ?? null, entry)
1942
+ );
1943
+ const actions = [];
1944
+ let conflictsRunId;
1945
+ const existingSkillFiles = new Set(existingManifest?.skillFiles ?? []);
1946
+ for (const asset of allDesiredAssets) {
1947
+ if (desiredSkillFileSet.has(asset.relativePath)) {
1948
+ const action = planDesiredSkillAsset({
1949
+ targetDir,
1950
+ asset,
1951
+ existingManifest,
1952
+ existingSkillFiles,
1953
+ previousSkillContent
1954
+ });
1955
+ if (action.type === "skip-conflict") {
1956
+ conflictsRunId ??= createRunId();
1957
+ }
1958
+ actions.push(action);
1959
+ continue;
1960
+ }
1961
+ if (isSkillExposureAsset(asset)) {
1962
+ throw new Error(
1963
+ `Skill exposure asset ${asset.relativePath} is missing from the desired skill file set.`
1964
+ );
1965
+ }
1966
+ assertTextDocumentAsset(asset);
1967
+ if (p4ProjectionSelected) {
1968
+ assertManagedPathHasNoSymlinks(targetDir, asset.relativePath);
1969
+ }
1970
+ const absolutePath = relativePathToTarget(targetDir, asset.relativePath);
1971
+ const desiredHash = getManifestHashForAsset(asset);
1972
+ if (!existsSync4(absolutePath)) {
1973
+ actions.push({
1974
+ type: "create",
1975
+ relativePath: asset.relativePath,
1976
+ sourceId: asset.sourceId,
1977
+ content: asset.content,
1978
+ contentHash: desiredHash
1979
+ });
1980
+ continue;
1981
+ }
1982
+ const currentContent = readTextFile(absolutePath);
1983
+ const manifestEntry = existingManifest?.files[asset.relativePath];
1984
+ const currentHash = getCurrentManifestHash(
1985
+ asset.relativePath,
1986
+ currentContent,
1987
+ existingManifest?.schemaVersion ?? null
1988
+ );
1989
+ const schemaOneInstructionStop = getSchemaOneInstructionOwnershipStop(
1990
+ existingManifest,
1991
+ asset.relativePath,
1992
+ currentContent
1993
+ );
1994
+ if (schemaOneInstructionStop) {
1995
+ conflictsRunId ??= createRunId();
1996
+ actions.push({
1997
+ type: "skip-conflict",
1998
+ relativePath: asset.relativePath,
1999
+ sourceId: asset.sourceId,
2000
+ reason: schemaOneInstructionStop
2001
+ });
2002
+ continue;
2003
+ }
2004
+ if (currentHash === desiredHash) {
2005
+ actions.push({
2006
+ type: "noop",
2007
+ relativePath: asset.relativePath,
2008
+ sourceId: asset.sourceId,
2009
+ contentHash: desiredHash
2010
+ });
2011
+ continue;
2012
+ }
2013
+ const projectOwnedResource = getVerifiedProjectOwnedResourceOverride(
2014
+ existingManifest,
2015
+ asset.relativePath,
2016
+ asset.sourceId,
2017
+ currentHash
2018
+ );
2019
+ if (projectOwnedResource) {
2020
+ desiredFiles[asset.relativePath] = projectOwnedResource.file;
2021
+ selectedProjection.state.resources[projectOwnedResource.uri] = projectOwnedResource.resource;
2022
+ actions.push({
2023
+ type: "noop",
2024
+ relativePath: asset.relativePath,
2025
+ sourceId: asset.sourceId,
2026
+ reviewedConflictResolution: "skip",
2027
+ contentHash: projectOwnedResource.file.hash,
2028
+ reason: "Preserve the verified project-owned resource override."
2029
+ });
2030
+ continue;
2031
+ }
2032
+ if (!isInstructionPath(asset.relativePath) && hasVerifiedCleanLegacyManagedOwnership(
2033
+ existingManifest,
2034
+ asset.relativePath,
2035
+ currentHash
2036
+ )) {
2037
+ actions.push({
2038
+ type: "update",
2039
+ relativePath: asset.relativePath,
2040
+ sourceId: asset.sourceId,
2041
+ content: asset.content,
2042
+ contentHash: desiredHash,
2043
+ reason: "Refresh the verified clean legacy managed asset."
2044
+ });
2045
+ continue;
2046
+ }
2047
+ if (asset.sourceId.startsWith("resource:") && !hasVerifiedResourceOwnership(existingManifest, asset.relativePath, asset.sourceId)) {
2048
+ conflictsRunId ??= createRunId();
2049
+ actions.push({
2050
+ type: "skip-conflict",
2051
+ relativePath: asset.relativePath,
2052
+ sourceId: asset.sourceId,
2053
+ content: asset.content,
2054
+ contentHash: desiredHash,
2055
+ reason: "Existing resource path lacks verified URI, provider, digest, destination, and ownership evidence."
2056
+ });
2057
+ continue;
2058
+ }
2059
+ if (isInstructionPath(asset.relativePath) && parseManagedBlock(currentContent).state === "malformed") {
2060
+ conflictsRunId ??= createRunId();
2061
+ actions.push({
2062
+ type: "skip-conflict",
2063
+ relativePath: asset.relativePath,
2064
+ sourceId: asset.sourceId,
2065
+ content: asset.content,
2066
+ contentHash: desiredHash,
2067
+ reason: "The managed block is malformed or duplicated. Repair it before setup can continue."
2068
+ });
2069
+ continue;
2070
+ }
2071
+ const migrationContent = getInstructionMigrationContent(
2072
+ asset,
2073
+ currentContent,
2074
+ manifestEntry,
2075
+ currentHash
2076
+ );
2077
+ if (migrationContent) {
2078
+ actions.push({
2079
+ type: "update",
2080
+ relativePath: asset.relativePath,
2081
+ sourceId: asset.sourceId,
2082
+ content: migrationContent.content,
2083
+ contentHash: desiredHash,
2084
+ reason: migrationContent.reason
2085
+ });
2086
+ continue;
2087
+ }
2088
+ if (manifestEntry && currentHash === manifestEntry.hash && manifestEntry.sourceId === asset.sourceId && manifestEntry.systemAsset?.logicalAssetId === asset.relativePath && manifestEntry.systemAsset.localPath === asset.relativePath && manifestEntry.systemAsset.expectedHashes.includes(manifestEntry.hash)) {
2089
+ actions.push({
2090
+ type: "update",
2091
+ relativePath: asset.relativePath,
2092
+ sourceId: asset.sourceId,
2093
+ content: asset.content,
2094
+ contentHash: desiredHash,
2095
+ reason: "Refresh the verified clean managed system asset."
2096
+ });
2097
+ continue;
2098
+ }
2099
+ const conflictClassification = classifyReviewableManagedFileConflictPath(
2100
+ asset.relativePath,
2101
+ { isDesiredSkillAsset: desiredSkillFileSet.has(asset.relativePath) }
2102
+ );
2103
+ const conflictResolution = getManagedFileConflictResolution(
2104
+ asset.relativePath,
2105
+ conflictClassification,
2106
+ managedFileConflictResolutions
2107
+ );
2108
+ if (conflictClassification && conflictResolution === "overwrite") {
2109
+ const content = getPlannedUpdateContent(asset, currentContent);
2110
+ actions.push({
2111
+ type: "update",
2112
+ relativePath: asset.relativePath,
2113
+ sourceId: asset.sourceId,
2114
+ reviewedConflictResolution: conflictResolution,
2115
+ content,
2116
+ contentHash: desiredHash,
2117
+ reason: getManagedFileConflictOverwriteReason(conflictClassification)
2118
+ });
2119
+ continue;
2120
+ }
2121
+ if (conflictClassification && conflictResolution === "skip") {
2122
+ const resourceUri = asset.sourceId.startsWith("resource:") ? asset.sourceId.slice("resource:".length) : null;
2123
+ const projectedResource = resourceUri ? selectedProjection.state.resources[resourceUri] : void 0;
2124
+ if (manifestEntry && resourceUri && currentHash !== null && projectedResource?.managedDestination === asset.relativePath) {
2125
+ desiredFiles[asset.relativePath] = {
2126
+ hash: currentHash,
2127
+ sourceId: asset.sourceId,
2128
+ ownershipClass: "project-owned"
2129
+ };
2130
+ selectedProjection.state.resources[resourceUri] = {
2131
+ ...projectedResource,
2132
+ ownershipClass: "project-owned",
2133
+ installedDigest: currentHash,
2134
+ lastVerifiedAt: verifiedAt
2135
+ };
2136
+ forceManifestWrite = true;
2137
+ actions.push({
2138
+ type: "noop",
2139
+ relativePath: asset.relativePath,
2140
+ sourceId: asset.sourceId,
2141
+ reviewedConflictResolution: conflictResolution,
2142
+ contentHash: currentHash,
2143
+ reason: getManagedFileConflictSkipReason(
2144
+ conflictClassification,
2145
+ conflictResolution,
2146
+ true
2147
+ )
2148
+ });
2149
+ continue;
2150
+ }
2151
+ actions.push({
2152
+ type: "skip",
2153
+ relativePath: asset.relativePath,
2154
+ sourceId: asset.sourceId,
2155
+ reviewedConflictResolution: conflictResolution,
2156
+ contentHash: desiredHash,
2157
+ reason: getManagedFileConflictSkipReason(
2158
+ conflictClassification,
2159
+ conflictResolution,
2160
+ Boolean(manifestEntry)
2161
+ )
2162
+ });
2163
+ continue;
2164
+ }
2165
+ conflictsRunId ??= createRunId();
2166
+ actions.push({
2167
+ type: "skip-conflict",
2168
+ relativePath: asset.relativePath,
2169
+ sourceId: asset.sourceId,
2170
+ content: getPlannedUpdateContent(asset, currentContent),
2171
+ contentHash: desiredHash,
2172
+ reason: getManagedFileConflictSkipReason(
2173
+ conflictClassification,
2174
+ conflictResolution,
2175
+ Boolean(manifestEntry)
2176
+ )
2177
+ });
2178
+ }
2179
+ if (existingManifest) {
2180
+ for (const [relativePath, manifestEntry] of Object.entries(existingManifest.files)) {
2181
+ if (relativePath === RETIRED_PATH_HELPER) continue;
2182
+ if (relativePath in desiredFiles) {
2183
+ continue;
2184
+ }
2185
+ if (manifestEntry.ownershipClass === "project-owned") {
2186
+ actions.push({
2187
+ type: "skip",
2188
+ relativePath,
2189
+ sourceId: manifestEntry.sourceId,
2190
+ reason: "Preserve project-owned content outside the current managed asset set."
2191
+ });
2192
+ continue;
2193
+ }
2194
+ if (relativePath === RETIRED_PLAYBOOK_CONTRACT_PATH) {
2195
+ let clean = false;
2196
+ try {
2197
+ assertManagedPathHasNoSymlinks(targetDir, relativePath);
2198
+ const retiredPath = relativePathToTarget(targetDir, relativePath);
2199
+ clean = hasTrustedRetiredPlaybookContractOwnership(manifestEntry) && (!existsSync4(retiredPath) || lstatSync3(retiredPath).isFile() && hashText(readTextFile(retiredPath)) === RETIRED_PLAYBOOK_CONTRACT_HASH);
2200
+ } catch {
2201
+ }
2202
+ actions.push({
2203
+ type: clean ? "remove-managed" : "skip",
2204
+ relativePath,
2205
+ sourceId: manifestEntry.sourceId,
2206
+ ...clean ? { contentHash: RETIRED_PLAYBOOK_CONTRACT_HASH } : {},
2207
+ reason: clean ? "Retire the verified shipped Playbook contract at checkpoint 11 after backup." : "Preserve the legacy Playbook contract because trusted ownership and unchanged regular-file bytes are not proved."
2208
+ });
2209
+ continue;
2210
+ }
2211
+ const absolutePath = relativePathToTarget(targetDir, relativePath);
2212
+ if (p4ProjectionSelected || isInstructionPath(relativePath) || isPreservedLegacyPlaybook(relativePath) || isRetiredTemplateOwnedChildRouterPath(relativePath)) {
2213
+ assertManagedPathHasNoSymlinks(targetDir, relativePath);
2214
+ }
2215
+ if (isPreservedLegacyPlaybook(relativePath) && existsSync4(absolutePath)) {
2216
+ if (!lstatSync3(absolutePath).isFile()) {
2217
+ conflictsRunId ??= createRunId();
2218
+ actions.push({
2219
+ type: "skip-conflict",
2220
+ relativePath,
2221
+ sourceId: manifestEntry.sourceId,
2222
+ reason: "Legacy Playbook adoption stopped because the preserved path is not a regular file."
2223
+ });
2224
+ continue;
2225
+ }
2226
+ const currentHash2 = hashText(readTextFile(absolutePath));
2227
+ const projectSourceId = `project:${relativePath}`;
2228
+ desiredFiles[relativePath] = {
2229
+ hash: currentHash2,
2230
+ sourceId: projectSourceId,
2231
+ ownershipClass: "project-owned"
2232
+ };
2233
+ forceManifestWrite = true;
2234
+ actions.push({
2235
+ type: "noop",
2236
+ relativePath,
2237
+ sourceId: projectSourceId,
2238
+ contentHash: currentHash2,
2239
+ reason: "Adopt the preserved legacy Playbook as project-owned content after the shipped default retires."
2240
+ });
2241
+ continue;
2242
+ }
2243
+ if (!existsSync4(absolutePath)) {
2244
+ actions.push({
2245
+ type: "remove-managed",
2246
+ relativePath,
2247
+ sourceId: manifestEntry.sourceId
2248
+ });
2249
+ continue;
2250
+ }
2251
+ if (manifestEntry.skillExposure) {
2252
+ const action = planStaleSkillFile({
2253
+ targetDir,
2254
+ relativePath,
2255
+ existingManifest,
2256
+ previousSkillContent
2257
+ });
2258
+ if (action.type === "skip-conflict") {
2259
+ conflictsRunId ??= createRunId();
2260
+ }
2261
+ actions.push(action);
2262
+ continue;
2263
+ }
2264
+ if (!lstatSync3(absolutePath).isFile()) {
2265
+ conflictsRunId ??= createRunId();
2266
+ actions.push({
2267
+ type: "skip-conflict",
2268
+ relativePath,
2269
+ sourceId: manifestEntry.sourceId,
2270
+ reason: "Existing managed file path is no longer a regular file and will not be removed automatically."
2271
+ });
2272
+ continue;
2273
+ }
2274
+ if (manifestEntry.sourceId.startsWith("resource:") && !hasVerifiedResourceOwnership(existingManifest, relativePath, manifestEntry.sourceId)) {
2275
+ conflictsRunId ??= createRunId();
2276
+ actions.push({
2277
+ type: "skip-conflict",
2278
+ relativePath,
2279
+ sourceId: manifestEntry.sourceId,
2280
+ reason: "Resource removal stopped because applied destination, digest, and ownership evidence is incomplete."
2281
+ });
2282
+ continue;
2283
+ }
2284
+ const currentContent = readTextFile(absolutePath);
2285
+ const currentHash = getCurrentManifestHash(
2286
+ relativePath,
2287
+ currentContent,
2288
+ existingManifest.schemaVersion
2289
+ );
2290
+ const schemaOneInstructionStop = getSchemaOneInstructionOwnershipStop(
2291
+ existingManifest,
2292
+ relativePath,
2293
+ currentContent
2294
+ );
2295
+ if (schemaOneInstructionStop) {
2296
+ conflictsRunId ??= createRunId();
2297
+ actions.push({
2298
+ type: "skip-conflict",
2299
+ relativePath,
2300
+ sourceId: manifestEntry.sourceId,
2301
+ reason: schemaOneInstructionStop
2302
+ });
2303
+ continue;
2304
+ }
2305
+ const legacyFullFileHash = hashText(currentContent);
2306
+ const legacyMigrationTarget = getSystemToolResourceMigrationTarget(relativePath);
2307
+ const replacementTarget = legacyMigrationTarget ?? getRetiredResourceReplacement(relativePath);
2308
+ const parsedInstructionBlock = isInstructionPath(relativePath) ? parseManagedBlock(currentContent) : null;
2309
+ const isCleanInstructionBlock = parsedInstructionBlock?.state === "valid" && currentHash === manifestEntry.hash && instructionHasNoOutsideContent(currentContent);
2310
+ const hasOutsideInstructionContent = parsedInstructionBlock?.state === "valid" && (parsedInstructionBlock.prefix.trim().length > 0 || parsedInstructionBlock.suffix.trim().length > 0);
2311
+ if (legacyMigrationTarget && !hasVerifiedLegacySystemResourceOwnership(
2312
+ existingManifest,
2313
+ relativePath,
2314
+ manifestEntry
2315
+ )) {
2316
+ conflictsRunId ??= createRunId();
2317
+ actions.push({
2318
+ type: "skip-conflict",
2319
+ relativePath,
2320
+ sourceId: manifestEntry.sourceId,
2321
+ reason: `Legacy system resource migration or removal at ${relativePath} stopped because managed ownership and trusted hashes are incomplete.`
2322
+ });
2323
+ continue;
2324
+ }
2325
+ if (currentHash === manifestEntry.hash && (!isInstructionPath(relativePath) || isCleanInstructionBlock)) {
2326
+ actions.push({
2327
+ type: "remove-managed",
2328
+ relativePath,
2329
+ sourceId: manifestEntry.sourceId,
2330
+ ...replacementTarget && replacementTarget in desiredFiles ? {
2331
+ reason: `Remove verified legacy system resource after ${replacementTarget} is materialized.`
2332
+ } : {}
2333
+ });
2334
+ continue;
2335
+ }
2336
+ if (currentHash === manifestEntry.hash && hasOutsideInstructionContent) {
2337
+ actions.push({
2338
+ type: "strip-managed-block",
2339
+ relativePath,
2340
+ sourceId: manifestEntry.sourceId,
2341
+ content: `${parsedInstructionBlock.prefix}${parsedInstructionBlock.suffix}`,
2342
+ reason: "Remove the clean managed block and preserve project content outside it."
2343
+ });
2344
+ continue;
2345
+ }
2346
+ if (isInstructionPath(relativePath) && legacyFullFileHash === manifestEntry.hash) {
2347
+ actions.push({
2348
+ type: "remove-managed",
2349
+ relativePath,
2350
+ sourceId: manifestEntry.sourceId
2351
+ });
2352
+ continue;
2353
+ }
2354
+ conflictsRunId ??= createRunId();
2355
+ actions.push({
2356
+ type: "skip-conflict",
2357
+ relativePath,
2358
+ sourceId: manifestEntry.sourceId,
2359
+ ...replacementTarget && currentHash !== null ? { content: currentContent, contentHash: currentHash } : {},
2360
+ reason: "Existing managed file differs from the recorded manifest and will not be removed automatically."
2361
+ });
2362
+ }
2363
+ for (const relativePath of existingSkillFiles) {
2364
+ if (relativePath in desiredFiles || relativePath in existingManifest.files) {
2365
+ continue;
2366
+ }
2367
+ const action = planStaleSkillFile({
2368
+ targetDir,
2369
+ relativePath,
2370
+ existingManifest,
2371
+ previousSkillContent
2372
+ });
2373
+ if (action.type === "skip-conflict") {
2374
+ conflictsRunId ??= createRunId();
2375
+ }
2376
+ actions.push(action);
2377
+ }
2378
+ }
2379
+ const helperRetirement = planRetiredPathHelper(targetDir, existingManifest, actions);
2380
+ if (helperRetirement) actions.push(helperRetirement);
2381
+ const annotatedActions = annotateLifecycleActions(actions.map(withAgenticRole).sort(comparePlannedActions));
2382
+ const stops = Array.from(/* @__PURE__ */ new Set([
2383
+ ...resourceProjectionStops(annotatedActions),
2384
+ ...annotatedActions.filter((action) => action.reason?.includes("managed block is malformed")).map((action) => action.relativePath)
2385
+ ])).sort();
2386
+ return {
2387
+ packageName: packageMeta.name,
2388
+ packageVersion: packageMeta.version,
2389
+ profile,
2390
+ systemAssetMaterialization: systemAssetManifestState,
2391
+ actions: annotatedActions,
2392
+ desiredFiles,
2393
+ desiredSkillFiles: desiredSkillFiles.sort(),
2394
+ conflictsRunId,
2395
+ operation,
2396
+ routerOwnership: createRouterOwnershipManifestState(profile, routerAssets, {
2397
+ packageMeta,
2398
+ verifiedAt,
2399
+ existingState: existingManifest?.routerOwnership
2400
+ }),
2401
+ resourceProjection: selectedProjection.state,
2402
+ classificationSnapshot: createLifecyclePlanSnapshot(
2403
+ targetDir,
2404
+ annotatedActions,
2405
+ []
2406
+ ),
2407
+ stops,
2408
+ forceManifestWrite
2409
+ };
2410
+ }
2411
+ function isPreservedLegacyPlaybook(relativePath) {
2412
+ return [
2413
+ "docs/assets/playbooks/agent/make-docs-lifecycle.playbook.md",
2414
+ "docs/assets/playbooks/agent/naive-uat-facilitator.playbook.md",
2415
+ "docs/assets/playbooks/user/naive-uat-tester.playbook.md"
2416
+ ].includes(relativePath);
2417
+ }
2418
+ async function createSkillsOnlyInstallPlan(options) {
2419
+ const { targetDir, packageMeta, profile, existingManifest, remove, skillRegistry } = options;
2420
+ if (!remove && !options.reviewedSkillAdoption) assertStandardSkillLayout(existingManifest, targetDir, profile.selections);
2421
+ const desiredSkillAssets = remove ? [] : await getDesiredSkillAssets(profile.selections, skillRegistry);
2422
+ if (!remove && !options.reviewedSkillAdoption) assertStandardSkillDestinations(existingManifest, desiredSkillAssets);
2423
+ const desiredSkillFiles = desiredSkillAssets.map((asset) => asset.relativePath);
2424
+ const desiredFiles = Object.fromEntries(
2425
+ desiredSkillAssets.map((asset) => [
2426
+ asset.relativePath,
2427
+ applyP4ManifestOwnership(asset.relativePath, {
2428
+ hash: getManifestHashForAsset(asset),
2429
+ sourceId: asset.sourceId,
2430
+ ...isSkillExposureAsset(asset) ? { skillExposure: asset.skillExposure } : {}
2431
+ })
2432
+ ])
2433
+ );
2434
+ const previousSkillContent = await getPreviousSkillContentByPath(existingManifest);
2435
+ const existingSkillFiles = new Set(existingManifest?.skillFiles ?? []);
2436
+ const actions = [];
2437
+ let conflictsRunId;
2438
+ if (!remove) {
2439
+ for (const asset of desiredSkillAssets) {
2440
+ const action = planDesiredSkillAsset({
2441
+ targetDir,
2442
+ asset,
2443
+ existingManifest,
2444
+ existingSkillFiles,
2445
+ previousSkillContent
2446
+ });
2447
+ if (action.type === "skip-conflict") {
2448
+ conflictsRunId ??= createRunId();
2449
+ }
2450
+ actions.push(action);
2451
+ }
2452
+ }
2453
+ if (existingManifest) {
2454
+ for (const relativePath of existingSkillFiles) {
2455
+ if (relativePath in desiredFiles) {
2456
+ continue;
2457
+ }
2458
+ const action = planStaleSkillFile({
2459
+ targetDir,
2460
+ relativePath,
2461
+ existingManifest,
2462
+ previousSkillContent
2463
+ });
2464
+ if (action.type === "skip-conflict") {
2465
+ conflictsRunId ??= createRunId();
2466
+ }
2467
+ actions.push(action);
2468
+ }
2469
+ }
2470
+ const annotatedActions = actions.map(withAgenticRole).sort(comparePlannedActions);
2471
+ const needsCurrentOwnershipProof = !(remove && !existingManifest) && (!existingManifest?.routerOwnership || !existingManifest.resourceProjection);
2472
+ const proofPlan = needsCurrentOwnershipProof ? await createInstallPlan({
2473
+ targetDir,
2474
+ packageMeta,
2475
+ profile: {
2476
+ ...profile,
2477
+ selections: {
2478
+ ...profile.selections,
2479
+ resourceProjection: []
2480
+ }
2481
+ },
2482
+ existingManifest,
2483
+ operation: existingManifest ? "setup.sync" : "setup",
2484
+ reviewedSkillAdoption: options.reviewedSkillAdoption
2485
+ }) : null;
2486
+ const routerActions = proofPlan?.actions.filter(
2487
+ (action) => action.sourceId?.startsWith("router:")
2488
+ ) ?? [];
2489
+ const routerDesiredFiles = Object.fromEntries(
2490
+ Object.entries(proofPlan?.desiredFiles ?? {}).filter(
2491
+ ([, entry]) => entry.sourceId.startsWith("router:")
2492
+ )
2493
+ );
2494
+ return {
2495
+ packageName: packageMeta.name,
2496
+ packageVersion: packageMeta.version,
2497
+ profile: existingManifest && !proofPlan ? resolveInstallProfile({ ...profile.selections, skillHarnesses: profile.selections.skillHarnesses ?? profile.selections.harnesses, harnesses: existingManifest.selections.harnesses }) : profile,
2498
+ systemAssetMaterialization: proofPlan?.systemAssetMaterialization ?? createSkillsOnlySystemAssetMaterializationPlan(),
2499
+ actions: [...routerActions, ...annotatedActions].sort(comparePlannedActions),
2500
+ desiredFiles: { ...routerDesiredFiles, ...desiredFiles },
2501
+ desiredSkillFiles: desiredSkillFiles.sort(),
2502
+ conflictsRunId,
2503
+ routerOwnership: proofPlan?.routerOwnership ?? existingManifest?.routerOwnership,
2504
+ resourceProjection: proofPlan?.resourceProjection ?? existingManifest?.resourceProjection
2505
+ };
2506
+ }
2507
+ function withAgenticRole(action) {
2508
+ if (action.skillExposure) {
2509
+ return {
2510
+ ...action,
2511
+ agenticRole: action.skillExposure.mode === "copy-mirror" ? "copy-mirror" : "native-exposure"
2512
+ };
2513
+ }
2514
+ const agenticRole = classifyAgenticSkillFileRole({
2515
+ relativePath: action.relativePath,
2516
+ sourceId: action.sourceId
2517
+ });
2518
+ return agenticRole ? { ...action, agenticRole } : action;
2519
+ }
2520
+ function createSkillsOnlySystemAssetMaterializationPlan() {
2521
+ return {
2522
+ mode: DEFAULT_SYSTEM_ASSET_MATERIALIZATION_MODE,
2523
+ localBootstrapPaths: [],
2524
+ deferredSystemAssetPaths: [],
2525
+ materializationClasses: {},
2526
+ recoveryGuidance: "Skills-only sync preserves existing system asset provenance when a manifest is already present.",
2527
+ assets: {}
2528
+ };
2529
+ }
2530
+ function planDesiredSkillAsset(options) {
2531
+ const { targetDir, asset, existingManifest, existingSkillFiles, previousSkillContent } = options;
2532
+ const root = asset.relativePath.match(/^(.*(?:^|\/)(?:\.make-docs\/agentics|\.agents|\.claude|\.codex)\/skills\/[^/]+)(?:\/|$)/)?.[1];
2533
+ const guardedRoots = [...new Set((isSkillExposureAsset(asset) ? [asset.relativePath, asset.skillExposure.canonicalPayloadPath] : [root]).filter((p) => !!p))];
2534
+ if (guardedRoots.some((root2) => lstatSync3(relativePathToTarget(targetDir, root2), { throwIfNoEntry: false }) && !Object.keys(existingManifest?.files ?? {}).some((p) => p === root2 || p.startsWith(root2 + "/")) && ![...existingSkillFiles].some((p) => p === root2 || p.startsWith(root2 + "/")))) {
2535
+ return {
2536
+ type: "skip-conflict",
2537
+ relativePath: asset.relativePath,
2538
+ sourceId: asset.sourceId,
2539
+ ...isSkillExposureAsset(asset) ? { skillExposure: asset.skillExposure, copyMirrorAssets: asset.copyMirrorAssets } : { content: asset.content },
2540
+ reason: "Existing unowned Skill content needs setup skills --adopt-existing and an exact reviewed digest before managed changes."
2541
+ };
2542
+ }
2543
+ if (isSkillExposureAsset(asset)) {
2544
+ return planDesiredSkillExposure({
2545
+ targetDir,
2546
+ asset,
2547
+ existingManifest,
2548
+ previousSkillContent
2549
+ });
2550
+ }
2551
+ const absolutePath = relativePathToTarget(targetDir, asset.relativePath);
2552
+ const desiredHash = hashText(asset.content);
2553
+ if (!existsSync4(absolutePath)) {
2554
+ return {
2555
+ type: "create",
2556
+ relativePath: asset.relativePath,
2557
+ sourceId: asset.sourceId,
2558
+ content: asset.content,
2559
+ contentHash: desiredHash
2560
+ };
2561
+ }
2562
+ const currentContent = readFileSync4(absolutePath);
2563
+ if (contentEquals(currentContent, asset.content)) {
2564
+ return {
2565
+ type: "noop",
2566
+ relativePath: asset.relativePath,
2567
+ sourceId: asset.sourceId,
2568
+ contentHash: desiredHash
2569
+ };
2570
+ }
2571
+ const currentHash = hashText(currentContent);
2572
+ const manifestEntry = existingManifest?.files[asset.relativePath];
2573
+ if (manifestEntry && manifestEntry.hash === currentHash) {
2574
+ return {
2575
+ type: "update",
2576
+ relativePath: asset.relativePath,
2577
+ sourceId: asset.sourceId,
2578
+ content: asset.content,
2579
+ contentHash: desiredHash
2580
+ };
2581
+ }
2582
+ const previousContent = previousSkillContent.get(asset.relativePath);
2583
+ if (existingSkillFiles.has(asset.relativePath) && previousContent !== void 0 && contentEquals(currentContent, previousContent)) {
2584
+ return {
2585
+ type: "update",
2586
+ relativePath: asset.relativePath,
2587
+ sourceId: asset.sourceId,
2588
+ content: asset.content,
2589
+ contentHash: desiredHash,
2590
+ reason: "Managed skill file will be refreshed."
2591
+ };
2592
+ }
2593
+ return {
2594
+ type: "skip-conflict",
2595
+ relativePath: asset.relativePath,
2596
+ sourceId: asset.sourceId,
2597
+ content: asset.content,
2598
+ contentHash: desiredHash,
2599
+ reason: existingSkillFiles.has(asset.relativePath) ? "Existing managed skill file differs from the desired skill content." : "Unmanaged skill file already exists with different content."
2600
+ };
2601
+ }
2602
+ function planDesiredSkillExposure(options) {
2603
+ const { targetDir, asset, existingManifest, previousSkillContent } = options;
2604
+ const absolutePath = relativePathToTarget(targetDir, asset.relativePath);
2605
+ const desiredHash = getSkillExposureHash(asset);
2606
+ const manifestEntry = existingManifest?.files[asset.relativePath];
2607
+ const baseAction = {
2608
+ relativePath: asset.relativePath,
2609
+ sourceId: asset.sourceId,
2610
+ skillExposure: asset.skillExposure,
2611
+ copyMirrorAssets: asset.copyMirrorAssets,
2612
+ contentHash: desiredHash
2613
+ };
2614
+ if (!existsSync4(absolutePath)) {
2615
+ return {
2616
+ ...baseAction,
2617
+ type: "create"
2618
+ };
2619
+ }
2620
+ const existingExposure = classifyExistingSkillExposure(targetDir, asset);
2621
+ if (existingExposure === "symlink" || existingExposure === "copy-mirror") {
2622
+ return {
2623
+ ...baseAction,
2624
+ type: "noop",
2625
+ skillExposure: {
2626
+ ...asset.skillExposure,
2627
+ mode: existingExposure
2628
+ }
2629
+ };
2630
+ }
2631
+ if (existingExposure === "legacy-clean-managed") {
2632
+ return {
2633
+ ...baseAction,
2634
+ type: "update",
2635
+ reason: "Clean managed harness stub or duplicated payload will be replaced with a native skill exposure."
2636
+ };
2637
+ }
2638
+ if (manifestEntry?.skillExposure?.skillName === asset.skillExposure.skillName && manifestEntry.skillExposure.canonicalPayloadPath === asset.skillExposure.canonicalPayloadPath && isCleanOwnedSkillCopy(targetDir, asset, existingManifest)) {
2639
+ return {
2640
+ ...baseAction,
2641
+ type: "update",
2642
+ reason: "Managed native skill exposure will be refreshed."
2643
+ };
2644
+ }
2645
+ if (isCleanManifestOwnedLegacySkillExposureDirectory(
2646
+ targetDir,
2647
+ asset.relativePath,
2648
+ existingManifest
2649
+ )) {
2650
+ return {
2651
+ ...baseAction,
2652
+ type: "update",
2653
+ reason: "Clean manifest-owned harness stub or duplicated payload will be replaced with a native skill exposure."
2654
+ };
2655
+ }
2656
+ if (isCleanLegacySkillExposureDirectory(targetDir, asset.relativePath, previousSkillContent)) {
2657
+ return {
2658
+ ...baseAction,
2659
+ type: "update",
2660
+ reason: "Clean legacy managed skill directory will be replaced with a native skill exposure."
2661
+ };
2662
+ }
2663
+ return {
2664
+ ...baseAction,
2665
+ type: "skip-conflict",
2666
+ reason: "Existing harness skill path is not a managed native exposure and will not be replaced automatically."
2667
+ };
2668
+ }
2669
+ function isCleanOwnedSkillCopy(targetDir, asset, manifest) {
2670
+ const absolute = relativePathToTarget(targetDir, asset.relativePath);
2671
+ if (!manifest || !lstatSync3(absolute).isDirectory()) return false;
2672
+ const canonicalRoot = asset.skillExposure.canonicalPayloadPath;
2673
+ const expected = Object.keys(manifest.files).filter((p) => p.startsWith(canonicalRoot + "/"));
2674
+ const files = [];
2675
+ const visit = (directory) => readdirSync3(directory, { withFileTypes: true }).every((entry) => {
2676
+ const target = path5.join(directory, entry.name);
2677
+ const ownedPath = canonicalRoot + "/" + path5.relative(absolute, target).split(path5.sep).join("/");
2678
+ if (entry.isDirectory()) return expected.some((p) => p.startsWith(ownedPath + "/")) && visit(target);
2679
+ if (!entry.isFile()) return false;
2680
+ files.push(target);
2681
+ return true;
2682
+ });
2683
+ if (!visit(absolute)) return false;
2684
+ if (files.length !== expected.length) return false;
2685
+ return files.every((p) => {
2686
+ if (!lstatSync3(p).isFile()) return false;
2687
+ const canonicalPath = canonicalRoot + "/" + path5.relative(absolute, p).split(path5.sep).join("/");
2688
+ const entry = manifest.files[canonicalPath];
2689
+ return entry !== void 0 && hashText(readFileSync4(p)) === entry.hash;
2690
+ });
2691
+ }
2692
+ function planStaleSkillFile(options) {
2693
+ const { targetDir, relativePath, existingManifest, previousSkillContent } = options;
2694
+ const manifestEntry = existingManifest.files[relativePath];
2695
+ const absolutePath = relativePathToTarget(targetDir, relativePath);
2696
+ if (!existsSync4(absolutePath)) {
2697
+ return {
2698
+ type: "remove-managed",
2699
+ relativePath,
2700
+ sourceId: manifestEntry?.sourceId ?? `skill:${relativePath}`
2701
+ };
2702
+ }
2703
+ const stats = lstatSync3(absolutePath);
2704
+ if (!stats.isFile()) {
2705
+ if ((manifestEntry?.skillExposure || isSkillExposurePath(relativePath)) && (manifestEntry?.skillExposure && isCleanOwnedSkillCopy(targetDir, { relativePath, skillExposure: manifestEntry.skillExposure }, existingManifest) || isManagedSkillExposurePath(
2706
+ absolutePath,
2707
+ targetDir,
2708
+ relativePath,
2709
+ previousSkillContent,
2710
+ manifestEntry?.skillExposure
2711
+ ))) {
2712
+ return {
2713
+ type: "remove-managed",
2714
+ relativePath,
2715
+ sourceId: manifestEntry?.sourceId ?? `skill:${relativePath}`,
2716
+ skillExposure: manifestEntry?.skillExposure
2717
+ };
2718
+ }
2719
+ return {
2720
+ type: "skip-conflict",
2721
+ relativePath,
2722
+ sourceId: manifestEntry?.sourceId ?? `skill:${relativePath}`,
2723
+ reason: "Existing managed skill path is no longer a regular file and will not be removed automatically."
2724
+ };
2725
+ }
2726
+ const currentContent = readFileSync4(absolutePath);
2727
+ const currentHash = hashText(currentContent);
2728
+ if (manifestEntry && manifestEntry.hash === currentHash) {
2729
+ return {
2730
+ type: "remove-managed",
2731
+ relativePath,
2732
+ sourceId: manifestEntry.sourceId
2733
+ };
2734
+ }
2735
+ const previousContent = previousSkillContent.get(relativePath);
2736
+ if (!manifestEntry && (previousContent === void 0 || contentEquals(currentContent, previousContent))) {
2737
+ return {
2738
+ type: "remove-managed",
2739
+ relativePath,
2740
+ sourceId: `skill:${relativePath}`
2741
+ };
2742
+ }
2743
+ return {
2744
+ type: "skip-conflict",
2745
+ relativePath,
2746
+ sourceId: manifestEntry?.sourceId ?? `skill:${relativePath}`,
2747
+ reason: "Existing managed file differs from the recorded manifest and will not be removed automatically."
2748
+ };
2749
+ }
2750
+ async function getPreviousSkillContentByPath(existingManifest) {
2751
+ if (!existingManifest) {
2752
+ return /* @__PURE__ */ new Map();
2753
+ }
2754
+ const selections = structuredClone(existingManifest.selections);
2755
+ selections.skills = true;
2756
+ try {
2757
+ const [previousAssets, retiredAssets] = await Promise.all([
2758
+ getDesiredSkillAssets(selections),
2759
+ getRetiredManagedSkillAssets(selections)
2760
+ ]);
2761
+ return new Map(
2762
+ [...retiredAssets, ...previousAssets].flatMap(
2763
+ (asset) => isSkillExposureAsset(asset) ? asset.copyMirrorAssets : [asset]
2764
+ ).map((asset) => [asset.relativePath, asset.content])
2765
+ );
2766
+ } catch {
2767
+ return /* @__PURE__ */ new Map();
2768
+ }
2769
+ }
2770
+ function classifyExistingSkillExposure(targetDir, asset) {
2771
+ const absolutePath = relativePathToTarget(targetDir, asset.relativePath);
2772
+ const stats = lstatSync3(absolutePath);
2773
+ if (stats.isSymbolicLink()) {
2774
+ const currentTarget = path5.resolve(
2775
+ path5.dirname(absolutePath),
2776
+ readlinkSync(absolutePath)
2777
+ );
2778
+ const expectedTarget = relativePathToTarget(
2779
+ targetDir,
2780
+ asset.skillExposure.canonicalPayloadPath
2781
+ );
2782
+ return path5.resolve(currentTarget) === path5.resolve(expectedTarget) ? "symlink" : "conflict";
2783
+ }
2784
+ if (!stats.isDirectory()) {
2785
+ return "conflict";
2786
+ }
2787
+ if (copyMirrorMatches(asset.copyMirrorAssets, targetDir, asset.relativePath)) {
2788
+ return "copy-mirror";
2789
+ }
2790
+ return "conflict";
2791
+ }
2792
+ function isCleanManifestOwnedLegacySkillExposureDirectory(targetDir, relativePath, existingManifest) {
2793
+ const absolutePath = relativePathToTarget(targetDir, relativePath);
2794
+ if (!existingManifest || !existsSync4(absolutePath) || !lstatSync3(absolutePath).isDirectory()) {
2795
+ return false;
2796
+ }
2797
+ const descendantPaths = listDescendantFilePaths(absolutePath).map(
2798
+ (filePath) => normalizeSkillDescendantPath(targetDir, relativePath, filePath)
2799
+ );
2800
+ if (descendantPaths.length === 0) {
2801
+ return false;
2802
+ }
2803
+ return descendantPaths.every((descendantPath) => {
2804
+ const manifestEntry = existingManifest.files[descendantPath];
2805
+ return manifestEntry !== void 0 && isLegacySkillSourceId(manifestEntry.sourceId) && getManifestFileHash(
2806
+ descendantPath,
2807
+ readFileSync4(relativePathToTarget(targetDir, descendantPath))
2808
+ ) === manifestEntry.hash;
2809
+ });
2810
+ }
2811
+ function isLegacySkillSourceId(sourceId) {
2812
+ return sourceId.startsWith("skill-stub:") || sourceId.startsWith("skill:") || sourceId.startsWith("skill-asset:") || sourceId.startsWith("retired-skill-asset:");
2813
+ }
2814
+ function isCleanLegacySkillExposureDirectory(targetDir, relativePath, previousSkillContent) {
2815
+ const absolutePath = relativePathToTarget(targetDir, relativePath);
2816
+ if (!existsSync4(absolutePath) || !lstatSync3(absolutePath).isDirectory()) {
2817
+ return false;
2818
+ }
2819
+ const descendantPaths = listDescendantFilePaths(absolutePath).map(
2820
+ (filePath) => normalizeSkillDescendantPath(targetDir, relativePath, filePath)
2821
+ );
2822
+ if (descendantPaths.length === 0) {
2823
+ return true;
2824
+ }
2825
+ return descendantPaths.every((descendantPath) => {
2826
+ const expectedContent = previousSkillContent.get(descendantPath);
2827
+ return expectedContent !== void 0 && contentEquals(readFileSync4(relativePathToTarget(targetDir, descendantPath)), expectedContent);
2828
+ });
2829
+ }
2830
+ function copyMirrorMatches(copyMirrorAssets, targetDir, exposurePath) {
2831
+ const absoluteExposurePath = relativePathToTarget(targetDir, exposurePath);
2832
+ if (!existsSync4(absoluteExposurePath) || !lstatSync3(absoluteExposurePath).isDirectory()) {
2833
+ return false;
2834
+ }
2835
+ const expectedContentByPath = new Map(
2836
+ copyMirrorAssets.map((asset) => [normalizePlanPath(asset.relativePath), asset.content])
2837
+ );
2838
+ const existingFiles = listDescendantFilePaths(absoluteExposurePath).map(
2839
+ (filePath) => normalizeSkillDescendantPath(targetDir, exposurePath, filePath)
2840
+ );
2841
+ if (existingFiles.length !== expectedContentByPath.size) {
2842
+ return false;
2843
+ }
2844
+ return existingFiles.every((relativePath) => {
2845
+ const expectedContent = expectedContentByPath.get(relativePath);
2846
+ return expectedContent !== void 0 && contentEquals(readFileSync4(relativePathToTarget(targetDir, relativePath)), expectedContent);
2847
+ });
2848
+ }
2849
+ function listDescendantFilePaths(root) {
2850
+ const entries = readdirSync3(root, { withFileTypes: true });
2851
+ return entries.flatMap((entry) => {
2852
+ const entryPath = path5.join(root, entry.name);
2853
+ if (entry.isDirectory()) {
2854
+ return listDescendantFilePaths(entryPath);
2855
+ }
2856
+ if (entry.isFile()) {
2857
+ return [entryPath];
2858
+ }
2859
+ return [];
2860
+ });
2861
+ }
2862
+ function isManagedSkillExposurePath(absolutePath, targetDir, relativePath, previousSkillContent, manifestSkillExposure) {
2863
+ const stats = lstatSync3(absolutePath);
2864
+ if (stats.isSymbolicLink()) {
2865
+ if (manifestSkillExposure?.canonicalPayloadPath) {
2866
+ return skillExposureSymlinkTargetMatches(
2867
+ absolutePath,
2868
+ targetDir,
2869
+ manifestSkillExposure.canonicalPayloadPath
2870
+ );
2871
+ }
2872
+ return skillExposureDescendantsMatch(targetDir, relativePath, previousSkillContent);
2873
+ }
2874
+ return stats.isDirectory() && isCleanLegacySkillExposureDirectory(targetDir, relativePath, previousSkillContent);
2875
+ }
2876
+ function skillExposureSymlinkTargetMatches(absolutePath, targetDir, canonicalPayloadPath) {
2877
+ const currentTarget = path5.resolve(path5.dirname(absolutePath), readlinkSync(absolutePath));
2878
+ const expectedTarget = relativePathToTarget(targetDir, canonicalPayloadPath);
2879
+ return path5.resolve(currentTarget) === path5.resolve(expectedTarget);
2880
+ }
2881
+ function skillExposureDescendantsMatch(targetDir, relativePath, previousSkillContent) {
2882
+ const absolutePath = relativePathToTarget(targetDir, relativePath);
2883
+ if (!existsSync4(absolutePath) || !statSync2(absolutePath).isDirectory()) {
2884
+ return false;
2885
+ }
2886
+ const descendantPaths = listDescendantFilePaths(absolutePath).map(
2887
+ (filePath) => normalizeSkillDescendantPath(targetDir, relativePath, filePath)
2888
+ );
2889
+ return descendantPaths.every((descendantPath) => {
2890
+ const expectedContent = previousSkillContent.get(descendantPath);
2891
+ return expectedContent !== void 0 && contentEquals(readFileSync4(relativePathToTarget(targetDir, descendantPath)), expectedContent);
2892
+ });
2893
+ }
2894
+ function normalizeSkillDescendantPath(targetDir, skillRootPath, descendantPath) {
2895
+ return path5.isAbsolute(skillRootPath) ? normalizePlanPath(descendantPath) : normalizePlanPath(path5.relative(targetDir, descendantPath));
2896
+ }
2897
+ function isSkillExposurePath(relativePath) {
2898
+ const normalizedPath = normalizePlanPath(relativePath);
2899
+ return normalizedPath.startsWith(".claude/skills/") || normalizedPath.startsWith(".agents/skills/") || normalizedPath.includes("/.claude/skills/") || normalizedPath.includes("/.agents/skills/");
2900
+ }
2901
+ function comparePlannedActions(left, right) {
2902
+ const leftLegacyRemoval = isLegacySystemResourceRemoval(left);
2903
+ const rightLegacyRemoval = isLegacySystemResourceRemoval(right);
2904
+ if (leftLegacyRemoval !== rightLegacyRemoval) {
2905
+ return leftLegacyRemoval ? 1 : -1;
2906
+ }
2907
+ if (left.relativePath === right.relativePath) {
2908
+ return getActionOrder(left) - getActionOrder(right);
2909
+ }
2910
+ if (isDescendantPath(right.relativePath, left.relativePath)) {
2911
+ return getAncestorActionOrder(left) - getDescendantActionOrder(right);
2912
+ }
2913
+ if (isDescendantPath(left.relativePath, right.relativePath)) {
2914
+ return getDescendantActionOrder(left) - getAncestorActionOrder(right);
2915
+ }
2916
+ return left.relativePath.localeCompare(right.relativePath);
2917
+ }
2918
+ function isLegacySystemResourceRemoval(action) {
2919
+ return action.type === "remove-managed" && action.reason?.startsWith("Remove verified legacy system resource after ") === true;
2920
+ }
2921
+ function hasVerifiedLegacySystemResourceOwnership(manifest, relativePath, entry) {
2922
+ if (manifest.schemaVersion === 1 && isLegacySamePathSource(entry.sourceId, relativePath) && entry.ownershipClass === void 0) {
2923
+ return true;
2924
+ }
2925
+ if (entry.ownershipClass === "managed-projection") {
2926
+ return hasVerifiedResourceOwnership(manifest, relativePath, entry.sourceId);
2927
+ }
2928
+ if (entry.ownershipClass === "managed-block") {
2929
+ return entry.sourceId === `file:${relativePath}` || entry.sourceId.startsWith("router:");
2930
+ }
2931
+ if (entry.ownershipClass !== void 0 && entry.ownershipClass !== "managed-snapshot") {
2932
+ return false;
2933
+ }
2934
+ return entry.sourceId === `file:${relativePath}` && entry.systemAsset?.logicalAssetId === relativePath && entry.systemAsset.hashAlgorithm === "sha256" && entry.systemAsset.expectedHashes.includes(entry.hash);
2935
+ }
2936
+ function getActionOrder(action) {
2937
+ return action.type === "remove-managed" ? 0 : 1;
2938
+ }
2939
+ function getAncestorActionOrder(action) {
2940
+ return action.skillExposure && action.type !== "remove-managed" ? 2 : 1;
2941
+ }
2942
+ function getDescendantActionOrder(action) {
2943
+ return action.type === "remove-managed" ? 0 : 1;
2944
+ }
2945
+ function isDescendantPath(candidate, possibleAncestor) {
2946
+ const normalizedCandidate = normalizePlanPath(candidate);
2947
+ const normalizedAncestor = normalizePlanPath(possibleAncestor);
2948
+ return normalizedCandidate.startsWith(`${normalizedAncestor}/`);
2949
+ }
2950
+ function getManagedFileConflictResolution(relativePath, classification, managedFileConflictResolutions) {
2951
+ if (!classification) {
2952
+ return null;
2953
+ }
2954
+ return managedFileConflictResolutions?.[relativePath] ?? null;
2955
+ }
2956
+ function classifyReviewableManagedFileConflictPath(relativePath, options = {}) {
2957
+ if (options.isDesiredSkillAsset || isSkillAssetPath(relativePath)) {
2958
+ return {
2959
+ group: "skills",
2960
+ instructionKind: getInstructionKindForPath(relativePath) ?? void 0
2961
+ };
2962
+ }
2963
+ if (relativePath.startsWith(".make-docs/contracts/") || relativePath.startsWith(".make-docs/references/") || relativePath.startsWith("docs/assets/references/")) {
2964
+ return {
2965
+ group: "references",
2966
+ instructionKind: getInstructionKindForPath(relativePath) ?? void 0
2967
+ };
2968
+ }
2969
+ if (relativePath.startsWith(".make-docs/templates/") || relativePath.startsWith("docs/assets/templates/")) {
2970
+ return {
2971
+ group: "templates",
2972
+ instructionKind: getInstructionKindForPath(relativePath) ?? void 0
2973
+ };
2974
+ }
2975
+ if (relativePath.startsWith("docs/assets/prompts/")) {
2976
+ return {
2977
+ group: "prompts",
2978
+ instructionKind: getInstructionKindForPath(relativePath) ?? void 0
2979
+ };
2980
+ }
2981
+ const instructionKind = getInstructionKindForPath(relativePath);
2982
+ if (instructionKind) {
2983
+ return {
2984
+ group: "agent-instructions",
2985
+ instructionKind,
2986
+ scope: "managed-block"
2987
+ };
2988
+ }
2989
+ return {
2990
+ group: "managed-files"
2991
+ };
2992
+ }
2993
+ function getInstructionKindForPath(relativePath) {
2994
+ const basename = path5.posix.basename(relativePath);
2995
+ return INSTRUCTION_KINDS.includes(basename) ? basename : null;
2996
+ }
2997
+ function isSkillAssetPath(relativePath) {
2998
+ return relativePath.startsWith(".make-docs/agentics/skills/") || relativePath.startsWith(".claude/skills/") || relativePath.startsWith(".claude/skill-assets/") || relativePath.startsWith(".agents/skills/") || relativePath.startsWith(".agents/skill-assets/");
2999
+ }
3000
+ function getManagedFileConflictOverwriteReason(classification) {
3001
+ if (classification.scope === "managed-block") {
3002
+ return "Reassert the make-docs managed block inside the existing agent instruction file.";
3003
+ }
3004
+ switch (classification.group) {
3005
+ case "agent-instructions":
3006
+ return "Overwrite existing conflicting agent instruction file.";
3007
+ case "managed-files":
3008
+ return "Overwrite existing conflicting managed file.";
3009
+ case "prompts":
3010
+ return "Overwrite existing conflicting prompt file.";
3011
+ case "references":
3012
+ return "Overwrite existing conflicting reference file.";
3013
+ case "skills":
3014
+ return "Overwrite existing conflicting skill file.";
3015
+ case "templates":
3016
+ return "Overwrite existing conflicting template file.";
3017
+ }
3018
+ }
3019
+ function getManagedFileConflictSkipReason(classification, resolution, isManifestOwned) {
3020
+ if (!classification) {
3021
+ return isManifestOwned ? "Existing managed file differs from the recorded manifest." : "Unmanaged file already exists with different content.";
3022
+ }
3023
+ if (resolution === "skip") {
3024
+ if (classification.scope === "managed-block") {
3025
+ return "Existing conflicting make-docs managed block was explicitly kept.";
3026
+ }
3027
+ return `Existing conflicting ${getManagedFileConflictGroupLabel(
3028
+ classification.group
3029
+ )} was explicitly skipped.`;
3030
+ }
3031
+ if (classification.scope === "managed-block") {
3032
+ return "Existing conflicting make-docs managed block was skipped because no reassert resolution was provided.";
3033
+ }
3034
+ return `Existing conflicting ${getManagedFileConflictGroupLabel(
3035
+ classification.group
3036
+ )} was skipped because no overwrite resolution was provided.`;
3037
+ }
3038
+ function getManagedFileConflictGroupLabel(group) {
3039
+ switch (group) {
3040
+ case "agent-instructions":
3041
+ return "agent instruction file";
3042
+ case "managed-files":
3043
+ return "managed file";
3044
+ case "prompts":
3045
+ return "prompt file";
3046
+ case "references":
3047
+ return "reference file";
3048
+ case "skills":
3049
+ return "skill file";
3050
+ case "templates":
3051
+ return "template file";
3052
+ }
3053
+ }
3054
+ function getManifestHashForAsset(asset) {
3055
+ if (isSkillExposureAsset(asset)) {
3056
+ return getSkillExposureHash(asset);
3057
+ }
3058
+ const manifestHash = getManifestFileHash(asset.relativePath, asset.content);
3059
+ if (manifestHash === null) {
3060
+ throw new Error(`Instruction asset ${asset.relativePath} is missing a valid managed block.`);
3061
+ }
3062
+ return manifestHash;
3063
+ }
3064
+ function getSkillExposureHash(asset) {
3065
+ return hashText(
3066
+ JSON.stringify({
3067
+ canonicalPayloadPath: normalizePlanPath(asset.skillExposure.canonicalPayloadPath),
3068
+ copyMirrorHashes: asset.copyMirrorAssets.map((copyAsset) => [
3069
+ normalizePlanPath(path5.relative(asset.relativePath, copyAsset.relativePath)),
3070
+ hashText(copyAsset.content)
3071
+ ]),
3072
+ exposurePath: normalizePlanPath(asset.skillExposure.exposurePath),
3073
+ harness: asset.skillExposure.harness,
3074
+ installName: asset.skillExposure.installName,
3075
+ preferredMode: asset.skillExposure.preferredMode,
3076
+ skillName: asset.skillExposure.skillName,
3077
+ symlinkTarget: normalizePlanPath(asset.skillExposure.symlinkTarget)
3078
+ })
3079
+ );
3080
+ }
3081
+ function isSkillExposureAsset(asset) {
3082
+ return asset.kind === "skill-exposure";
3083
+ }
3084
+ function normalizePlanPath(relativePath) {
3085
+ return relativePath.replace(/\\/g, "/");
3086
+ }
3087
+ function getCurrentManifestHash(relativePath, content, sourceSchemaVersion) {
3088
+ return getManifestFileHashForSourceSchema(
3089
+ relativePath,
3090
+ content,
3091
+ sourceSchemaVersion
3092
+ );
3093
+ }
3094
+ function getPlannedUpdateContent(asset, currentContent) {
3095
+ if (!isInstructionPath(asset.relativePath)) {
3096
+ return asset.content;
3097
+ }
3098
+ const parsed = parseManagedBlock(asset.content);
3099
+ if (parsed.state !== "valid" || parsed.body === null) {
3100
+ return asset.content;
3101
+ }
3102
+ return upsertManagedBlock(currentContent, parsed.body).content;
3103
+ }
3104
+ function isInstructionPath(relativePath) {
3105
+ return getInstructionKindForPath(relativePath) !== null;
3106
+ }
3107
+ function instructionHasNoOutsideContent(content) {
3108
+ const parsed = parseManagedBlock(content);
3109
+ return parsed.state === "valid" && parsed.prefix.trim().length === 0 && parsed.suffix.trim().length === 0;
3110
+ }
3111
+ function getInstructionMigrationContent(asset, currentContent, manifestEntry, currentHash) {
3112
+ if (!isInstructionPath(asset.relativePath)) {
3113
+ return null;
3114
+ }
3115
+ const currentBlock = parseManagedBlock(currentContent);
3116
+ if (currentBlock.state !== "absent") {
3117
+ if (currentBlock.state === "valid" && currentHash !== null && manifestEntry?.hash === currentHash) {
3118
+ return {
3119
+ content: getPlannedUpdateContent(asset, currentContent),
3120
+ reason: "Refresh the manifest-owned instruction block to the current routing."
3121
+ };
3122
+ }
3123
+ return null;
3124
+ }
3125
+ if (manifestEntry) {
3126
+ if (manifestEntry.hash !== hashText(currentContent)) {
3127
+ return null;
3128
+ }
3129
+ return {
3130
+ content: asset.content,
3131
+ reason: "Migrate legacy instruction file to the managed-block model."
3132
+ };
3133
+ }
3134
+ return {
3135
+ content: getPlannedUpdateContent(asset, currentContent),
3136
+ reason: "Insert the make-docs managed block into the existing instruction file."
3137
+ };
3138
+ }
3139
+ function getSchemaOneInstructionOwnershipStop(manifest, relativePath, currentContent) {
3140
+ if (manifest?.schemaVersion !== 1 || !isInstructionPath(relativePath)) {
3141
+ return null;
3142
+ }
3143
+ const parsed = parseManagedBlock(currentContent);
3144
+ if (parsed.state !== "absent") {
3145
+ return "Schema-1 instruction ownership is contradictory because V2 managed-block markers are present.";
3146
+ }
3147
+ const entry = manifest.files[relativePath];
3148
+ if (!entry) {
3149
+ return null;
3150
+ }
3151
+ if (entry.hash !== hashText(currentContent)) {
3152
+ return "Schema-1 whole-file instruction ownership does not match the recorded path and hash.";
3153
+ }
3154
+ return null;
3155
+ }
3156
+ function hasVerifiedResourceOwnership(manifest, relativePath, sourceId) {
3157
+ if (!manifest?.resourceProjection || !sourceId.startsWith("resource:")) {
3158
+ return false;
3159
+ }
3160
+ const uri = sourceId.slice("resource:".length);
3161
+ const entry = manifest.resourceProjection.resources[uri];
3162
+ const manifestFile = manifest.files[relativePath];
3163
+ return Boolean(
3164
+ entry && entry.uri === uri && entry.managedDestination === relativePath && entry.ownershipClass === "managed-snapshot" && entry.lifecycleDisposition === "active" && manifestFile?.ownershipClass === "managed-projection" && manifestFile.sourceId === sourceId && manifestFile.hash === entry.installedDigest
3165
+ );
3166
+ }
3167
+ function getVerifiedProjectOwnedResourceOverride(manifest, relativePath, sourceId, currentHash) {
3168
+ if (!manifest?.resourceProjection || !sourceId.startsWith("resource:") || !currentHash) {
3169
+ return null;
3170
+ }
3171
+ const uri = sourceId.slice("resource:".length);
3172
+ const resource = manifest.resourceProjection.resources[uri];
3173
+ const file2 = manifest.files[relativePath];
3174
+ if (!resource || resource.uri !== uri || resource.managedDestination !== relativePath || resource.ownershipClass !== "project-owned" || resource.lifecycleDisposition !== "active" || resource.installedDigest !== currentHash || file2?.ownershipClass !== "project-owned" || file2.sourceId !== sourceId || file2.hash !== currentHash) {
3175
+ return null;
3176
+ }
3177
+ return {
3178
+ uri,
3179
+ file: { ...file2 },
3180
+ resource: { ...resource }
3181
+ };
3182
+ }
3183
+ function hasVerifiedCleanLegacyManagedOwnership(manifest, relativePath, currentHash) {
3184
+ if (!manifest || manifest.schemaVersion >= 4 || !currentHash) return false;
3185
+ const entry = manifest.files[relativePath];
3186
+ if (!entry || entry.hash !== currentHash || !isLegacySamePathSource(entry.sourceId, relativePath) || entry.ownershipClass !== void 0 && entry.ownershipClass !== "managed-snapshot") {
3187
+ return false;
3188
+ }
3189
+ if (!entry.systemAsset) return manifest.schemaVersion === 1;
3190
+ return entry.systemAsset.logicalAssetId === relativePath && entry.systemAsset.localPath === relativePath && entry.systemAsset.sourcePackage === manifest.packageName && entry.systemAsset.hashAlgorithm === "sha256" && entry.systemAsset.expectedHashes.includes(entry.hash);
3191
+ }
3192
+ function isLegacySamePathSource(sourceId, relativePath) {
3193
+ return sourceId === `file:${relativePath}` || sourceId === `build:${relativePath}`;
3194
+ }
3195
+ function schemaOneSurfaceHasPreservedContent(options) {
3196
+ const surfaceRoot = path5.join(options.targetDir, options.directory);
3197
+ if (!existsSync4(surfaceRoot)) return false;
3198
+ const surfaceStat = lstatSync3(surfaceRoot);
3199
+ if (!surfaceStat.isDirectory() || surfaceStat.isSymbolicLink()) return false;
3200
+ const visit = (directory) => readdirSync3(directory, { withFileTypes: true }).some((entry) => {
3201
+ const absolutePath = path5.join(directory, entry.name);
3202
+ if (entry.isDirectory()) return visit(absolutePath);
3203
+ const relativePath = normalizePlanPath(
3204
+ path5.relative(options.targetDir, absolutePath)
3205
+ );
3206
+ const manifestEntry = options.manifest.files[relativePath];
3207
+ if (!manifestEntry || manifestEntry.ownershipClass === "project-owned") {
3208
+ return true;
3209
+ }
3210
+ if (!entry.isFile()) return true;
3211
+ return hashText(readTextFile(absolutePath)) !== manifestEntry.hash;
3212
+ });
3213
+ return visit(surfaceRoot);
3214
+ }
3215
+ function getCarriedOnDemandRouterAssets(options) {
3216
+ const manifest = options.existingManifest;
3217
+ if (!manifest || !manifest.routerOwnership && !options.completedRemovalHandoff && manifest.schemaVersion !== 1) {
3218
+ return [];
3219
+ }
3220
+ const surfaceDirectories = {
3221
+ archive: ".make-docs/archive",
3222
+ assets: "docs/assets"
3223
+ };
3224
+ const assets = [];
3225
+ for (const [surface, directory] of Object.entries(surfaceDirectories)) {
3226
+ const surfaceExists = existsSync4(path5.join(options.targetDir, directory));
3227
+ const schemaOneSurfaceNeedsRouters = manifest.schemaVersion === 1 && schemaOneSurfaceHasPreservedContent({
3228
+ targetDir: options.targetDir,
3229
+ directory,
3230
+ manifest
3231
+ });
3232
+ for (const asset of createProjectSurfaceRouterAssets(
3233
+ options.profile,
3234
+ surface
3235
+ )) {
3236
+ const proof = manifest.routerOwnership?.routers[asset.relativePath];
3237
+ const file2 = manifest.files[asset.relativePath];
3238
+ const completedRemovalFileProof = options.completedRemovalHandoff === true && file2?.sourceId === asset.sourceId && (file2.ownershipClass === void 0 || file2.ownershipClass === "managed-block");
3239
+ if (completedRemovalFileProof || schemaOneSurfaceNeedsRouters || surfaceExists && (!proof || proof.routerClass === "bootstrap" || proof.routerClass === "on-demand-surface") && (!proof || proof.provenanceState === "verified" && proof.ownershipClass === "managed-snapshot" && proof.lifecycleDisposition === "active" && proof.sourceId === asset.sourceId && file2?.sourceId === asset.sourceId && file2.ownershipClass === "managed-block")) {
3240
+ assets.push(asset);
3241
+ }
3242
+ }
3243
+ }
3244
+ return assets.sort((left, right) => left.relativePath.localeCompare(right.relativePath));
3245
+ }
3246
+ function assertTextDocumentAsset(asset) {
3247
+ if (typeof asset.content !== "string") throw new Error(`Document asset ${asset.relativePath} must contain text.`);
3248
+ }
3249
+ function assertStandardSkillLayout(manifest, targetDir, selections) {
3250
+ if (selections && (!selections.skills || selections.selectedSkills.length === 0)) return;
3251
+ if (targetDir && selections) {
3252
+ const oldRoot = path5.join(selections.skillScope === "global" ? homedir() : targetDir, ".make-docs/agentics");
3253
+ if (lstatSync3(oldRoot, { throwIfNoEntry: false })) throw new Error(`Existing legacy directory needs inspection and reviewed cutover before Skill changes: ${oldRoot}. Preserve its content. Review named owned Skills with setup skills --adopt-existing <selected names> --dry-run, then --review <digest>. Unowned or unknown legacy content needs an explicit resolution before normal setup.`);
3254
+ }
3255
+ if ((manifest?.skillFiles ?? []).some((p) => /(?:^|\/)\.make-docs\/agentics\/skills(?:\/|$)/.test(p.replace(/\\/g, "/"))) || Object.entries(manifest?.files ?? {}).some(([p, entry]) => /(?:^|\/)\.make-docs\/agentics\/skills(?:\/|$)/.test(p.replace(/\\/g, "/")) || /(?:^|\/)\.make-docs\/agentics\/skills(?:\/|$)/.test(entry.skillExposure?.canonicalPayloadPath ?? ""))) {
3256
+ throw new Error("Legacy Skill layout needs reviewed cutover. Run setup skills --adopt-existing <selected names> --dry-run with the same target, scope, and tools; review the result, then repeat with --review <digest>. Existing content is preserved.");
3257
+ }
3258
+ }
3259
+ function assertStandardSkillDestinations(manifest, assets) {
3260
+ if (!manifest) return;
3261
+ const entries = Object.entries(manifest.files);
3262
+ if (assets.some((asset) => isSkillExposureAsset(asset) ? entries.some(([p, entry]) => p.startsWith(asset.relativePath + "/") && (entry.sourceId.startsWith("skill:shared:") || entry.sourceId.startsWith("skill-shared-asset:"))) : entries.some(([p, entry]) => entry.skillExposure && asset.relativePath.startsWith(p + "/")))) {
3263
+ throw new Error("The selected Skill tools change a native link or canonical directory. Run setup skills --adopt-existing <selected names> --dry-run with the new target, scope, and tools; review the result, then repeat with --review <digest>. Existing content is preserved.");
3264
+ }
3265
+ }
3266
+
3267
+ // src/install.ts
3268
+ import { homedir as homedir2 } from "os";
3269
+ async function planInstall(options) {
3270
+ const packageMeta = options.packageMeta ?? readPackageMeta();
3271
+ const profile = resolveInstallProfile(options.selections);
3272
+ return createInstallPlan({
3273
+ targetDir: options.targetDir,
3274
+ packageMeta,
3275
+ profile,
3276
+ existingManifest: options.existingManifest,
3277
+ completedRemovalHandoff: options.completedRemovalHandoff,
3278
+ managedFileConflictResolutions: options.managedFileConflictResolutions,
3279
+ systemAssetMaterializationMode: options.systemAssetMaterializationMode,
3280
+ skillRegistry: options.skillRegistry,
3281
+ preserveExistingSkills: options.preserveExistingSkills,
3282
+ operation: options.operation
3283
+ });
3284
+ }
3285
+ async function planSkillsOnlyInstall(options) {
3286
+ const packageMeta = options.packageMeta ?? readPackageMeta();
3287
+ const profile = resolveInstallProfile(options.selections);
3288
+ return createSkillsOnlyInstallPlan({
3289
+ targetDir: options.targetDir,
3290
+ packageMeta,
3291
+ profile,
3292
+ existingManifest: options.existingManifest,
3293
+ remove: options.remove,
3294
+ reviewedSkillAdoption: options.reviewedSkillAdoption,
3295
+ skillRegistry: options.skillRegistry
3296
+ });
3297
+ }
3298
+ function findReviewableManagedFileConflicts(plan) {
3299
+ return plan.actions.flatMap((action) => {
3300
+ if (action.type !== "skip-conflict" || action.content === void 0 || !action.reason) {
3301
+ return [];
3302
+ }
3303
+ const classification = classifyReviewableManagedFileConflictPath(action.relativePath);
3304
+ if (!classification || !action.sourceId) {
3305
+ return [];
3306
+ }
3307
+ return [
3308
+ {
3309
+ relativePath: action.relativePath,
3310
+ group: classification.group,
3311
+ sourceId: action.sourceId,
3312
+ reason: action.reason,
3313
+ ...classification.instructionKind ? { instructionKind: classification.instructionKind } : {},
3314
+ ...classification.scope ? { scope: classification.scope } : {}
3315
+ }
3316
+ ];
3317
+ }).sort(compareReviewableManagedFileConflicts);
3318
+ }
3319
+ function applyInstallPlan(options) {
3320
+ if ((options.plan.stops?.length ?? 0) > 0) {
3321
+ throw new Error(
3322
+ `Cannot apply install plan because ownership or managed-block evidence is not trusted: ${options.plan.stops.join(", ")}.`
3323
+ );
3324
+ }
3325
+ const unresolvedConflicts = findReviewableManagedFileConflicts(options.plan);
3326
+ if (unresolvedConflicts.length > 0) {
3327
+ const paths = unresolvedConflicts.map((conflict) => conflict.relativePath).join(", ");
3328
+ throw new Error(`Cannot apply install plan with unresolved managed-file conflicts: ${paths}.`);
3329
+ }
3330
+ return applyInstallPlanInternal({
3331
+ ...options,
3332
+ trackSkillFilesInManifestFiles: true
3333
+ });
3334
+ }
3335
+ function applySkillsOnlyInstallPlan(options) {
3336
+ return applyInstallPlanInternal({
3337
+ ...options,
3338
+ trackSkillFilesInManifestFiles: false
3339
+ });
3340
+ }
3341
+ function applyInstallPlanInternal(options) {
3342
+ const { targetDir, existingManifest } = options;
3343
+ const plan = options.plan;
3344
+ if (plan.desiredSkillFiles.length > 0) assertStandardSkillLayout(existingManifest, targetDir, plan.profile.selections);
3345
+ if (plan.actions.some((action) => action.type === "remove-managed" && action.relativePath === RETIRED_PLAYBOOK_CONTRACT_PATH)) {
3346
+ throw new Error("Retired Playbook contract removal requires reviewed migration checkpoint 11.");
3347
+ }
3348
+ const p4ProjectionSelected = plan.profile.selections.resourceProjection !== void 0;
3349
+ if (p4ProjectionSelected) {
3350
+ assertManagedPathHasNoSymlinks(targetDir, MANIFEST_RELATIVE_PATH);
3351
+ for (const action of plan.actions) {
3352
+ if (isP4ProjectionAction(action)) {
3353
+ assertManagedPathHasNoSymlinks(targetDir, action.relativePath);
3354
+ }
3355
+ }
3356
+ }
3357
+ if (plan.classificationSnapshot) {
3358
+ assertLifecyclePlanSnapshotCurrent(targetDir, plan.classificationSnapshot);
3359
+ }
3360
+ if (options.projectHarnessConfig) {
3361
+ const reviewedConfig = existsSync5(options.projectHarnessConfig.configPath) ? readFileSync5(options.projectHarnessConfig.configPath, "utf8") : null;
3362
+ if (reviewedConfig !== options.projectHarnessConfig.beforeContent) {
3363
+ throw new Error("Project config changed after review. Create and review a fresh setup plan.");
3364
+ }
3365
+ }
3366
+ if (!plan.forceManifestWrite && !options.projectHarnessConfig?.changed && existingManifest && existingManifest.projectId && plan.actions.every((action) => action.type === "noop") && existingManifest.schemaVersion === 4 && JSON.stringify(existingManifest.selections) === JSON.stringify(plan.profile.selections) && JSON.stringify(existingManifest.routerOwnership ?? null) === JSON.stringify(plan.routerOwnership ?? null) && JSON.stringify(existingManifest.resourceProjection ?? null) === JSON.stringify(plan.resourceProjection ?? null)) {
3367
+ const state = readInstallationStatus(targetDir);
3368
+ if (state.status !== "ready") throw new Error(`Installation cannot report an unchanged result: ${state.status}. ${state.nextAction}`);
3369
+ if (!isDeepStrictEqual2(loadManifest(targetDir), existingManifest)) throw new Error("Installation state changed after plan review. Create and review a fresh plan before writing.");
3370
+ return {
3371
+ manifest: existingManifest,
3372
+ appliedActions: plan.actions,
3373
+ conflictFiles: [],
3374
+ mutationApplied: false
3375
+ };
3376
+ }
3377
+ return withInstallationOperation(targetDir, options.trackSkillFilesInManifestFiles ? plan.operation ?? "setup" : "setup.skills", () => {
3378
+ const projectId = getInstallationProjectId(targetDir);
3379
+ if (options.projectHarnessConfig) {
3380
+ const currentConfig = existsSync5(options.projectHarnessConfig.configPath) ? readFileSync5(options.projectHarnessConfig.configPath, "utf8") : null;
3381
+ const expectedConfig = addDeclarativeProjectId(options.projectHarnessConfig.beforeContent ?? "", projectId);
3382
+ if (currentConfig !== expectedConfig) {
3383
+ throw new Error("Project config changed after review. Create and review a fresh setup plan.");
3384
+ }
3385
+ }
3386
+ const currentManifest = loadManifest(targetDir);
3387
+ if (!isDeepStrictEqual2(currentManifest, existingManifest)) {
3388
+ throw new Error("Installation state changed after plan review. Create and review a fresh plan before writing.");
3389
+ }
3390
+ if (plan.classificationSnapshot) assertLifecyclePlanSnapshotCurrent(targetDir, plan.classificationSnapshot);
3391
+ const nextFiles = {
3392
+ ...existingManifest?.files ?? {}
3393
+ };
3394
+ const nextSkillFiles = new Set(existingManifest?.skillFiles ?? []);
3395
+ const desiredSkillFiles = new Set(plan.desiredSkillFiles);
3396
+ const conflictFiles = [];
3397
+ for (const action of plan.actions) {
3398
+ const desired = plan.desiredFiles[action.relativePath];
3399
+ if (["remove-managed", "strip-managed-block", "update-conflict"].includes(action.type)) delete nextFiles[action.relativePath];
3400
+ else if (["create", "update", "generate", "noop"].includes(action.type) && desired) {
3401
+ nextFiles[action.relativePath] = action.skillExposure ? { ...desired, skillExposure: action.skillExposure } : desired;
3402
+ }
3403
+ if (desiredSkillFiles.has(action.relativePath) && ["create", "update", "generate", "noop"].includes(action.type)) nextSkillFiles.add(action.relativePath);
3404
+ if (action.type === "remove-managed") nextSkillFiles.delete(action.relativePath);
3405
+ }
3406
+ const routerOwnership = plan.routerOwnership ?? existingManifest?.routerOwnership;
3407
+ const resourceProjection = plan.resourceProjection ?? existingManifest?.resourceProjection;
3408
+ if (!routerOwnership || !resourceProjection) {
3409
+ throw new Error(
3410
+ "Schema 4 install apply requires router ownership and resource projection proof."
3411
+ );
3412
+ }
3413
+ const manifest = createManifest(
3414
+ {
3415
+ name: plan.packageName,
3416
+ version: plan.packageVersion
3417
+ },
3418
+ plan.profile,
3419
+ nextFiles,
3420
+ Array.from(nextSkillFiles).sort(),
3421
+ options.trackSkillFilesInManifestFiles ? plan.systemAssetMaterialization : existingManifest?.systemAssetMaterialization ?? plan.systemAssetMaterialization,
3422
+ projectId,
3423
+ routerOwnership,
3424
+ resourceProjection
3425
+ );
3426
+ writeManifest(targetDir, manifest);
3427
+ const hasExposureMutation = plan.actions.some((action) => action.skillExposure && ["create", "update", "generate", "remove-managed"].includes(action.type));
3428
+ const projectConfigChanges = prepareProjectHarnessConfigChange(
3429
+ targetDir,
3430
+ options.projectHarnessConfig,
3431
+ projectId
3432
+ );
3433
+ if (!hasExposureMutation) {
3434
+ const changes = [
3435
+ ...plan.actions.flatMap((action) => prepareInstallAction(targetDir, plan, action, conflictFiles)),
3436
+ ...projectConfigChanges
3437
+ ];
3438
+ sealInstallationOperation(targetDir);
3439
+ for (const change of changes) change();
3440
+ } else {
3441
+ for (const action of plan.actions) {
3442
+ applyAction({
3443
+ targetDir,
3444
+ plan,
3445
+ action,
3446
+ nextFiles,
3447
+ conflictFiles,
3448
+ stageExposure(entry) {
3449
+ nextFiles[action.relativePath] = entry;
3450
+ manifest.files = nextFiles;
3451
+ writeManifest(targetDir, manifest);
3452
+ }
3453
+ });
3454
+ }
3455
+ for (const change of projectConfigChanges) change();
3456
+ }
3457
+ for (const action of plan.actions) {
3458
+ if (action.type === "remove-managed") pruneRemovedManagedPathParents(targetDir, action.relativePath, relativePathToTarget(targetDir, action.relativePath));
3459
+ }
3460
+ manifest.files = nextFiles;
3461
+ const receipt = createLifecycleMutationReceipt({
3462
+ operation: plan.operation ?? "setup",
3463
+ projectId,
3464
+ manifestSchemaVersion: manifest.schemaVersion,
3465
+ profileId: manifest.profileId,
3466
+ selectedResourceTypes: manifest.selections.resourceProjection ?? [],
3467
+ actions: plan.actions,
3468
+ committedAt: manifest.updatedAt
3469
+ });
3470
+ if (p4ProjectionSelected) {
3471
+ assertManagedPathHasNoSymlinks(targetDir, MANIFEST_RELATIVE_PATH);
3472
+ }
3473
+ writeManifest(targetDir, manifest);
3474
+ return {
3475
+ manifest,
3476
+ appliedActions: plan.actions,
3477
+ conflictFiles,
3478
+ receipt,
3479
+ mutationApplied: true
3480
+ };
3481
+ }, { projectId: existingManifest?.projectId });
3482
+ }
3483
+ function prepareProjectHarnessConfigChange(targetDir, projectHarnessConfig, projectId) {
3484
+ if (!projectHarnessConfig?.changed) return [];
3485
+ const content = addDeclarativeProjectId(projectHarnessConfig.content, projectId);
3486
+ return [preparePlannedFileChange(
3487
+ targetDir,
3488
+ ".make-docs/config.yaml",
3489
+ { kind: "file", content },
3490
+ () => writeContentFile(projectHarnessConfig.configPath, content)
3491
+ )];
3492
+ }
3493
+ function addDeclarativeProjectId(content, projectId) {
3494
+ const document = parseDocument(content, { uniqueKeys: true });
3495
+ if (document.errors.length > 0) {
3496
+ throw new Error("The reviewed project config content is invalid.");
3497
+ }
3498
+ const current = document.get("projectId");
3499
+ if (current !== void 0) {
3500
+ if (current !== projectId) throw new Error("The reviewed project config has a conflicting project identity.");
3501
+ return content;
3502
+ }
3503
+ document.set("projectId", projectId);
3504
+ return document.toString();
3505
+ }
3506
+ function prepareInstallAction(targetDir, plan, action, conflictFiles) {
3507
+ const absolute = relativePathToTarget(targetDir, action.relativePath);
3508
+ if (["create", "update", "generate", "update-conflict", "strip-managed-block"].includes(action.type)) {
3509
+ if (action.content === void 0) throw new Error(`Missing content for ${action.relativePath}.`);
3510
+ return [preparePlannedFileChange(targetDir, action.relativePath, { kind: "file", content: action.content }, () => writeContentFile(absolute, action.content))];
3511
+ }
3512
+ if (action.type === "remove-managed") return prepareInstallationRemoval(targetDir, action.relativePath);
3513
+ if (action.type === "skip-conflict" && action.content !== void 0 && plan.conflictsRunId) {
3514
+ const relative = path6.join(CONFLICTS_RELATIVE_DIR, plan.conflictsRunId, toConflictRelativePath(action.relativePath));
3515
+ const conflictPath = path6.join(targetDir, relative);
3516
+ return [preparePlannedFileChange(targetDir, relative, { kind: "file", content: action.content }, () => {
3517
+ writeContentFile(conflictPath, action.content);
3518
+ conflictFiles.push(conflictPath);
3519
+ })];
3520
+ }
3521
+ return [];
3522
+ }
3523
+ function applyAction(options) {
3524
+ const { targetDir, plan, action, nextFiles, conflictFiles } = options;
3525
+ const absolutePath = relativePathToTarget(targetDir, action.relativePath);
3526
+ const desiredEntry = plan.desiredFiles[action.relativePath];
3527
+ if (plan.profile.selections.resourceProjection !== void 0 && isP4ProjectionAction(action) || action.type === "remove-managed" && isRetiredTemplateOwnedChildRouterPath(action.relativePath) || action.type === "strip-managed-block") {
3528
+ assertManagedPathHasNoSymlinks(targetDir, action.relativePath);
3529
+ }
3530
+ switch (action.type) {
3531
+ case "create":
3532
+ case "update":
3533
+ case "generate": {
3534
+ if (action.skillExposure) {
3535
+ if (!desiredEntry) {
3536
+ throw new Error(`Missing desired manifest entry for ${action.relativePath}.`);
3537
+ }
3538
+ nextFiles[action.relativePath] = applySkillExposureAction({
3539
+ targetDir,
3540
+ action,
3541
+ desiredEntry,
3542
+ stageExposure: options.stageExposure
3543
+ });
3544
+ return;
3545
+ }
3546
+ if (action.content === void 0 || !desiredEntry) {
3547
+ throw new Error(`Missing content for ${action.type} action on ${action.relativePath}.`);
3548
+ }
3549
+ recordPlannedFileChange(targetDir, action.relativePath, { kind: "file", content: action.content }, () => writeContentFile(absolutePath, action.content));
3550
+ nextFiles[action.relativePath] = desiredEntry;
3551
+ return;
3552
+ }
3553
+ case "update-conflict": {
3554
+ if (action.content === void 0) {
3555
+ throw new Error(`Missing content for ${action.type} action on ${action.relativePath}.`);
3556
+ }
3557
+ recordPlannedFileChange(targetDir, action.relativePath, { kind: "file", content: action.content }, () => writeContentFile(absolutePath, action.content));
3558
+ delete nextFiles[action.relativePath];
3559
+ return;
3560
+ }
3561
+ case "noop": {
3562
+ if (desiredEntry) {
3563
+ nextFiles[action.relativePath] = action.skillExposure ? {
3564
+ ...desiredEntry,
3565
+ skillExposure: action.skillExposure
3566
+ } : desiredEntry;
3567
+ }
3568
+ return;
3569
+ }
3570
+ case "skip": {
3571
+ return;
3572
+ }
3573
+ case "strip-managed-block": {
3574
+ if (action.content === void 0) {
3575
+ throw new Error(`Missing preserved content for ${action.type} action on ${action.relativePath}.`);
3576
+ }
3577
+ recordPlannedFileChange(targetDir, action.relativePath, { kind: "file", content: action.content }, () => writeContentFile(absolutePath, action.content));
3578
+ delete nextFiles[action.relativePath];
3579
+ return;
3580
+ }
3581
+ case "remove-managed": {
3582
+ if (existsSync5(absolutePath)) {
3583
+ removeInstallationPath(targetDir, action.relativePath);
3584
+ }
3585
+ delete nextFiles[action.relativePath];
3586
+ return;
3587
+ }
3588
+ case "skip-conflict": {
3589
+ if (action.content !== void 0 && plan.conflictsRunId) {
3590
+ const conflictPath = path6.join(
3591
+ targetDir,
3592
+ CONFLICTS_RELATIVE_DIR,
3593
+ plan.conflictsRunId,
3594
+ toConflictRelativePath(action.relativePath)
3595
+ );
3596
+ recordPlannedFileChange(targetDir, path6.relative(targetDir, conflictPath), { kind: "file", content: action.content }, () => writeContentFile(conflictPath, action.content));
3597
+ conflictFiles.push(conflictPath);
3598
+ }
3599
+ return;
3600
+ }
3601
+ default: {
3602
+ const exhaustiveCheck = action.type;
3603
+ throw new Error(`Unhandled action type: ${exhaustiveCheck}`);
3604
+ }
3605
+ }
3606
+ }
3607
+ function isP4ProjectionAction(action) {
3608
+ return action.sourceId?.startsWith("router:") === true || action.sourceId?.startsWith("resource:") === true;
3609
+ }
3610
+ function applySkillExposureAction(options) {
3611
+ const { targetDir, action, desiredEntry } = options;
3612
+ if (!action.skillExposure || !action.copyMirrorAssets) {
3613
+ throw new Error(`Missing skill exposure metadata for ${action.relativePath}.`);
3614
+ }
3615
+ const absolutePath = relativePathToTarget(targetDir, action.relativePath);
3616
+ if (existsSync5(absolutePath)) {
3617
+ removeInstallationPath(targetDir, action.relativePath);
3618
+ }
3619
+ ensureParentDir(absolutePath);
3620
+ if (process.env.MAKE_DOCS_DISABLE_SKILL_SYMLINKS !== "1") {
3621
+ let symlinkFailure;
3622
+ try {
3623
+ recordPlannedFileChange(targetDir, action.relativePath, { kind: "symlink", target: action.skillExposure.symlinkTarget }, () => {
3624
+ try {
3625
+ symlinkSync(action.skillExposure.symlinkTarget, absolutePath, "dir");
3626
+ } catch (error) {
3627
+ symlinkFailure = error;
3628
+ throw error;
3629
+ }
3630
+ });
3631
+ return {
3632
+ ...desiredEntry,
3633
+ skillExposure: {
3634
+ ...action.skillExposure,
3635
+ mode: "symlink"
3636
+ }
3637
+ };
3638
+ } catch (error) {
3639
+ if (error !== symlinkFailure || !["EPERM", "EACCES", "ENOSYS", "ENOTSUP", "EOPNOTSUPP"].includes(error.code ?? "")) throw error;
3640
+ const fallback = { ...desiredEntry, skillExposure: { ...action.skillExposure, mode: "copy-mirror", fallbackReason: toErrorMessage(error) } };
3641
+ options.stageExposure(fallback);
3642
+ writeCopyMirror(action.copyMirrorAssets, targetDir);
3643
+ return {
3644
+ ...desiredEntry,
3645
+ skillExposure: {
3646
+ ...action.skillExposure,
3647
+ mode: "copy-mirror",
3648
+ fallbackReason: toErrorMessage(error)
3649
+ }
3650
+ };
3651
+ }
3652
+ }
3653
+ options.stageExposure({ ...desiredEntry, skillExposure: { ...action.skillExposure, mode: "copy-mirror", fallbackReason: "Symlink creation disabled by MAKE_DOCS_DISABLE_SKILL_SYMLINKS=1." } });
3654
+ writeCopyMirror(action.copyMirrorAssets, targetDir);
3655
+ return {
3656
+ ...desiredEntry,
3657
+ skillExposure: {
3658
+ ...action.skillExposure,
3659
+ mode: "copy-mirror",
3660
+ fallbackReason: "Symlink creation disabled by MAKE_DOCS_DISABLE_SKILL_SYMLINKS=1."
3661
+ }
3662
+ };
3663
+ }
3664
+ function writeCopyMirror(assets, targetDir) {
3665
+ if (!assets) {
3666
+ return;
3667
+ }
3668
+ for (const asset of assets) {
3669
+ const parents = [];
3670
+ let parent = path6.dirname(asset.relativePath);
3671
+ while (!existsSync5(relativePathToTarget(targetDir, parent)) && parent !== "." && parent !== path6.dirname(parent)) {
3672
+ parents.unshift(parent);
3673
+ parent = path6.dirname(parent);
3674
+ }
3675
+ for (const directory of parents) recordPlannedFileChange(targetDir, directory, { kind: "directory" }, () => mkdirSync(relativePathToTarget(targetDir, directory)));
3676
+ recordPlannedFileChange(targetDir, asset.relativePath, { kind: "file", content: asset.content }, () => writeContentFile(relativePathToTarget(targetDir, asset.relativePath), asset.content));
3677
+ }
3678
+ }
3679
+ function pruneRemovedManagedPathParents(targetDir, relativePath, absolutePath) {
3680
+ const boundary = getRemoveManagedPruneBoundary(targetDir, relativePath, absolutePath);
3681
+ if (!boundary) {
3682
+ return;
3683
+ }
3684
+ pruneInstallationParents(targetDir, path6.dirname(absolutePath), boundary);
3685
+ }
3686
+ function getRemoveManagedPruneBoundary(targetDir, relativePath, absolutePath) {
3687
+ if (relativePath === ".make-docs/scripts/check_path_hygiene.py") return path6.join(targetDir, ".make-docs");
3688
+ if (!path6.isAbsolute(relativePath)) {
3689
+ return targetDir;
3690
+ }
3691
+ return getGlobalSelectedAgenticsPruneBoundary(absolutePath);
3692
+ }
3693
+ function getGlobalSelectedAgenticsPruneBoundary(absolutePath) {
3694
+ const currentRoots = [path6.join(homedir2(), ".agents/skills"), getHarnessSkillDirectory("codex", "global"), getHarnessSkillDirectory("claude-code", "global")];
3695
+ const root = currentRoots.find((root2) => absolutePath.startsWith(root2 + path6.sep));
3696
+ if (root) return path6.dirname(root);
3697
+ const segments = path6.resolve(absolutePath).split(path6.sep);
3698
+ const agenticsIndex = segments.lastIndexOf("agentics");
3699
+ if (agenticsIndex < 1 || segments[agenticsIndex - 1] !== ".make-docs") {
3700
+ return null;
3701
+ }
3702
+ return segments.slice(0, agenticsIndex).join(path6.sep) || path6.sep;
3703
+ }
3704
+ function compareReviewableManagedFileConflicts(left, right) {
3705
+ const leftGroup = MANAGED_FILE_CONFLICT_GROUP_ORDER[left.group];
3706
+ const rightGroup = MANAGED_FILE_CONFLICT_GROUP_ORDER[right.group];
3707
+ return leftGroup - rightGroup || left.relativePath.localeCompare(right.relativePath);
3708
+ }
3709
+ var MANAGED_FILE_CONFLICT_GROUP_ORDER = {
3710
+ "agent-instructions": 0,
3711
+ references: 1,
3712
+ templates: 2,
3713
+ prompts: 3,
3714
+ skills: 4,
3715
+ "managed-files": 5
3716
+ };
3717
+ function toConflictRelativePath(relativePath) {
3718
+ const segments = relativePath.split(/[/\\]+/).filter(Boolean);
3719
+ const safeSegments = segments.filter((segment) => segment !== "." && segment !== "..");
3720
+ if (path6.isAbsolute(relativePath)) {
3721
+ const [first, ...rest] = safeSegments;
3722
+ const drive = first?.replace(/:$/, "");
3723
+ return path6.join("__absolute__", ...drive ? [drive, ...rest] : rest);
3724
+ }
3725
+ return path6.join(...safeSegments);
3726
+ }
3727
+ function toErrorMessage(error) {
3728
+ return error instanceof Error ? error.message : String(error);
3729
+ }
3730
+
3731
+ // src/skills-adoption.ts
3732
+ import { lstatSync as lstatSync4, readFileSync as readFileSync6, readdirSync as readdirSync4, readlinkSync as readlinkSync2 } from "fs";
3733
+ import path7 from "path";
3734
+ import os from "os";
3735
+ import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
3736
+ var OPERATION = "setup.skills.adopt";
3737
+ var missing = () => ({ kind: "missing" });
3738
+ var normalized = (p) => p.split(path7.sep).join("/");
3739
+ var under = (p, root) => p === root || p.startsWith(root + "/");
3740
+ var depth = (p) => p.split("/").length;
3741
+ function canonical(value) {
3742
+ const sort = (v) => Array.isArray(v) ? v.map(sort) : v && typeof v === "object" ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sort(v[k])])) : v;
3743
+ return JSON.stringify(sort(value));
3744
+ }
3745
+ function plain(state) {
3746
+ const { contentBase64, payload, ...identity } = state;
3747
+ return identity;
3748
+ }
3749
+ function same(a, b) {
3750
+ return canonical(plain(a)) === canonical(plain(b));
3751
+ }
3752
+ function file(content, mode = 420) {
3753
+ const bytes = Buffer.isBuffer(content) ? content : Buffer.from(content);
3754
+ return { kind: "file", digest: hashText(bytes), contentBase64: bytes.toString("base64"), mode };
3755
+ }
3756
+ function inspect(root, p) {
3757
+ const absolute = relativePathToTarget(root, p);
3758
+ const st = lstatSync4(absolute, { throwIfNoEntry: false });
3759
+ if (!st) return missing();
3760
+ if (st.isSymbolicLink()) return { kind: "symlink", target: readlinkSync2(absolute) };
3761
+ if (st.isDirectory()) return { kind: "directory", mode: st.mode & 511 };
3762
+ if (st.isFile()) return file(readFileSync6(absolute), st.mode & 511);
3763
+ throw new Error(`Unsupported Skill path: ${p}. Preserve it and resolve its type before adoption.`);
3764
+ }
3765
+ function snapshot(root, roots, exact) {
3766
+ const result = {};
3767
+ const visit = (p) => {
3768
+ if (result[p]) return;
3769
+ const state = inspect(root, p);
3770
+ result[p] = state;
3771
+ if (state.kind === "directory") for (const name of readdirSync4(relativePathToTarget(root, p)).sort()) visit(p + "/" + name);
3772
+ };
3773
+ for (const p of roots) visit(p);
3774
+ for (const p of exact) if (!result[p]) result[p] = inspect(root, p);
3775
+ return result;
3776
+ }
3777
+ function checkParents(root, roots) {
3778
+ const issues = [];
3779
+ for (const p of roots) {
3780
+ let parent = path7.dirname(relativePathToTarget(root, p));
3781
+ while (parent !== path7.dirname(parent)) {
3782
+ const st = lstatSync4(parent, { throwIfNoEntry: false });
3783
+ if (st?.isSymbolicLink()) issues.push(`Unsafe link parent: ${parent}.`);
3784
+ if (st && !st.isDirectory()) issues.push(`Non-directory parent: ${parent}.`);
3785
+ if (parent === root || parent === os.homedir()) break;
3786
+ parent = path7.dirname(parent);
3787
+ }
3788
+ }
3789
+ return [...new Set(issues)];
3790
+ }
3791
+ function skillRoot(p) {
3792
+ return p.match(/^(.*(?:^|\/)(?:\.make-docs\/agentics|\.agents|\.claude|\.codex)\/skills\/[^/]+)(?:\/|$)/)?.[1] ?? null;
3793
+ }
3794
+ var legacySkillRoot = (p) => p.startsWith(".make-docs/agentics/skills/") || path7.isAbsolute(p) && [os.homedir(), canonicalInstallationPath(os.homedir())].some((home) => p.startsWith(normalized(path7.join(home, ".make-docs/agentics/skills")) + "/"));
3795
+ function addParents(map, before, p, boundary) {
3796
+ let parent = normalized(path7.dirname(p));
3797
+ while (under(parent, boundary)) {
3798
+ map[parent] ??= before[parent]?.kind === "directory" ? before[parent] : { kind: "directory", mode: 493 };
3799
+ if (parent === boundary) break;
3800
+ parent = normalized(path7.dirname(parent));
3801
+ }
3802
+ }
3803
+ function setAsset(map, before, asset, boundary) {
3804
+ map[asset.relativePath] = file(asset.content, before[asset.relativePath]?.kind === "file" ? before[asset.relativePath].mode : 420);
3805
+ addParents(map, before, asset.relativePath, boundary);
3806
+ }
3807
+ function changesBetween(before, after) {
3808
+ const remove = [], dirs = [], files = [], links = [];
3809
+ for (const p of [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].sort()) {
3810
+ const old = before[p] ?? missing(), next = after[p] ?? missing();
3811
+ if (same(old, next)) continue;
3812
+ let from = old;
3813
+ if (old.kind !== "missing" && (next.kind === "missing" || old.kind !== next.kind || old.kind === "symlink" && old.target !== next.target)) {
3814
+ remove.push({ path: p, before: old, after: missing() });
3815
+ from = missing();
3816
+ }
3817
+ if (next.kind === "missing") continue;
3818
+ const change = { path: p, before: from, after: next };
3819
+ (next.kind === "directory" ? dirs : next.kind === "symlink" ? links : files).push(change);
3820
+ }
3821
+ remove.sort((a, b) => depth(b.path) - depth(a.path) || a.path.localeCompare(b.path));
3822
+ dirs.sort((a, b) => depth(a.path) - depth(b.path) || a.path.localeCompare(b.path));
3823
+ return [...remove, ...dirs, ...files, ...links];
3824
+ }
3825
+ async function buildSkillAdoptionReview(options) {
3826
+ const targetRoot = canonicalInstallationPath(options.targetDir);
3827
+ const configParents = checkParents(targetRoot, [".make-docs/config.yaml"]);
3828
+ if (configParents.length) throw new Error(configParents.join("\n"));
3829
+ loadMakeDocsConfigOrThrow(targetRoot);
3830
+ const beforeLedger = loadManifest(targetRoot);
3831
+ const names = [...new Set(options.adoptExisting)].sort();
3832
+ const selections = structuredClone(options.selections);
3833
+ selections.selectedSkills = [...new Set(selections.selectedSkills)].sort();
3834
+ selections.skillHarnesses = { ...selections.skillHarnesses ?? selections.harnesses };
3835
+ if (options.effectiveRegistry.source.kind !== "built-in") throw new Error("Existing-copy adoption requires the built-in first-party registry.");
3836
+ const registryNames = new Set(options.effectiveRegistry.registry.skills.map((s) => s.name));
3837
+ if (!names.length || names.some((name) => !registryNames.has(name) || !selections.selectedSkills.includes(name))) throw new Error("Adoption names must be selected first-party Skills. Review --selected-skills and --adopt-existing.");
3838
+ const packageDigest = await getEmbeddedSkillPackageDigest();
3839
+ const packageMeta = readPackageMeta();
3840
+ const assets = await getDesiredSkillAssets(selections, options.effectiveRegistry.registry);
3841
+ const exposures = assets.filter((a) => a.kind === "skill-exposure");
3842
+ const payloads = assets.filter((a) => a.kind !== "skill-exposure");
3843
+ const roots = [...new Set([...assets.map((a) => a.kind === "skill-exposure" ? a.relativePath : skillRoot(a.relativePath)), ...(beforeLedger?.skillFiles ?? []).map((p) => beforeLedger?.files[p]?.skillExposure ? p : skillRoot(p))].filter((p) => p !== null))].sort();
3844
+ const legacyContainers = [".make-docs/agentics", ...selections.skillScope === "global" || beforeLedger?.selections.skillScope === "global" ? [normalized(path7.join(os.homedir(), ".make-docs/agentics"))] : []];
3845
+ const unownedLegacy = [];
3846
+ for (const container of legacyContainers) {
3847
+ const parentIssues = checkParents(targetRoot, [container]);
3848
+ if (parentIssues.length) throw new Error(parentIssues.join("\n"));
3849
+ const current = inspect(targetRoot, container);
3850
+ if (current.kind === "missing") continue;
3851
+ if (current.kind !== "directory") throw new Error(`Unsafe retired Skill container: ${container}. Preserve it before layout review.`);
3852
+ const inventory = snapshot(targetRoot, [container], []);
3853
+ for (const p of Object.keys(inventory)) if (p !== container && p !== container + "/skills" && !roots.some((r) => legacySkillRoot(r) && under(p, r))) unownedLegacy.push(p);
3854
+ for (const name of names) {
3855
+ const legacy = container + "/skills/" + name;
3856
+ if (!roots.includes(legacy)) roots.push(legacy);
3857
+ }
3858
+ }
3859
+ roots.sort();
3860
+ const rootParents = checkParents(targetRoot, roots);
3861
+ if (rootParents.length) throw new Error(rootParents.join("\n"));
3862
+ const normal = await planSkillsOnlyInstall({ targetDir: targetRoot, selections, existingManifest: beforeLedger, remove: false, packageMeta, skillRegistry: options.effectiveRegistry.registry, reviewedSkillAdoption: true });
3863
+ const bootstrapPaths = normal.actions.filter((a) => a.sourceId?.startsWith("router:")).map((a) => a.relativePath).sort();
3864
+ const exactPaths = [...bootstrapPaths, ".make-docs/config.yaml"];
3865
+ const blockers = checkParents(targetRoot, [...roots, ...exactPaths]);
3866
+ if (blockers.length) throw new Error(blockers.join("\n"));
3867
+ if (unownedLegacy.length) blockers.push(`Unowned retired Skill content needs explicit disposition before cutover: ${unownedLegacy.join(", ")}. Preserve it; directory location alone does not prove ownership.`);
3868
+ const before = snapshot(targetRoot, roots, exactPaths);
3869
+ const claims = readInstallationPathClaims(targetRoot, roots);
3870
+ for (const claim of claims) if (canonicalInstallationPath(claim.rootPath) !== targetRoot || claim.kind === "pending") blockers.push(`Another ${claim.kind === "pending" ? "pending operation" : "checkout owner"} claims ${claim.path}: ${claim.rootPath}${claim.operationId ? ` (${claim.operationId})` : ""}.`);
3871
+ const after = {};
3872
+ const cleanupPaths = [];
3873
+ for (const oldRoot of roots.filter(legacySkillRoot)) if (!names.includes(path7.basename(oldRoot))) blockers.push(`Legacy Skill ${path7.basename(oldRoot)} must be named in --adopt-existing for its reviewed layout cutover.`);
3874
+ for (const oldName of beforeLedger?.selections.selectedSkills ?? []) if (!selections.selectedSkills.includes(oldName)) blockers.push(`Adoption cannot also deselect ${oldName}. Use normal setup skills to remove it, then create a new adoption review.`);
3875
+ const alternatives = {};
3876
+ const known = /* @__PURE__ */ new Set([...payloads.map((a) => a.relativePath), ...exposures.flatMap((a) => a.copyMirrorAssets.map((f) => f.relativePath)), ...Object.keys(beforeLedger?.files ?? {}).filter((p) => skillRoot(p))]);
3877
+ for (const [p, entry] of Object.entries(beforeLedger?.files ?? {})) if (entry.skillExposure) {
3878
+ const canonicalRoot = entry.skillExposure.canonicalPayloadPath;
3879
+ for (const owned of Object.keys(beforeLedger.files)) if (under(owned, canonicalRoot)) known.add(p + owned.slice(canonicalRoot.length));
3880
+ }
3881
+ for (const [p, state] of Object.entries(before)) {
3882
+ if (!roots.some((root) => under(p, root))) continue;
3883
+ if (state.kind === "file" && !known.has(p)) blockers.push(`Unknown extra file: ${p}. Preserve it before adoption.`);
3884
+ if (state.kind === "symlink") {
3885
+ const exposure = exposures.find((e) => e.relativePath === p);
3886
+ const expectedTarget = beforeLedger?.files[p]?.skillExposure?.symlinkTarget ?? exposure?.skillExposure.symlinkTarget;
3887
+ if (!expectedTarget || state.target !== expectedTarget) blockers.push(`Unsafe or wrong-target Skill link: ${p}.`);
3888
+ }
3889
+ if (state.kind === "directory" && !roots.includes(p) && ![...known].some((f) => under(f, p))) blockers.push(`Unknown extra directory: ${p}. Preserve it before adoption.`);
3890
+ }
3891
+ const adoptedRoots = new Set(exposures.filter((e) => names.includes(e.skillExposure.skillName)).flatMap((e) => [e.relativePath, e.skillExposure.canonicalPayloadPath]));
3892
+ for (const entry of options.effectiveRegistry.registry.skills.filter((s) => names.includes(s.name))) {
3893
+ for (const root of roots) if (root.endsWith("/" + entry.installName)) adoptedRoots.add(root);
3894
+ }
3895
+ for (const root of roots) if (before[root]?.kind !== "missing" && !adoptedRoots.has(root) && !Object.keys(beforeLedger?.files ?? {}).some((p) => under(p, root))) {
3896
+ blockers.push(`Existing unowned Skill path needs an explicit --adopt-existing selection: ${root}.`);
3897
+ }
3898
+ for (const name of names) {
3899
+ const copies = [...adoptedRoots].filter((root) => root.endsWith("/" + options.effectiveRegistry.registry.skills.find((e) => e.name === name).installName));
3900
+ const byFile = /* @__PURE__ */ new Map();
3901
+ for (const root of copies) for (const [p, state] of Object.entries(before)) if (under(p, root) && state.kind === "file") {
3902
+ const suffix = p.slice(root.length + 1), hashes = byFile.get(suffix) ?? /* @__PURE__ */ new Set();
3903
+ hashes.add(state.digest);
3904
+ byFile.set(suffix, hashes);
3905
+ }
3906
+ for (const [suffix, hashes] of byFile) if (hashes.size > 1) blockers.push(`Conflicting existing copies for ${name}/${suffix}. Choose one preserved source before adoption.`);
3907
+ }
3908
+ for (const asset of payloads) setAsset(after, before, asset, skillRoot(asset.relativePath));
3909
+ const desiredFiles = { ...normal.desiredFiles };
3910
+ const copyFallbacks = {};
3911
+ const symlinkTargets = {};
3912
+ const beforeSymlinkTargets = {};
3913
+ for (const [p, state] of Object.entries(before)) if (state.kind === "symlink" && state.target === beforeLedger?.files[p]?.skillExposure?.symlinkTarget) beforeSymlinkTargets[p] = state.target;
3914
+ for (const exposure of exposures) {
3915
+ const copy = {};
3916
+ for (const asset of exposure.copyMirrorAssets) setAsset(copy, before, asset, exposure.relativePath);
3917
+ copy[exposure.relativePath] ??= { kind: "directory", mode: 493 };
3918
+ const currentCopy = Object.fromEntries(Object.entries(before).filter(([p]) => under(p, exposure.relativePath)));
3919
+ const matchesCopy = canonical(Object.fromEntries(Object.entries(currentCopy).map(([p, s]) => [p, plain(s)]))) === canonical(Object.fromEntries(Object.entries(copy).map(([p, s]) => [p, plain(s)])));
3920
+ const asCopy = process.env.MAKE_DOCS_DISABLE_SKILL_SYMLINKS === "1" || matchesCopy;
3921
+ const entry = desiredFiles[exposure.relativePath];
3922
+ const priorFallback = asCopy && matchesCopy ? beforeLedger?.files[exposure.relativePath]?.skillExposure?.fallbackReason : void 0;
3923
+ desiredFiles[exposure.relativePath] = { ...entry, skillExposure: { ...exposure.skillExposure, mode: asCopy ? "copy-mirror" : "symlink", ...priorFallback ? { fallbackReason: priorFallback } : {} } };
3924
+ if (asCopy) Object.assign(after, copy);
3925
+ else {
3926
+ after[exposure.relativePath] = { kind: "symlink", target: exposure.skillExposure.symlinkTarget };
3927
+ symlinkTargets[exposure.relativePath] = exposure.skillExposure.symlinkTarget;
3928
+ alternatives[exposure.relativePath] = copy;
3929
+ copyFallbacks[exposure.relativePath] = { changes: changesBetween({ [exposure.relativePath]: missing() }, copy), ledgerEntry: { ...entry, skillExposure: { ...exposure.skillExposure, mode: "copy-mirror", fallbackReason: "The reviewed native symlink is unavailable; use its declared copy mirror." } } };
3930
+ }
3931
+ }
3932
+ for (const action of normal.actions) {
3933
+ const root = roots.find((p) => under(action.relativePath, p)) ?? skillRoot(action.relativePath);
3934
+ if (!root) {
3935
+ if (action.type === "noop") after[action.relativePath] = before[action.relativePath] ?? inspect(targetRoot, action.relativePath);
3936
+ else if (["create", "update", "generate"].includes(action.type) && typeof action.content === "string") after[action.relativePath] = file(action.content, before[action.relativePath]?.mode);
3937
+ else if (action.type !== "skip") blockers.push(`Bootstrap path needs normal setup review before adoption: ${action.relativePath}.`);
3938
+ continue;
3939
+ }
3940
+ if (action.type === "skip-conflict") {
3941
+ const owned = beforeLedger?.files[action.relativePath];
3942
+ const prior = owned?.skillExposure;
3943
+ const desired = exposures.find((exposure) => exposure.relativePath === action.relativePath);
3944
+ const current = before[action.relativePath];
3945
+ const reviewedLegacyRetarget = prior && desired && current?.kind === "symlink" && prior.mode === "symlink" && current.target === prior.symlinkTarget && names.includes(prior.skillName) && beforeLedger?.skillFiles?.includes(action.relativePath) && owned.sourceId === desired.sourceId && prior.exposurePath === action.relativePath && prior.skillName === desired.skillExposure.skillName && prior.installName === desired.skillExposure.installName && prior.harness === desired.skillExposure.harness && prior.scope === desired.skillExposure.scope && legacySkillRoot(prior.canonicalPayloadPath) && roots.includes(prior.canonicalPayloadPath) && path7.resolve(path7.dirname(relativePathToTarget(targetRoot, action.relativePath)), prior.symlinkTarget) === path7.resolve(targetRoot, prior.canonicalPayloadPath);
3946
+ if (!adoptedRoots.has(root) || owned && !reviewedLegacyRetarget) blockers.push(`Protected managed or unselected adoption conflict: ${action.relativePath}.`);
3947
+ }
3948
+ if (action.type === "remove-managed") delete desiredFiles[action.relativePath];
3949
+ }
3950
+ const configBefore = before[".make-docs/config.yaml"];
3951
+ const configObject = configBefore.kind === "file" ? parse(Buffer.from(configBefore.contentBase64, "base64").toString("utf8")) ?? {} : {};
3952
+ const projectId = beforeLedger?.projectId ?? (typeof configObject.projectId === "string" ? configObject.projectId : mintProjectId());
3953
+ after[".make-docs/config.yaml"] = configObject.projectId ? configBefore : file(stringify({ ...configObject, projectId }), configBefore.mode);
3954
+ const inventoryDigest = hashText(canonical({ before, packageDigest, selections, names, claims }));
3955
+ const backupRoot = `.make-docs/backup/skill-adoption-${inventoryDigest.slice(0, 12)}`;
3956
+ const backups = [];
3957
+ for (const [p, old] of Object.entries(before)) if (old.kind === "file" && roots.some((root) => under(p, root)) && !same(old, after[p] ?? missing())) {
3958
+ const destination = backupRoot + "/" + (path7.isAbsolute(p) ? "_global/" + p.replace(/^\/+/, "") : p);
3959
+ backups.push({ source: p, destination, digest: old.digest });
3960
+ after[destination] = old;
3961
+ addParents(after, before, destination, backupRoot);
3962
+ }
3963
+ if (backups.length) {
3964
+ const existingBackup = inspect(targetRoot, backupRoot);
3965
+ if (existingBackup.kind !== "missing") blockers.push(`The reviewed backup destination already exists: ${backupRoot}. Preserve it and create a fresh review.`);
3966
+ before[backupRoot] = existingBackup;
3967
+ }
3968
+ for (const p of Object.keys(after)) {
3969
+ let parent = normalized(path7.dirname(p));
3970
+ while (parent !== "." && parent !== "/" && !roots.some((r) => under(parent, r))) {
3971
+ if (path7.isAbsolute(parent) && !roots.some((r) => r.startsWith(parent + "/"))) break;
3972
+ if (path7.isAbsolute(parent) && parent === os.homedir()) break;
3973
+ if (path7.isAbsolute(parent) && parent === path7.join(os.homedir(), ".make-docs")) break;
3974
+ const current = inspect(targetRoot, parent);
3975
+ before[parent] ??= current;
3976
+ if (current.kind === "missing") after[parent] ??= { kind: "directory", mode: 493 };
3977
+ else if (current.kind === "directory") after[parent] ??= current;
3978
+ else blockers.push(`Unsafe parent for planned output: ${parent}.`);
3979
+ parent = normalized(path7.dirname(parent));
3980
+ }
3981
+ }
3982
+ const legacyParents = [...new Set(roots.filter(legacySkillRoot).flatMap((p) => [normalized(path7.dirname(p)), normalized(path7.dirname(path7.dirname(p)))]))].sort((a, b) => depth(b) - depth(a));
3983
+ for (const parent of legacyParents) {
3984
+ const inventory = snapshot(targetRoot, [parent], []);
3985
+ const unknown = Object.keys(inventory).filter((p) => p !== parent && !legacyParents.includes(p) && !roots.some((r) => under(p, r)));
3986
+ if (unknown.length) {
3987
+ blockers.push(`Legacy Skill directory contains unrelated content: ${unknown.join(", ")}. Preserve it before layout cutover.`);
3988
+ continue;
3989
+ }
3990
+ Object.assign(before, inventory);
3991
+ if (before[parent].kind === "directory") {
3992
+ after[parent] = missing();
3993
+ cleanupPaths.push(parent);
3994
+ } else if (before[parent].kind !== "missing") blockers.push(`Unsafe legacy Skill parent: ${parent}.`);
3995
+ }
3996
+ const files = { ...beforeLedger?.files ?? {}, ...desiredFiles };
3997
+ for (const action of normal.actions) if (action.type === "remove-managed") delete files[action.relativePath];
3998
+ for (const p of Object.keys(files)) if (legacySkillRoot(p) || beforeLedger?.files[p]?.skillExposure && !desiredFiles[p] && after[p]?.kind === "directory") delete files[p];
3999
+ const skillFiles = [.../* @__PURE__ */ new Set([...beforeLedger?.skillFiles ?? [], ...normal.desiredSkillFiles])].filter((p) => !!files[p] && !normal.actions.some((a) => a.relativePath === p && a.type === "remove-managed"));
4000
+ const afterLedger = createManifest(packageMeta, normal.profile, files, skillFiles, beforeLedger?.systemAssetMaterialization ?? normal.systemAssetMaterialization, projectId, normal.routerOwnership, normal.resourceProjection);
4001
+ const ownershipChanges = [.../* @__PURE__ */ new Set([...Object.keys(beforeLedger?.files ?? {}), ...Object.keys(files)])].filter((p) => roots.some((root) => under(p, root))).map((p) => ({ path: p, effect: !beforeLedger?.files[p] ? "register" : !files[p] ? "remove" : isDeepStrictEqual3(beforeLedger.files[p], files[p]) ? "retain" : "update", before: beforeLedger?.files[p] ?? null, after: files[p] ?? null }));
4002
+ const changes = changesBetween(before, after);
4003
+ const filtered = changes.filter((c) => !(c.after.kind === "missing" && !roots.some((root) => under(c.path, root)) && !exactPaths.includes(c.path) && !cleanupPaths.includes(c.path)));
4004
+ const backupFirst = (c) => backups.length > 0 && c.before.kind === "missing" && (under(c.path, backupRoot) || c.after.kind === "directory" && under(backupRoot, c.path));
4005
+ const retiredRemoval = (c) => c.after.kind === "missing" && (legacySkillRoot(c.path) || cleanupPaths.includes(c.path));
4006
+ const filteredChanges = [...filtered.filter(backupFirst), ...filtered.filter((c) => !backupFirst(c) && !retiredRemoval(c)), ...filtered.filter((c) => !backupFirst(c) && retiredRemoval(c))];
4007
+ const digestAfter = { ...after, ".make-docs/config.yaml": configObject.projectId ? configBefore : { kind: "file", generatedProjectIdentity: true, existingConfig: configBefore.digest ?? null } };
4008
+ const digest = hashText(canonical({ targetRoot, packageDigest, package: packageMeta, selections, names, roots, cleanupPaths, before, after: digestAfter, alternatives, backups, claims, beforeLedger, ownershipChanges, bootstrapPaths, blockers }));
4009
+ const intermediateStates = {};
4010
+ for (const change of filteredChanges) (intermediateStates[change.path] ??= []).push(change.before, change.after);
4011
+ const review = { schemaVersion: 1, targetRoot, digest, packageDigest, package: packageMeta, selections, adoptExisting: names, roots, cleanupPaths, bootstrapPaths, before, after, alternatives, intermediateStates, backups, claims, beforeLedger, blockers: [...new Set(blockers)].sort(), ownershipChanges, plan: void 0 };
4012
+ review.plan = { schemaVersion: 1, reviewDigest: digest, mode: "cli", metadata: void 0, changes: filteredChanges, afterLedger, skillScope: { roots, symlinkTargets, beforeSymlinkTargets, bootstrapPaths, backupRoots: backups.length ? [backupRoot] : [] }, copyFallbacks };
4013
+ review.plan.metadata = { ...review, plan: void 0 };
4014
+ return review;
4015
+ }
4016
+ function presentSkillAdoptionReview(review) {
4017
+ const unchanged = !review.plan.changes.length && review.ownershipChanges.every((c) => c.effect === "retain") && isDeepStrictEqual3(review.beforeLedger?.selections, review.plan.afterLedger?.selections);
4018
+ return {
4019
+ schemaVersion: 1,
4020
+ status: review.blockers.length ? "blocked" : unchanged ? "unchanged" : "ready",
4021
+ targetRoot: review.targetRoot,
4022
+ reviewDigest: review.digest,
4023
+ package: review.package,
4024
+ packageDigest: review.packageDigest,
4025
+ scope: review.selections.skillScope,
4026
+ selectedTools: Object.entries(review.selections.skillHarnesses ?? review.selections.harnesses).filter(([, v]) => v).map(([k]) => k),
4027
+ selectedSkills: review.selections.selectedSkills,
4028
+ adoptExisting: review.adoptExisting,
4029
+ inventory: Object.entries(review.before).map(([p, s]) => ({ path: p, ...plain(s) })),
4030
+ changes: review.plan.changes.map((c) => ({ path: c.path, before: plain(c.before), after: plain(c.after) })),
4031
+ backups: review.backups,
4032
+ recoveryLimits: review.roots.some(legacySkillRoot) ? ["This layout cutover supports forward resume. Rollback that would recreate retired .make-docs/agentics paths is blocked; preserved bytes remain in the reviewed backups and Store."] : [],
4033
+ currentOwner: review.beforeLedger ? { projectId: review.beforeLedger.projectId, checkoutRoot: review.targetRoot } : null,
4034
+ ownership: review.ownershipChanges,
4035
+ claims: review.claims,
4036
+ blockers: review.blockers,
4037
+ nextAction: review.blockers.length ? "Preserve blocked inputs and resolve them before a new review." : unchanged ? "These Skill files and ownership already match. No adoption is needed." : `Repeat setup skills with the same target, scope, tools, selected Skills, and --adopt-existing ${review.adoptExisting.join(",")}; replace --dry-run with --review ${review.digest}.`
4038
+ };
4039
+ }
4040
+ function verifySkillAdoption(root, metadata, phase, temporaryFiles) {
4041
+ const review = metadata;
4042
+ if (!review || review.schemaVersion !== 1 || canonicalInstallationPath(root) !== review.targetRoot) return ["Adoption review belongs to another target."];
4043
+ const issues = checkParents(root, review.roots);
4044
+ if (issues.length) return issues;
4045
+ const expected = phase === "before" ? review.before : review.after;
4046
+ const exact = Object.keys(review.before).filter((p) => !review.roots.some((r) => under(p, r)));
4047
+ let current;
4048
+ try {
4049
+ current = snapshot(root, [...review.roots, ...review.cleanupPaths ?? [], ...new Set(review.backups.map((b) => b.destination.split("/").slice(0, 3).join("/")))], exact);
4050
+ } catch (error) {
4051
+ return [String(error)];
4052
+ }
4053
+ const allowed = { ...expected };
4054
+ if (phase !== "before") for (const [exposure, copy] of Object.entries(review.alternatives)) {
4055
+ if (current[exposure]?.kind === "directory") {
4056
+ for (const p of Object.keys(allowed)) if (under(p, exposure)) delete allowed[p];
4057
+ Object.assign(allowed, copy);
4058
+ }
4059
+ }
4060
+ for (const [p, state] of Object.entries(current)) {
4061
+ if (temporaryFiles?.[p] && phase === "progress" && same(state, temporaryFiles[p])) continue;
4062
+ const matches = same(state, allowed[p] ?? missing()) || phase === "progress" && (same(state, review.before[p] ?? missing()) || review.intermediateStates[p]?.some((s) => same(state, s)));
4063
+ if (!matches) issues.push(`Adoption input/output changed: ${p}.`);
4064
+ }
4065
+ for (const [p, state] of Object.entries(allowed)) if (!current[p] && state.kind !== "missing" && !(phase === "progress" && ((review.before[p]?.kind ?? "missing") === "missing" || review.intermediateStates[p]?.some((s) => s.kind === "missing")))) issues.push(`Adoption path is missing: ${p}.`);
4066
+ return [...new Set(issues)];
4067
+ }
4068
+ function verifySkillAdoptionBeforeCleanup(root, metadata) {
4069
+ const review = metadata;
4070
+ if (!review || review.schemaVersion !== 1 || canonicalInstallationPath(root) !== review.targetRoot) return ["Adoption review belongs to another target."];
4071
+ const after = { ...review.after };
4072
+ for (const [p, before] of Object.entries(review.before)) if (legacySkillRoot(p) || review.cleanupPaths.includes(p)) {
4073
+ const current = inspect(root, p);
4074
+ if (!same(current, before) && current.kind !== "missing") return [`Retired source changed before cleanup: ${p}.`];
4075
+ after[p] = current;
4076
+ }
4077
+ return verifySkillAdoption(root, { ...review, after }, "after");
4078
+ }
4079
+ var recoveryRegistered = false;
4080
+ function registerSkillAdoptionRecovery() {
4081
+ if (recoveryRegistered) return;
4082
+ registerDetachedInstallationOperation(OPERATION, {
4083
+ validate: verifySkillAdoption,
4084
+ beforeRetiredCleanup: verifySkillAdoptionBeforeCleanup,
4085
+ nextAction: (root, id) => `Inspect make-docs project state recover ${id} --resume --dry-run --target-root ${JSON.stringify(root)}.`
4086
+ });
4087
+ recoveryRegistered = true;
4088
+ }
4089
+ registerSkillAdoptionRecovery();
4090
+ function applySkillAdoptionReview(review, digest) {
4091
+ if (digest !== review.digest) throw new Error("Adoption review changed. Run a new dry run and review its exact digest.");
4092
+ if (review.blockers.length) throw new Error(review.blockers.join("\n"));
4093
+ if (presentSkillAdoptionReview(review).status === "unchanged") return { status: "unchanged", reviewDigest: review.digest };
4094
+ const prepared = prepareDetachedInstallationOperation(review.targetRoot, OPERATION, () => {
4095
+ assertEmbeddedSkillPackageDigest(review.packageDigest);
4096
+ if (!isDeepStrictEqual3(loadManifest(review.targetRoot), review.beforeLedger)) throw new Error("Installation ownership changed after adoption review.");
4097
+ if (!isDeepStrictEqual3(readInstallationPathClaims(review.targetRoot, review.roots), review.claims)) throw new Error("Skill ownership or pending operations changed after review.");
4098
+ const problems = verifySkillAdoption(review.targetRoot, review, "before");
4099
+ if (problems.length) throw new Error(problems.join("\n"));
4100
+ return review.plan;
4101
+ });
4102
+ return { ...recoverInstallationOperation(review.targetRoot, prepared.operationId, "resume", false), reviewDigest: review.digest };
4103
+ }
4104
+
4105
+ export {
4106
+ createDefaultMakeDocsConfig,
4107
+ getConfigRenderingLabels,
4108
+ getDocumentKindLabel,
4109
+ loadMakeDocsConfig,
4110
+ loadMakeDocsConfigOrThrow,
4111
+ planProjectHarnessIntegrationWrite,
4112
+ resolveEffectiveHarnessIntegration,
4113
+ getRetiredResourceReplacement,
4114
+ SYSTEM_RESOURCE_TYPES,
4115
+ SYSTEM_RESOURCE_TYPE_DIRECTORIES,
4116
+ SYSTEM_RESOURCE_ORIGINS,
4117
+ SYSTEM_RESOURCE_ENSURE_APPROVAL,
4118
+ createSystemResourceIdentity,
4119
+ parseSystemResourceUri,
4120
+ canonicalSystemResourcePath,
4121
+ loadInstalledSystemResourceProvider,
4122
+ matchesSystemResourceCatalogPath,
4123
+ createRouterOwnershipManifestEntry,
4124
+ createProjectSurfaceRouterAssets,
4125
+ getThinRouterManagedBody,
4126
+ planInstall,
4127
+ planSkillsOnlyInstall,
4128
+ findReviewableManagedFileConflicts,
4129
+ applyInstallPlan,
4130
+ applySkillsOnlyInstallPlan,
4131
+ buildSkillAdoptionReview,
4132
+ presentSkillAdoptionReview,
4133
+ registerSkillAdoptionRecovery,
4134
+ applySkillAdoptionReview
4135
+ };
4136
+ //# sourceMappingURL=chunk-C2IBRVUA.js.map