dreamteamer 0.49.1 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (958) hide show
  1. package/bin/dreamteamer.js +74 -130
  2. package/collections/modules.collection.yaml +5 -1
  3. package/collections/repos.collection.yaml +1 -1
  4. package/dist/api.d.ts +88 -0
  5. package/dist/api.js +138 -0
  6. package/dist/changes/commitPending.d.ts +28 -0
  7. package/dist/changes/commitPending.js +648 -0
  8. package/dist/changes/composeSubject.d.ts +9 -0
  9. package/dist/changes/composeSubject.js +19 -0
  10. package/dist/changes/consts.d.ts +11 -0
  11. package/dist/changes/consts.js +19 -0
  12. package/dist/changes/deriveEvents.d.ts +17 -0
  13. package/dist/changes/deriveEvents.js +115 -0
  14. package/dist/changes/foldChanges.d.ts +12 -0
  15. package/dist/changes/foldChanges.js +46 -0
  16. package/dist/changes/groupChanges.d.ts +3 -0
  17. package/dist/changes/groupChanges.js +19 -0
  18. package/dist/changes/lib/reportLine.d.ts +7 -0
  19. package/dist/changes/lib/reportLine.js +14 -0
  20. package/dist/changes/printChanges.d.ts +11 -0
  21. package/dist/changes/printChanges.js +20 -0
  22. package/dist/changes/recordChanges.d.ts +20 -0
  23. package/dist/changes/recordChanges.js +30 -0
  24. package/dist/changes/rowChanges.d.ts +7 -0
  25. package/dist/changes/rowChanges.js +24 -0
  26. package/dist/changes/types.d.ts +26 -0
  27. package/dist/changes/types.js +1 -0
  28. package/dist/check/check.d.ts +11 -0
  29. package/dist/check/check.js +449 -0
  30. package/dist/check/checkAlone.d.ts +9 -0
  31. package/dist/check/checkAlone.js +200 -0
  32. package/dist/check/consts.d.ts +1 -0
  33. package/dist/check/consts.js +3 -0
  34. package/dist/check/engineRun.d.ts +3 -0
  35. package/dist/check/engineRun.js +20 -0
  36. package/dist/check/freshWorkspace.d.ts +5 -0
  37. package/dist/check/freshWorkspace.js +24 -0
  38. package/dist/check/isStale.d.ts +3 -0
  39. package/dist/check/isStale.js +2 -0
  40. package/dist/check/symlinkedChildRoots.d.ts +3 -0
  41. package/dist/check/symlinkedChildRoots.js +13 -0
  42. package/dist/check/unreadData.d.ts +7 -0
  43. package/dist/check/unreadData.js +112 -0
  44. package/dist/cli.d.ts +21 -0
  45. package/dist/cli.js +150 -0
  46. package/dist/collections/addField.d.ts +23 -0
  47. package/dist/collections/addField.js +28 -0
  48. package/dist/collections/collectionsCommand.d.ts +7 -0
  49. package/dist/collections/collectionsCommand.js +357 -0
  50. package/dist/collections/createCollection.d.ts +21 -0
  51. package/dist/collections/createCollection.js +134 -0
  52. package/dist/collections/lib/applyRewrites.d.ts +4 -0
  53. package/dist/collections/lib/applyRewrites.js +26 -0
  54. package/dist/collections/lib/consts.d.ts +18 -0
  55. package/dist/collections/lib/consts.js +56 -0
  56. package/dist/collections/lib/declaringSource.d.ts +18 -0
  57. package/dist/collections/lib/declaringSource.js +44 -0
  58. package/dist/collections/lib/descriptorSources.d.ts +4 -0
  59. package/dist/collections/lib/descriptorSources.js +16 -0
  60. package/dist/collections/lib/fieldRenameWalk.d.ts +10 -0
  61. package/dist/collections/lib/fieldRenameWalk.js +50 -0
  62. package/dist/collections/lib/mixinDeclaring.d.ts +7 -0
  63. package/dist/collections/lib/mixinDeclaring.js +13 -0
  64. package/dist/collections/lib/mixinSources.d.ts +6 -0
  65. package/dist/collections/lib/mixinSources.js +18 -0
  66. package/dist/collections/lib/mixinsListedBy.d.ts +3 -0
  67. package/dist/collections/lib/mixinsListedBy.js +14 -0
  68. package/dist/collections/lib/placeField.d.ts +7 -0
  69. package/dist/collections/lib/placeField.js +19 -0
  70. package/dist/collections/lib/positionLines.d.ts +10 -0
  71. package/dist/collections/lib/positionLines.js +7 -0
  72. package/dist/collections/lib/qualify.d.ts +2 -0
  73. package/dist/collections/lib/qualify.js +5 -0
  74. package/dist/collections/lib/recordRewrites.d.ts +5 -0
  75. package/dist/collections/lib/recordRewrites.js +27 -0
  76. package/dist/collections/lib/removeFieldPlan.d.ts +26 -0
  77. package/dist/collections/lib/removeFieldPlan.js +57 -0
  78. package/dist/collections/lib/renameFieldPlan.d.ts +12 -0
  79. package/dist/collections/lib/renameFieldPlan.js +18 -0
  80. package/dist/collections/lib/renameInConstraint.d.ts +2 -0
  81. package/dist/collections/lib/renameInConstraint.js +45 -0
  82. package/dist/collections/lib/renameInDisplay.d.ts +2 -0
  83. package/dist/collections/lib/renameInDisplay.js +52 -0
  84. package/dist/collections/lib/renameInTemplate.d.ts +3 -0
  85. package/dist/collections/lib/renameInTemplate.js +12 -0
  86. package/dist/collections/lib/renameKeys.d.ts +13 -0
  87. package/dist/collections/lib/renameKeys.js +31 -0
  88. package/dist/collections/lib/renameMirrorOf.d.ts +3 -0
  89. package/dist/collections/lib/renameMirrorOf.js +10 -0
  90. package/dist/collections/lib/renameOwnField.d.ts +3 -0
  91. package/dist/collections/lib/renameOwnField.js +30 -0
  92. package/dist/collections/lib/renameValueInCondition.d.ts +4 -0
  93. package/dist/collections/lib/renameValueInCondition.js +42 -0
  94. package/dist/collections/lib/renameValueInConstraint.d.ts +3 -0
  95. package/dist/collections/lib/renameValueInConstraint.js +19 -0
  96. package/dist/collections/lib/renameValueInSubschema.d.ts +3 -0
  97. package/dist/collections/lib/renameValueInSubschema.js +24 -0
  98. package/dist/collections/lib/renameValuePlan.d.ts +13 -0
  99. package/dist/collections/lib/renameValuePlan.js +33 -0
  100. package/dist/collections/lib/reportMirror.d.ts +8 -0
  101. package/dist/collections/lib/reportMirror.js +19 -0
  102. package/dist/collections/lib/types.d.ts +36 -0
  103. package/dist/collections/lib/types.js +1 -0
  104. package/dist/collections/lib/upsertField.d.ts +22 -0
  105. package/dist/collections/lib/upsertField.js +39 -0
  106. package/dist/collections/lib/valueRenameWalk.d.ts +4 -0
  107. package/dist/collections/lib/valueRenameWalk.js +60 -0
  108. package/dist/collections/lib/viewSources.d.ts +6 -0
  109. package/dist/collections/lib/viewSources.js +20 -0
  110. package/dist/collections/lib/walkFilter.d.ts +3 -0
  111. package/dist/collections/lib/walkFilter.js +25 -0
  112. package/dist/collections/lib/walkSources.d.ts +17 -0
  113. package/dist/collections/lib/walkSources.js +80 -0
  114. package/dist/collections/moveCollection.d.ts +42 -0
  115. package/dist/collections/moveCollection.js +176 -0
  116. package/dist/collections/removeCollection.d.ts +8 -0
  117. package/dist/collections/removeCollection.js +40 -0
  118. package/dist/collections/removeField.d.ts +30 -0
  119. package/dist/collections/removeField.js +150 -0
  120. package/dist/collections/renameCollection.d.ts +55 -0
  121. package/dist/collections/renameCollection.js +487 -0
  122. package/dist/collections/renameField.d.ts +32 -0
  123. package/dist/collections/renameField.js +49 -0
  124. package/dist/collections/renameValue.d.ts +29 -0
  125. package/dist/collections/renameValue.js +35 -0
  126. package/dist/collections/setCollectionScalars.d.ts +32 -0
  127. package/dist/collections/setCollectionScalars.js +248 -0
  128. package/dist/collections/updateField.d.ts +27 -0
  129. package/dist/collections/updateField.js +20 -0
  130. package/dist/commands/addCommand.d.ts +1 -0
  131. package/dist/commands/addCommand.js +2 -0
  132. package/dist/commands/addFieldCommand.d.ts +1 -0
  133. package/dist/commands/addFieldCommand.js +2 -0
  134. package/dist/commands/changesCommand.d.ts +10 -0
  135. package/dist/commands/changesCommand.js +37 -0
  136. package/dist/commands/checkCommand.d.ts +1 -0
  137. package/dist/commands/checkCommand.js +22 -0
  138. package/dist/commands/commitCommand.d.ts +6 -0
  139. package/dist/commands/commitCommand.js +89 -0
  140. package/dist/commands/compileCommand.d.ts +2 -0
  141. package/dist/commands/compileCommand.js +35 -0
  142. package/dist/commands/diffCommand.d.ts +1 -0
  143. package/dist/commands/diffCommand.js +2 -0
  144. package/dist/commands/doctorCommand.d.ts +1 -0
  145. package/dist/commands/doctorCommand.js +14 -0
  146. package/dist/commands/exportsCommand.d.ts +1 -0
  147. package/dist/commands/exportsCommand.js +7 -0
  148. package/dist/commands/fmtCommand.d.ts +1 -0
  149. package/dist/commands/fmtCommand.js +26 -0
  150. package/dist/commands/getCommand.d.ts +1 -0
  151. package/dist/commands/getCommand.js +2 -0
  152. package/dist/commands/helpCommand.d.ts +5 -0
  153. package/dist/commands/helpCommand.js +27 -0
  154. package/dist/commands/historyCommand.d.ts +1 -0
  155. package/dist/commands/historyCommand.js +2 -0
  156. package/dist/commands/initCommand.d.ts +2 -0
  157. package/dist/commands/initCommand.js +17 -0
  158. package/dist/commands/installCommand.d.ts +1 -0
  159. package/dist/commands/installCommand.js +12 -0
  160. package/dist/commands/lib/fieldVerb.d.ts +12 -0
  161. package/dist/commands/lib/fieldVerb.js +26 -0
  162. package/dist/commands/lib/recordVerb.d.ts +2 -0
  163. package/dist/commands/lib/recordVerb.js +53 -0
  164. package/dist/commands/lib/unknownVerb.d.ts +14 -0
  165. package/dist/commands/lib/unknownVerb.js +74 -0
  166. package/dist/commands/lib/verify.d.ts +3 -0
  167. package/dist/commands/lib/verify.js +4 -0
  168. package/dist/commands/listCommand.d.ts +1 -0
  169. package/dist/commands/listCommand.js +2 -0
  170. package/dist/commands/nextCommand.d.ts +1 -0
  171. package/dist/commands/nextCommand.js +2 -0
  172. package/dist/commands/relationsCommand.d.ts +11 -0
  173. package/dist/commands/relationsCommand.js +181 -0
  174. package/dist/commands/relocateCommand.d.ts +1 -0
  175. package/dist/commands/relocateCommand.js +39 -0
  176. package/dist/commands/renameCommand.d.ts +1 -0
  177. package/dist/commands/renameCommand.js +2 -0
  178. package/dist/commands/renameFieldCommand.d.ts +1 -0
  179. package/dist/commands/renameFieldCommand.js +2 -0
  180. package/dist/commands/renameValueCommand.d.ts +1 -0
  181. package/dist/commands/renameValueCommand.js +2 -0
  182. package/dist/commands/reorderCommand.d.ts +1 -0
  183. package/dist/commands/reorderCommand.js +2 -0
  184. package/dist/commands/resolveCommand.d.ts +15 -0
  185. package/dist/commands/resolveCommand.js +69 -0
  186. package/dist/commands/revertCommand.d.ts +1 -0
  187. package/dist/commands/revertCommand.js +2 -0
  188. package/dist/commands/rmCommand.d.ts +1 -0
  189. package/dist/commands/rmCommand.js +2 -0
  190. package/dist/commands/rmFieldCommand.d.ts +1 -0
  191. package/dist/commands/rmFieldCommand.js +2 -0
  192. package/dist/commands/runCommand.d.ts +5 -0
  193. package/dist/commands/runCommand.js +9 -0
  194. package/dist/commands/setCommand.d.ts +1 -0
  195. package/dist/commands/setCommand.js +2 -0
  196. package/dist/commands/setFieldCommand.d.ts +1 -0
  197. package/dist/commands/setFieldCommand.js +2 -0
  198. package/dist/commands/setupCommand.d.ts +5 -0
  199. package/dist/commands/setupCommand.js +196 -0
  200. package/dist/commands/statusCommand.d.ts +1 -0
  201. package/dist/commands/statusCommand.js +16 -0
  202. package/dist/commands/updateCommand.d.ts +1 -0
  203. package/dist/commands/updateCommand.js +10 -0
  204. package/dist/commands/valuesCommand.d.ts +1 -0
  205. package/dist/commands/valuesCommand.js +2 -0
  206. package/dist/commands/versionCommand.d.ts +2 -0
  207. package/dist/commands/versionCommand.js +7 -0
  208. package/dist/compile/compile.d.ts +24 -0
  209. package/dist/compile/compile.js +1488 -0
  210. package/dist/compile/consts.d.ts +52 -0
  211. package/dist/compile/consts.js +119 -0
  212. package/dist/compile/ensureEditorRecommendation.d.ts +1 -0
  213. package/dist/compile/ensureEditorRecommendation.js +31 -0
  214. package/dist/compile/isV2.d.ts +2 -0
  215. package/dist/compile/isV2.js +1 -0
  216. package/dist/compile/kindDir.d.ts +11 -0
  217. package/dist/compile/kindDir.js +19 -0
  218. package/dist/compile/lib/bindingErrors.d.ts +11 -0
  219. package/dist/compile/lib/bindingErrors.js +47 -0
  220. package/dist/compile/lib/buildCollectionsIndex.d.ts +8 -0
  221. package/dist/compile/lib/buildCollectionsIndex.js +49 -0
  222. package/dist/compile/lib/buildModulesIndex.d.ts +9 -0
  223. package/dist/compile/lib/buildModulesIndex.js +54 -0
  224. package/dist/compile/lib/compileCollections.d.ts +70 -0
  225. package/dist/compile/lib/compileCollections.js +522 -0
  226. package/dist/compile/lib/consts.d.ts +5 -0
  227. package/dist/compile/lib/consts.js +10 -0
  228. package/dist/compile/lib/ensureEnvExample.d.ts +28 -0
  229. package/dist/compile/lib/ensureEnvExample.js +79 -0
  230. package/dist/compile/lib/ensureGitignored.d.ts +6 -0
  231. package/dist/compile/lib/ensureGitignored.js +16 -0
  232. package/dist/compile/lib/filterFields.d.ts +5 -0
  233. package/dist/compile/lib/filterFields.js +17 -0
  234. package/dist/compile/lib/harnessMarkers.d.ts +2 -0
  235. package/dist/compile/lib/harnessMarkers.js +4 -0
  236. package/dist/compile/lib/mergeMixins.d.ts +14 -0
  237. package/dist/compile/lib/mergeMixins.js +55 -0
  238. package/dist/compile/lib/mergeOverlays.d.ts +6 -0
  239. package/dist/compile/lib/mergeOverlays.js +37 -0
  240. package/dist/compile/lib/nameErrors.d.ts +6 -0
  241. package/dist/compile/lib/nameErrors.js +57 -0
  242. package/dist/compile/lib/namespaceProblems.d.ts +8 -0
  243. package/dist/compile/lib/namespaceProblems.js +34 -0
  244. package/dist/compile/lib/overlayView.d.ts +2 -0
  245. package/dist/compile/lib/overlayView.js +17 -0
  246. package/dist/compile/lib/renderContributions.d.ts +14 -0
  247. package/dist/compile/lib/renderContributions.js +50 -0
  248. package/dist/compile/lib/resolveFields.d.ts +21 -0
  249. package/dist/compile/lib/resolveFields.js +232 -0
  250. package/dist/compile/lib/runHarnessAdapters.d.ts +19 -0
  251. package/dist/compile/lib/runHarnessAdapters.js +590 -0
  252. package/dist/compile/lib/shapeErrors.d.ts +3 -0
  253. package/dist/compile/lib/shapeErrors.js +64 -0
  254. package/dist/compile/lib/storageOverlaps.d.ts +17 -0
  255. package/dist/compile/lib/storageOverlaps.js +26 -0
  256. package/dist/compile/lib/subpathProblem.d.ts +6 -0
  257. package/dist/compile/lib/subpathProblem.js +14 -0
  258. package/dist/compile/lib/toJsonSchema.d.ts +9 -0
  259. package/dist/compile/lib/toJsonSchema.js +100 -0
  260. package/dist/compile/lib/types.d.ts +46 -0
  261. package/dist/compile/lib/types.js +1 -0
  262. package/dist/compile/lib/unqualifiedProblems.d.ts +6 -0
  263. package/dist/compile/lib/unqualifiedProblems.js +18 -0
  264. package/dist/compile/lib/viewDisplay.d.ts +6 -0
  265. package/dist/compile/lib/viewDisplay.js +21 -0
  266. package/dist/compile/lib/viewErrors.d.ts +20 -0
  267. package/dist/compile/lib/viewErrors.js +143 -0
  268. package/dist/compile/lib/writeLine.d.ts +12 -0
  269. package/dist/compile/lib/writeLine.js +31 -0
  270. package/dist/compile/sha256.d.ts +1 -0
  271. package/dist/compile/sha256.js +2 -0
  272. package/dist/compile/stagedKindDir.d.ts +18 -0
  273. package/dist/compile/stagedKindDir.js +32 -0
  274. package/dist/compile/staleness.d.ts +11 -0
  275. package/dist/compile/staleness.js +118 -0
  276. package/dist/compile/toPosix.d.ts +2 -0
  277. package/dist/compile/toPosix.js +3 -0
  278. package/dist/compile/types.d.ts +30 -0
  279. package/dist/compile/types.js +1 -0
  280. package/dist/compile/v1ManifestRefusal.d.ts +8 -0
  281. package/dist/compile/v1ManifestRefusal.js +16 -0
  282. package/dist/compile/v1Refusal.d.ts +2 -0
  283. package/dist/compile/v1Refusal.js +5 -0
  284. package/dist/compile/views.d.ts +2 -0
  285. package/dist/compile/views.js +3 -0
  286. package/dist/compile/warnIfStale.d.ts +3 -0
  287. package/dist/compile/warnIfStale.js +10 -0
  288. package/dist/coreVerbs.d.ts +6 -0
  289. package/dist/coreVerbs.js +50 -0
  290. package/dist/doctor/consts.d.ts +10 -0
  291. package/dist/doctor/consts.js +10 -0
  292. package/dist/doctor/doctorBoard.d.ts +7 -0
  293. package/dist/doctor/doctorBoard.js +97 -0
  294. package/dist/doctor/renderBoard.d.ts +2 -0
  295. package/dist/doctor/renderBoard.js +9 -0
  296. package/dist/doctor/types.d.ts +7 -0
  297. package/dist/doctor/types.js +1 -0
  298. package/dist/entities/createSkill.d.ts +12 -0
  299. package/dist/entities/createSkill.js +56 -0
  300. package/dist/entities/entitiesCommand.d.ts +7 -0
  301. package/dist/entities/entitiesCommand.js +97 -0
  302. package/dist/entities/lib/consts.d.ts +2 -0
  303. package/dist/entities/lib/consts.js +2 -0
  304. package/dist/entities/lib/entitySource.d.ts +10 -0
  305. package/dist/entities/lib/entitySource.js +17 -0
  306. package/dist/entities/lib/refuseBuiltSkill.d.ts +9 -0
  307. package/dist/entities/lib/refuseBuiltSkill.js +23 -0
  308. package/dist/entities/lib/refuseHandAuthored.d.ts +7 -0
  309. package/dist/entities/lib/refuseHandAuthored.js +15 -0
  310. package/dist/entities/lib/setFrontmatterKey.d.ts +8 -0
  311. package/dist/entities/lib/setFrontmatterKey.js +21 -0
  312. package/dist/entities/removeEntity.d.ts +7 -0
  313. package/dist/entities/removeEntity.js +35 -0
  314. package/dist/entities/renameEntity.d.ts +11 -0
  315. package/dist/entities/renameEntity.js +51 -0
  316. package/dist/entities/setEntityFrontmatter.d.ts +9 -0
  317. package/dist/entities/setEntityFrontmatter.js +58 -0
  318. package/dist/exports/planExports.d.ts +10 -0
  319. package/dist/exports/planExports.js +57 -0
  320. package/dist/exports/runExports.d.ts +6 -0
  321. package/dist/exports/runExports.js +86 -0
  322. package/dist/exports/serializeExports.d.ts +6 -0
  323. package/dist/exports/serializeExports.js +17 -0
  324. package/dist/extensions/consts.d.ts +1 -0
  325. package/dist/extensions/consts.js +1 -0
  326. package/dist/extensions/declaredExtensions.d.ts +16 -0
  327. package/dist/extensions/declaredExtensions.js +57 -0
  328. package/dist/extensions/extensions.d.ts +21 -0
  329. package/dist/extensions/extensions.js +24 -0
  330. package/dist/extensions/lib/consts.d.ts +2 -0
  331. package/dist/extensions/lib/consts.js +2 -0
  332. package/dist/extensions/lib/validateSetup.d.ts +15 -0
  333. package/dist/extensions/lib/validateSetup.js +128 -0
  334. package/dist/extensions/loadExtensions.d.ts +14 -0
  335. package/dist/extensions/loadExtensions.js +146 -0
  336. package/dist/extensions/manifestViolations.d.ts +11 -0
  337. package/dist/extensions/manifestViolations.js +17 -0
  338. package/dist/fmt/formatDescriptors.d.ts +20 -0
  339. package/dist/fmt/formatDescriptors.js +67 -0
  340. package/dist/fmt/formatSource.d.ts +7 -0
  341. package/dist/fmt/formatSource.js +50 -0
  342. package/dist/init/consts.d.ts +1 -0
  343. package/dist/init/consts.js +1 -0
  344. package/dist/init/escapes.d.ts +2 -0
  345. package/dist/init/escapes.js +64 -0
  346. package/dist/init/init.d.ts +7 -0
  347. package/dist/init/init.js +151 -0
  348. package/dist/init/initCommand.d.ts +30 -0
  349. package/dist/init/initCommand.js +407 -0
  350. package/dist/init/initFootprint.d.ts +6 -0
  351. package/dist/init/initFootprint.js +19 -0
  352. package/dist/init/seedBlock.d.ts +7 -0
  353. package/dist/init/seedBlock.js +36 -0
  354. package/dist/install/applyInstall.d.ts +15 -0
  355. package/dist/install/applyInstall.js +180 -0
  356. package/dist/install/declaredDeps.d.ts +3 -0
  357. package/dist/install/declaredDeps.js +2 -0
  358. package/dist/install/indexFolder.d.ts +6 -0
  359. package/dist/install/indexFolder.js +32 -0
  360. package/dist/install/installCheckout.d.ts +15 -0
  361. package/dist/install/installCheckout.js +142 -0
  362. package/dist/install/installCommand.d.ts +15 -0
  363. package/dist/install/installCommand.js +55 -0
  364. package/dist/install/installModules.d.ts +17 -0
  365. package/dist/install/installModules.js +208 -0
  366. package/dist/install/installedModules.d.ts +12 -0
  367. package/dist/install/installedModules.js +27 -0
  368. package/dist/install/lib/readTarballManifest.d.ts +6 -0
  369. package/dist/install/lib/readTarballManifest.js +27 -0
  370. package/dist/install/npmAndCompile.d.ts +35 -0
  371. package/dist/install/npmAndCompile.js +151 -0
  372. package/dist/install/observeState.d.ts +28 -0
  373. package/dist/install/observeState.js +75 -0
  374. package/dist/install/planInstall.d.ts +9 -0
  375. package/dist/install/planInstall.js +63 -0
  376. package/dist/install/presetMembers.d.ts +17 -0
  377. package/dist/install/presetMembers.js +25 -0
  378. package/dist/install/readHookInput.d.ts +17 -0
  379. package/dist/install/readHookInput.js +29 -0
  380. package/dist/install/readSpecManifest.d.ts +12 -0
  381. package/dist/install/readSpecManifest.js +55 -0
  382. package/dist/install/readStdin.d.ts +12 -0
  383. package/dist/install/readStdin.js +25 -0
  384. package/dist/install/resolveClosure.d.ts +21 -0
  385. package/dist/install/resolveClosure.js +69 -0
  386. package/dist/install/resolves.d.ts +8 -0
  387. package/dist/install/resolves.js +9 -0
  388. package/dist/install/types.d.ts +26 -0
  389. package/dist/install/types.js +1 -0
  390. package/dist/install/versions.d.ts +12 -0
  391. package/dist/install/versions.js +25 -0
  392. package/dist/lib/alreadyThat.d.ts +5 -0
  393. package/dist/lib/alreadyThat.js +8 -0
  394. package/dist/lib/appendMissing.d.ts +1 -0
  395. package/dist/lib/appendMissing.js +7 -0
  396. package/dist/lib/atomicWrite.d.ts +1 -0
  397. package/dist/lib/atomicWrite.js +9 -0
  398. package/dist/lib/baseDescriptorSource.d.ts +18 -0
  399. package/dist/lib/baseDescriptorSource.js +52 -0
  400. package/dist/lib/childEnv.d.ts +12 -0
  401. package/dist/lib/childEnv.js +16 -0
  402. package/dist/lib/collectionSourceFile.d.ts +26 -0
  403. package/dist/lib/collectionSourceFile.js +56 -0
  404. package/dist/lib/consts.d.ts +93 -0
  405. package/dist/lib/consts.js +180 -0
  406. package/dist/lib/dryRunPlan.d.ts +21 -0
  407. package/dist/lib/dryRunPlan.js +23 -0
  408. package/dist/lib/editWorkspacePkg.d.ts +8 -0
  409. package/dist/lib/editWorkspacePkg.js +19 -0
  410. package/dist/lib/emit.d.ts +32 -0
  411. package/dist/lib/emit.js +46 -0
  412. package/dist/lib/emitDocument.d.ts +6 -0
  413. package/dist/lib/emitDocument.js +61 -0
  414. package/dist/lib/endOf.d.ts +11 -0
  415. package/dist/lib/endOf.js +25 -0
  416. package/dist/lib/escapeRe.d.ts +2 -0
  417. package/dist/lib/escapeRe.js +2 -0
  418. package/dist/lib/fieldFromFlags.d.ts +13 -0
  419. package/dist/lib/fieldFromFlags.js +195 -0
  420. package/dist/lib/gatedTreeOp.d.ts +30 -0
  421. package/dist/lib/gatedTreeOp.js +59 -0
  422. package/dist/lib/git/commitArg.d.ts +1 -0
  423. package/dist/lib/git/commitArg.js +13 -0
  424. package/dist/lib/git/defaultGit.d.ts +1 -0
  425. package/dist/lib/git/defaultGit.js +20 -0
  426. package/dist/lib/git/describeCheckout.d.ts +9 -0
  427. package/dist/lib/git/describeCheckout.js +45 -0
  428. package/dist/lib/git/gitOk.d.ts +2 -0
  429. package/dist/lib/git/gitOk.js +11 -0
  430. package/dist/lib/git/inProgress.d.ts +5 -0
  431. package/dist/lib/git/inProgress.js +28 -0
  432. package/dist/lib/git/repoRootOf.d.ts +6 -0
  433. package/dist/lib/git/repoRootOf.js +20 -0
  434. package/dist/lib/git/tryGit.d.ts +1 -0
  435. package/dist/lib/git/tryGit.js +10 -0
  436. package/dist/lib/isEntityKind.d.ts +2 -0
  437. package/dist/lib/isEntityKind.js +3 -0
  438. package/dist/lib/nearest.d.ts +5 -0
  439. package/dist/lib/nearest.js +21 -0
  440. package/dist/lib/need.d.ts +1 -0
  441. package/dist/lib/need.js +5 -0
  442. package/dist/lib/npm/exact.d.ts +5 -0
  443. package/dist/lib/npm/exact.js +5 -0
  444. package/dist/lib/npm/npmFloor.d.ts +2 -0
  445. package/dist/lib/npm/npmFloor.js +18 -0
  446. package/dist/lib/npm/resolveNpm.d.ts +10 -0
  447. package/dist/lib/npm/resolveNpm.js +35 -0
  448. package/dist/lib/npm/satisfies.d.ts +11 -0
  449. package/dist/lib/npm/satisfies.js +66 -0
  450. package/dist/lib/oneValue.d.ts +7 -0
  451. package/dist/lib/oneValue.js +12 -0
  452. package/dist/lib/pairs.d.ts +5 -0
  453. package/dist/lib/pairs.js +15 -0
  454. package/dist/lib/parseArgs.d.ts +17 -0
  455. package/dist/lib/parseArgs.js +36 -0
  456. package/dist/lib/refuseUnknownFlags.d.ts +3 -0
  457. package/dist/lib/refuseUnknownFlags.js +53 -0
  458. package/dist/lib/rel.d.ts +1 -0
  459. package/dist/lib/rel.js +3 -0
  460. package/dist/lib/schema-ops.d.ts +105 -0
  461. package/dist/lib/schema-ops.js +177 -0
  462. package/dist/lib/singular.d.ts +1 -0
  463. package/dist/lib/singular.js +23 -0
  464. package/dist/lib/stripMeta.d.ts +2 -0
  465. package/dist/lib/stripMeta.js +2 -0
  466. package/dist/lib/symlinkBelow.d.ts +13 -0
  467. package/dist/lib/symlinkBelow.js +33 -0
  468. package/dist/lib/types.d.ts +22 -0
  469. package/dist/lib/types.js +1 -0
  470. package/dist/lib/walk.d.ts +5 -0
  471. package/dist/lib/walk.js +21 -0
  472. package/dist/lib/writeSource.d.ts +7 -0
  473. package/dist/lib/writeSource.js +77 -0
  474. package/dist/lib/yaml.d.ts +18 -0
  475. package/dist/lib/yaml.js +26 -0
  476. package/dist/modules/createModule.d.ts +16 -0
  477. package/dist/modules/createModule.js +136 -0
  478. package/dist/modules/lib/consts.d.ts +10 -0
  479. package/dist/modules/lib/consts.js +17 -0
  480. package/dist/modules/lib/extensionText.d.ts +3 -0
  481. package/dist/modules/lib/extensionText.js +36 -0
  482. package/dist/modules/lib/readmeText.d.ts +6 -0
  483. package/dist/modules/lib/readmeText.js +25 -0
  484. package/dist/modules/lib/scaffoldKey.d.ts +2 -0
  485. package/dist/modules/lib/scaffoldKey.js +2 -0
  486. package/dist/modules/lib/testText.d.ts +7 -0
  487. package/dist/modules/lib/testText.js +19 -0
  488. package/dist/modules/modulesCommand.d.ts +4 -0
  489. package/dist/modules/modulesCommand.js +121 -0
  490. package/dist/modules/removeModule.d.ts +25 -0
  491. package/dist/modules/removeModule.js +91 -0
  492. package/dist/modules/renameModule.d.ts +15 -0
  493. package/dist/modules/renameModule.js +102 -0
  494. package/dist/modules/runModuleScript.d.ts +16 -0
  495. package/dist/modules/runModuleScript.js +99 -0
  496. package/dist/modules/setModule.d.ts +9 -0
  497. package/dist/modules/setModule.js +88 -0
  498. package/dist/openWorkspace.d.ts +12 -0
  499. package/dist/openWorkspace.js +22 -0
  500. package/dist/record/bodyField.d.ts +2 -0
  501. package/dist/record/bodyField.js +4 -0
  502. package/dist/record/collectRefFields.d.ts +3 -0
  503. package/dist/record/collectRefFields.js +16 -0
  504. package/dist/record/consts.d.ts +43 -0
  505. package/dist/record/consts.js +85 -0
  506. package/dist/record/descriptor.d.ts +44 -0
  507. package/dist/record/descriptor.js +56 -0
  508. package/dist/record/displayOf.d.ts +3 -0
  509. package/dist/record/displayOf.js +13 -0
  510. package/dist/record/expectedMirrors.d.ts +10 -0
  511. package/dist/record/expectedMirrors.js +27 -0
  512. package/dist/record/exportsContext.d.ts +9 -0
  513. package/dist/record/exportsContext.js +34 -0
  514. package/dist/record/fields.d.ts +9 -0
  515. package/dist/record/fields.js +30 -0
  516. package/dist/record/idFromRecordPath.d.ts +16 -0
  517. package/dist/record/idFromRecordPath.js +28 -0
  518. package/dist/record/lib/applyFilter.d.ts +5 -0
  519. package/dist/record/lib/applyFilter.js +32 -0
  520. package/dist/record/lib/consts.d.ts +7 -0
  521. package/dist/record/lib/consts.js +7 -0
  522. package/dist/record/lib/enumChoices.d.ts +2 -0
  523. package/dist/record/lib/enumChoices.js +16 -0
  524. package/dist/record/lib/fmtDate.d.ts +1 -0
  525. package/dist/record/lib/fmtDate.js +18 -0
  526. package/dist/record/lib/placedChildAt.d.ts +10 -0
  527. package/dist/record/lib/placedChildAt.js +25 -0
  528. package/dist/record/lib/rootRecords.d.ts +8 -0
  529. package/dist/record/lib/rootRecords.js +37 -0
  530. package/dist/record/lib/types.d.ts +6 -0
  531. package/dist/record/lib/types.js +1 -0
  532. package/dist/record/namespace.d.ts +22 -0
  533. package/dist/record/namespace.js +36 -0
  534. package/dist/record/nav.d.ts +41 -0
  535. package/dist/record/nav.js +237 -0
  536. package/dist/record/normalizeNamespaces.d.ts +8 -0
  537. package/dist/record/normalizeNamespaces.js +20 -0
  538. package/dist/record/outsideRefs.d.ts +19 -0
  539. package/dist/record/outsideRefs.js +34 -0
  540. package/dist/record/ownerIdOf.d.ts +11 -0
  541. package/dist/record/ownerIdOf.js +12 -0
  542. package/dist/record/parentFolders.d.ts +6 -0
  543. package/dist/record/parentFolders.js +18 -0
  544. package/dist/record/parseRecordText.d.ts +2 -0
  545. package/dist/record/parseRecordText.js +19 -0
  546. package/dist/record/parseRef.d.ts +11 -0
  547. package/dist/record/parseRef.js +27 -0
  548. package/dist/record/parseTemplate.d.ts +3 -0
  549. package/dist/record/parseTemplate.js +24 -0
  550. package/dist/record/pathToRecord.d.ts +9 -0
  551. package/dist/record/pathToRecord.js +38 -0
  552. package/dist/record/placedRecords.d.ts +8 -0
  553. package/dist/record/placedRecords.js +22 -0
  554. package/dist/record/placement.d.ts +15 -0
  555. package/dist/record/placement.js +19 -0
  556. package/dist/record/presentation.d.ts +3 -0
  557. package/dist/record/presentation.js +236 -0
  558. package/dist/record/readExports.d.ts +2 -0
  559. package/dist/record/readExports.js +14 -0
  560. package/dist/record/records.d.ts +15 -0
  561. package/dist/record/records.js +53 -0
  562. package/dist/record/ref.d.ts +12 -0
  563. package/dist/record/ref.js +26 -0
  564. package/dist/record/regenerate.d.ts +17 -0
  565. package/dist/record/regenerate.js +56 -0
  566. package/dist/record/relationsOf.d.ts +3 -0
  567. package/dist/record/relationsOf.js +33 -0
  568. package/dist/record/renderDisplay.d.ts +13 -0
  569. package/dist/record/renderDisplay.js +33 -0
  570. package/dist/record/sees.d.ts +6 -0
  571. package/dist/record/sees.js +7 -0
  572. package/dist/record/serialize.d.ts +2 -0
  573. package/dist/record/serialize.js +35 -0
  574. package/dist/record/splitRef.d.ts +10 -0
  575. package/dist/record/splitRef.js +23 -0
  576. package/dist/record/storageOf.d.ts +3 -0
  577. package/dist/record/storageOf.js +34 -0
  578. package/dist/record/template.d.ts +12 -0
  579. package/dist/record/template.js +28 -0
  580. package/dist/record/temporal.d.ts +2 -0
  581. package/dist/record/temporal.js +8 -0
  582. package/dist/record/types.d.ts +73 -0
  583. package/dist/record/types.js +1 -0
  584. package/dist/record/unknownOperators.d.ts +5 -0
  585. package/dist/record/unknownOperators.js +25 -0
  586. package/dist/record/unknownTokens.d.ts +5 -0
  587. package/dist/record/unknownTokens.js +17 -0
  588. package/dist/record/validateTemplate.d.ts +14 -0
  589. package/dist/record/validateTemplate.js +36 -0
  590. package/dist/record/valuesAt.d.ts +2 -0
  591. package/dist/record/valuesAt.js +11 -0
  592. package/dist/records/commandsFor.d.ts +18 -0
  593. package/dist/records/commandsFor.js +65 -0
  594. package/dist/records/distinctValues.d.ts +16 -0
  595. package/dist/records/distinctValues.js +63 -0
  596. package/dist/records/history.d.ts +19 -0
  597. package/dist/records/history.js +35 -0
  598. package/dist/records/historyDiff.d.ts +7 -0
  599. package/dist/records/historyDiff.js +14 -0
  600. package/dist/records/lib/coerceArrays.d.ts +3 -0
  601. package/dist/records/lib/coerceArrays.js +26 -0
  602. package/dist/records/lib/compareValues.d.ts +8 -0
  603. package/dist/records/lib/compareValues.js +21 -0
  604. package/dist/records/lib/consts.d.ts +3 -0
  605. package/dist/records/lib/consts.js +3 -0
  606. package/dist/records/lib/contributedNotes.d.ts +14 -0
  607. package/dist/records/lib/contributedNotes.js +28 -0
  608. package/dist/records/lib/fmtCell.d.ts +1 -0
  609. package/dist/records/lib/fmtCell.js +1 -0
  610. package/dist/records/lib/keyBetween.d.ts +2 -0
  611. package/dist/records/lib/keyBetween.js +4 -0
  612. package/dist/records/lib/landedIn.d.ts +9 -0
  613. package/dist/records/lib/landedIn.js +13 -0
  614. package/dist/records/lib/listColumns.d.ts +3 -0
  615. package/dist/records/lib/listColumns.js +6 -0
  616. package/dist/records/lib/looseEq.d.ts +6 -0
  617. package/dist/records/lib/looseEq.js +6 -0
  618. package/dist/records/lib/matchesFilter.d.ts +2 -0
  619. package/dist/records/lib/matchesFilter.js +151 -0
  620. package/dist/records/lib/narrowRows.d.ts +16 -0
  621. package/dist/records/lib/narrowRows.js +79 -0
  622. package/dist/records/lib/parseTemporal.d.ts +9 -0
  623. package/dist/records/lib/parseTemporal.js +27 -0
  624. package/dist/records/lib/placementKey.d.ts +12 -0
  625. package/dist/records/lib/placementKey.js +31 -0
  626. package/dist/records/lib/recordResolver.d.ts +8 -0
  627. package/dist/records/lib/recordResolver.js +35 -0
  628. package/dist/records/lib/sortRows.d.ts +6 -0
  629. package/dist/records/lib/sortRows.js +20 -0
  630. package/dist/records/lib/sourceHintFor.d.ts +3 -0
  631. package/dist/records/lib/sourceHintFor.js +12 -0
  632. package/dist/records/lib/tokenValue.d.ts +3 -0
  633. package/dist/records/lib/tokenValue.js +17 -0
  634. package/dist/records/lib/trackedPaths.d.ts +14 -0
  635. package/dist/records/lib/trackedPaths.js +29 -0
  636. package/dist/records/lib/whereKeys.d.ts +8 -0
  637. package/dist/records/lib/whereKeys.js +2 -0
  638. package/dist/records/nextCommand.d.ts +4 -0
  639. package/dist/records/nextCommand.js +53 -0
  640. package/dist/records/recordsCommand.d.ts +7 -0
  641. package/dist/records/recordsCommand.js +291 -0
  642. package/dist/records-api.d.ts +42 -0
  643. package/dist/records-api.js +41 -0
  644. package/dist/repos/lib/relPath.d.ts +1 -0
  645. package/dist/repos/lib/relPath.js +5 -0
  646. package/dist/repos/lib/repoPath.d.ts +3 -0
  647. package/dist/repos/lib/repoPath.js +11 -0
  648. package/dist/repos/listRepos.d.ts +12 -0
  649. package/dist/repos/listRepos.js +28 -0
  650. package/dist/repos/materializeRepo.d.ts +9 -0
  651. package/dist/repos/materializeRepo.js +26 -0
  652. package/dist/repos/repos.d.ts +14 -0
  653. package/dist/repos/repos.js +17 -0
  654. package/dist/repos/reposCommand.d.ts +4 -0
  655. package/dist/repos/reposCommand.js +28 -0
  656. package/dist/repos/types.d.ts +29 -0
  657. package/dist/repos/types.js +1 -0
  658. package/dist/runtime/consts.d.ts +12 -0
  659. package/dist/runtime/consts.js +12 -0
  660. package/dist/runtime/exportsFacts.d.ts +5 -0
  661. package/dist/runtime/exportsFacts.js +6 -0
  662. package/dist/runtime/loadDescriptors.d.ts +8 -0
  663. package/dist/runtime/loadDescriptors.js +46 -0
  664. package/dist/runtime/runtime.d.ts +35 -0
  665. package/dist/runtime/runtime.js +66 -0
  666. package/dist/runtime/sourceRoots.d.ts +10 -0
  667. package/dist/runtime/sourceRoots.js +22 -0
  668. package/dist/scripts/migrate-descriptors-v2.js +1248 -0
  669. package/dist/scripts/migrate-stubs.js +152 -0
  670. package/dist/setup/consts.d.ts +2 -0
  671. package/dist/setup/consts.js +2 -0
  672. package/dist/setup/fillInputs.d.ts +28 -0
  673. package/dist/setup/fillInputs.js +142 -0
  674. package/dist/setup/fold.d.ts +6 -0
  675. package/dist/setup/fold.js +30 -0
  676. package/dist/setup/lib/consent.d.ts +9 -0
  677. package/dist/setup/lib/consent.js +14 -0
  678. package/dist/setup/lib/env-write.d.ts +6 -0
  679. package/dist/setup/lib/env-write.js +10 -0
  680. package/dist/setup/lib/envSpans.d.ts +17 -0
  681. package/dist/setup/lib/envSpans.js +27 -0
  682. package/dist/setup/lib/fingerprint.d.ts +2 -0
  683. package/dist/setup/lib/fingerprint.js +21 -0
  684. package/dist/setup/lib/gitExposure.d.ts +8 -0
  685. package/dist/setup/lib/gitExposure.js +50 -0
  686. package/dist/setup/lib/judgeEnvAction.d.ts +25 -0
  687. package/dist/setup/lib/judgeEnvAction.js +60 -0
  688. package/dist/setup/lib/leftoverTemps.d.ts +2 -0
  689. package/dist/setup/lib/leftoverTemps.js +15 -0
  690. package/dist/setup/lib/redact.d.ts +7 -0
  691. package/dist/setup/lib/redact.js +28 -0
  692. package/dist/setup/lib/secretPathProblem.d.ts +2 -0
  693. package/dist/setup/lib/secretPathProblem.js +16 -0
  694. package/dist/setup/lib/setEnvValues.d.ts +12 -0
  695. package/dist/setup/lib/setEnvValues.js +57 -0
  696. package/dist/setup/lib/setup-contract.d.ts +5 -0
  697. package/dist/setup/lib/setup-contract.js +2 -0
  698. package/dist/setup/lib/validateEnvAction.d.ts +16 -0
  699. package/dist/setup/lib/validateEnvAction.js +25 -0
  700. package/dist/setup/lib/writeEnvAtomic.d.ts +7 -0
  701. package/dist/setup/lib/writeEnvAtomic.js +60 -0
  702. package/dist/setup/parseAllow.d.ts +8 -0
  703. package/dist/setup/parseAllow.js +20 -0
  704. package/dist/setup/parseInputFlags.d.ts +3 -0
  705. package/dist/setup/parseInputFlags.js +17 -0
  706. package/dist/setup/printUnitResults.d.ts +3 -0
  707. package/dist/setup/printUnitResults.js +23 -0
  708. package/dist/setup/renderStatusLines.d.ts +2 -0
  709. package/dist/setup/renderStatusLines.js +14 -0
  710. package/dist/setup/runUnit.d.ts +21 -0
  711. package/dist/setup/runUnit.js +204 -0
  712. package/dist/setup/safeInspect.d.ts +7 -0
  713. package/dist/setup/safeInspect.js +28 -0
  714. package/dist/setup/setup.d.ts +14 -0
  715. package/dist/setup/setup.js +28 -0
  716. package/dist/setup/setupAndCommit.d.ts +28 -0
  717. package/dist/setup/setupAndCommit.js +103 -0
  718. package/dist/setup/statusLines.d.ts +6 -0
  719. package/dist/setup/statusLines.js +90 -0
  720. package/dist/setup/ttyIO.d.ts +5 -0
  721. package/dist/setup/ttyIO.js +25 -0
  722. package/dist/setup/types.d.ts +65 -0
  723. package/dist/setup/types.js +1 -0
  724. package/dist/setup/unitEnvFor.d.ts +11 -0
  725. package/dist/setup/unitEnvFor.js +29 -0
  726. package/dist/setup/units.d.ts +4 -0
  727. package/dist/setup/units.js +7 -0
  728. package/dist/statusCommand.d.ts +2 -0
  729. package/dist/statusCommand.js +168 -0
  730. package/dist/store/Store.d.ts +543 -0
  731. package/dist/store/Store.js +710 -0
  732. package/dist/store/add.d.ts +14 -0
  733. package/dist/store/add.js +92 -0
  734. package/dist/store/addFile.d.ts +7 -0
  735. package/dist/store/addFile.js +43 -0
  736. package/dist/store/addedDates.d.ts +2 -0
  737. package/dist/store/addedDates.js +44 -0
  738. package/dist/store/createdOf.d.ts +3 -0
  739. package/dist/store/createdOf.js +20 -0
  740. package/dist/store/external.d.ts +6 -0
  741. package/dist/store/external.js +8 -0
  742. package/dist/store/findInboundRefs.d.ts +2 -0
  743. package/dist/store/findInboundRefs.js +13 -0
  744. package/dist/store/gitHead.d.ts +2 -0
  745. package/dist/store/gitHead.js +13 -0
  746. package/dist/store/ids.d.ts +2 -0
  747. package/dist/store/ids.js +19 -0
  748. package/dist/store/lib/applyMirrorEdits.d.ts +7 -0
  749. package/dist/store/lib/applyMirrorEdits.js +124 -0
  750. package/dist/store/lib/assertUnambiguous.d.ts +2 -0
  751. package/dist/store/lib/assertUnambiguous.js +11 -0
  752. package/dist/store/lib/checkRefs.d.ts +4 -0
  753. package/dist/store/lib/checkRefs.js +62 -0
  754. package/dist/store/lib/commit.d.ts +3 -0
  755. package/dist/store/lib/commit.js +37 -0
  756. package/dist/store/lib/commitIn.d.ts +3 -0
  757. package/dist/store/lib/commitIn.js +37 -0
  758. package/dist/store/lib/dirTreeStamps.d.ts +7 -0
  759. package/dist/store/lib/dirTreeStamps.js +33 -0
  760. package/dist/store/lib/filePath.d.ts +3 -0
  761. package/dist/store/lib/filePath.js +32 -0
  762. package/dist/store/lib/generateId.d.ts +4 -0
  763. package/dist/store/lib/generateId.js +72 -0
  764. package/dist/store/lib/gitDateToStamp.d.ts +6 -0
  765. package/dist/store/lib/gitDateToStamp.js +8 -0
  766. package/dist/store/lib/idsKey.d.ts +3 -0
  767. package/dist/store/lib/idsKey.js +22 -0
  768. package/dist/store/lib/indexAdd.d.ts +5 -0
  769. package/dist/store/lib/indexAdd.js +39 -0
  770. package/dist/store/lib/mirrorRemedy.d.ts +19 -0
  771. package/dist/store/lib/mirrorRemedy.js +24 -0
  772. package/dist/store/lib/moveRecord.d.ts +4 -0
  773. package/dist/store/lib/moveRecord.js +29 -0
  774. package/dist/store/lib/normalizeRecord.d.ts +2 -0
  775. package/dist/store/lib/normalizeRecord.js +28 -0
  776. package/dist/store/lib/normalizeTemporal.d.ts +10 -0
  777. package/dist/store/lib/normalizeTemporal.js +38 -0
  778. package/dist/store/lib/pathAt.d.ts +3 -0
  779. package/dist/store/lib/pathAt.js +29 -0
  780. package/dist/store/lib/placedChildrenIn.d.ts +8 -0
  781. package/dist/store/lib/placedChildrenIn.js +18 -0
  782. package/dist/store/lib/placementOfFile.d.ts +11 -0
  783. package/dist/store/lib/placementOfFile.js +20 -0
  784. package/dist/store/lib/pruneEmptyDirs.d.ts +8 -0
  785. package/dist/store/lib/pruneEmptyDirs.js +20 -0
  786. package/dist/store/lib/qualifyBareRefs.d.ts +3 -0
  787. package/dist/store/lib/qualifyBareRefs.js +16 -0
  788. package/dist/store/lib/recordFileName.d.ts +3 -0
  789. package/dist/store/lib/recordFileName.js +6 -0
  790. package/dist/store/lib/refuseDuplicateValues.d.ts +3 -0
  791. package/dist/store/lib/refuseDuplicateValues.js +16 -0
  792. package/dist/store/lib/refuseEngineWrites.d.ts +3 -0
  793. package/dist/store/lib/refuseEngineWrites.js +12 -0
  794. package/dist/store/lib/refuseMirrorWrites.d.ts +2 -0
  795. package/dist/store/lib/refuseMirrorWrites.js +8 -0
  796. package/dist/store/lib/snapshot.d.ts +17 -0
  797. package/dist/store/lib/snapshot.js +60 -0
  798. package/dist/store/lib/validate.d.ts +5 -0
  799. package/dist/store/lib/validate.js +33 -0
  800. package/dist/store/lib/walkIds.d.ts +3 -0
  801. package/dist/store/lib/walkIds.js +31 -0
  802. package/dist/store/lib/walkRoot.d.ts +3 -0
  803. package/dist/store/lib/walkRoot.js +24 -0
  804. package/dist/store/lib/writableDescriptor.d.ts +3 -0
  805. package/dist/store/lib/writableDescriptor.js +15 -0
  806. package/dist/store/recordFiles.d.ts +2 -0
  807. package/dist/store/recordFiles.js +24 -0
  808. package/dist/store/recordRoot.d.ts +3 -0
  809. package/dist/store/recordRoot.js +19 -0
  810. package/dist/store/relocate.d.ts +9 -0
  811. package/dist/store/relocate.js +52 -0
  812. package/dist/store/relocatePlan.d.ts +5 -0
  813. package/dist/store/relocatePlan.js +79 -0
  814. package/dist/store/rename.d.ts +8 -0
  815. package/dist/store/rename.js +86 -0
  816. package/dist/store/revert.d.ts +7 -0
  817. package/dist/store/revert.js +86 -0
  818. package/dist/store/rewriteRefsBatch.d.ts +3 -0
  819. package/dist/store/rewriteRefsBatch.js +142 -0
  820. package/dist/store/rm.d.ts +7 -0
  821. package/dist/store/rm.js +187 -0
  822. package/dist/store/set.d.ts +6 -0
  823. package/dist/store/set.js +80 -0
  824. package/dist/store/types.d.ts +35 -0
  825. package/dist/store/types.js +1 -0
  826. package/dist/store/vouched.d.ts +13 -0
  827. package/dist/store/vouched.js +30 -0
  828. package/dist/store/withWriteLock.d.ts +2 -0
  829. package/dist/store/withWriteLock.js +40 -0
  830. package/dist/store/writeLockPath.d.ts +2 -0
  831. package/dist/store/writeLockPath.js +20 -0
  832. package/dist/targetCommand.d.ts +2 -0
  833. package/dist/targetCommand.js +45 -0
  834. package/dist/testing.d.ts +23 -0
  835. package/dist/testing.js +85 -0
  836. package/dist/types.d.ts +665 -0
  837. package/dist/types.js +1 -0
  838. package/dist/ui-views/lib/assignPath.d.ts +17 -0
  839. package/dist/ui-views/lib/assignPath.js +34 -0
  840. package/dist/ui-views/lib/assignViewValue.d.ts +5 -0
  841. package/dist/ui-views/lib/assignViewValue.js +9 -0
  842. package/dist/ui-views/lib/consts.d.ts +21 -0
  843. package/dist/ui-views/lib/consts.js +27 -0
  844. package/dist/ui-views/lib/parseViewValue.d.ts +6 -0
  845. package/dist/ui-views/lib/parseViewValue.js +50 -0
  846. package/dist/ui-views/lib/viewOverlayOf.d.ts +2 -0
  847. package/dist/ui-views/lib/viewOverlayOf.js +19 -0
  848. package/dist/ui-views/moveUiView.d.ts +31 -0
  849. package/dist/ui-views/moveUiView.js +56 -0
  850. package/dist/ui-views/removeUiView.d.ts +6 -0
  851. package/dist/ui-views/removeUiView.js +17 -0
  852. package/dist/ui-views/saveUiView.d.ts +25 -0
  853. package/dist/ui-views/saveUiView.js +80 -0
  854. package/dist/ui-views/uiViewsCommand.d.ts +4 -0
  855. package/dist/ui-views/uiViewsCommand.js +118 -0
  856. package/dist/update/parseUpdateArgs.d.ts +9 -0
  857. package/dist/update/parseUpdateArgs.js +32 -0
  858. package/dist/update/updateModules.d.ts +19 -0
  859. package/dist/update/updateModules.js +221 -0
  860. package/dist/update-setup.d.ts +1 -0
  861. package/dist/update-setup.js +14 -0
  862. package/dist/usage.d.ts +1 -0
  863. package/dist/usage.js +271 -0
  864. package/dist/workspace/commitByRepo.d.ts +4 -0
  865. package/dist/workspace/commitByRepo.js +51 -0
  866. package/dist/workspace/discoverModules.d.ts +21 -0
  867. package/dist/workspace/discoverModules.js +85 -0
  868. package/dist/workspace/envContext.d.ts +3 -0
  869. package/dist/workspace/envContext.js +11 -0
  870. package/dist/workspace/findWorkspace.d.ts +2 -0
  871. package/dist/workspace/findWorkspace.js +49 -0
  872. package/dist/workspace/lib/aheadCount.d.ts +6 -0
  873. package/dist/workspace/lib/aheadCount.js +29 -0
  874. package/dist/workspace/lib/assertCommentsKept.d.ts +16 -0
  875. package/dist/workspace/lib/assertCommentsKept.js +27 -0
  876. package/dist/workspace/lib/isTracked.d.ts +2 -0
  877. package/dist/workspace/lib/isTracked.js +14 -0
  878. package/dist/workspace/lib/shortHead.d.ts +1 -0
  879. package/dist/workspace/lib/shortHead.js +10 -0
  880. package/dist/workspace/moduleRows.d.ts +7 -0
  881. package/dist/workspace/moduleRows.js +9 -0
  882. package/dist/workspace/navFragments.d.ts +54 -0
  883. package/dist/workspace/navFragments.js +223 -0
  884. package/dist/workspace/parseEnvValues.d.ts +1 -0
  885. package/dist/workspace/parseEnvValues.js +13 -0
  886. package/dist/workspace/renderTemplate.d.ts +2 -0
  887. package/dist/workspace/renderTemplate.js +26 -0
  888. package/dist/workspace/reportCommits.d.ts +10 -0
  889. package/dist/workspace/reportCommits.js +18 -0
  890. package/dist/workspace/types.d.ts +85 -0
  891. package/dist/workspace/types.js +1 -0
  892. package/dist/workspace/writeGated.d.ts +9 -0
  893. package/dist/workspace/writeGated.js +128 -0
  894. package/package.json +45 -22
  895. package/skills/using-dreamteamer/SKILL.md +10 -11
  896. package/skills/using-dreamteamer/references/before-you-build.md +2 -2
  897. package/skills/using-dreamteamer/references/changes.md +6 -7
  898. package/skills/using-dreamteamer/references/collections.md +22 -91
  899. package/skills/using-dreamteamer/references/records.md +1 -2
  900. package/skills/using-dreamteamer/references/skills.md +7 -0
  901. package/skills/using-dreamteamer/references/writing-a-module.md +14 -0
  902. package/scripts/migrate-descriptors-v2.mjs +0 -795
  903. package/scripts/migrate-stubs.mjs +0 -98
  904. package/src/api.d.ts +0 -154
  905. package/src/api.js +0 -109
  906. package/src/check-alone.js +0 -171
  907. package/src/check.js +0 -427
  908. package/src/checkout.js +0 -705
  909. package/src/cli.js +0 -1000
  910. package/src/collections-cli.js +0 -1352
  911. package/src/commit.js +0 -611
  912. package/src/compile-collections.js +0 -481
  913. package/src/compile.js +0 -1511
  914. package/src/descriptor-v2.js +0 -167
  915. package/src/descriptor.js +0 -99
  916. package/src/doctor.js +0 -69
  917. package/src/env-vars.js +0 -59
  918. package/src/env-write.js +0 -162
  919. package/src/events.js +0 -204
  920. package/src/exports-cli.js +0 -91
  921. package/src/exports.js +0 -162
  922. package/src/extensions.js +0 -228
  923. package/src/field-values.js +0 -70
  924. package/src/fields.js +0 -255
  925. package/src/filter.js +0 -154
  926. package/src/fractional-index.js +0 -44
  927. package/src/harnesses.js +0 -649
  928. package/src/history.js +0 -90
  929. package/src/init.js +0 -473
  930. package/src/install-modules.js +0 -450
  931. package/src/namespace.js +0 -215
  932. package/src/nav-fragments.js +0 -190
  933. package/src/nav.js +0 -185
  934. package/src/placement.js +0 -219
  935. package/src/presentation.js +0 -182
  936. package/src/record-commands.js +0 -94
  937. package/src/records-api.d.ts +0 -210
  938. package/src/records-api.js +0 -41
  939. package/src/records.js +0 -109
  940. package/src/ref.js +0 -39
  941. package/src/relations.js +0 -62
  942. package/src/runtime.js +0 -160
  943. package/src/scaffold-templates.js +0 -85
  944. package/src/schema-ops.js +0 -2959
  945. package/src/semver.js +0 -36
  946. package/src/setup-contract.js +0 -101
  947. package/src/setup.js +0 -518
  948. package/src/store.js +0 -1964
  949. package/src/template.js +0 -201
  950. package/src/temporal.js +0 -157
  951. package/src/testing.d.ts +0 -29
  952. package/src/testing.js +0 -86
  953. package/src/unread-data.js +0 -74
  954. package/src/update-setup.js +0 -22
  955. package/src/update.js +0 -139
  956. package/src/views.js +0 -206
  957. package/src/workspace.js +0 -253
  958. package/src/yaml.js +0 -251
package/src/schema-ops.js DELETED
@@ -1,2959 +0,0 @@
1
- // schema operations — source-writing mutations shared by the CLI meta verbs and the
2
- // server's schema endpoints. the contract (audit finding 11, clean-room bug 2): an op
3
- // writes sources, proves them with a REAL compile, and only then commits — an
4
- // uncompilable source can never land in history. the successful gate compile also
5
- // leaves the runtime fresh, which kills the add-field-right-after-collections-add
6
- // papercut (review finding 7): schema ops ARE explicit compiles.
7
- import fs from 'node:fs';
8
- import path from 'node:path';
9
- import { execFileSync } from 'node:child_process';
10
- import { load, dump, writeSource, renameKeys, commentCount, formatSource } from './yaml.js';
11
- import { compile, kindDir, KINDS, repoRootOf, discoverModules } from './compile.js';
12
- import { V2_KEYS, isV2 } from './descriptor-v2.js';
13
- import { v1Refusal } from './compile-collections.js';
14
- import { readManifest, loadDescriptors, engineId } from './runtime.js';
15
- import { normalizeNamespaces, namespaceOf, baseNameOf, qualify, defaultStoragePath, singular } from './namespace.js';
16
- import { fieldsOf, targetsOf, storageOf, isRuntime, bodyFieldOf, moduleOf } from './descriptor.js';
17
- import { SCALAR_TYPES, enumValues, INJECTED_FIELDS } from './fields.js';
18
- import { FIELD_OPTIONS, TEMPLATE_OPTIONS, viewOverlayOf } from './views.js';
19
-
20
- // Same rule as store.js: a git failure we CATCH must not also print git's own error on top of the
21
- // clean message we throw. stdout stays piped because some callers read it.
22
- const GIT_QUIET = ['ignore', 'pipe', 'ignore'];
23
- import { walk, idFromRecordPath, parseRecord, EXT } from './records.js';
24
- import { Store, serialize, atomicWrite } from './store.js';
25
- import { readmeText, extensionText, testText, scaffoldKey } from './scaffold-templates.js';
26
-
27
- // ---- the gate -------------------------------------------------------------------
28
-
29
- /**
30
- * A SOURCE WRITE MAY NOT SILENTLY LOSE A COMMENT — the invariant that would have caught the
31
- * re-serialization bug on the first rename instead of the twenty-seventh.
32
- *
33
- * A module source is where this project writes down WHY a collection exists, and every gate it had
34
- * was blind to losing that: the schema is unchanged, so `compile` and `check` both stay green while
35
- * the reasoning is deleted. Counting comment lines is crude on purpose — it is structural, it costs
36
- * one pass over bytes already in hand, and it fails the op rather than reporting it afterwards.
37
- *
38
- * ⚠ THE OPT-OUT IS REAL AND NARROW. `rm-field` takes the comment ABOVE the field with the field,
39
- * which is the correct outcome and a decrease; so does deleting a file. Those ops say so explicitly
40
- * (`commentsMayDecrease`) rather than being exempted by a heuristic that would also excuse a bug.
41
- */
42
- function assertCommentsKept(ws, snapshots) {
43
- for (const { f, prev } of snapshots) {
44
- if (prev === null || !fs.existsSync(f)) continue;
45
- const before = commentCount(prev.toString('utf8'));
46
- const after = commentCount(fs.readFileSync(f, 'utf8'));
47
- if (after >= before) continue;
48
- throw new Error(`${path.relative(ws.root, f)} would lose ${before - after} comment line(s) — a source write may not delete a module's own reasoning. Nothing was changed.`);
49
- }
50
- }
51
-
52
- function writeGated(ws, store, files, subject, mutate, after, { commentsMayDecrease = false } = {}) {
53
- // same guarantees as record writes (docs-audit catch): the STORE's cross-process lock
54
- // serializes schema ops too, and a failed git commit rolls the source back — a schema
55
- // op fails closed exactly like a record mutation.
56
- return store.withWriteLock(() => {
57
- const snapshots = files.map((f) => ({ f, prev: fs.existsSync(f) ? fs.readFileSync(f) : null }));
58
- const restore = () => {
59
- for (const { f, prev } of snapshots) {
60
- if (prev === null) fs.rmSync(f, { force: true });
61
- else fs.writeFileSync(f, prev);
62
- }
63
- };
64
- mutate();
65
- if (!commentsMayDecrease) {
66
- try {
67
- assertCommentsKept(ws, snapshots);
68
- } catch (e) {
69
- restore();
70
- throw e;
71
- }
72
- }
73
- try {
74
- compile(ws); // dry-run that doubles as the materialization — throws CompileError on bad sources
75
- } catch (e) {
76
- restore();
77
- try { compile(ws); } catch { /* runtime was already broken before this op */ }
78
- // ⚠ THE ROLLBACK IS THE HALF THE OPERATOR CANNOT SEE. compile's sentence is correct and
79
- // names the missing declaration; what it cannot know is that a verb just undid itself over
80
- // it. The commonest case by far is an overlay write into a module that does not yet declare
81
- // its base, so the remedy is spelled as the verb that fixes it — §13. The module names in
82
- // compile's sentence are PACKAGE names while `dt set modules/<id>` takes an ID; for anything
83
- // `add modules` created they are the same string, for a forked module they are not.
84
- const dep = /an overlay of "[^"]+", but module "([^"]+)" neither depends on "([^"]+)"/.exec(e.message);
85
- if (dep) {
86
- const idOf = (pkgName) => moduleRows(store).find((r) => r.fields.name === pkgName)?.id ?? pkgName;
87
- throw new Error(`${e.message}\n rolled back — dt set modules/${idOf(dep[1])} dependencies=modules/${idOf(dep[2])}, then re-run`);
88
- }
89
- throw e;
90
- }
91
- // ⚠ AFTER THE GATE COMPILE, BEFORE THE COMMIT, INSIDE THE LOCK. A schema op that INVALIDATES
92
- // DATA cleans that data up in the same act — see dropOrphanedMirrors for the case this exists
93
- // for. It has to run after the compile because it reads the NEW runtime to decide what is
94
- // residue, and before the commit because a source change and the data repair it forces are one
95
- // change. It fails the whole op like anything else here: nothing half-done.
96
- let extra = { files: [], undo: () => {}, dropped: [], cleared: 0 };
97
- if (after) {
98
- try {
99
- extra = { ...extra, ...after() };
100
- } catch (e) {
101
- restore();
102
- try { compile(ws); } catch { /* nothing else moved */ }
103
- throw e;
104
- }
105
- }
106
- // ⚠ A WRITE THAT CHANGED NO BYTES MUST NOT REACH `git commit`. `git commit` on an empty index
107
- // exits NON-ZERO, so the catch below read a successful no-op as a failed op and reported
108
- // `✖ git commit failed — the schema change was rolled back` with the raw git command appended,
109
- // at exit 1 — for `dt set collections/people description=<the value it already has>`, which
110
- // asked for nothing and got nothing. Every sibling verb already has the graceful spelling
111
- // ("already named that, nothing to do"), and the documented namespace cleanup path
112
- // (`dt set modules/<m> namespaces=<ns>` where it is already declared) ran straight into it.
113
- //
114
- // Compared as BYTES, after the gate compile: an op whose mutation is a re-serialization can
115
- // produce an identical file, and "identical" is the only definition of no-op the caller can
116
- // act on.
117
- const moved = snapshots.some(({ f, prev }) => {
118
- const now = fs.existsSync(f) ? fs.readFileSync(f) : null;
119
- return now === null ? prev !== null : prev === null || !now.equals(prev);
120
- });
121
- if (!moved && !extra.files.length) return { ...extra, commits: [], unchanged: true };
122
- const rels = [...files, ...extra.files].map((f) => path.relative(ws.root, f));
123
- // Schema ops commit UNCONDITIONALLY — `auto-commit` governs RECORD writes only. A source
124
- // change is inseparable from the compile that validated it, and `dt commit` scopes itself
125
- // to record directories, so a deferred source edit would be publishable by nothing.
126
- // Extending `dt commit` to module sources is the natural follow-on; it is not this wave.
127
- //
128
- // ⚠ IN THE REPO THAT HOLDS THE SOURCE, not at the workspace root — see commitByRepo for what
129
- // running it at the root cost a git-shape module.
130
- let commits;
131
- try {
132
- commits = commitByRepo(ws, store, rels, subject);
133
- } catch (e) {
134
- extra.undo();
135
- restore();
136
- try { compile(ws); } catch { /* pre-op sources were compilable */ }
137
- const landed = (e.commits ?? []).length
138
- ? ` (${e.commits.map((c) => `${c.repo} already committed as ${c.sha}`).join('; ')} — that commit stands; two repos cannot commit atomically)`
139
- : '';
140
- throw new Error(`git commit failed — the schema change was rolled back, nothing was changed.${landed} (${e.message.split('\n')[0]})`);
141
- }
142
- // The hook's own report, for the caller to print: what a source change did to DATA is not
143
- // visible in the file list, and a silent data change is a different act from a reported one.
144
- return { ...extra, commits };
145
- });
146
- }
147
-
148
- /** The compile half of the gate, under the same lock, with no source write and no commit — for a
149
- * schema op that turns out to ask for what is already on disk. Materializing `.dreamteamer/` is the
150
- * point rather than a side effect: the caller is about to report success, and success has always
151
- * meant "the compiled runtime is valid and current". */
152
- function compileGated(ws, store) {
153
- return store.withWriteLock(() => compile(ws));
154
- }
155
-
156
- /**
157
- * THE GATE FOR AN OP WHOSE MUTATION IS NOT A SET OF FILE WRITES — a folder move, a delete, several
158
- * package.json edits at once.
159
- *
160
- * `writeGated` snapshots BYTES per file, which cannot express any of those: a directory hands
161
- * `readFileSync` an EISDIR, and a pathspec naming only one file inside a deleted tree commits one
162
- * deletion and leaves the rest staged-but-uncommitted. So the caller supplies its own `undo` and
163
- * this owns the ORDER, which is the part that must not be re-derived per op: mutate → compile →
164
- * commit, and on any failure undo, recompile, rethrow.
165
- *
166
- * Same cross-process write lock, same "nothing half-done" contract, same `headMoved()` after a
167
- * commit. `renameCollection` is the precedent — it has carried its own copy of this block since it
168
- * needed to move a record folder, and this is that block with the mutation lifted out.
169
- *
170
- * `mutate()` may return `{ paths }` to extend the commit pathspec with files it discovered; its
171
- * return value is what this returns.
172
- */
173
- export function gatedTreeOp(ws, store, { subject, paths, mutate, undo }) {
174
- return store.withWriteLock(() => {
175
- let out;
176
- try {
177
- out = mutate() ?? {};
178
- compile(ws); // the gate: an uncompilable change never reaches history
179
- } catch (e) {
180
- undo();
181
- try { compile(ws); } catch { /* pre-op sources were compilable */ }
182
- throw e;
183
- }
184
- // ⚠ NO PATHSPEC FILTER HERE ANY MORE. `commitByRepo` does it per repo, which is the correct
185
- // place: `isTracked` has to run in the repo that would track the path, and running it at the
186
- // workspace root answered "no" for every path inside a clone.
187
- const rels = [...new Set([...paths, ...(out.paths ?? [])])];
188
- try {
189
- out.commits = commitByRepo(ws, store, rels, subject);
190
- } catch (e) {
191
- undo();
192
- try { compile(ws); } catch { /* pre-op sources were compilable */ }
193
- const landed = (e.commits ?? []).length
194
- ? ` (${e.commits.map((c) => `${c.repo} already committed as ${c.sha}`).join('; ')} — that commit stands)`
195
- : '';
196
- throw new Error(`git commit failed — ${subject} was rolled back, nothing was changed.${landed} (${e.message.split('\n')[0]})`);
197
- }
198
- return out;
199
- });
200
- }
201
-
202
- /**
203
- * `dt fmt [<collection>]` — rewrite descriptor and mixin sources in block style with their top-level
204
- * keys in canonical order (`formatSource`). One collection's sources, or every inline source.
205
- *
206
- * A source under `git_modules/` or `node_modules/` belongs to another repo and is only counted: it
207
- * is formatted there. A v1 source is refused, every one listed, before anything is written. The
208
- * write goes through `writeGated` — comment guard, compile gate, one commit per repo.
209
- * @returns {{ changed: string[], unchanged: number, skipped: string[], commits?: object[] }}
210
- */
211
- export function formatDescriptors(ws, { collection = null, dryRun = false } = {}) {
212
- const roots = [{ root: ws.root, channel: 'inline' }, ...discoverModules(ws.root, ws.pkg).modules];
213
- const rel = (f) => path.relative(ws.root, f);
214
- const sources = [], skipped = [];
215
- for (const { root, channel } of roots) {
216
- for (const [kind, suffix] of [['collections', '.collection.yaml'], ['mixins', '.mixin.yaml']]) {
217
- const dir = kindDir(root, kind);
218
- if ((collection && kind === 'mixins') || !fs.existsSync(dir)) continue;
219
- for (const file of [...walk(dir)].filter((f) => f.endsWith(suffix))) {
220
- const text = fs.readFileSync(file, 'utf8');
221
- let doc;
222
- try { doc = load(text); } catch (e) { throw new Error(`${rel(file)}: ${e.message.split('\n')[0]} — fix the YAML, then re-run dt fmt`); }
223
- if (collection && doc?.name !== collection) continue;
224
- (channel === 'inline' ? sources : skipped).push({ file, text, doc, kind });
225
- }
226
- }
227
- }
228
- if (collection && !sources.length && !skipped.length) throw new Error(`no source declares collection "${collection}" — dt list collections names them`);
229
- const v1 = sources.filter((s) => s.kind === 'collections' && !isV2(s.doc)).map((s) => rel(s.file));
230
- if (v1.length) throw new Error(v1Refusal(v1.sort()));
231
- const edits = sources.map((s) => ({ ...s, out: formatSource(s.text, V2_KEYS) })).filter((s) => s.out !== s.text);
232
- const result = { changed: edits.map((s) => rel(s.file)), unchanged: sources.length - edits.length, skipped: skipped.map((s) => rel(s.file)) };
233
- if (dryRun || !edits.length) return result;
234
- const out = writeGated(ws, new Store(ws), edits.map((s) => s.file), `dreamteamer: fmt ${edits.length} descriptor source(s)`,
235
- () => { for (const s of edits) fs.writeFileSync(s.file, s.out); });
236
- return { ...result, commits: out.commits };
237
- }
238
-
239
- // ---- modules ---------------------------------------------------------------------------------
240
- // A module is THREE-SPELLED today: the package `name` (discovery, `dependencies`), the
241
- // folder (the `workspace_module` key), and the slugged scope-stripped record id. The RECORD ID is
242
- // the identity everywhere the operator types it — `--module <id>`, `modules/<id>` references,
243
- // `dependencies` values — and the engine maps id → package name internally. `add modules` sets all
244
- // three to one string so a new module never forks; an existing forked module keeps working, and
245
- // `dt list modules` prints all three columns so the fork is visible.
246
-
247
- /** A module id: the same id-safe alphabet a namespace segment uses, because it becomes a folder
248
- * name, a package name and a record id at once. */
249
- const MODULE_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
250
-
251
- /** Every module as `{ id, fields }`, off the compiled projection — the one enumeration, so `--module`
252
- * validation, the "known:" list and the id→package-name map cannot disagree. */
253
- function moduleRows(store) {
254
- if (!store.descriptors.has('modules')) return [];
255
- return [...store.readAll('modules')].map((r) => ({ id: r.id, fields: r.fields }));
256
- }
257
-
258
- /** One module, or the refusal §13 requires: `no module "nope" — known: core, hr, default (dt list
259
- * modules). A module is named by its id.` */
260
- export function moduleRecord(store, id) {
261
- const rows = moduleRows(store);
262
- const hit = rows.find((r) => r.id === id);
263
- if (hit) return hit;
264
- throw new Error(`no module "${id}" — known: ${rows.map((r) => r.id).join(', ') || 'none'} (dt list modules). A module is named by its id.`);
265
- }
266
-
267
- /** id → the package `name` its sources actually spell, which is what `dependencies` and `disable`
268
- * are written in. Equal to the id for anything `add modules` created. */
269
- const packageNameOf = (store, id) => moduleRecord(store, id).fields.name;
270
-
271
- /** A module's own package.json, absolute. */
272
- function modulePkgFile(ws, store, id) {
273
- return path.join(ws.root, moduleRecord(store, id).fields.path, 'package.json');
274
- }
275
-
276
- /** Read → mutate the `dreamteamer` section → write, preserving every other key and the tab
277
- * indentation `init` uses. Returns the file path so a caller can put it in a pathspec. */
278
- function editModulePkg(file, mutate) {
279
- const pkg = JSON.parse(fs.readFileSync(file, 'utf8'));
280
- pkg.dreamteamer ??= {};
281
- mutate(pkg.dreamteamer, pkg);
282
- fs.writeFileSync(file, JSON.stringify(pkg, null, '\t') + '\n');
283
- return file;
284
- }
285
-
286
- /** The workspace's own package.json, read → mutate → write. `ws.pkg` is refreshed in place because
287
- * `compile({root, pkg})` reads the object it was handed, not the file — a rename that moved
288
- * `workspace_module` and did not do this compiled the PREVIOUS layout and failed on a stray-sources
289
- * error naming a module that no longer exists. */
290
- function editWorkspacePkg(ws, mutate) {
291
- const file = path.join(ws.root, 'package.json');
292
- const pkg = JSON.parse(fs.readFileSync(file, 'utf8'));
293
- pkg.dreamteamer ??= {};
294
- mutate(pkg.dreamteamer, pkg);
295
- fs.writeFileSync(file, JSON.stringify(pkg, null, '\t') + '\n');
296
- for (const k of Object.keys(ws.pkg)) delete ws.pkg[k];
297
- Object.assign(ws.pkg, pkg);
298
- return file;
299
- }
300
-
301
- const NPM_NAME = /^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
302
- const ENGINE_VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
303
-
304
- export function createModule(ws, store, { name, description, namespace, extension = false, pkg: pkgName = null }) {
305
- if (!name || name === true) throw new Error('missing module name — dreamteamer add modules --name <id>');
306
- if (pkgName === true) throw new Error('--package takes the npm name: dreamteamer add modules --name <id> --package @scope/<id>');
307
- if (pkgName && (pkgName.length > 214 || !NPM_NAME.test(pkgName))) throw new Error(`"${pkgName}" is not an npm package name — lowercase, URL-safe, optionally @scope/name`);
308
- if (extension && !/^[a-z]/.test(name)) throw new Error(`--extension needs a module id that starts with a letter — "${name}" becomes the setup unit's id and its env key (${scaffoldKey(name)}), and both must start with one`);
309
- if (pkgName) {
310
- const holder = discoverModules(ws.root, ws.pkg).modules.find((m) => { try { return JSON.parse(fs.readFileSync(path.join(m.root, 'package.json'), 'utf8')).name === pkgName; } catch { return false; } });
311
- if (holder) throw new Error(`${pkgName} is already the package name of ${path.relative(ws.root, holder.root) || holder.root} — two modules under one name would shadow each other; pick another --package`);
312
- }
313
- if (!MODULE_ID.test(name)) {
314
- throw new Error(`invalid module id "${name}" — lowercase alphanumeric with single hyphens. It becomes a folder name, a package name and a record id at once, so there is only one spelling.`);
315
- }
316
- const rows = moduleRows(store);
317
- const clash = rows.find((r) => r.id === name);
318
- if (clash) throw new Error(`module "${name}" already exists (${clash.fields.path}) — dt list modules`);
319
- const root = path.join(ws.root, 'modules', name);
320
- if (fs.existsSync(root)) throw new Error(`modules/${name} already exists on disk — remove it or pick another id`);
321
-
322
- const dt = {};
323
- if (typeof description === 'string' && description) dt.description = description;
324
- // §6.2: `--namespace hr` DECLARES THE NAMESPACE IN THE MODULE, which is the whole point of §8 —
325
- // the workspace's effective set is the union of what its modules declare, so a module that owns a
326
- // namespace can be copied alone into a bare workspace and still compile.
327
- //
328
- // ⚠ It used to be dropped on the floor. `dt add modules --name hr --namespace hr` reported ✔,
329
- // shipped `"dreamteamer": {}`, left the manifest's `namespaces: []`, and the next
330
- // `add collections --module hr` then created an UNPREFIXED collection — four steps of silence
331
- // behind one accepted-and-ignored flag. Normalized here rather than trusted: a leading or
332
- // trailing slash in a declaration re-splits every reference under it.
333
- const ns = typeof namespace === 'string' ? namespace.replace(/^\/+|\/+$/g, '') : '';
334
- if (ns) {
335
- const owner = moduleRows(store).find((r) => normalizeNamespaces(r.fields.namespaces).includes(ns));
336
- // compile refuses two declarations of one namespace, and refusing it HERE names the verb that
337
- // fixes it instead of rolling a created module back over a compile error.
338
- if (owner) throw new Error(`namespace "${ns}" is already declared by ${owner.id} — one owner. Remove it there first (dt set modules/${owner.id} namespaces=…), or pick another namespace.`);
339
- dt.namespaces = [ns];
340
- }
341
- // `files` is the npm publish surface: every kind a module CAN ship, so a kind added to the engine
342
- // does not silently stop being packaged.
343
- // `engine` is the floor the module is written against: the engine that scaffolded it (cr-dt-007)
344
- dt.engine = `>=${ENGINE_VERSION}`;
345
- if (extension) { dt.extension = './src/extension.js'; dt.env = [scaffoldKey(name)]; }
346
- const files = [...KINDS, ...(extension ? ['src'] : []), 'README.md'];
347
- // `--package` makes it publishable: its npm name (the module id stays the folder), a first version,
348
- // and the engine as a devDependency for its own tests — never `dependencies`, which would nest a second engine (D66)
349
- const mpkg = pkgName
350
- ? { name: pkgName, version: '0.1.0', type: 'module', files, scripts: { test: 'node --test' }, devDependencies: { dreamteamer: ENGINE_VERSION }, dreamteamer: dt }
351
- : { name, private: true, version: '0.0.1', type: 'module', files, scripts: { test: 'node --test' }, dreamteamer: dt };
352
- const pkgFile = path.join(root, 'package.json');
353
- const written = { 'README.md': readmeText({ id: name, pkgName: mpkg.name, description, extension }), 'test/module.test.mjs': testText({ id: name }), ...(extension ? { 'src/extension.js': extensionText({ id: name }) } : {}) };
354
-
355
- const out = gatedTreeOp(ws, store, {
356
- subject: `dreamteamer: modules add ${name}`,
357
- // compile regenerates .env.example from the declared keys, so a module that declares one (--extension)
358
- // changes it — it rides in the same commit rather than being left modified outside it
359
- paths: [path.relative(ws.root, pkgFile), ...Object.keys(written).map((f) => path.relative(ws.root, path.join(root, f))), ...(extension && fs.existsSync(path.join(ws.root, '.env.example')) ? ['.env.example'] : [])],
360
- mutate: () => {
361
- // ⚠ SCAFFOLD EVERY KIND FOLDER. Not decoration: it is what makes the module's shape
362
- // self-documenting the moment it exists, and compile's "contributed no recognised sources"
363
- // warning is taught to read a scaffolded folder as a module being authored (see compile.js)
364
- // rather than as a mistake — a verb whose own output triggers a warning reads as broken.
365
- // git cannot track an empty directory, so only package.json is in the pathspec.
366
- for (const kind of KINDS) fs.mkdirSync(path.join(root, kind), { recursive: true });
367
- fs.writeFileSync(pkgFile, JSON.stringify(mpkg, null, '\t') + '\n');
368
- for (const [f, text] of Object.entries(written)) { fs.mkdirSync(path.dirname(path.join(root, f)), { recursive: true }); fs.writeFileSync(path.join(root, f), text); }
369
- },
370
- undo: () => fs.rmSync(root, { recursive: true, force: true }),
371
- });
372
- return { id: name, root: path.relative(ws.root, root), file: pkgFile, files: ['package.json', ...Object.keys(written)], namespace: ns || null, commits: out.commits };
373
- }
374
-
375
- /** The settable fields of a `modules` record, and how each translates from the record-shaped value
376
- * the operator types to the form the source file uses. */
377
- const MODULE_SETTABLE = {
378
- description: { key: 'description', from: (v) => String(v) },
379
- dependencies: { key: 'dependencies', from: (v, store) => asList(v).map((r) => moduleIdFromRef(r, store)) },
380
- // the collections a module references but does not own — names, never references, in the source
381
- peer_collections: { key: 'peer_collections', from: (v) => asList(v).map((r) => String(r).replace(/^collections\//, '')) },
382
- // §8. A namespace is a plain name, not a reference — there is no `namespaces` collection and
383
- // there should not be: the value's whole job is to be parseable before anything has compiled.
384
- namespaces: { key: 'namespaces', from: (v) => asList(v).map((x) => x.replace(/^\/+|\/+$/g, '')).filter(Boolean) },
385
- };
386
-
387
- const asList = (v) => (Array.isArray(v) ? v : String(v).split(',')).map((s) => String(s).trim()).filter(Boolean);
388
-
389
- /** `modules/core` → the package name `core` spells. A bare `core` is accepted and named as a
390
- * mistake-in-waiting rather than silently: a reference VALUE is `<collection>/<id>` everywhere else
391
- * in this engine, and `check` rejects the bare form. */
392
- function moduleIdFromRef(ref, store) {
393
- const s = String(ref);
394
- if (!s.startsWith('modules/')) {
395
- throw new Error(`dependencies takes record-shaped values — write "modules/${s}", not "${s}" (a reference is <collection>/<id> everywhere in this engine).`);
396
- }
397
- return packageNameOf(store, s.slice('modules/'.length));
398
- }
399
-
400
- export function setModule(ws, store, id, changes) {
401
- const rec = moduleRecord(store, id);
402
- const unknown = Object.keys(changes).filter((k) => !(k in MODULE_SETTABLE));
403
- if (unknown.length) {
404
- throw new Error(`"${unknown[0]}" is not a settable field of modules — settable: ${Object.keys(MODULE_SETTABLE).join(', ')}. Everything else on a module record is PROJECTED by compile from its package.json.`);
405
- }
406
- const file = path.join(ws.root, rec.fields.path, 'package.json');
407
- if (IN_NODE_MODULES(rec.fields.path)) {
408
- throw new Error(`module "${id}" ships from node_modules (${rec.fields.path}) — a write there is erased by the next \`npm install\`. Vendor it into modules/ or install it as a git module.`);
409
- }
410
- const changed = [];
411
- // ⚠ THE WORKSPACE'S REDUNDANT COPY GOES IN THE SAME WRITE. Declaring a namespace on the module
412
- // is what makes the workspace-level entry redundant, and compile WARNS about it — so leaving it
413
- // behind makes the warning permanent and the fix a second command nobody is told to run.
414
- const wsFile = path.join(ws.root, 'package.json');
415
- const files = 'namespaces' in changes ? [file, wsFile] : [file];
416
- const gate = writeGated(ws, store, files, `dreamteamer: modules set ${id}`, () => {
417
- let declared = [];
418
- editModulePkg(file, (dt) => {
419
- for (const [k, raw] of Object.entries(changes)) {
420
- const spec = MODULE_SETTABLE[k];
421
- // An empty value REMOVES the key — the same convention `store.set` has always had for a
422
- // record field, extended to the package.json a module record is projected from.
423
- if (raw === '' || raw === null) { delete dt[spec.key]; changed.push(k); continue; }
424
- const value = spec.from(raw, store);
425
- if (Array.isArray(value) && !value.length) { delete dt[spec.key]; changed.push(k); continue; }
426
- dt[spec.key] = value;
427
- changed.push(k);
428
- if (k === 'namespaces') declared = value;
429
- }
430
- });
431
- if (declared.length) {
432
- editWorkspacePkg(ws, (dt) => {
433
- if (!Array.isArray(dt.namespaces)) return;
434
- dt.namespaces = dt.namespaces.filter((n) => !declared.includes(String(n).replace(/^\/+|\/+$/g, '')));
435
- if (!dt.namespaces.length) delete dt.namespaces;
436
- });
437
- }
438
- }, undefined, { commentsMayDecrease: true });
439
- return { id, file, changed, commits: gate.commits, unchanged: gate.unchanged };
440
- }
441
-
442
- export function removeModule(ws, store, id, { force = false, dryRun = false } = {}) {
443
- const { fields } = moduleRecord(store, id);
444
- if (fields.location === 'node_modules') {
445
- throw new Error(`module "${id}" is installed by npm (${fields.path}) — remove it from package.json dependencies and run \`npm install\`; a delete under node_modules/ is erased by the next install.`);
446
- }
447
- if (fields.location === 'git_modules') {
448
- throw new Error(`module "${id}" is a clone under ${fields.path}, and its package.json lives in ANOTHER repo — remove it from dreamteamer.git_modules and delete the clone. This verb removes inline modules only.`);
449
- }
450
- if (ws.pkg.dreamteamer?.workspace_module === id) {
451
- throw new Error(`module "${id}" IS this workspace's own module (dreamteamer.workspace_module) — removing it would leave the workspace with no sources of its own. Point workspace_module at another module first.`);
452
- }
453
- const shipped = (fields.collections ?? []).map((r) => String(r).replace(/^collections\//, '')).sort();
454
- // A collection the module OWNS (`owns_data`, or its own `storage.owner: module`) keeps its records
455
- // inside the module folder, so removing the sources would take the records with them.
456
- const inside = shipped.filter((c) => store.descriptors.has(c) && `${storageOf(store.descriptor(c)).path}/`.startsWith(`${fields.path}/`) && store.ids(c).size > 0);
457
- if (inside.length) {
458
- throw new Error(`module "${id}" keeps the records of ${inside.join(', ')} INSIDE ${fields.path}/data — removing the module would delete them, which this verb never does. Move the records out first (drop owns_data, or the collection's storage.owner).`);
459
- }
460
- const withRecords = shipped.filter((c) => store.descriptors.has(c) && store.ids(c).size > 0);
461
- // A `dependencies` entry naming this module in ANOTHER module fails the gate compile ("depends
462
- // on X, which is not installed"), so it goes in the SAME write — otherwise --force is a verb that
463
- // cannot succeed. peer_collections names COLLECTIONS and needs no edit: a peer whose provider is
464
- // gone is exactly what `unresolved_peers` exists to excuse.
465
- const pkgName = fields.name;
466
- const dependents = moduleRows(store)
467
- .filter((r) => r.id !== id && (r.fields.dependencies ?? []).includes(`modules/${id}`))
468
- .map((r) => r.id);
469
- const plan = {
470
- collections: shipped, withRecords, dependents,
471
- records: 0, refs: 0, descriptors: shipped.length,
472
- cleared: 0,
473
- };
474
- // ⚠ THE DRY RUN COMES FIRST, BEFORE THE --force REFUSAL. A dry run writes nothing, so refusing
475
- // it for the want of a flag is pure friction — and it is the WRONG WAY ROUND: the plan is what
476
- // the operator reads to decide whether `--force` is a thing they want to type.
477
- if (dryRun) return { ...plan, dryRun: true };
478
- if (shipped.length && !force) {
479
- throw new Error(`${id} still ships ${shipped.length} collection${shipped.length === 1 ? '' : 's'} (${shipped.join(', ')}), ${withRecords.length} with records. --force removes the sources; records stay and become unindexed.`);
480
- }
481
-
482
- const root = path.join(ws.root, 'modules', id);
483
- // ⚠ STASH, DO NOT DELETE, UNTIL THE COMMIT LANDS. `gatedTreeOp`'s `undo` has to be able to put the
484
- // whole tree back, and a `rmSync` cannot be undone. `.dreamteamer/` is gitignored and on the same
485
- // device (a cross-device rename would fail), and compile only ever removes the kind folders and
486
- // `system/`/`ui/` by name — a dot-prefixed sibling survives it.
487
- const stash = path.join(ws.root, '.dreamteamer', `.rm-module-${id}`);
488
- const depFiles = dependents.map((m) => modulePkgFile(ws, store, m));
489
- const depBytes = new Map(depFiles.map((f) => [f, fs.readFileSync(f)]));
490
- fs.rmSync(stash, { recursive: true, force: true });
491
-
492
- let out;
493
- try {
494
- out = gatedTreeOp(ws, store, {
495
- subject: `dreamteamer: modules rm ${id}`,
496
- paths: [path.relative(ws.root, root), ...depFiles.map((f) => path.relative(ws.root, f))],
497
- mutate: () => {
498
- for (const f of depFiles) {
499
- editModulePkg(f, (dt) => {
500
- dt.dependencies = (dt.dependencies ?? []).filter((n) => n !== pkgName);
501
- if (!dt.dependencies.length) delete dt.dependencies;
502
- });
503
- }
504
- fs.mkdirSync(path.dirname(stash), { recursive: true });
505
- fs.renameSync(root, stash);
506
- },
507
- undo: () => {
508
- if (fs.existsSync(stash)) fs.renameSync(stash, root);
509
- for (const [f, bytes] of depBytes) fs.writeFileSync(f, bytes);
510
- },
511
- });
512
- } finally {
513
- fs.rmSync(stash, { recursive: true, force: true });
514
- }
515
- return { removed: id, ...plan, commits: out.commits };
516
- }
517
-
518
- export function renameModule(ws, store, oldId, newId) {
519
- if (!newId || newId === true) throw new Error('missing new module id — dreamteamer rename modules/<old> <new>');
520
- if (oldId === newId) return { renamed: false, id: newId, files: [], rewrites: 0 };
521
- if (!MODULE_ID.test(newId)) throw new Error(`invalid module id "${newId}" — lowercase alphanumeric with single hyphens.`);
522
- const { fields } = moduleRecord(store, oldId);
523
- if (moduleRows(store).some((r) => r.id === newId)) throw new Error(`module "${newId}" already exists — dt list modules`);
524
- if (fields.location === 'node_modules') {
525
- throw new Error(`module "${oldId}" ships from node_modules (${fields.path}) — a write there is erased by the next \`npm install\`. Rename it in its own repo and release.`);
526
- }
527
- if (fields.location === 'git_modules') {
528
- // ⚠ TWO COMMITS BY CONSTRUCTION, and the verb says so rather than half-doing it: the module's
529
- // package.json lives in the clone's own repo, and this workspace's half (git_modules,
530
- // dependencies, modules/<id> refs) is a commit here. Perform the workspace half only after the
531
- // clone half has landed and been pushed.
532
- throw new Error(`module "${oldId}" is a clone under ${fields.path}, whose package.json is in ANOTHER repo — a git-shape rename is TWO commits by construction.\n 1. rename it there (package.json name → "${newId}") and push;\n 2. re-run this to perform the workspace half: dreamteamer.git_modules, every dependencies entry, and modules/${oldId} references.`);
533
- }
534
- const oldPkgName = fields.name;
535
- const oldRoot = path.join(ws.root, 'modules', oldId);
536
- const newRoot = path.join(ws.root, 'modules', newId);
537
- if (fs.existsSync(newRoot)) throw new Error(`modules/${newId} already exists on disk`);
538
-
539
- const snapshots = new Map(); // absolute file -> bytes, for undo
540
- const snap = (f) => { if (!snapshots.has(f) && fs.existsSync(f)) snapshots.set(f, fs.readFileSync(f)); return f; };
541
- const paths = new Set([`modules/${oldId}`, `modules/${newId}`, 'package.json']);
542
- let moved = false;
543
- let rewrites = 0;
544
- const undoRefs = [];
545
-
546
- const out = gatedTreeOp(ws, store, {
547
- subject: `dreamteamer: modules rename ${oldId} → ${newId}`,
548
- paths: [...paths],
549
- mutate: () => {
550
- // 1. the module's own record refs, BEFORE the folder moves — `store.rewriteRefsBatch`
551
- // resolves each collection's directory from the descriptors the Store was built with,
552
- // and those are still correct until compile re-runs.
553
- const refs = store.rewriteRefs(`modules/${oldId}`, `modules/${newId}`);
554
- undoRefs.push(refs.restore);
555
- rewrites += refs.rewrites;
556
- for (const f of refs.touched) paths.add(path.relative(ws.root, f));
557
-
558
- // 2. the folder, then its package.json `name`
559
- fs.renameSync(oldRoot, newRoot);
560
- moved = true;
561
- const ownPkg = path.join(newRoot, 'package.json');
562
- const ownBytes = fs.readFileSync(ownPkg);
563
- snapshots.set(path.join(oldRoot, 'package.json'), ownBytes); // restored after the un-move
564
- const own = JSON.parse(ownBytes.toString('utf8'));
565
- own.name = newId;
566
- fs.writeFileSync(ownPkg, JSON.stringify(own, null, '\t') + '\n');
567
-
568
- // 3. the WORKSPACE package.json: `workspace_module` when it names this module. `disable`
569
- // needs nothing: a `<kind>/<id>` entry names an entity, never its module, and a module a
570
- // `modules/<id>` entry drops is never discovered, so it cannot be the one renamed here.
571
- // SNAPSHOTTED FIRST — editWorkspacePkg writes, so capturing the pre-image afterwards is
572
- // impossible.
573
- snap(path.join(ws.root, 'package.json'));
574
- const wsFile = editWorkspacePkg(ws, (dt) => {
575
- if (dt.workspace_module === oldId) dt.workspace_module = newId;
576
- });
577
- paths.add(path.relative(ws.root, wsFile));
578
-
579
- // 4. every OTHER module's `dreamteamer.dependencies` naming it. peer_collections names
580
- // collections and is untouched.
581
- for (const r of moduleRows(store)) {
582
- if (r.id === oldId || r.fields.location === 'node_modules') continue;
583
- const f = path.join(ws.root, r.fields.path, 'package.json');
584
- if (!fs.existsSync(f)) continue;
585
- const dt = JSON.parse(fs.readFileSync(f, 'utf8')).dreamteamer ?? {};
586
- if (!(dt.dependencies ?? []).includes(oldPkgName)) continue;
587
- snap(f);
588
- editModulePkg(f, (d) => { d.dependencies = d.dependencies.map((n) => (n === oldPkgName ? newId : n)); });
589
- paths.add(path.relative(ws.root, f));
590
- rewrites++;
591
- }
592
-
593
- return { paths: [...paths] };
594
- },
595
- undo: () => {
596
- for (const u of [...undoRefs].reverse()) u();
597
- if (moved && fs.existsSync(newRoot)) fs.renameSync(newRoot, oldRoot);
598
- for (const [f, bytes] of snapshots) {
599
- fs.mkdirSync(path.dirname(f), { recursive: true });
600
- fs.writeFileSync(f, bytes);
601
- }
602
- // re-read the workspace package.json into ws.pkg, whatever it now says on disk
603
- editWorkspacePkg(ws, () => {});
604
- },
605
- });
606
- return { renamed: true, id: newId, files: out.paths ?? [], rewrites, commits: out.commits };
607
- }
608
-
609
- // ---- moving a collection between modules -------------------------------------------------------
610
- // §7. `dt set collections/teams module=hr` — NOT `move`/`reorder` (the nav's order is nav.yaml since 0.49). The descriptor
611
- // SOURCE relocates; the RECORDS do not, because a namespace and a `storage.path` are properties of
612
- // the collection rather than of the module, so a move never changes an id and never touches data.
613
-
614
- /**
615
- * WHAT THE MOVE WOULD MAKE ILLEGAL, and what the fix would cost — computed BEFORE anything moves.
616
- *
617
- * The reference contract says every collection a field references is owned by the
618
- * referencing module, declared in its `dependencies`, or named in its `peer_collections`. Moving a
619
- * collection changes who owns it, so it can break the contract in two directions at once: this
620
- * collection's own outbound refs, and every inbound ref pointing at it.
621
- *
622
- * ⚠ AND THE FIX CAN BE WORSE THAN THE BREAK. `dependencies` must be acyclic, so "add A to B's
623
- * dependencies" is only a fix when B does not already sit upstream of A — otherwise it is a ring,
624
- * and the honest answer is `peer_collections` (which names a COLLECTION and therefore cannot cycle)
625
- * or moving the other collection too. Naming the ring is the difference between a refusal an
626
- * operator can act on and one they have to re-derive.
627
- *
628
- * Reads the compiled projections through the Store rather than re-running discovery: `modules`
629
- * records carry `dependencies`, each compiled descriptor carries its `module`, and the manifest is
630
- * what actually compiled.
631
- */
632
- function moveImpact(store, name, toModule) {
633
- const mods = moduleRows(store);
634
- const depsOf = new Map(mods.map((m) => [m.id, (m.fields.dependencies ?? []).map((r) => String(r).replace(/^modules\//, ''))]));
635
- // the module RECORD's `peer_collections`, projected from package.json under the same name
636
- const peersOf = new Map(mods.map((m) => [m.id, (m.fields.peer_collections ?? []).map((r) => String(r).replace(/^collections\//, ''))]));
637
- const ownerOf = new Map();
638
- for (const [id, d] of store.descriptors) ownerOf.set(id, moduleOf(d));
639
- ownerOf.set(name, toModule); // the world as the move would leave it
640
-
641
- /** Does `from` reach `to` along `dependencies`? */
642
- const reaches = (from, to, seen = new Set()) => {
643
- if (from === to) return true;
644
- if (seen.has(from)) return false;
645
- seen.add(from);
646
- return (depsOf.get(from) ?? []).some((d) => reaches(d, to, seen));
647
- };
648
-
649
- const needs = [];
650
- const add = (referrer, target) => {
651
- const owner = ownerOf.get(target);
652
- if (!owner || owner === referrer) return;
653
- if ((depsOf.get(referrer) ?? []).includes(owner)) return;
654
- if ((peersOf.get(referrer) ?? []).includes(target)) return;
655
- // CORE_COLLECTIONS is an implicit dependency of every module — the entity kinds the compiler
656
- // materializes plus `repos`. Asked of the descriptor rather than of a list here: a
657
- // runtime-stored collection is exactly that set.
658
- if (isRuntime(store.descriptors.get(target)) || target === 'repos') return;
659
- needs.push({ referrer, target, owner, ring: reaches(owner, referrer) });
660
- };
661
-
662
- for (const [cName, d] of store.descriptors) {
663
- const referrer = ownerOf.get(cName);
664
- if (!referrer) continue;
665
- for (const target of outboundTargets(d)) {
666
- if (cName !== name && target !== name) continue; // only edges this move actually re-owns
667
- add(referrer, target);
668
- }
669
- }
670
- return needs;
671
- }
672
-
673
- /** Every collection a field of this descriptor references — a scalar or a union, on a top-level
674
- * field or inside an object's `fields`. `reference` (any record) names no collection, so it is
675
- * skipped: it is exempt from the reference contract by construction. */
676
- function outboundTargets(d) {
677
- const out = new Set();
678
- const walkFields = (fields) => {
679
- for (const f of Object.values(fields ?? {})) {
680
- const t = targetsOf(f);
681
- if (Array.isArray(t)) for (const x of t) out.add(x);
682
- if (f?.fields) walkFields(f.fields);
683
- }
684
- };
685
- walkFields(fieldsOf(d));
686
- return out;
687
- }
688
-
689
- export function moveCollection(ws, store, name, toModule, { dryRun = false } = {}) {
690
- const d = store.descriptor(name); // throws with the known-collection list
691
- if (isRuntime(d)) {
692
- throw new Error(`"${name}" is a compiled source, not a data collection — it has no module to move it to.`);
693
- }
694
- const to = moduleRecord(store, toModule); // throws with the known-module list
695
- const from = moduleOf(d);
696
- if (from === toModule) return { moved: false, name, from, to: toModule };
697
- if (IN_NODE_MODULES(to.fields.path)) {
698
- throw new Error(`module "${toModule}" ships from node_modules (${to.fields.path}) — a write there is erased by the next \`npm install\`. Vendor it into modules/ first.`);
699
- }
700
- const { base } = baseDescriptorSource(ws, name);
701
- if (!base) throw new Error(`"${name}" has no writable descriptor source in this workspace — the manifest names none under a module here.`);
702
- if (IN_NODE_MODULES(base)) {
703
- throw new Error(`"${name}" ships from node_modules (${base}) — a write there is erased by the next \`npm install\`. Add fields from your own module instead, which writes an overlay: dreamteamer add-field ${name} --module <your-module> …`);
704
- }
705
-
706
- // ---- the reference contract, BEFORE anything moves ------------------------------------------
707
- const needs = moveImpact(store, name, toModule);
708
- const plan = {
709
- name, from, to: toModule, needs,
710
- records: store.ids(name).size,
711
- refs: 0,
712
- // an overlay names the collection, never the module that owns it, so a move rewrites the base alone
713
- descriptors: 1,
714
- cleared: 0,
715
- };
716
- if (needs.length) {
717
- const lines = needs.map((n) => {
718
- const fix = n.ring
719
- ? `${n.referrer} → ${n.owner} would be a ring (${n.owner} already reaches ${n.referrer}). Add ${n.target} to ${n.referrer}'s peer_collections (dt set modules/${n.referrer} peer_collections=collections/${n.target}), or move ${n.target} as well.`
720
- : `add it: dt set modules/${n.referrer} dependencies=modules/${n.owner} — or dt set modules/${n.referrer} peer_collections=collections/${n.target} if ${n.referrer} should work without it.`;
721
- return ` ${n.referrer} references ${n.target}, owned by ${n.owner} after the move. ${fix}`;
722
- });
723
- throw new Error(`move rolled back. ${name} → ${toModule} breaks the reference contract:\n${lines.join('\n')}`);
724
- }
725
- if (dryRun) return { ...plan, moved: false, dryRun: true };
726
-
727
- const dest = path.join(kindDir(path.join(ws.root, to.fields.path), 'collections'), `${name}.collection.yaml`);
728
- if (fs.existsSync(dest)) throw new Error(`${path.relative(ws.root, dest)} already exists — move or remove it first; nothing was moved`);
729
- const src = path.join(ws.root, base);
730
- const fromRow = moduleRows(store).find((m) => m.id === from);
731
- // The floor `pruneEmpty` walks up to: the SOURCE MODULE'S OWN collections dir. Deriving it from
732
- // the path's first segment resolved to `<root>/modules`, which could delete the module's whole
733
- // `collections/` folder after its last collection left — re-triggering the "contributed no
734
- // recognised sources" warning for a module whose only kind folder that was.
735
- const pruneFloor = fromRow ? kindDir(path.join(ws.root, fromRow.fields.path), 'collections') : path.dirname(src);
736
-
737
- const snapshots = new Map([[src, fs.readFileSync(src)]]);
738
- const touched = new Set([base, path.relative(ws.root, dest)]);
739
- let moved = false;
740
-
741
- const out = gatedTreeOp(ws, store, {
742
- subject: `dreamteamer: collections set ${name} module=${toModule}`,
743
- paths: [...touched],
744
- mutate: () => {
745
- // 1. the descriptor itself. Its BYTES, not a re-dump: a descriptor's comments are where a
746
- // module writes down why the collection exists, and the move changes no key at all — the
747
- // file is identical, at a new path.
748
- fs.mkdirSync(path.dirname(dest), { recursive: true });
749
- fs.writeFileSync(dest, snapshots.get(src));
750
- fs.rmSync(src);
751
- pruneEmpty(path.dirname(src), pruneFloor);
752
- moved = true;
753
-
754
- return { paths: [...touched] };
755
- },
756
- undo: () => {
757
- if (moved && fs.existsSync(dest)) fs.rmSync(dest);
758
- for (const [f, bytes] of snapshots) {
759
- fs.mkdirSync(path.dirname(f), { recursive: true });
760
- fs.writeFileSync(f, bytes);
761
- }
762
- },
763
- });
764
- return { ...plan, moved: true, commits: out.commits };
765
- }
766
-
767
- /**
768
- * The collection-level keys `dt set collections/<c>` writes, each by its v2 path, and how each
769
- * parses. A dotted key is a position inside a block (`display.nav.icon=pulse`). `display.nav.order`
770
- * stays settable and compiles, but since 0.49 it moves no row — the nav's order is nav.yaml, and
771
- * `dt reorder collections/<c>` is refused saying so.
772
- *
773
- * ⚠ `name` is deliberately absent, and so are `fields`, `storage` and `ids`. Renaming a
774
- * collection moves its descriptor, its records, their filenames and every inbound reference in one
775
- * commit — that is `rename collections/<old> <new>`, and offering `name=` here would be a second
776
- * spelling for it that does one of those five things. Fields have verbs of their own.
777
- */
778
- const text = (v) => String(v);
779
- const bool = (k) => (v) => {
780
- if (v === true || v === 'true') return true;
781
- if (v === false || v === 'false') return false;
782
- // a privacy or visibility switch that coerces "yes" to false is the wrong kind of forgiving
783
- throw new Error(`${k} takes true or false — got "${v}"`);
784
- };
785
- const nameList = (v) => (Array.isArray(v) ? v : String(v).split(',')).map((x) => String(x).trim()).filter(Boolean);
786
- const COLLECTION_SETTABLE = {
787
- description: text,
788
- use_when: text,
789
- title: text,
790
- singular: text, // the word the CLI accepts beside the name; compile refuses a collision
791
- record_title: text,
792
- // `sensitive=true` withholds the WHOLE collection from every export
793
- sensitive: bool('sensitive'),
794
- // `internal=true` takes the collection out of the domain listing and onto a surface's schema
795
- // surface; where its records live and whether they can be written are unchanged
796
- internal: bool('internal'),
797
- 'display.nav.icon': text,
798
- 'display.nav.order': (v) => {
799
- const n = Number(v);
800
- if (!Number.isFinite(n)) throw new Error(`display.nav.order takes a number — got "${v}"`);
801
- return n;
802
- },
803
- 'display.nav.section': text,
804
- 'display.list.layout': text,
805
- 'display.list.columns': nameList,
806
- 'display.list.sort': text,
807
- 'display.record.layout': text,
808
- 'display.record.subtitle': text,
809
- 'display.record.badge': text,
810
- 'display.record.color_by': text,
811
- };
812
- /** A layout option, `display.list.options.<key>` or `display.record.options.<key>`: the block is open
813
- * (each layout reads its own keys), so the value is read as JSON where it parses — a number, a
814
- * boolean, a list — and as the string typed otherwise. */
815
- const OPTION_KEY = /^display\.(list|record)\.options\.[a-z][a-z0-9_]*$/;
816
- const optionValue = (v) => { if (typeof v !== 'string') return v; try { return JSON.parse(v); } catch { return v; } };
817
- const settableOf = (k) => COLLECTION_SETTABLE[k] ?? (OPTION_KEY.test(k) ? optionValue : undefined);
818
-
819
- /** "people has no field X" / "people has no fields X, Y" — the plural without a second sentence. */
820
- const collectionMissingFields = (name, missing) => `${name} has no field${missing.length === 1 ? '' : 's'} ${missing.join(', ')}`;
821
-
822
- /** Set a dotted path in a plain object, creating the blocks on the way. */
823
- function setPath(obj, dotted, value) {
824
- const keys = dotted.split('.');
825
- let at = obj;
826
- for (const k of keys.slice(0, -1)) {
827
- if (!at[k] || typeof at[k] !== 'object' || Array.isArray(at[k])) at[k] = {};
828
- at = at[k];
829
- }
830
- at[keys[keys.length - 1]] = value;
831
- }
832
-
833
- /** Delete a dotted path, and every block the deletion leaves empty — an empty `display.nav` is a
834
- * statement nobody made. */
835
- function deletePath(obj, dotted) {
836
- const keys = dotted.split('.');
837
- const trail = [obj];
838
- for (const k of keys.slice(0, -1)) {
839
- const next = trail[trail.length - 1]?.[k];
840
- if (!next || typeof next !== 'object') return;
841
- trail.push(next);
842
- }
843
- delete trail[trail.length - 1][keys[keys.length - 1]];
844
- for (let i = trail.length - 1; i > 0; i--) {
845
- if (Object.keys(trail[i]).length) break;
846
- delete trail[i - 1][keys[i - 1]];
847
- }
848
- }
849
-
850
- export function setCollectionScalars(ws, store, name, changes, { moduleId } = {}) {
851
- const d = store.descriptor(name);
852
- const unknown = Object.keys(changes).filter((k) => !settableOf(k));
853
- if (unknown.length) {
854
- const k = unknown[0];
855
- const extra = k === 'name' ? ` — a collection is renamed with its records and every inbound reference in one commit: dreamteamer rename collections/${name} <new-name>` : '';
856
- throw new Error(`"${k}" is not a settable key of a collection${extra}. Settable: ${Object.keys(COLLECTION_SETTABLE).join(', ')}, display.list.options.<key>, display.record.options.<key>, plus module= (which MOVES it). A field is written with dreamteamer add-field/set-field ${name}.`);
857
- }
858
- // The columns and the sort name fields of THIS collection. compile refuses a dangling one too;
859
- // refusing here names the verb that declares the field instead of rolling a write back.
860
- const known = fieldsOf(d);
861
- for (const key of ['display.list.columns', 'display.list.sort', 'display.record.badge', 'display.record.color_by']) {
862
- if (!(key in changes) || changes[key] === '' || changes[key] === null) continue; // a clear has nothing to validate
863
- const named = key === 'display.list.sort' ? [String(changes[key]).replace(/^-/, '')] : nameList(changes[key]);
864
- const missing = named.filter((f) => f && !known[f]);
865
- if (missing.length) {
866
- throw new Error(`${key}: ${collectionMissingFields(name, missing)} — declare it first (dreamteamer add-field ${name} --name ${missing[0]} --type <t>).`);
867
- }
868
- }
869
- // ⚠ NAMED, not resolved to an overlay. `collectionSourceFile` falls back to a workspace-module
870
- // path for a base it cannot write, which is right for `add-field` (an overlay IS the remedy) and
871
- // wrong here: a collection-level key belongs to the base, and an overlay that set it would
872
- // silently win over the owner's choice.
873
- const owned = baseDescriptorSource(ws, name).base;
874
- if (owned && IN_NODE_MODULES(owned)) {
875
- // How the collection is DRAWN is the one collection-level thing a workspace may change about a
876
- // package's collection — compile already merges an overlay's `display` per sub-block — so a
877
- // display write becomes that overlay. Every other key belongs to the module that owns it.
878
- const notDisplay = Object.keys(changes).filter((k) => !k.startsWith('display.'));
879
- if (!notDisplay.length) return setCollectionDisplayOverlay(ws, store, name, changes, owned);
880
- throw new Error(`"${name}" ships from node_modules (${owned}) — a write there is erased by the next \`npm install\`, and a collection-level key (${notDisplay.join(', ')}) belongs to the module that owns it. Its display.* keys can be changed from here (they are written as an overlay in the workspace module); for the rest, add "collections/${name}" to dreamteamer.disable and declare your own instead.`);
881
- }
882
- const { file } = collectionSourceFile(ws, store, name, moduleId, { subject: name });
883
- if (!fs.existsSync(file)) throw new Error(`${path.relative(ws.root, file)} is not on disk — run \`dreamteamer compile\` and re-run.`);
884
- const previousText = fs.readFileSync(file, 'utf8');
885
- const doc = load(previousText);
886
- const changed = [];
887
- const gate = writeGated(ws, store, [file], `dreamteamer: collections set ${name} ${Object.keys(changes).join(' ')}`, () => {
888
- for (const [k, raw] of Object.entries(changes)) {
889
- // An empty value REMOVES the key — `store.set`'s convention, extended to the descriptor.
890
- if (raw === '' || raw === null) deletePath(doc, k);
891
- else setPath(doc, k, settableOf(k)(raw));
892
- changed.push(k);
893
- }
894
- fs.writeFileSync(file, writeSource(previousText, doc));
895
- });
896
- return { name, file, changed, commits: gate.commits, unchanged: gate.unchanged };
897
- }
898
-
899
- /**
900
- * A package collection's DISPLAY, changed from the workspace: the `display.*` keys that differ from the
901
- * package's own source, written into the workspace module's overlay of it (created, updated, or removed
902
- * when nothing differs any more). A cleared key falls back to the package's value — an overlay can
903
- * refine a block and cannot delete from it. `options` is written WHOLE when any option differs:
904
- * compile merges `display.<block>` one key deep, so a lone option would drop every option the package
905
- * sets beside it.
906
- */
907
- function setCollectionDisplayOverlay(ws, store, name, changes, owned) {
908
- const { file } = collectionSourceFile(ws, store, name, undefined, { subject: name });
909
- const base = load(fs.readFileSync(path.join(ws.root, owned), 'utf8')) ?? {};
910
- const existed = fs.existsSync(file);
911
- const previousText = existed ? fs.readFileSync(file, 'utf8') : null;
912
- // `fields: {}` is what makes a source v2 at all (`isV2`), the same scaffold add-field writes
913
- const doc = existed ? load(previousText) : { name, overlay: true, fields: {} };
914
- const at = (o, dotted) => dotted.split('.').reduce((n, k) => (n && typeof n === 'object' ? n[k] : undefined), o);
915
- const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
916
- const changed = [];
917
- for (const [k, raw] of Object.entries(changes)) {
918
- const clear = raw === '' || raw === null;
919
- const opt = /^(display\.[^.]+\.options)\.(.+)$/.exec(k);
920
- if (opt) {
921
- const options = structuredClone(at(doc, opt[1]) ?? at(base, opt[1]) ?? {});
922
- if (clear) delete options[opt[2]];
923
- else options[opt[2]] = settableOf(k)(raw);
924
- if (same(options, at(base, opt[1]))) deletePath(doc, opt[1]);
925
- else setPath(doc, opt[1], options);
926
- } else {
927
- const value = clear ? undefined : settableOf(k)(raw);
928
- if (clear || same(value, at(base, k))) deletePath(doc, k);
929
- else setPath(doc, k, value);
930
- }
931
- changed.push(k);
932
- }
933
- const empty = Object.keys(doc).every((k) => ['name', 'overlay'].includes(k) || (k === 'fields' && !Object.keys(doc.fields ?? {}).length));
934
- if (empty && !existed) return { name, file, changed, overlay: true, unchanged: true };
935
- // compile refuses an overlay whose module neither depends on the base's module nor lists the
936
- // collection in `peer_collections`. The PEER declaration is the one that fits a display overlay —
937
- // it applies while the package is installed and is inert once it is not — so it is written for the
938
- // person in the same gated write, rather than handed back as compile's remedy to type.
939
- const wmPkg = path.join(ws.pkg.dreamteamer?.workspace_module ? path.join(ws.root, 'modules', ws.pkg.dreamteamer.workspace_module) : ws.root, 'package.json');
940
- const owner = moduleRows(store).filter((r) => owned.startsWith(`${r.fields.path}/`)).sort((a, b) => b.fields.path.length - a.fields.path.length)[0];
941
- const declared = (JSON.parse(fs.readFileSync(wmPkg, 'utf8')).dreamteamer ?? {});
942
- const ownerPkg = owner ? packageNameOf(store, owner.id) : null;
943
- // the engine's own collections are every module's to overlay (compile asks nothing of those)
944
- const needsPeer = !empty && ownerPkg !== engineId().replace(/@[^@]*$/, '') && !(declared.peer_collections ?? []).includes(name)
945
- && !(ownerPkg && (declared.dependencies ?? []).includes(ownerPkg));
946
- const gate = writeGated(ws, store, needsPeer ? [file, wmPkg] : [file], `dreamteamer: collections set ${name} ${Object.keys(changes).join(' ')} (overlay)`, () => {
947
- if (empty) return fs.rmSync(file);
948
- fs.mkdirSync(path.dirname(file), { recursive: true });
949
- fs.writeFileSync(file, writeSource(previousText, doc));
950
- if (needsPeer) editModulePkg(wmPkg, (dt) => { dt.peer_collections = [...(dt.peer_collections ?? []), name]; });
951
- }, undefined, { commentsMayDecrease: true });
952
- // the declaration is a write to the module's manifest, so the result names it for every surface to say
953
- const peer = needsPeer ? { collection: name, module: ws.pkg.dreamteamer?.workspace_module ?? ws.pkg.name } : undefined;
954
- return { name, file, changed, overlay: true, removed: empty || undefined, peer, commits: gate.commits, unchanged: gate.unchanged };
955
- }
956
-
957
- // ---- the positions that name a field, and a value ----------------------------------------------
958
- // A field is referenced BY NAME, not as a `<collection>/<id>` reference, so `store.rewriteRefs` can
959
- // see none of it. Rule 6 is the list of every position a descriptor, a view or a binding may name a
960
- // field in — compile validates each one — and these walkers visit exactly that list:
961
- //
962
- // the collection's own sources (its base and every overlay):
963
- // `fields.<f>` · a field's `display.unit_field` · `storage.under.parent` · `ids.from` ·
964
- // `record_title` · `display.list.columns`/`sort`/`options` · `display.record.badge`/
965
- // `color_by`/`subtitle` · `display.form.sections` · every `constraints` property name
966
- // every other collection source: a mirror's `mirror_of` naming the field on this collection
967
- // ui-views: `filter` (one hop through a reference included) and the `display` block
968
- // command-bindings: `available_when` · `done_when`
969
- // the records: the frontmatter key
970
- //
971
- // Each walker REWRITES A COPY and records where it wrote, so a dry run, a refusal and the real run
972
- // are one traversal and cannot disagree about what is affected. A position that cannot be rewritten
973
- // — a source `npm install` would erase, a mixin every collection listing it shares, a filter hop
974
- // through a union — is recorded too, and the verb refuses naming every one of them.
975
-
976
- /** A layout option that names a field by the role it plays (§3.5.1). */
977
- const OPTION_FIELD_KEYS = FIELD_OPTIONS;
978
- /** A layout option that names several. */
979
- const OPTION_FIELD_LISTS = ['ref_fields', 'value_fields'];
980
- /** A layout option that is a template. */
981
- const OPTION_TEMPLATES = TEMPLATE_OPTIONS;
982
-
983
- /** A position label back to its path from the document root: `constraints[0].if.properties.status`
984
- * → `['constraints', 0, 'if', 'properties', 'status']`. Labels are built from field names and
985
- * operator keys, neither of which carries a `.` or a `[`. */
986
- const pathOf = (label) => [...label.matchAll(/([^.[\]]+)|\[(\d+)\]/g)].map((m) => (m[2] !== undefined ? Number(m[2]) : m[1]));
987
-
988
- /** A map with one key renamed in place — key order is form order, and a body field belongs last. */
989
- const renameKey = (obj, from, to) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [k === from ? to : k, v]));
990
-
991
- /** Rewrite `{{ <from> …}}` inside a template string, keeping any filters after the pipe. Matched on
992
- * the whole identifier so `{{ name }}` is not found inside `{{ full_name }}`. */
993
- function rewriteTemplateField(tpl, from, to) {
994
- if (typeof tpl !== 'string') return tpl;
995
- return tpl.replace(new RegExp(`(\\{\\{\\s*)${from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(\\s*(?:\\||\\}\\}))`, 'g'), `$1${to}$2`);
996
- }
997
-
998
- /** A template key on `holder`, rewritten when it names the field. */
999
- function renameInTemplate(holder, key, from, to, at, label) {
1000
- const v = holder?.[key];
1001
- if (typeof v !== 'string') return;
1002
- const next = rewriteTemplateField(v, from, to);
1003
- if (next !== v) { holder[key] = next; at(label); }
1004
- }
1005
-
1006
- /** The four display sub-blocks — a collection's default view, and a ui-view's variant of it. */
1007
- function renameInDisplay(display, from, to, at, label) {
1008
- if (!display || typeof display !== 'object') return;
1009
- const ren = (v) => (v === from ? to : v);
1010
- const list = display.list;
1011
- if (Array.isArray(list?.columns) && list.columns.includes(from)) { list.columns = list.columns.map(ren); at(`${label}.list.columns`); }
1012
- if (typeof list?.sort === 'string' && list.sort.replace(/^-/, '') === from) { list.sort = list.sort.replace(from, to); at(`${label}.list.sort`); }
1013
- const opts = list?.options;
1014
- if (opts && typeof opts === 'object') {
1015
- for (const k of OPTION_FIELD_KEYS) if (opts[k] === from) { opts[k] = to; at(`${label}.list.options.${k}`); }
1016
- for (const k of OPTION_FIELD_LISTS) if (Array.isArray(opts[k]) && opts[k].includes(from)) { opts[k] = opts[k].map(ren); at(`${label}.list.options.${k}`); }
1017
- for (const k of OPTION_TEMPLATES) renameInTemplate(opts, k, from, to, at, `${label}.list.options.${k}`);
1018
- }
1019
- const rec = display.record;
1020
- if (rec && typeof rec === 'object') {
1021
- for (const k of ['badge', 'color_by']) if (rec[k] === from) { rec[k] = to; at(`${label}.record.${k}`); }
1022
- renameInTemplate(rec, 'subtitle', from, to, at, `${label}.record.subtitle`);
1023
- }
1024
- (Array.isArray(display.form?.sections) ? display.form.sections : []).forEach((sec, i) => {
1025
- if (Array.isArray(sec?.fields) && sec.fields.includes(from)) { sec.fields = sec.fields.map(ren); at(`${label}.form.sections[${i}]`); }
1026
- });
1027
- }
1028
-
1029
- /**
1030
- * One constraint, at the level where its property names are THIS collection's fields: the root and
1031
- * every combinator branch (`if`/`then`/`else`/`not`, `allOf`/`anyOf`/`oneOf`, a dependent schema).
1032
- * Never inside `properties.<f>` — a nested `properties` there names the sub-fields of an object.
1033
- */
1034
- function renameInConstraint(node, from, to, at, label) {
1035
- if (!node || typeof node !== 'object' || Array.isArray(node)) return;
1036
- if (node.properties && typeof node.properties === 'object' && from in node.properties) {
1037
- node.properties = renameKey(node.properties, from, to);
1038
- at(`${label}.properties.${from}`, undefined, to);
1039
- }
1040
- if (Array.isArray(node.required) && node.required.includes(from)) { node.required = node.required.map((r) => (r === from ? to : r)); at(`${label}.required`); }
1041
- if (node.dependentRequired && typeof node.dependentRequired === 'object') {
1042
- if (from in node.dependentRequired) { node.dependentRequired = renameKey(node.dependentRequired, from, to); at(`${label}.dependentRequired.${from}`, undefined, to); }
1043
- for (const [k, list] of Object.entries(node.dependentRequired)) {
1044
- if (Array.isArray(list) && list.includes(from)) { node.dependentRequired[k] = list.map((r) => (r === from ? to : r)); at(`${label}.dependentRequired.${k}`); }
1045
- }
1046
- }
1047
- if (node.dependentSchemas && typeof node.dependentSchemas === 'object') {
1048
- if (from in node.dependentSchemas) { node.dependentSchemas = renameKey(node.dependentSchemas, from, to); at(`${label}.dependentSchemas.${from}`, undefined, to); }
1049
- for (const [k, sub] of Object.entries(node.dependentSchemas)) renameInConstraint(sub, from, to, at, `${label}.dependentSchemas.${k}`);
1050
- }
1051
- for (const k of ['if', 'then', 'else', 'not']) renameInConstraint(node[k], from, to, at, `${label}.${k}`);
1052
- for (const k of ['allOf', 'anyOf', 'oneOf']) (Array.isArray(node[k]) ? node[k] : []).forEach((sub, i) => renameInConstraint(sub, from, to, at, `${label}.${k}[${i}]`));
1053
- }
1054
-
1055
- /** Every position in one of the collection's OWN sources (its base, an overlay, a mixin it lists). */
1056
- function renameOwnField(doc, from, to, at) {
1057
- if (doc.fields && typeof doc.fields === 'object') {
1058
- if (from in doc.fields) { doc.fields = renameKey(doc.fields, from, to); at(`fields.${from}`, undefined, to); }
1059
- for (const [k, f] of Object.entries(doc.fields)) {
1060
- if (f?.display?.unit_field === from) { f.display.unit_field = to; at(`fields.${k}.display.unit_field`); }
1061
- }
1062
- }
1063
- if (doc.storage?.under?.parent === from) { doc.storage.under.parent = to; at('storage.under.parent'); }
1064
- if (Array.isArray(doc.ids?.from)) doc.ids.from.forEach((_, i) => renameInTemplate(doc.ids.from, i, from, to, at, `ids.from[${i}]`));
1065
- else renameInTemplate(doc.ids, 'from', from, to, at, 'ids.from');
1066
- renameInTemplate(doc, 'record_title', from, to, at, 'record_title');
1067
- renameInDisplay(doc.display, from, to, at, 'display');
1068
- (Array.isArray(doc.constraints) ? doc.constraints : []).forEach((c, i) => renameInConstraint(c, from, to, at, `constraints[${i}]`));
1069
- }
1070
-
1071
- /** A mirror elsewhere naming the field it mirrors on `collection`. */
1072
- function renameMirrorOf(doc, collection, from, to, at) {
1073
- for (const [k, f] of Object.entries(doc?.fields ?? {})) {
1074
- const t = targetsOf(f);
1075
- if (f?.mirror_of === from && Array.isArray(t) && t.length === 1 && t[0] === collection) { f.mirror_of = to; at(`fields.${k}.mirror_of`); }
1076
- }
1077
- }
1078
-
1079
- /**
1080
- * A filter, read against the collection it filters. A key that is not an operator names a field of
1081
- * `coll`; inside its condition, a further non-operator key is ONE HOP through that reference and
1082
- * names a field of the collection it points at — so a view over visits filtering `patient: { name:
1083
- * … }` names `health/patients.name`. A hop through a union cannot say which member's field it means.
1084
- */
1085
- function walkFilter(node, coll, fieldsOfColl, visit, at, label) {
1086
- if (!node || typeof node !== 'object' || Array.isArray(node)) return;
1087
- for (const key of Object.keys(node)) {
1088
- if (key === '_and' || key === '_or') {
1089
- (Array.isArray(node[key]) ? node[key] : []).forEach((c, i) => walkFilter(c, coll, fieldsOfColl, visit, at, `${label}.${key}[${i}]`));
1090
- continue;
1091
- }
1092
- if (key.startsWith('_')) continue;
1093
- const cond = node[key];
1094
- if (cond && typeof cond === 'object' && !Array.isArray(cond) && Object.keys(cond).some((k) => !k.startsWith('_'))) {
1095
- const t = targetsOf(fieldsOfColl(coll)?.[key]);
1096
- if (Array.isArray(t) && t.length === 1) walkFilter(cond, t[0], fieldsOfColl, visit, at, `${label}.${key}`);
1097
- else if (Array.isArray(t)) visit.union?.(cond, t, at, `${label}.${key}`);
1098
- }
1099
- visit.field(node, key, coll, at, label);
1100
- }
1101
- }
1102
-
1103
- /** The ui-views and command-bindings of every source root, with the collection each one is over. */
1104
- function viewSources(store) {
1105
- const out = [];
1106
- for (const root of store.sourceRoots()) {
1107
- for (const kind of ['ui-views', 'command-bindings']) {
1108
- const dir = kindDir(root, kind);
1109
- if (!fs.existsSync(dir)) continue;
1110
- for (const file of [...walk(dir)]) {
1111
- if (!/\.(ui-view|command-binding)\.yaml$/.test(file)) continue;
1112
- out.push({ file, kind });
1113
- }
1114
- }
1115
- }
1116
- return out;
1117
- }
1118
-
1119
- /** The filter positions of a view or a binding. */
1120
- const FILTER_KEYS = { 'ui-views': ['filter'], 'command-bindings': ['available_when', 'done_when'] };
1121
-
1122
- /** Every mixin source, by id — a mixin is shared by every collection that lists it. */
1123
- function mixinSources(store) {
1124
- const out = [];
1125
- for (const root of store.sourceRoots()) {
1126
- const dir = kindDir(root, 'mixins');
1127
- if (!fs.existsSync(dir)) continue;
1128
- for (const file of [...walk(dir)]) {
1129
- const m = /([^/\\]+)\.mixin\.yaml$/.exec(file);
1130
- if (m) out.push({ id: m[1], file });
1131
- }
1132
- }
1133
- return out;
1134
- }
1135
-
1136
- /** The mixins a collection's sources list. */
1137
- function mixinsListedBy(ws, collection) {
1138
- const { base, overlays } = baseDescriptorSource(ws, collection);
1139
- const ids = new Set();
1140
- for (const rel of [base, ...overlays].filter(Boolean)) {
1141
- const doc = readYaml(path.join(ws.root, rel));
1142
- for (const m of Array.isArray(doc?.mixins) ? doc.mixins : []) ids.add(String(m));
1143
- }
1144
- return ids;
1145
- }
1146
-
1147
- /** The mixin a collection takes `fieldName` from, or null. */
1148
- function mixinDeclaring(ws, store, collection, fieldName) {
1149
- const listed = mixinsListedBy(ws, collection);
1150
- for (const { id, file } of mixinSources(store)) {
1151
- if (listed.has(id) && readYaml(file)?.fields?.[fieldName] !== undefined) return { id, rel: path.relative(ws.root, file) };
1152
- }
1153
- return null;
1154
- }
1155
-
1156
- const readYaml = (file) => {
1157
- try { return load(fs.readFileSync(file, 'utf8')); } catch { return null; }
1158
- };
1159
-
1160
- /**
1161
- * Walk every source with `visit`, on copies. Returns `{ positions, edits }`: every position written
1162
- * (`{ rel, at, fixed, why }`), and for each file that changed the rewritten document beside its
1163
- * original text.
1164
- *
1165
- * `visit.own(doc, at)` runs on the collection's own sources and the mixins it lists;
1166
- * `visit.foreign(doc, at)` on every collection source; `visit.view(doc, kind, at)` on every view and
1167
- * binding.
1168
- */
1169
- function walkSources(ws, store, collection, visit) {
1170
- const positions = [];
1171
- const edits = new Map();
1172
- const record = (file, doc, before, why) => {
1173
- const rel = path.relative(ws.root, file);
1174
- const at = [];
1175
- // `renamedTo` marks a position that is a mapping KEY renamed in place — written to the bytes
1176
- // first (`renameKeys`), so the comments inside the pair stay with it
1177
- const note = (label, reason, renamedTo, keyPath) => at.push({ label, reason, ...(renamedTo !== undefined && { key: { path: keyPath ?? pathOf(label), to: renamedTo } }) });
1178
- return {
1179
- note,
1180
- done: () => {
1181
- if (!at.length) return;
1182
- const blocked = why ?? (IN_NODE_MODULES(rel) ? 'it ships from node_modules, and `npm install` would erase the write' : null);
1183
- for (const a of at) positions.push({ rel, at: a.label, fixed: !blocked && !a.reason, why: a.reason ?? blocked ?? undefined });
1184
- if (!blocked && !at.some((a) => a.reason)) edits.set(file, { before, doc, keys: at.filter((a) => a.key).map((a) => a.key) });
1185
- },
1186
- };
1187
- };
1188
- for (const file of descriptorSources(ws, store)) {
1189
- const before = fs.readFileSync(file, 'utf8');
1190
- const doc = load(before);
1191
- if (!doc || typeof doc !== 'object') continue;
1192
- const r = record(file, doc, before);
1193
- if (doc.name === collection) visit.own(doc, r.note);
1194
- visit.foreign?.(doc, r.note);
1195
- r.done();
1196
- }
1197
- const listed = mixinsListedBy(ws, collection);
1198
- for (const { id, file } of mixinSources(store)) {
1199
- const before = fs.readFileSync(file, 'utf8');
1200
- const doc = load(before);
1201
- if (!doc || typeof doc !== 'object') continue;
1202
- const r = record(file, doc, before, `mixin "${id}" is shared by every collection that lists it — rewrite it by hand, or move the field onto ${collection}`);
1203
- if (listed.has(id)) visit.own(doc, r.note);
1204
- visit.foreign?.(doc, r.note);
1205
- r.done();
1206
- }
1207
- for (const { file, kind } of viewSources(store)) {
1208
- const before = fs.readFileSync(file, 'utf8');
1209
- const doc = load(before);
1210
- if (!doc || typeof doc !== 'object') continue;
1211
- const r = record(file, doc, before);
1212
- visit.view(doc, kind, r.note);
1213
- r.done();
1214
- }
1215
- return { positions, edits };
1216
- }
1217
-
1218
- /** The collection a view or binding is over, bare. */
1219
- const viewCollection = (doc) => String(doc?.collection ?? '').replace(/^collections\//, '');
1220
-
1221
- /** Records of `collection` a value-level rewrite would change, with the fields it would write. */
1222
- function recordRewrites(store, collection, rewrite) {
1223
- const d = store.descriptors.get(collection);
1224
- if (!d || !store.canRewrite(collection)) return [];
1225
- const bf = bodyFieldOf(d);
1226
- const out = [];
1227
- for (const [, file] of store.ids(collection)) {
1228
- let fields;
1229
- // a record that will not parse is skipped: `check` already reports it, and one bad record must
1230
- // not wall off a schema change
1231
- try { fields = parseRecord(file, d, bf); } catch { continue; }
1232
- const next = rewrite(fields);
1233
- // the previous text goes with it, so a rewrite re-emits only the key it changed
1234
- if (next) out.push({ file, fields: next, text: fs.readFileSync(file, 'utf8') });
1235
- }
1236
- return out;
1237
- }
1238
-
1239
- /** The refusal every positional verb gives: the positions it cannot rewrite, each with why. */
1240
- function refusePositions(what, positions) {
1241
- const blocked = positions.filter((p) => !p.fixed);
1242
- if (!blocked.length) return;
1243
- throw new Error(`${what} cannot rewrite ${blocked.length} position${blocked.length === 1 ? '' : 's'} — nothing was changed:\n${blocked.map((p) => ` ${p.rel} ${p.at} — ${p.why}`).join('\n')}`);
1244
- }
1245
-
1246
- /** Write a walk's rewritten documents and records, inside a gate op; returns the touched paths. */
1247
- function applyRewrites(ws, edits, records, cd, snap) {
1248
- const touched = new Set();
1249
- for (const [file, { before, doc, keys }] of edits) {
1250
- const after = writeSource(keys.length ? renameKeys(before, keys) : before, doc);
1251
- if (!load(after) || commentCount(after) < commentCount(before)) {
1252
- throw new Error(`could not rewrite ${path.relative(ws.root, file)} without losing a comment — nothing was changed.`);
1253
- }
1254
- snap(file);
1255
- fs.writeFileSync(file, after);
1256
- touched.add(path.relative(ws.root, file));
1257
- }
1258
- for (const { file, fields, text } of records) {
1259
- snap(file);
1260
- atomicWrite(file, serialize(cd, fields, text));
1261
- touched.add(path.relative(ws.root, file));
1262
- }
1263
- return touched;
1264
- }
1265
-
1266
- // ---- rename-field ------------------------------------------------------------------------------
1267
-
1268
- /** Every position a rename of `collection.from` → `to` rewrites, the records it rewrites, and what
1269
- * it cannot. Read-only: the dry run IS this. */
1270
- function fieldRenameWalk(ws, store, collection, from, to, { records: withRecords = true } = {}) {
1271
- const fieldsOfColl = (c) => (store.descriptors.has(c) ? fieldsOf(store.descriptor(c)) : {});
1272
- const visit = {
1273
- own: (doc, at) => renameOwnField(doc, from, to, at),
1274
- foreign: (doc, at) => renameMirrorOf(doc, collection, from, to, at),
1275
- view: (doc, kind, at) => {
1276
- const over = viewCollection(doc);
1277
- if (over === collection && kind === 'ui-views') renameInDisplay(doc.display, from, to, at, 'display');
1278
- for (const key of FILTER_KEYS[kind]) {
1279
- walkFilter(doc[key], over, fieldsOfColl, {
1280
- field: (node, k, coll, note, label) => {
1281
- if (coll !== collection || k !== from) return;
1282
- const rebuilt = renameKey(node, from, to);
1283
- for (const x of Object.keys(node)) delete node[x];
1284
- Object.assign(node, rebuilt);
1285
- note(`${label}.${from}`, undefined, to);
1286
- },
1287
- union: (cond, targets, note, label) => {
1288
- if (targets.includes(collection) && from in cond) note(`${label}.${from}`, `a filter hop through a union (${targets.join(', ')}) cannot say which member's "${from}" it means — rewrite it by hand`);
1289
- },
1290
- }, at, key);
1291
- }
1292
- },
1293
- };
1294
- const { positions, edits } = walkSources(ws, store, collection, visit);
1295
- const d = store.descriptor(collection);
1296
- // the body field has no frontmatter key: its value is the prose, which `serialize` writes back under
1297
- // whatever the descriptor now calls it — the rename, done
1298
- const records = !withRecords || from === bodyFieldOf(d) ? [] : recordRewrites(store, collection, (fields) => (from in fields ? renameKey(fields, from, to) : null));
1299
- return { positions, edits, records };
1300
- }
1301
-
1302
- export function renameFieldPlan(ws, store, collection, from, to) {
1303
- const d = store.descriptor(collection);
1304
- if (!fieldsOf(d)[from]) throw new Error(`no field "${from}" on ${collection}`);
1305
- const { positions, records } = fieldRenameWalk(ws, store, collection, from, to ?? `<new-name>`);
1306
- return {
1307
- collection, from, to, positions, records: records.length, refs: 0, cleared: 0,
1308
- descriptors: new Set(positions.map((p) => p.rel)).size,
1309
- };
1310
- }
1311
-
1312
- export function renameField(ws, store, collection, from, to, { dryRun = false } = {}) {
1313
- const d = store.descriptor(collection);
1314
- if (!to || to === true) throw new Error(`missing --to <new-name>: dreamteamer rename-field ${collection} --name ${from} --to <new-name>`);
1315
- if (from === to) return { renamed: false, collection, from, to };
1316
- const fields = fieldsOf(d);
1317
- if (!fields[from]) throw new Error(`no field "${from}" on ${collection}`);
1318
- if (INJECTED.has(from)) throw new Error(`"${from}" is injected by the engine into every collection — it cannot be renamed`);
1319
- if (fields[to] || INJECTED.has(to)) throw new Error(`${collection} already has a field "${to}" — pick another name, or remove it first (dreamteamer rm-field ${collection} --name ${to}).`);
1320
- const plan = renameFieldPlan(ws, store, collection, from, to);
1321
- if (dryRun) return { ...plan, renamed: false, dryRun: true };
1322
- refusePositions(`rename-field ${collection} ${from} → ${to}`, plan.positions);
1323
-
1324
- const snapshots = new Map();
1325
- const snap = (f) => { if (!snapshots.has(f)) snapshots.set(f, fs.readFileSync(f)); };
1326
- const out = gatedTreeOp(ws, store, {
1327
- subject: `dreamteamer: ${collection} rename-field ${from} → ${to}`,
1328
- paths: [],
1329
- mutate: () => {
1330
- // walked again INSIDE the lock, so what is written is what is on disk now
1331
- const walked = fieldRenameWalk(ws, store, collection, from, to);
1332
- refusePositions(`rename-field ${collection} ${from} → ${to}`, walked.positions);
1333
- return { paths: [...applyRewrites(ws, walked.edits, walked.records, d, snap)] };
1334
- },
1335
- undo: () => { for (const [f, bytes] of snapshots) { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, bytes); } },
1336
- });
1337
- return { ...plan, renamed: true, commits: out.commits };
1338
- }
1339
-
1340
- // ---- rename-value ------------------------------------------------------------------------------
1341
- // The value half of rule 6: an enum value is named by the field's `enum` (a list, or the key of a
1342
- // decorated map), its `default`, a constraint's `const`/`enum` on that field, a view filter and a
1343
- // binding condition on it, and every record holding it.
1344
-
1345
- /** Rewrite the value inside one field's subschema of a constraint. */
1346
- function renameValueInSubschema(s, from, to, at, label) {
1347
- if (!s || typeof s !== 'object' || Array.isArray(s)) return;
1348
- if (s.const === from) { s.const = to; at(`${label}.const`); }
1349
- if (Array.isArray(s.enum) && s.enum.includes(from)) { s.enum = s.enum.map((v) => (v === from ? to : v)); at(`${label}.enum`); }
1350
- for (const k of ['items', 'contains', 'not', 'if', 'then', 'else']) renameValueInSubschema(s[k], from, to, at, `${label}.${k}`);
1351
- for (const k of ['allOf', 'anyOf', 'oneOf']) (Array.isArray(s[k]) ? s[k] : []).forEach((sub, i) => renameValueInSubschema(sub, from, to, at, `${label}.${k}[${i}]`));
1352
- }
1353
-
1354
- /** A constraint, at its root-level positions, for the subschemas that constrain `field`. */
1355
- function renameValueInConstraint(node, field, from, to, at, label) {
1356
- if (!node || typeof node !== 'object' || Array.isArray(node)) return;
1357
- if (node.properties?.[field]) renameValueInSubschema(node.properties[field], from, to, at, `${label}.properties.${field}`);
1358
- for (const k of ['if', 'then', 'else', 'not']) renameValueInConstraint(node[k], field, from, to, at, `${label}.${k}`);
1359
- for (const k of ['allOf', 'anyOf', 'oneOf']) (Array.isArray(node[k]) ? node[k] : []).forEach((sub, i) => renameValueInConstraint(sub, field, from, to, at, `${label}.${k}[${i}]`));
1360
- for (const [k, sub] of Object.entries(node.dependentSchemas ?? {})) renameValueInConstraint(sub, field, from, to, at, `${label}.dependentSchemas.${k}`);
1361
- }
1362
-
1363
- /** Operators whose operand IS a value, rewritten exactly. */
1364
- const VALUE_OPS = ['_eq', '_neq', '_ieq', '_nieq'];
1365
- const LIST_OPS = ['_in', '_nin'];
1366
- /** Operators whose operand matches PART of a value: a rename can change what they select, and no
1367
- * mechanical rewrite says how — so one that selects the old value is refused by name. */
1368
- const PARTIAL_OPS = {
1369
- _contains: (v, o) => v.includes(o), _ncontains: (v, o) => v.includes(o), _icontains: (v, o) => v.toLowerCase().includes(o.toLowerCase()),
1370
- _starts_with: (v, o) => v.startsWith(o), _istarts_with: (v, o) => v.toLowerCase().startsWith(o.toLowerCase()),
1371
- _ends_with: (v, o) => v.endsWith(o), _iends_with: (v, o) => v.toLowerCase().endsWith(o.toLowerCase()),
1372
- _regex: (v, o) => { try { return new RegExp(o).test(v); } catch { return false; } },
1373
- };
1374
-
1375
- /** One field's condition in a filter, with the value rewritten. */
1376
- function renameValueInCondition(node, key, from, to, at, label) {
1377
- const cond = node[key];
1378
- if (cond === from) { node[key] = to; at(`${label}.${key}`); return; }
1379
- if (!cond || typeof cond !== 'object' || Array.isArray(cond)) return;
1380
- for (const op of VALUE_OPS) if (cond[op] === from) { cond[op] = to; at(`${label}.${key}.${op}`); }
1381
- for (const op of LIST_OPS) {
1382
- const o = cond[op];
1383
- if (Array.isArray(o) && o.includes(from)) { cond[op] = o.map((v) => (v === from ? to : v)); at(`${label}.${key}.${op}`); }
1384
- else if (typeof o === 'string' && o.split(',').map((x) => x.trim()).includes(from)) { cond[op] = o.split(',').map((x) => (x.trim() === from ? to : x.trim())).join(','); at(`${label}.${key}.${op}`); }
1385
- }
1386
- for (const [op, selects] of Object.entries(PARTIAL_OPS)) {
1387
- if (typeof cond[op] === 'string' && cond[op] !== '' && selects(from, cond[op])) at(`${label}.${key}.${op}`, `\`${op}: ${cond[op]}\` selects "${from}" by part of its spelling — say what it should select now, by hand`);
1388
- }
1389
- }
1390
-
1391
- function valueRenameWalk(ws, store, collection, field, from, to) {
1392
- const fieldsOfColl = (c) => (store.descriptors.has(c) ? fieldsOf(store.descriptor(c)) : {});
1393
- const visit = {
1394
- own: (doc, at) => {
1395
- const f = doc.fields?.[field];
1396
- if (f && typeof f === 'object') {
1397
- if (Array.isArray(f.enum) && f.enum.includes(from)) { f.enum = f.enum.map((v) => (v === from ? to : v)); at(`fields.${field}.enum`); }
1398
- else if (f.enum && typeof f.enum === 'object' && from in f.enum) { f.enum = renameKey(f.enum, from, to); at(`fields.${field}.enum`, undefined, to, ['fields', field, 'enum', from]); }
1399
- if (f.default === from) { f.default = to; at(`fields.${field}.default`); }
1400
- else if (Array.isArray(f.default) && f.default.includes(from)) { f.default = f.default.map((v) => (v === from ? to : v)); at(`fields.${field}.default`); }
1401
- }
1402
- (Array.isArray(doc.constraints) ? doc.constraints : []).forEach((c, i) => renameValueInConstraint(c, field, from, to, at, `constraints[${i}]`));
1403
- },
1404
- view: (doc, kind, at) => {
1405
- for (const key of FILTER_KEYS[kind]) {
1406
- walkFilter(doc[key], viewCollection(doc), fieldsOfColl, {
1407
- field: (node, k, coll, note, label) => { if (coll === collection && k === field) renameValueInCondition(node, k, from, to, note, label); },
1408
- union: (cond, targets, note, label) => {
1409
- if (targets.includes(collection) && field in cond) note(`${label}.${field}`, `a filter hop through a union (${targets.join(', ')}) cannot say which member's "${field}" it means — rewrite it by hand`);
1410
- },
1411
- }, at, key);
1412
- }
1413
- },
1414
- };
1415
- const { positions, edits } = walkSources(ws, store, collection, visit);
1416
- const records = recordRewrites(store, collection, (fields) => {
1417
- const v = fields[field];
1418
- if (v === from) return { ...fields, [field]: to };
1419
- if (Array.isArray(v) && v.includes(from)) return { ...fields, [field]: v.map((x) => (x === from ? to : x)) };
1420
- return null;
1421
- });
1422
- return { positions, edits, records };
1423
- }
1424
-
1425
- /** The checks a value rename is held to before anything is walked. */
1426
- function valueRenameTarget(store, collection, field, from, to) {
1427
- const f = fieldsOf(store.descriptor(collection))[field];
1428
- if (!f) throw new Error(`no field "${field}" on ${collection}`);
1429
- const values = f.enum === undefined ? null : enumValues(f.enum);
1430
- if (!values) throw new Error(`${collection}.${field} has no enum — rename-value renames one value of an enum; a free value is rewritten with dreamteamer set`);
1431
- if (!values.includes(from)) throw new Error(`"${from}" is not a value of ${collection}.${field} — its enum is ${values.join(', ')}`);
1432
- if (to === undefined || to === true || to === '') throw new Error(`missing <new>: dreamteamer rename-value ${collection} ${field} ${from} <new>`);
1433
- if (values.includes(to)) throw new Error(`"${to}" is already a value of ${collection}.${field} — merging two values is a record edit, not a rename`);
1434
- }
1435
-
1436
- export function renameValuePlan(ws, store, collection, field, from, to) {
1437
- valueRenameTarget(store, collection, field, from, to);
1438
- const { positions, records } = valueRenameWalk(ws, store, collection, field, from, to);
1439
- return {
1440
- collection, field, from, to, positions, records: records.length, refs: 0, cleared: 0,
1441
- descriptors: new Set(positions.map((p) => p.rel)).size,
1442
- };
1443
- }
1444
-
1445
- export function renameValue(ws, store, collection, field, from, to, { dryRun = false } = {}) {
1446
- const plan = renameValuePlan(ws, store, collection, field, from, to);
1447
- if (dryRun) return { ...plan, renamed: false, dryRun: true };
1448
- refusePositions(`rename-value ${collection} ${field} ${from} → ${to}`, plan.positions);
1449
- const d = store.descriptor(collection);
1450
- const snapshots = new Map();
1451
- const snap = (f) => { if (!snapshots.has(f)) snapshots.set(f, fs.readFileSync(f)); };
1452
- const out = gatedTreeOp(ws, store, {
1453
- subject: `dreamteamer: ${collection} rename-value ${field} ${from} → ${to}`,
1454
- paths: [],
1455
- mutate: () => {
1456
- const walked = valueRenameWalk(ws, store, collection, field, from, to);
1457
- refusePositions(`rename-value ${collection} ${field} ${from} → ${to}`, walked.positions);
1458
- return { paths: [...applyRewrites(ws, walked.edits, walked.records, d, snap)] };
1459
- },
1460
- undo: () => { for (const [f, bytes] of snapshots) { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, bytes); } },
1461
- });
1462
- return { ...plan, renamed: true, commits: out.commits };
1463
- }
1464
-
1465
- /** The workspace's writable source dir for a kind (workspace_module aware). `kindDir` picks the
1466
- * layout that module already uses and falls back to flat, so a `collections add` never splits a
1467
- * half-moved module across both. */
1468
- export function workspaceSystemDir(ws, kind) {
1469
- const wm = ws.pkg.dreamteamer?.workspace_module;
1470
- return kindDir(wm ? path.join(ws.root, 'modules', wm) : ws.root, kind);
1471
- }
1472
-
1473
- /**
1474
- * WHERE A COLLECTION'S DESCRIPTOR ACTUALLY LIVES — asked of the manifest, not assumed.
1475
- *
1476
- * `renameCollection` used to derive this from `workspaceSystemDir`, which silently meant "only the
1477
- * workspace module's own collections can be renamed". That is the wrong line. The guard exists to
1478
- * stop a write that will be ERASED, and the thing that erases writes is `npm install` — so the test
1479
- * is `node_modules/`, not "which module". A module whose sources are inline in the workspace repo is
1480
- * under the same git history as everything else and is perfectly safe to rewrite; refusing it made
1481
- * `collections rename` unusable for exactly the migration it was built for, because a workspace's
1482
- * domain collections almost always live in a module.
1483
- *
1484
- * Returns `{ dir, file, overlays, sources }` — the base's kind dir to write into (the SAME module the
1485
- * descriptor came from, so a rename never teleports a collection into the workspace module) and its
1486
- * file; each overlay as `{ dir, file }` in ITS module, so the rename carries it along; and every
1487
- * descriptor source that contributed, so the caller can refuse the cases this cannot honestly do.
1488
- */
1489
- function descriptorSourceDir(ws, name) {
1490
- // The base is the source without `overlay: true` — see baseDescriptorSource; discovery order
1491
- // says nothing about which source is which.
1492
- const { base, overlays, sources } = baseDescriptorSource(ws, name);
1493
- // ⚠ `dir` IS THE OWNING MODULE'S `collections/` KIND DIR — asked of the manifest's module list,
1494
- // not re-derived by stripping the collection's name off the source path. That arithmetic only
1495
- // worked while the source path mirrored the name, which a module owning its own namespace need
1496
- // not do (see baseDescriptorSource). `file` is the ACTUAL path, so a caller renaming it moves the
1497
- // file that exists rather than a path it assumed.
1498
- const roots = (readManifest(ws.root)?.modules ?? []).map((m) => (m.root === '.' ? '' : `${m.root}/`));
1499
- const at = (rel) => {
1500
- const mod = roots.filter((r) => r === '' || rel.startsWith(r)).sort((a, b) => b.length - a.length)[0] ?? '';
1501
- return { dir: kindDir(path.join(ws.root, mod), 'collections'), file: path.join(ws.root, rel) };
1502
- };
1503
- if (!base) return { dir: null, file: null, overlays: overlays.map(at), sources };
1504
- return { ...at(base), overlays: overlays.map(at), sources };
1505
- }
1506
-
1507
- /**
1508
- * THE BASE DESCRIPTOR SOURCE, and the overlays beside it — asked of the manifest, decided by parsing.
1509
- *
1510
- * `descriptorSourceDir` above assumes `sources[0]` is the base, which is true in discovery order and
1511
- * is not a fact anything checks. Every EDIT verb needs the base specifically — the rule is that
1512
- * `set`, `rm`, `rename` and the field verbs act on the module that owns the entity and never teleport
1513
- * it into the workspace module — so the base is identified the only way it is actually defined: it is
1514
- * the contributing source that does not declare `overlay: true`.
1515
- *
1516
- * Returns workspace-relative paths. `base` is null when nothing in this workspace declares it (the
1517
- * engine's own nine collections reach here that way), which is the signal to write an overlay.
1518
- */
1519
- export function baseDescriptorSource(ws, name) {
1520
- const suffix = `collections/${name}.collection.yaml`;
1521
- const sources = (readManifest(ws.root)?.entries?.[suffix]?.sources ?? [])
1522
- // sources are `{path, hash}`; tolerate the pre-0.10 string form, as compile's staleness does
1523
- .map((s) => (typeof s === 'string' ? s : s?.path))
1524
- // ⚠ MATCHED ON THE KIND, not on the source path mirroring the collection's NAME. This used
1525
- // to require `endsWith('collections/<name>.collection.yaml')`, which assumes a namespaced
1526
- // descriptor is authored NESTED — true of what `dt add collections` writes, and NOT true of a
1527
- // module that authors `collections/positions.collection.yaml` with `name: hr/positions`,
1528
- // which is the ordinary shape for a module that OWNS its namespace (§8) and does not want to
1529
- // repeat it in every path. Measured on a scratch workspace: that module's base was invisible
1530
- // here, so `add-field hr/positions` created an overlay in the WORKSPACE module and failed
1531
- // compile for a dependency nobody asked for — the exact defect this wave exists to remove,
1532
- // surviving one layer down. `sources` is already scoped to THIS collection's manifest entry;
1533
- // the only other thing in it is a merged MIXIN, whose suffix differs.
1534
- .filter((p) => typeof p === 'string' && p.endsWith('.collection.yaml'));
1535
- let base = null;
1536
- const overlays = [];
1537
- for (const rel of sources) {
1538
- const file = path.join(ws.root, rel);
1539
- if (!fs.existsSync(file)) continue;
1540
- let doc;
1541
- try { doc = load(fs.readFileSync(file, 'utf8')); } catch { continue; }
1542
- if (doc?.overlay === true) overlays.push(rel);
1543
- else base ??= rel;
1544
- }
1545
- return { base, overlays, sources };
1546
- }
1547
-
1548
- /** A path git will not let us rewrite usefully: `npm install` erases it. Matched on the SEGMENT, in
1549
- * either separator, because manifest paths carry the host's. */
1550
- const IN_NODE_MODULES = (rel) => /(^|[\\/])node_modules([\\/]|$)/.test(String(rel));
1551
-
1552
- /**
1553
- * WHERE A FIELD VERB WRITES. The base descriptor's own file when this workspace may rewrite it; the
1554
- * named module's overlay when a selector says so; the workspace module's overlay when neither.
1555
- *
1556
- * ⚠ The guard is `node_modules/`, NOT "which module" — that is the line `descriptorSourceDir`
1557
- * already drew for `renameCollection` and the reason it drew it: the thing that erases a write is
1558
- * `npm install`, and a module whose sources are inline in the workspace repo is under the same git
1559
- * history as everything else. Resolving this from `workspaceSystemDir` instead meant a field verb on
1560
- * ANY other inline module's collection silently created an overlay in the workspace module and then
1561
- * failed compile for a dependency the operator never asked to declare.
1562
- *
1563
- * ⚠ `moduleId` IS A SELECTOR, NOT A DESTINATION. Naming the owner is redundant and naming a module
1564
- * that contributes nothing is the DEFECT this wave exists to remove: `upsertField` used to create an
1565
- * overlay wherever it was pointed, silently. So a selector that selects nothing is refused unless
1566
- * the caller is deliberately creating an overlay, which `allowNew` says out loud.
1567
- */
1568
- function collectionSourceFile(ws, store, collection, moduleId, { allowNew = false, subject } = {}) {
1569
- const { base, overlays } = baseDescriptorSource(ws, collection);
1570
- if (moduleId !== undefined && moduleId !== null && moduleId !== '') {
1571
- const rec = moduleRecord(store, moduleId); // throws with the known-module list
1572
- if (IN_NODE_MODULES(rec.fields.path)) {
1573
- throw new Error(`module "${moduleId}" ships from node_modules (${rec.fields.path}) — a write there is erased by the next \`npm install\`.\n to add fields from this workspace: dreamteamer add-field ${collection} --name <f> --module ${ws.pkg.dreamteamer?.workspace_module ?? 'default'}`);
1574
- }
1575
- // ⚠ A SELECTOR SELECTS AMONG THINGS. `--module` is only meaningful where the entity is
1576
- // declared by MORE than one module (a base plus overlays); anywhere else it is refused (§5),
1577
- // naming who does declare it. `allowNew` is the one caller deliberately CREATING an overlay.
1578
- const declared = declaringModules(ws, store, collection);
1579
- // naming the ONLY declarer is redundant even where an overlay may be created: it selects the base
1580
- if (declared.length < 2 && (!allowNew || declared.includes(moduleId))) {
1581
- throw new Error(`${subject ?? collection} is declared only by ${declared.join(', ') || '?'} — drop --module`);
1582
- }
1583
- const own = [base, ...overlays].find((p) => p && String(p).startsWith(`${rec.fields.path}/`));
1584
- if (own) return { file: path.join(ws.root, own), overlay: own !== base, module: moduleId };
1585
- if (!allowNew) {
1586
- throw new Error(`module "${moduleId}" contributes no source to ${collection} — it is declared by ${declared.join(', ') || 'nothing in this workspace'}. To ADD fields from ${moduleId}: dreamteamer add-field ${collection} --name <f> --module ${moduleId}`);
1587
- }
1588
- return { file: path.join(kindDir(path.join(ws.root, rec.fields.path), 'collections'), `${collection}.collection.yaml`), overlay: true, module: moduleId };
1589
- }
1590
- if (base && !IN_NODE_MODULES(base)) return { file: path.join(ws.root, base), overlay: false, module: null };
1591
- return { file: path.join(workspaceSystemDir(ws, 'collections'), `${collection}.collection.yaml`), overlay: true, module: null };
1592
- }
1593
-
1594
- /** The module ids whose sources declare this collection, base first — for the "declared only by X"
1595
- * refusal, which has to name them to be actionable. */
1596
- function declaringModules(ws, store, collection) {
1597
- const { base, overlays } = baseDescriptorSource(ws, collection);
1598
- const rows = moduleRows(store);
1599
- const idOf = (rel) => rows.find((r) => String(rel).startsWith(`${r.fields.path}/`))?.id ?? '?';
1600
- return [...new Set([base, ...overlays].filter(Boolean).map(idOf))];
1601
- }
1602
-
1603
- /** The source file ONE module contributes to a collection — the read half of `--module`. Exported
1604
- * because `dt get collections/<c> --module <m>` is the only way to see what a given module actually
1605
- * wrote, and the merged descriptor cannot answer it. */
1606
- export function collectionSourceFileFor(ws, store, collection, moduleId) {
1607
- return collectionSourceFile(ws, store, collection, moduleId);
1608
- }
1609
-
1610
- // ---- ops ------------------------------------------------------------------------
1611
-
1612
- export function createCollection(ws, store, { name, mixins, idFrom, namespace, moduleId, description, suffix }) {
1613
- if (!name) throw new Error('missing collection name');
1614
- // §8. `--namespace health --name doctors` and `--name health/doctors` are the SAME collection,
1615
- // because the qualified name IS the identity everywhere else in the engine — and a module that
1616
- // declares exactly one namespace makes even that redundant. The resolved name is ALWAYS echoed,
1617
- // because an inferred identity the operator did not type is one they must be able to read back.
1618
- //
1619
- // ⚠ THE COMPILED SET, not `ws.pkg.dreamteamer.namespaces`. Since §8 the declaration may live in
1620
- // any module's package.json, and the union is resolved by compile and stamped into the manifest —
1621
- // so a verb reading the workspace's own key alone would refuse a namespace a module declares.
1622
- const declared = store.namespaces;
1623
- const modNs = moduleId ? normalizeNamespaces(moduleRecord(store, moduleId).fields.namespaces) : [];
1624
- let inferred = false;
1625
- let ns0 = namespace;
1626
- if (ns0 === undefined && modNs.length === 1 && !namespaceOf(name, [modNs[0]])) {
1627
- ns0 = modNs[0];
1628
- inferred = true;
1629
- } else if (ns0 === undefined && modNs.length > 1 && !namespaceOf(name, modNs)) {
1630
- throw new Error(`module ${moduleId} declares ${modNs.join(', ')} — say which: --namespace ${modNs[0]}`);
1631
- }
1632
- // `--namespace ''` is the explicit "no namespace", the same convention `dt set` has for clearing
1633
- // a field. It arrives as the empty string and must not be confused with "not given".
1634
- // ⚠ `qualify(ns, baseNameOf(name, [ns]))` is what stops the prefix DOUBLING: `--name hr/grades
1635
- // --module hr` resolves the base name to `grades` and re-qualifies it once.
1636
- const qualified = ns0 ? qualify(ns0, baseNameOf(name, [ns0])) : name;
1637
- // The set INCLUDING a namespace this call is about to declare — `defaultStoragePath` and the
1638
- // suffix derivation both split on it, and a name whose prefix is not yet in the set derives
1639
- // `suffix: ops/plan` from `ops/plans`.
1640
- const declaredAll = [...new Set([...declared, ...(ns0 ? [ns0] : [])])];
1641
- const ns = namespaceOf(qualified, declaredAll);
1642
- if (qualified.includes('/') && !ns) {
1643
- throw new Error(`namespace "${qualified.slice(0, qualified.lastIndexOf('/'))}" is not declared — pass --namespace <ns> (which declares it where the collection will live), or declare it first: dt set modules/<m> namespaces=<ns>.`);
1644
- }
1645
- // ⚠ THE NAME AS TYPED, TOO, not only the qualified one. Namespace inference (§8) turns
1646
- // `--name people --module hr` into `hr/people`, which is a DIFFERENT collection — so with the
1647
- // qualified check alone, asking to create a collection that already exists silently created a
1648
- // second one in the module's namespace. §13 requires the refusal, and it has to fire on the name
1649
- // the operator actually typed.
1650
- for (const clash of new Set([qualified, name])) {
1651
- if (!store.descriptors.has(clash)) continue;
1652
- // §13: name both remedies, because the operator asking for this wants ONE of them and the
1653
- // generic "already exists" tells them which neither.
1654
- const owner = moduleOf(store.descriptors.get(clash));
1655
- const target = moduleId ?? ws.pkg.dreamteamer?.workspace_module ?? 'default';
1656
- throw new Error(`collection "${clash}" already exists, owned by ${owner}. Fields from ${target}: dreamteamer add-field ${clash} --module ${target} --name <f> --type <t> · move it: dreamteamer set collections/${clash} module=${target}`);
1657
- }
1658
- // NESTED, mirroring where compile puts it in the runtime: `collections/health/doctors.collection.yaml`.
1659
- // compile enumerates this kind recursively for exactly this reason — and `upsertField` derives the
1660
- // same path from the same name, which is what keeps a later `add-field` editing the base descriptor
1661
- // instead of quietly creating an overlay beside it.
1662
- // …and in the module the caller NAMED — the workspace module only by default. `--module` is what
1663
- // makes a module-first modeling session one verb per step instead of six manual ones.
1664
- const intoRoot = moduleId ? path.join(ws.root, moduleRecord(store, moduleId).fields.path) : null;
1665
- if (intoRoot && IN_NODE_MODULES(path.relative(ws.root, intoRoot))) {
1666
- throw new Error(`module "${moduleId}" ships from node_modules — a write there is erased by the next \`npm install\`. Vendor it into modules/ first.`);
1667
- }
1668
- const dest = path.join(intoRoot ? kindDir(intoRoot, 'collections') : workspaceSystemDir(ws, 'collections'), `${qualified}.collection.yaml`);
1669
- if (fs.existsSync(dest)) throw new Error(`${path.relative(ws.root, dest)} already exists`);
1670
-
1671
- // THE MINIMAL v2 DESCRIPTOR, in canonical key order: `name`, a `description` when one is given,
1672
- // the mixins, the id rule, and `fields`. Storage, title and singular are compile's to default —
1673
- // a default written into the source is a value nobody chose, and it stops following the name.
1674
- // Without a mixin the collection gets the one field its records are named by; with one, the mixin
1675
- // supplies the fields and `add-field` grows the rest.
1676
- const mixinList = mixins === undefined || mixins === '' ? [] : nameList(mixins);
1677
- const descriptor = { name: qualified };
1678
- // ⚠ A DESCRIPTION IS NOT DECORATION. compile WARNS about a collection without one, because it
1679
- // renders as a bare NAME in the orientation block every session loads — an agent learns the noun
1680
- // exists and nothing about when it is the right one.
1681
- if (typeof description === 'string' && description) descriptor.description = description;
1682
- if (mixinList.length) descriptor.mixins = mixinList;
1683
- if (typeof idFrom === 'string' && idFrom) descriptor.ids = { from: idFrom };
1684
- // An explicit suffix WINS over the derivation, and the derivation is echoed by the caller either
1685
- // way: every record filename carries it (`<id>.<suffix>.md`).
1686
- if (typeof suffix === 'string' && suffix) descriptor.storage = { suffix };
1687
- descriptor.fields = mixinList.length ? {} : { name: { type: 'string', required: true } };
1688
- // the SUFFIX comes off the bare name — `health/doctors` records are `<id>.doctor.md`, not
1689
- // `<id>.health/doctor.md` — exactly as compile derives it
1690
- const effectiveSuffix = descriptor.storage?.suffix ?? singular(baseNameOf(qualified, declaredAll));
1691
- // `--namespace x` where nobody declares `x` DECLARES it, in the module the collection is landing
1692
- // in — else the workspace. Writing a source that cannot compile and then telling the operator to
1693
- // go declare it is the shape §8 exists to remove; and the module is the right home, because that
1694
- // is what travels when the module is copied (decision 130's gate).
1695
- const needsDeclaration = !!ns && !declared.includes(ns);
1696
- const declFile = needsDeclaration
1697
- ? (moduleId ? path.join(ws.root, moduleRecord(store, moduleId).fields.path, 'package.json') : path.join(ws.root, 'package.json'))
1698
- : null;
1699
- const gate = writeGated(ws, store, declFile ? [dest, declFile] : [dest], `dreamteamer: collections add ${qualified}`, () => {
1700
- if (declFile && moduleId) {
1701
- editModulePkg(declFile, (dt) => { dt.namespaces = normalizeNamespaces([...(dt.namespaces ?? []), ns]); });
1702
- } else if (declFile) {
1703
- editWorkspacePkg(ws, (dt) => { dt.namespaces = normalizeNamespaces([...(dt.namespaces ?? []), ns]); });
1704
- }
1705
- fs.mkdirSync(path.dirname(dest), { recursive: true });
1706
- fs.writeFileSync(dest, dump(descriptor));
1707
- }, undefined, { commentsMayDecrease: true });
1708
- return {
1709
- file: dest, descriptor, name: qualified, inferred,
1710
- declaredNamespace: needsDeclaration ? ns : null,
1711
- suffix: effectiveSuffix,
1712
- suffixDerived: suffix === undefined || suffix === '',
1713
- commits: gate.commits,
1714
- };
1715
- }
1716
-
1717
- export function removeCollection(ws, store, name, { force = false } = {}) {
1718
- const d = store.descriptor(name);
1719
- // The module that SHIPS it, not the workspace module. Refusing every module-shipped collection
1720
- // made this verb unusable for exactly the workspace it was built for: a vault's domain
1721
- // collections almost always live in a module.
1722
- const { base, overlays } = baseDescriptorSource(ws, name);
1723
- if (!base) {
1724
- throw new Error(`"${name}" has no writable descriptor source — the manifest names none under a module in this workspace. It may be contributed by the engine itself; add "collections/${name}" to dreamteamer.disable instead.`);
1725
- }
1726
- if (IN_NODE_MODULES(base)) {
1727
- throw new Error(`"${name}" ships from node_modules (${base}) — a write there is erased by the next \`npm install\`. Add "collections/${name}" to dreamteamer.disable instead.`);
1728
- }
1729
- // An overlay with no base fails compile ("every source declares `overlay: true` — no base found"),
1730
- // so removing the base under a live overlay is a half-migration that cannot compile.
1731
- if (overlays.length) {
1732
- throw new Error(`"${name}" is overlaid by ${overlays.join(', ')} — an overlay cannot compile without its base, so removing the base alone would break the workspace. Remove the overlay first: dreamteamer rm-field ${name} --module <overlay-module> --name <field> (removing its last field removes the overlay).`);
1733
- }
1734
- const dest = path.join(ws.root, base);
1735
- const storage = storageOf(d);
1736
- const dataDir = path.resolve(ws.root, storage.path); // resolve: an env-pointed root is absolute
1737
- // the index, not only the folder: a collection stored UNDER another keeps most of its records
1738
- // inside the parent's folders, where a readdir of its own root sees nothing
1739
- const hasRecords = store.ids(name).size > 0 || (fs.existsSync(dataDir) && fs.readdirSync(dataDir).some((e) => !e.startsWith('.')));
1740
- if (hasRecords && !force) throw new Error(`collection "${name}" still has records under ${storage.path}${storage.under ? ` and inside ${storage.under.collection} folders` : ''} — remove them first or pass force`);
1741
- for (const c of store.descriptors.values()) {
1742
- if (storageOf(c).under?.collection === name) throw new Error(`collection "${c.name}" stores its records under ${name}'s folders (storage.under) — drop that declaration or relocate its records first; removing the parent would strand them`);
1743
- }
1744
- const gate = writeGated(ws, store, [dest], `dreamteamer: collections rm ${name}`, () => fs.rmSync(dest), undefined, { commentsMayDecrease: true });
1745
- return { removed: name, commits: gate.commits };
1746
- }
1747
-
1748
- /**
1749
- * Rename a collection — descriptor, records, and every inbound reference, in ONE commit.
1750
- *
1751
- * This exists because namespacing EXISTING data was otherwise a hand migration: `git mv` the
1752
- * descriptor, edit `name` and `storage.path`, `git mv` the record folder, re-suffix every file, then
1753
- * find and rewrite every reference — six steps with no gate, where forgetting the last one dangles
1754
- * every link silently. `dt collections rename doctors health/doctors` is the whole thing.
1755
- *
1756
- * DERIVED-VS-AUTHORED is the rule for both moving parts, the same rule `createCollection` uses:
1757
- * - `storage.path` moves only if it was DERIVED (equal to the default for the old name). An authored
1758
- * path is a deliberate choice about where records live and a rename must not overrule it.
1759
- * - `storage.suffix` is re-derived only if it was DERIVED (the singular of the old base name), because
1760
- * otherwise the filenames would start lying about what they hold. `doctors` → `health/doctors` keeps
1761
- * the base name, so nothing is re-suffixed — which is the common case and the cheap one.
1762
- *
1763
- * References are rewritten by asking the STORE to do it, in ONE batch of old→new pairs, rather than
1764
- * by matching the collection prefix with a new regex. `store.rewriteRefsBatch` already knows the
1765
- * boundary rules and already scopes prose to `[[wikilinks]]` (decision 7) — a fresh `oldName/`
1766
- * pattern would have to relearn both, and would corrupt `data/tasks/` in a path or a URL on its
1767
- * first outing.
1768
- *
1769
- * ⚠ IT USED TO BE O(records x files), TWICE, and the history is worth keeping because each stage was
1770
- * measured and each was wrong about the one after it. Measured 2026-08-17 on a real 2,291-record
1771
- * collection in a 3,391-file workspace: 3 minutes, 142s of it system time, 7.7M file reads to
1772
- * rewrite ZERO references — the pass ran per id whether or not anything pointed at the collection.
1773
- * Reproduced 2026-08-22 by `npm run perf -- --records=2291 --filler=1100`, which generates a
1774
- * workspace that shape, and the real number was **15.6M reads, not 7.7M**: `captureRefs` walked
1775
- * every record file for the rollback snapshot before `rewriteRefs` walked them all again, so 7.7M
1776
- * was the PER-PASS number. That is what a generated fixture is for — the finding was right about the
1777
- * shape and off by 2x on the count, and no comment could have told you.
1778
- *
1779
- * Both factors are gone as of 2026-09-01. The rewrite is one pass for every id, and the snapshot
1780
- * pass disappeared entirely because the rewrite snapshots what it writes as it writes it.
1781
- * `--records=400 --filler=100`, the same machine, best of three: 6.39s and 410,678 reads → 0.16s
1782
- * and 1,075 — which is 504 files twice over, the batch pass and the `collections/<name>` one.
1783
- */
1784
- export function renameCollection(ws, store, oldName, newName) {
1785
- const d = store.descriptor(oldName); // throws with the known-collection list if absent
1786
- if (!newName) throw new Error('missing new collection name');
1787
- if (oldName === newName) return { renamed: false, name: newName };
1788
-
1789
- // ⚠ THE COMPILED SET (§8) — the declaration may live in any module's package.json now, and the
1790
- // union is what compile stamped into the manifest.
1791
- const declared = store.namespaces;
1792
- if (newName.includes('/') && !namespaceOf(newName, declared)) {
1793
- throw new Error(`namespace "${newName.slice(0, newName.lastIndexOf('/'))}" is not declared — declare it where the collection will live (dt set modules/<m> namespaces=<ns>), or in dreamteamer.namespaces for a workspace-level one.`);
1794
- }
1795
- if (store.descriptors.has(newName)) throw new Error(`collection "${newName}" already exists`);
1796
- if (isRuntime(d)) throw new Error(`"${oldName}" is a compiled source, not a data collection — it cannot be renamed`);
1797
- // Its records are spread across the parent's folders, and the per-file re-suffix below walks ONE
1798
- // directory. Refused rather than half-done — the fix is small and nothing has asked for it yet.
1799
- if (storageOf(d).under) throw new Error(`"${oldName}" is stored under ${storageOf(d).under.collection} (storage.under) — renaming a placed collection is not supported yet. The supported order: dreamteamer relocate ${oldName} --to-root · remove storage.under from its descriptor · compile · rename · declare storage.under again · compile · dreamteamer relocate ${newName}`);
1800
-
1801
- // The descriptor is renamed IN THE MODULE THAT SHIPS IT — see `descriptorSourceDir` — and so is
1802
- // every overlay of it, each in its own module: an overlay names only the collection, so one left
1803
- // behind would overlay a collection with no base. Refused where doing it halfway is worse than not
1804
- // doing it:
1805
- const { dir: sourceDir, file: sourceFile, overlays, sources } = descriptorSourceDir(ws, oldName);
1806
- const shipped = sources.find((p) => IN_NODE_MODULES(p));
1807
- if (shipped) {
1808
- throw new Error(`"${oldName}" ships from node_modules (${shipped}) — a write there is erased by the next \`npm install\`. rename it in its own repo and release.`);
1809
- }
1810
- // An overlay's `storage` wins over the base's, and the path and suffix are re-derived from the
1811
- // base's below — so an overlay that sets either has no rename this can do honestly.
1812
- const overlayMoves = overlays.map(({ dir, file }) => {
1813
- const text = fs.readFileSync(file, 'utf8');
1814
- const odoc = load(text);
1815
- const set = ['path', 'suffix'].filter((k) => odoc?.storage?.[k] !== undefined);
1816
- if (set.length) throw new Error(`${path.relative(ws.root, file)} overlays "${oldName}" and sets storage.${set.join(' and storage.')} — move ${set.length === 1 ? 'it' : 'them'} into the base descriptor, then rename. nothing was renamed.`);
1817
- const to = path.join(dir, `${newName}.collection.yaml`);
1818
- if (to !== file && fs.existsSync(to)) throw new Error(`${path.relative(ws.root, to)} already exists — move or remove it first; nothing was renamed`);
1819
- return { file, to, text, doc: odoc };
1820
- });
1821
- // The base's ACTUAL path, not one rebuilt from the name — a module that owns its namespace may
1822
- // author `collections/positions.collection.yaml` as `hr/positions`, and rebuilding the path then
1823
- // named a file that does not exist.
1824
- const src = sourceFile ?? path.join(workspaceSystemDir(ws, 'collections'), `${oldName}.collection.yaml`);
1825
- const dest = path.join(sourceDir ?? workspaceSystemDir(ws, 'collections'), `${newName}.collection.yaml`);
1826
- if (!fs.existsSync(src)) {
1827
- throw new Error(`"${oldName}" has no writable descriptor source — the manifest names none under a module in this workspace. it may be contributed by the engine itself.`);
1828
- }
1829
-
1830
- const doc = load(fs.readFileSync(src, 'utf8'));
1831
- const dataPath = ws.pkg.dreamteamer?.data_path ?? 'data';
1832
- // `d` is the COMPILED descriptor, so its storage.path already carries any module prefix; the
1833
- // authored source is what we compare against, and what we rewrite.
1834
- const authoredPath = String(doc.storage?.path ?? '');
1835
- const pathWasDerived = authoredPath === '' || authoredPath === defaultStoragePath(oldName, declared, dataPath);
1836
- const newPath = pathWasDerived ? defaultStoragePath(newName, declared, dataPath) : authoredPath;
1837
-
1838
- const oldBase = baseNameOf(oldName, declared);
1839
- const newBase = baseNameOf(newName, declared);
1840
- const oldSuffix = storageOf(d).suffix;
1841
- // AUTHORED is the test: an absent suffix is compile's default and follows the name by itself. An
1842
- // authored one that merely spells the old default is re-derived too, so filenames keep telling the
1843
- // truth about what they hold.
1844
- const authoredSuffix = doc.storage?.suffix;
1845
- const suffixWasDerived = authoredSuffix === undefined || authoredSuffix === singular(oldBase);
1846
- const newSuffix = suffixWasDerived ? singular(newBase) : oldSuffix;
1847
-
1848
- // Every id BEFORE anything moves — the store's index is keyed on the old collection.
1849
- const ids = [...store.ids(oldName).keys()];
1850
- for (const [id, f] of store.ids(oldName)) {
1851
- const layer = store.layerOfFile(d, f);
1852
- if (layer) throw new Error(`${oldName}/${id} is held by layer ${layer.layer} (${layer.path}) — a collection with records in a record layer is renamed in that workspace first; nothing was renamed`);
1853
- }
1854
- const oldDir = store.dir(d);
1855
- const newDir = path.join(ws.root, newPath);
1856
- if (newDir !== oldDir && fs.existsSync(newDir)) {
1857
- throw new Error(`${newPath} already exists on disk — move or remove it first; nothing was renamed`);
1858
- }
1859
-
1860
- // ---- rollback state, captured before the first mutation --------------------------------------
1861
- const srcBytes = fs.readFileSync(src);
1862
- let movedData = false;
1863
- let resuffixed = [];
1864
- const undo = () => {
1865
- for (const [from, to] of resuffixed) { if (fs.existsSync(to)) fs.renameSync(to, from); }
1866
- if (movedData && fs.existsSync(newDir)) {
1867
- fs.mkdirSync(path.dirname(oldDir), { recursive: true });
1868
- fs.renameSync(newDir, oldDir);
1869
- pruneEmpty(path.dirname(newDir), path.join(ws.root, dataPath));
1870
- }
1871
- fs.mkdirSync(path.dirname(src), { recursive: true });
1872
- fs.writeFileSync(src, srcBytes);
1873
- if (dest !== src) fs.rmSync(dest, { force: true });
1874
- for (const o of overlayMoves) {
1875
- fs.mkdirSync(path.dirname(o.file), { recursive: true });
1876
- fs.writeFileSync(o.file, o.text);
1877
- if (o.to !== o.file) fs.rmSync(o.to, { force: true });
1878
- }
1879
- };
1880
-
1881
- return store.withWriteLock(() => {
1882
- // ⚠ THERE IS NO CAPTURE PASS ANY MORE. This used to ask `findInboundRefs` per id — a full walk
1883
- // of every record file — purely to snapshot the referencing files for rollback, and then step 2
1884
- // walked them all again to rewrite them: the same bytes read twice, per id. The rewrite
1885
- // snapshots what it writes as it writes it (`store.rewriteRefsBatch`), so its own `restore` is
1886
- // the rollback and the pre-walk is pure cost. `refFiles` holds the sources steps 4 and 5
1887
- // rewrite (descriptors, mixins, views, package.json files), which no record walk visits.
1888
- const refFiles = new Map();
1889
- const rootPkg = path.join(ws.root, 'package.json');
1890
- const undoRewrites = [];
1891
- const restoreRefs = () => {
1892
- // reverse-chronological: one file can be written by both ref passes, and undoing the earlier
1893
- // write first would leave the later one standing
1894
- for (const u of [...undoRewrites].reverse()) u();
1895
- for (const [f, bytes] of refFiles) {
1896
- fs.mkdirSync(path.dirname(f), { recursive: true }); // pruneEmpty may have taken the parent
1897
- fs.writeFileSync(f, bytes);
1898
- }
1899
- };
1900
-
1901
- const touched = new Set();
1902
- let rewrites = 0;
1903
- try {
1904
- // 1. the descriptor source, at its new path — ROUND-TRIPPED, never re-dumped.
1905
- //
1906
- // ⚠ `fs.writeFileSync(dest, dump(doc))` destroyed every comment in the descriptor, and a
1907
- // descriptor's comments are where this project keeps its reasoning: 194 lines across 24
1908
- // files in one real migration, including 22-line headers stating what belongs in a
1909
- // collection and which failure mode it guards against. The record survived; the thinking
1910
- // did not, and nothing said so.
1911
- //
1912
- // A rename changes `name`, and `storage.path`/`storage.suffix` only where they are AUTHORED —
1913
- // an absent one is compile's default and follows the name by itself. `writeSource` rewrites
1914
- // exactly those; every other byte is restored from the source it was parsed out of. The parse
1915
- // afterwards still proves the edit landed rather than trusting the writer, and the comment
1916
- // count is asserted here because a rename does not go through `writeGated`'s invariant.
1917
- const beforeText = srcBytes.toString('utf8');
1918
- doc.name = newName;
1919
- if (authoredPath !== '') doc.storage.path = newPath;
1920
- if (authoredSuffix !== undefined) doc.storage.suffix = newSuffix;
1921
- const edited = writeSource(beforeText, doc);
1922
- const parsed = load(edited);
1923
- if (parsed?.name !== newName || (authoredPath !== '' && parsed?.storage?.path !== newPath) || (authoredSuffix !== undefined && parsed?.storage?.suffix !== newSuffix)) {
1924
- throw new Error(`could not rewrite ${path.relative(ws.root, src)} in place — name/storage.path/storage.suffix did not take. nothing was changed.`);
1925
- }
1926
- if (commentCount(edited) < commentCount(beforeText)) {
1927
- throw new Error(`renaming "${oldName}" would lose ${commentCount(beforeText) - commentCount(edited)} comment line(s) from ${path.relative(ws.root, src)} — nothing was changed.`);
1928
- }
1929
- fs.mkdirSync(path.dirname(dest), { recursive: true });
1930
- fs.writeFileSync(dest, edited);
1931
- if (dest !== src) fs.rmSync(src);
1932
- touched.add(src);
1933
- touched.add(dest);
1934
- // each overlay the same way: only its `name` changes, round-tripped over its own bytes
1935
- for (const o of overlayMoves) {
1936
- o.doc.name = newName;
1937
- const out = writeSource(o.text, o.doc);
1938
- if (load(out)?.name !== newName || commentCount(out) < commentCount(o.text)) {
1939
- throw new Error(`could not rewrite ${path.relative(ws.root, o.file)} in place — its name did not take without reformatting it. nothing was changed.`);
1940
- }
1941
- fs.mkdirSync(path.dirname(o.to), { recursive: true });
1942
- fs.writeFileSync(o.to, out);
1943
- if (o.to !== o.file) fs.rmSync(o.file);
1944
- touched.add(o.file);
1945
- touched.add(o.to);
1946
- }
1947
-
1948
- // 2. INBOUND REFERENCES FIRST, while the records are still where the store thinks they are.
1949
- //
1950
- // ⚠ This used to run AFTER the folder move and it silently missed every SELF-reference.
1951
- // `store.rewriteRefs` walks `recordFiles()`, which resolves each collection's directory
1952
- // from the descriptor loaded when the Store was built — i.e. the OLD `storage.path`. Move
1953
- // the records first and that walk finds an empty directory, so a record pointing at its
1954
- // own collection is never rewritten and dangles the moment compile catches up.
1955
- //
1956
- // It is not a corner case: it hit `finance/accounts`, where every card and loan carries
1957
- // `settled_by: <the account that settles it>` — 5 dangling refs out of 11 records, found
1958
- // only because `check` ran afterwards. Doing the rewrite first needs no descriptor reload
1959
- // and no second code path: the files are still at the old path, which is exactly what the
1960
- // old refs say.
1961
- // ONE pass for every id, not one pass per id — see `store.rewriteRefsBatch`. The
1962
- // `collections/<name>` retarget stays its own call: it is a different ref (into the
1963
- // `collections` collection), and folding it in would put a needle in the batch that shares
1964
- // no prefix with the rest and so switch the negative pre-filter off for all of them.
1965
- const out = store.rewriteRefsBatch(ids.map((id) => [`${oldName}/${id}`, `${newName}/${id}`]));
1966
- undoRewrites.push(out.restore);
1967
- rewrites += out.rewrites;
1968
- for (const f of out.touched) touched.add(f);
1969
- const collOut = store.rewriteRefs(`collections/${oldName}`, `collections/${newName}`);
1970
- undoRewrites.push(collOut.restore);
1971
- rewrites += collOut.rewrites;
1972
- for (const f of collOut.touched) touched.add(f);
1973
-
1974
- // 3. the record folder, then the per-file suffix if it was derived
1975
- if (newDir !== oldDir && fs.existsSync(oldDir)) {
1976
- fs.mkdirSync(path.dirname(newDir), { recursive: true });
1977
- fs.renameSync(oldDir, newDir);
1978
- movedData = true;
1979
- pruneEmpty(path.dirname(oldDir), path.join(ws.root, dataPath));
1980
- }
1981
- if (newSuffix !== oldSuffix && fs.existsSync(newDir)) {
1982
- // Match on the OLD suffix, keep whatever extension the file already had — an opaque
1983
- // record's extension is its own, and a re-suffix must not rename it into another format.
1984
- const old = { storage: { ...storageOf(d), suffix: oldSuffix } };
1985
- for (const file of walk(newDir)) {
1986
- const id = idFromRecordPath(old, path.relative(newDir, file));
1987
- if (id === null) continue;
1988
- const to = path.join(newDir, `${id}.${newSuffix}${path.basename(file).slice(path.basename(id).length + oldSuffix.length + 1)}`);
1989
- fs.renameSync(file, to);
1990
- resuffixed.push([file, to]);
1991
- }
1992
- }
1993
- if (movedData) { touched.add(oldDir); touched.add(newDir); }
1994
-
1995
- // 4. every SOURCE naming the collection bare: a field's `type` (scalar or union, nested
1996
- // object fields and map values included) in every collection and mixin, and the
1997
- // `collection: collections/<name>` a ui-view or binding is over. Not a `<collection>/<id>`
1998
- // ref, so step 2 cannot see it — and leaving it makes compile fail on an unknown type.
1999
- //
2000
- // ⚠ ROUND-TRIPPED, for the same reason step 1 is: a descriptor's comments are where its
2001
- // module writes down why the collection exists. The edit is made on the parsed value and
2002
- // `writeSource` puts it back over the original bytes; the parse afterwards proves it landed.
2003
- const sourcesNaming = [
2004
- ...descriptorSources(ws, store).map((f) => ({ f, edit: (doc) => retargetTypes(doc.fields, oldName, newName) })),
2005
- ...mixinSources(store).map(({ file }) => ({ f: file, edit: (doc) => retargetTypes(doc.fields, oldName, newName) })),
2006
- ...viewSources(store).map(({ file }) => ({ f: file, edit: (doc) => {
2007
- if (doc.collection !== `collections/${oldName}`) return false;
2008
- doc.collection = `collections/${newName}`;
2009
- return true;
2010
- } })),
2011
- ];
2012
- for (const { f, edit } of sourcesNaming) {
2013
- const before = fs.readFileSync(f, 'utf8');
2014
- const probe = load(before);
2015
- if (!probe || typeof probe !== 'object' || !edit(probe)) continue;
2016
- const after = writeSource(before, probe);
2017
- const reparsed = load(after);
2018
- if (!reparsed || edit(reparsed) || commentCount(after) < commentCount(before)) {
2019
- throw new Error(`could not retarget "${oldName}" in ${path.relative(ws.root, f)} without reformatting it — nothing was changed.`);
2020
- }
2021
- if (!refFiles.has(f)) refFiles.set(f, Buffer.from(before));
2022
- fs.writeFileSync(f, after);
2023
- touched.add(f);
2024
- rewrites++;
2025
- }
2026
-
2027
- // 5. every module's `dreamteamer.peer_collections` naming the collection: the list that
2028
- // lets a module overlay or reference it while it is installed. Step 4 retargeted those
2029
- // types and overlays, so a peer list left on the old name makes compile refuse them.
2030
- for (const f of modulePackageFiles(ws)) {
2031
- const before = fs.readFileSync(f, 'utf8');
2032
- let pkg;
2033
- try { pkg = JSON.parse(before); } catch { continue; }
2034
- const peers = pkg?.dreamteamer?.peer_collections;
2035
- if (!Array.isArray(peers) || !peers.includes(oldName)) continue;
2036
- pkg.dreamteamer.peer_collections = peers.map((p) => (p === oldName ? newName : p));
2037
- if (!refFiles.has(f)) refFiles.set(f, Buffer.from(before));
2038
- fs.writeFileSync(f, JSON.stringify(pkg, null, '\t') + '\n');
2039
- if (f === rootPkg) refreshWorkspacePkg(ws);
2040
- touched.add(f);
2041
- rewrites++;
2042
- }
2043
-
2044
- compile(ws); // the gate: an uncompilable rename never reaches history
2045
- } catch (e) {
2046
- // ⚠ undo() FIRST. A captured file can be a SELF-reference — a record of the collection being
2047
- // renamed — so its path only exists again once undo() has moved the folder back. Restoring
2048
- // before that wrote into a directory that was no longer there, and the ENOENT masked the
2049
- // error actually being rolled back from.
2050
- undo();
2051
- restoreRefs();
2052
- if (refFiles.has(rootPkg)) refreshWorkspacePkg(ws);
2053
- try { compile(ws); } catch { /* pre-rename sources were compilable */ }
2054
- throw e;
2055
- }
2056
-
2057
- // The pathspec filter now lives in `commitByRepo`, per repo — `isTracked` has to run in the
2058
- // repo that would track the path, and running it at the workspace root answered "no" for
2059
- // every path inside a git-shape module.
2060
- const rels = [...touched].map((f) => path.relative(ws.root, f));
2061
- let commits;
2062
- try {
2063
- commits = commitByRepo(ws, store, rels, `dreamteamer: collections rename ${oldName} → ${newName}`);
2064
- } catch (e) {
2065
- undo();
2066
- restoreRefs();
2067
- if (refFiles.has(rootPkg)) refreshWorkspacePkg(ws);
2068
- try { compile(ws); } catch { /* pre-rename sources were compilable */ }
2069
- throw new Error(`git commit failed — the rename was rolled back, nothing was changed. (${e.message.split('\n')[0]})`);
2070
- }
2071
-
2072
- return {
2073
- renamed: true, name: newName, records: ids.length, rewrites, commits,
2074
- from: path.relative(ws.root, oldDir), to: path.relative(ws.root, newDir),
2075
- suffix: newSuffix !== oldSuffix ? { from: oldSuffix, to: newSuffix } : null,
2076
- pathKept: pathWasDerived ? null : authoredPath,
2077
- };
2078
- });
2079
- }
2080
-
2081
- /** Does git know this path? A deleted-and-never-committed file must be dropped from a pathspec. */
2082
- function isTracked(root, rel) {
2083
- try {
2084
- execFileSync('git', ['ls-files', '--error-unmatch', '--', rel], { cwd: root, stdio: ['ignore', 'ignore', 'ignore'] });
2085
- return true;
2086
- } catch { return false; }
2087
- }
2088
-
2089
- /**
2090
- * ONE COMMIT PER REPO, in the repo that actually holds each source.
2091
- *
2092
- * ⚠ THE DEFECT THIS FIXES WAS SILENT ABOUT ITS OWN CAUSE. Every schema commit ran at the WORKSPACE
2093
- * root, and `git_modules/` is gitignored there — so `git add -- git_modules/hr/collections/…` added
2094
- * nothing, the pathspec-scoped `git commit` had nothing to record and failed, and the gate rolled
2095
- * the whole op back with a message naming git. A schema write into a git-shape module was therefore
2096
- * impossible, and the reason was invisible: the source compiled, the field was live for one
2097
- * instant, and then the file was restored.
2098
- *
2099
- * `repoRootOf` (compile.js, there since `owns_data` needed it) answers "which repo holds this path"
2100
- * — nearest `.git` at or above it, workspace-relative, `.` for the workspace itself. Grouping by it
2101
- * is the whole fix.
2102
- *
2103
- * Returns `[{repo, sha, ahead}]` so the caller can say WHERE the change landed. `ahead` is the count
2104
- * of commits the repo has that its upstream does not — meaningful only for a clone, and `null` for
2105
- * the workspace, whose publishing story is `git push` like any repo the operator already thinks
2106
- * about.
2107
- *
2108
- * ⚠ ALL-OR-NOTHING ACROSS REPOS IS NOT ACHIEVABLE and is not claimed. Two repos cannot commit
2109
- * atomically. So the FIRST failure aborts, the caller's `undo` restores every source in every repo,
2110
- * and any commit already made is left standing with its own subject — which is honest and
2111
- * inspectable, unlike a partial write with no history. `dt status` then shows the drift. Extending
2112
- * `dt commit` to module sources is the follow-on this file has always named; it is not this wave.
2113
- */
2114
- function commitByRepo(ws, store, rels, subject) {
2115
- const byRepo = new Map(); // workspace-relative repo root -> {root, paths relative to THAT repo}
2116
- for (const rel of new Set(rels)) {
2117
- const abs = path.join(ws.root, rel);
2118
- // A path that is neither on disk nor in any index cannot be a pathspec, and one bad entry
2119
- // aborts the whole `git add` — the lesson `renameCollection` paid for. ⚠ The filter runs PER
2120
- // REPO: `isTracked` has to run in the repo that would track the path, and running it at the
2121
- // workspace root answered "no" for every path inside a clone.
2122
- const repo = repoRootOf(path.dirname(abs), ws.root);
2123
- const repoAbs = repo === '.' ? ws.root : path.join(ws.root, repo);
2124
- const inRepo = path.relative(repoAbs, abs);
2125
- if (!fs.existsSync(abs) && !isTracked(repoAbs, inRepo)) continue;
2126
- if (!byRepo.has(repo)) byRepo.set(repo, { root: repoAbs, paths: [] });
2127
- byRepo.get(repo).paths.push(inRepo);
2128
- }
2129
- const out = [];
2130
- try {
2131
- for (const [repo, { root, paths }] of byRepo) {
2132
- execFileSync('git', ['add', '--all', '--', ...paths], { cwd: root, stdio: GIT_QUIET });
2133
- execFileSync('git', ['commit', '--quiet', '-m', subject, '--', ...paths], { cwd: root, stdio: GIT_QUIET });
2134
- out.push({ repo, sha: shortHead(root), ahead: repo === '.' ? null : aheadCount(root) });
2135
- }
2136
- } catch (e) {
2137
- // unstage everything this call touched, in every repo, before handing the failure back
2138
- for (const [, { root, paths }] of byRepo) {
2139
- try { execFileSync('git', ['reset', '--quiet', '--', ...paths], { cwd: root, stdio: GIT_QUIET }); } catch { /* nothing staged */ }
2140
- }
2141
- e.commits = out; // what DID land, for the caller's message
2142
- throw e;
2143
- } finally {
2144
- store.headMoved(); // this ran `git commit` — see store.gitHead
2145
- }
2146
- return out;
2147
- }
2148
-
2149
- const shortHead = (root) => {
2150
- try { return execFileSync('git', ['rev-parse', '--short', 'HEAD'], { cwd: root, stdio: GIT_QUIET }).toString().trim(); } catch { return null; }
2151
- };
2152
-
2153
- /** How many commits this repo has that its upstream does not. Falls back to "not on any remote",
2154
- * because a fresh `dt install --clone` has no upstream configured and "ahead of nothing" is not a
2155
- * number the report can print. */
2156
- function aheadCount(root) {
2157
- try {
2158
- const n = execFileSync('git', ['rev-list', '--count', '@{upstream}..HEAD'], { cwd: root, stdio: GIT_QUIET }).toString().trim();
2159
- return Number(n);
2160
- } catch {
2161
- try {
2162
- const n = execFileSync('git', ['rev-list', '--count', 'HEAD', '--not', '--remotes'], { cwd: root, stdio: GIT_QUIET }).toString().trim();
2163
- return Number(n) || 1;
2164
- } catch { return 1; }
2165
- }
2166
- }
2167
-
2168
- /** Every workspace-owned descriptor source, recursively (namespaced descriptors are nested). */
2169
- function descriptorSources(ws, store) {
2170
- const out = [];
2171
- for (const root of store.sourceRoots()) {
2172
- const dir = kindDir(root, 'collections');
2173
- // ⚠ SPREAD FIRST. `walk` is a GENERATOR, and `Iterator.prototype.filter` is a Node 22 iterator
2174
- // helper — so `walk(dir).filter(...)` works on 22 and throws "filter is not a function" on 20,
2175
- // which package.json still supports (`"node": ">=20"`). Caught by the CI matrix, not by local runs.
2176
- if (fs.existsSync(dir)) out.push(...[...walk(dir)].filter((f) => f.endsWith('.collection.yaml')));
2177
- }
2178
- return out;
2179
- }
2180
-
2181
- /** Every package.json in this workspace that can declare `peer_collections` — the workspace's own
2182
- * and each module's outside node_modules (a write there is erased by the next install). */
2183
- function modulePackageFiles(ws) {
2184
- const roots = new Set(['.', ...(readManifest(ws.root)?.modules ?? []).map((m) => m.root)]);
2185
- return [...roots]
2186
- .filter((r) => typeof r === 'string' && !IN_NODE_MODULES(r))
2187
- .map((r) => path.join(ws.root, r, 'package.json'))
2188
- .filter((f) => fs.existsSync(f));
2189
- }
2190
-
2191
- /** Re-read the workspace package.json into `ws.pkg` in place — `compile({root, pkg})` reads the
2192
- * object it was handed, not the file. */
2193
- function refreshWorkspacePkg(ws) {
2194
- let pkg;
2195
- try { pkg = JSON.parse(fs.readFileSync(path.join(ws.root, 'package.json'), 'utf8')); } catch { return; }
2196
- for (const k of Object.keys(ws.pkg)) delete ws.pkg[k];
2197
- Object.assign(ws.pkg, pkg);
2198
- }
2199
-
2200
- /** Rewrite a field `type` naming `oldName` → `newName` — a scalar type or a union member, at any
2201
- * depth of object `fields` and map `values`. Returns true if anything changed. */
2202
- function retargetTypes(fields, oldName, newName) {
2203
- let changed = false;
2204
- for (const f of Object.values(fields ?? {})) {
2205
- if (!f || typeof f !== 'object') continue;
2206
- if (f.type === oldName) { f.type = newName; changed = true; }
2207
- else if (Array.isArray(f.type) && f.type.includes(oldName)) { f.type = f.type.map((t) => (t === oldName ? newName : t)); changed = true; }
2208
- if (f.fields && retargetTypes(f.fields, oldName, newName)) changed = true;
2209
- if (f.values && typeof f.values === 'object') {
2210
- if (f.values.type !== undefined && retargetTypes({ v: f.values }, oldName, newName)) changed = true;
2211
- } else if (f.values === oldName) { f.values = newName; changed = true; }
2212
- }
2213
- return changed;
2214
- }
2215
-
2216
- /** Remove now-empty parents up to (not including) the data root — a moved collection leaves its
2217
- * namespace folder behind otherwise. */
2218
- function pruneEmpty(dir, stopAt) {
2219
- while (dir !== stopAt && dir.startsWith(stopAt) && fs.existsSync(dir) && fs.readdirSync(dir).length === 0) {
2220
- fs.rmdirSync(dir);
2221
- dir = path.dirname(dir);
2222
- }
2223
- }
2224
-
2225
- // ---- the field verbs ----------------------------------------------------------------------------
2226
- // A field is one entry of a descriptor's `fields` map, in the vocabulary a person writes (`type:
2227
- // date`, `many: true`, `mirror_of: patient`). The verbs build that entry from flags, place it in the
2228
- // source that declares it, and write it through the YAML document, so every comment and every
2229
- // untouched byte stays where its author put it.
2230
-
2231
- /** The order a field's keys are written in (§3.4.1): facts about the data, `display`, then what it means. */
2232
- const FIELD_KEY_ORDER = ['type', 'title', 'required', 'many', 'default', 'enum', 'unique', 'mirror_of', 'on_delete', 'soft', 'sensitive', 'body', 'derived', 'virtual', 'deprecated', 'passthrough', 'fields', 'values', 'item_title', 'examples', 'pattern', 'minimum', 'maximum', 'minItems', 'maxItems', 'minLength', 'maxLength', 'const', 'display', 'description'];
2233
-
2234
- /** The fields compile injects into every collection — no source declares one. */
2235
- const INJECTED = new Set(Object.keys(INJECTED_FIELDS));
2236
-
2237
- /** `--type`: a built-in type, a collection, `a,b` for a union of collections, or `reference`. A
2238
- * collection may not be named after a built-in type (compile refuses it), so the two never collide. */
2239
- function parseType(store, raw) {
2240
- const known = `one of ${SCALAR_TYPES.join(' ')}, a collection name, or a,b for a union of collections`;
2241
- if (raw === true || raw === '') throw new Error(`--type takes a value — ${known}`);
2242
- const parts = String(raw).split(',').map((x) => x.trim()).filter(Boolean);
2243
- if (parts.length > 1) {
2244
- const bad = parts.filter((t) => !store.descriptors.has(t));
2245
- if (bad.length) throw new Error(`--type ${raw}: a union names collections, and ${bad.join(', ')} ${bad.length === 1 ? 'is' : 'are'} not one — ${known}`);
2246
- return parts;
2247
- }
2248
- if (SCALAR_TYPES.includes(parts[0]) || store.descriptors.has(parts[0])) return parts[0];
2249
- throw new Error(`unknown type "${parts[0]}" — ${known}`);
2250
- }
2251
-
2252
- /** A boolean flag: bare or `true` turns it on; `false` or the empty value clears it. */
2253
- function flagOn(flags, key) {
2254
- const v = flags[key];
2255
- if (v === true || v === 'true') return true;
2256
- if (v === false || v === 'false' || v === '') return false;
2257
- throw new Error(`--${key} takes true or false — got "${v}"`);
2258
- }
2259
-
2260
- /** A flag that takes a value; the empty value (`--x=`) clears what it names. */
2261
- function flagText(flags, key) {
2262
- const v = flags[key];
2263
- if (v === true) throw new Error(`--${key} takes a value (--${key}= clears it)`);
2264
- return String(v);
2265
- }
2266
-
2267
- /** A CLI default arrives as a string; which JSON value it becomes depends on the field's type. */
2268
- const coerceDefault = (type, def) => (type === 'boolean'
2269
- ? def === 'true' || def === true
2270
- : type === 'number' || type === 'integer' ? Number(def) : def);
2271
-
2272
- /** `a,b,c` → the values, trimmed. */
2273
- const optionList = (v) => (Array.isArray(v) ? v : String(v).split(',')).map((x) => String(x).trim()).filter(Boolean);
2274
-
2275
- /**
2276
- * One field, built from the flag vocabulary over `previous` — the field as its source declares it
2277
- * (`{}` for a new one). Each flag owns the key it names and nothing else, so a flag that is not
2278
- * passed leaves its key exactly as authored: `set-field --description "…"` changes the description
2279
- * and only the description. The empty value clears a key (`--enum=`), and `false` clears a boolean.
2280
- *
2281
- * --type string|markdown|…|<collection>|a,b|reference --many --required --unique
2282
- * --enum a,b --default-value v --mirror-of <field> --on-delete restrict|set-null --soft
2283
- * --sensitive --body --description "…"
2284
- */
2285
- export function fieldFromFlags(store, flags, previous = {}) {
2286
- const f = structuredClone(previous ?? {});
2287
- const has = (k) => flags[k] !== undefined;
2288
- if (has('type')) f.type = parseType(store, flags.type);
2289
- f.type ??= 'string';
2290
- for (const k of ['required', 'many', 'unique', 'soft', 'sensitive', 'body']) {
2291
- if (!has(k)) continue;
2292
- if (flagOn(flags, k)) f[k] = true;
2293
- else delete f[k];
2294
- }
2295
- if (has('enum')) {
2296
- const v = flagText(flags, 'enum');
2297
- if (v === '') delete f.enum;
2298
- else {
2299
- const values = optionList(v);
2300
- // a decorated enum keeps each surviving value's label, icon and colour
2301
- f.enum = f.enum && typeof f.enum === 'object' && !Array.isArray(f.enum)
2302
- ? Object.fromEntries(values.map((x) => [x, f.enum[x] ?? {}]))
2303
- : values;
2304
- }
2305
- }
2306
- if (has('mirror-of')) {
2307
- const v = flagText(flags, 'mirror-of');
2308
- if (v === '') delete f.mirror_of;
2309
- else {
2310
- const t = targetsOf(f);
2311
- if (!Array.isArray(t) || t.length !== 1) throw new Error(`--mirror-of ${v} needs --type <collection>: the one collection whose "${v}" field points here`);
2312
- const fk = fieldsOf(store.descriptor(t[0]))[v];
2313
- if (!fk) throw new Error(`--mirror-of ${v}: ${t[0]} has no field "${v}"`);
2314
- f.mirror_of = v;
2315
- // the far side's key decides the cardinality: a unique scalar key is claimed by one record,
2316
- // so its mirror holds one; any other key can be claimed by many
2317
- if (!has('many')) {
2318
- if (fk.unique && !fk.many) delete f.many;
2319
- else f.many = true;
2320
- }
2321
- }
2322
- }
2323
- if (has('on-delete')) {
2324
- const v = flags['on-delete'];
2325
- if (v === '') delete f.on_delete;
2326
- else if (v === 'restrict' || v === 'set-null') f.on_delete = v;
2327
- else throw new Error('--on-delete takes restrict or set-null');
2328
- }
2329
- const def = flags['default-value'] ?? flags.default;
2330
- if (def !== undefined) {
2331
- if (def === true) throw new Error('--default-value takes a value (--default-value= clears it)');
2332
- if (def === '') delete f.default;
2333
- else f.default = f.many ? optionList(def).map((x) => coerceDefault(f.type, x)) : coerceDefault(f.type, def);
2334
- }
2335
- if (has('description')) {
2336
- const v = flagText(flags, 'description');
2337
- if (v === '') delete f.description;
2338
- else f.description = v;
2339
- }
2340
- // what a flag can be held to before the gate compile, so the refusal names the flag
2341
- if (f.body && f.type !== 'markdown') throw new Error(`--body marks the field a record's prose lands in, so it is --type markdown (got ${f.type})`);
2342
- if (has('enum') && f.enum !== undefined && f.type !== 'string') throw new Error(`--enum belongs to --type string (got ${Array.isArray(f.type) ? f.type.join(',') : f.type})`);
2343
- if (has('on-delete') && f.on_delete !== undefined && !targetsOf(f)) throw new Error(`--on-delete belongs to a reference — give --type <collection>`);
2344
- if (has('soft') && f.soft && !targetsOf(f)) throw new Error(`--soft belongs to a reference — give --type <collection>`);
2345
- return orderField(previous ?? {}, f);
2346
- }
2347
-
2348
- /**
2349
- * The field's keys in writing order: the keys the source already had stay where its author put
2350
- * them, and a new key goes in at its canonical place among them — so `set-field --unique` adds one
2351
- * line and moves none.
2352
- */
2353
- function orderField(previous, next) {
2354
- const rank = (k) => { const i = FIELD_KEY_ORDER.indexOf(k); return i < 0 ? FIELD_KEY_ORDER.length : i; };
2355
- const keys = Object.keys(previous).filter((k) => k in next);
2356
- for (const k of Object.keys(next).filter((x) => !keys.includes(x)).sort((a, b) => rank(a) - rank(b))) {
2357
- const at = keys.findIndex((x) => rank(x) > rank(k));
2358
- keys.splice(at < 0 ? keys.length : at, 0, k);
2359
- }
2360
- return Object.fromEntries(keys.map((k) => [k, next[k]]));
2361
- }
2362
-
2363
- /**
2364
- * The `fields` map with `name` set. A NEW field lands before the body field, because field order is
2365
- * form order and a record's prose belongs last; an EXISTING one keeps its place, because `set-field`
2366
- * must not reorder a descriptor its author ordered by hand.
2367
- */
2368
- function placeField(fields, name, field) {
2369
- if (fields[name] !== undefined) return { ...fields, [name]: field };
2370
- const body = Object.keys(fields).find((k) => fields[k]?.body === true);
2371
- if (body === undefined) return { ...fields, [name]: field };
2372
- const out = {};
2373
- for (const [k, v] of Object.entries(fields)) {
2374
- if (k === body) out[name] = field;
2375
- out[k] = v;
2376
- }
2377
- return out;
2378
- }
2379
-
2380
- /** Deep value equality as a string, key ORDER ignored — "is this already exactly that field" must
2381
- * not turn on whether the keys came back in authored order or in flag order. */
2382
- function canonical(v) {
2383
- if (v === null || typeof v !== 'object') return JSON.stringify(v ?? null);
2384
- if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]`;
2385
- return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(',')}}`;
2386
- }
2387
-
2388
- /**
2389
- * THE SOURCE THAT DECLARES AN EXISTING FIELD — the one `set-field` and `rm-field` edit.
2390
- *
2391
- * The base when it declares it; the one overlay that does when the base does not (a field another
2392
- * module added); `--module` to choose between a base and an overlay that both do. A field a mixin
2393
- * contributes is refused, because the mixin is shared by every collection listing it, and an
2394
- * injected field has no source at all.
2395
- */
2396
- function declaringSource(ws, store, collection, fieldName, moduleId, verb) {
2397
- if (INJECTED.has(fieldName)) throw new Error(`"${fieldName}" is injected by the engine into every collection — no source declares it, so ${verb} cannot edit it`);
2398
- if (!fieldsOf(store.descriptor(collection))[fieldName]) throw new Error(`no field "${fieldName}" on ${collection}`);
2399
- if (moduleId !== undefined && moduleId !== null && moduleId !== '') {
2400
- return collectionSourceFile(ws, store, collection, moduleId, { subject: `${collection}.${fieldName}`, allowNew: verb === 'set-field' });
2401
- }
2402
- const { base, overlays } = baseDescriptorSource(ws, collection);
2403
- const declares = (rel) => !!rel && readYaml(path.join(ws.root, rel))?.fields?.[fieldName] !== undefined;
2404
- if (declares(base) && !IN_NODE_MODULES(base)) return { file: path.join(ws.root, base), overlay: false };
2405
- const own = overlays.filter(declares);
2406
- if (own.length > 1) throw new Error(`${collection}.${fieldName} is declared by ${own.join(', ')} — say which with --module <m>`);
2407
- if (own.length === 1 && !IN_NODE_MODULES(own[0])) return { file: path.join(ws.root, own[0]), overlay: true };
2408
- const mixin = mixinDeclaring(ws, store, collection, fieldName);
2409
- if (mixin) throw new Error(`${collection}.${fieldName} comes from mixin "${mixin.id}" (${mixin.rel}), which every collection listing it shares — edit the mixin, or declare the field on ${collection} itself`);
2410
- if (verb === 'rm-field') throw new Error(`${collection}.${fieldName} is declared by ${base ?? own[0] ?? 'a source this workspace cannot rewrite'}, which ships from node_modules — an overlay can override a field there, never remove it`);
2411
- // declared only where `npm install` would erase a write: an override in an overlay is the remedy
2412
- return collectionSourceFile(ws, store, collection, undefined, { subject: `${collection}.${fieldName}` });
2413
- }
2414
-
2415
- /** What an override in a NEW overlay starts from: the shape it overrides, so the overlay validates
2416
- * on its own — every other key is inherited from the base. */
2417
- const overrideSeed = (merged) => ({ type: merged.type, ...(merged.many && { many: true }) });
2418
-
2419
- export function addField(ws, store, collection, { name: fieldName, field, moduleId }) {
2420
- if (!fieldName || fieldName === true) throw new Error('missing --name <field>');
2421
- if (INJECTED.has(fieldName)) throw new Error(`"${fieldName}" is injected by the engine into every collection — pick another name`);
2422
- const merged = fieldsOf(store.descriptor(collection))[fieldName];
2423
- const target = collectionSourceFile(ws, store, collection, moduleId, { allowNew: true, subject: `${collection}.${fieldName}` });
2424
- // ⚠ On an OVERLAY, a field the base already declares is an OVERRIDE, not a duplicate — that is
2425
- // what an overlay is for. Only a write to the base, or to an overlay that already declares it,
2426
- // can collide.
2427
- if (merged !== undefined) {
2428
- const mixin = mixinDeclaring(ws, store, collection, fieldName);
2429
- const inTarget = readYaml(target.file)?.fields?.[fieldName] !== undefined;
2430
- if (!target.overlay || inTarget || mixin) {
2431
- throw new Error(`field "${fieldName}" already exists on ${collection}${mixin ? ` (from mixin "${mixin.id}")` : ''} — change it with dreamteamer set-field ${collection} --name ${fieldName} …`);
2432
- }
2433
- }
2434
- return upsertField(ws, store, collection, fieldName, field, `add-field ${fieldName}`, target);
2435
- }
2436
-
2437
- /**
2438
- * Change one field. `flags` is the flag vocabulary (`fieldFromFlags`), applied over the field as its
2439
- * source declares it; `field` is a whole v2 field from a surface, which replaces it.
2440
- */
2441
- export function updateField(ws, store, collection, fieldName, { flags = {}, field, moduleId } = {}) {
2442
- const target = declaringSource(ws, store, collection, fieldName, moduleId, 'set-field');
2443
- const authored = readYaml(target.file)?.fields?.[fieldName];
2444
- const previous = authored ?? overrideSeed(fieldsOf(store.descriptor(collection))[fieldName]);
2445
- return upsertField(ws, store, collection, fieldName, field ?? fieldFromFlags(store, flags, previous), `set-field ${fieldName}`, target);
2446
- }
2447
-
2448
- function upsertField(ws, store, collection, fieldName, field, verb, { file: dest, overlay }) {
2449
- if (field == null || typeof field !== 'object' || Array.isArray(field)) {
2450
- throw new Error(`field "${fieldName}" must be a map of field keys (got ${Array.isArray(field) ? 'a list' : typeof field}) — nothing was written.`);
2451
- }
2452
- // The BYTES, not just the parse: `dump` cannot round-trip a comment, and a collection descriptor is
2453
- // where a module writes down why the collection exists (see writeSource).
2454
- const previousText = fs.existsSync(dest) ? fs.readFileSync(dest, 'utf8') : null;
2455
- let doc;
2456
- if (previousText !== null) doc = load(previousText);
2457
- // Reached when no source this workspace may rewrite declares the collection — an npm-shipped or
2458
- // engine-contributed one. An overlay in the workspace module is the remedy, and compile still
2459
- // requires that module to declare the base's in its dependencies.
2460
- else if (overlay) doc = { name: collection, overlay: true, fields: {} };
2461
- else throw new Error(`${path.relative(ws.root, dest)} is named by the compiled manifest but is not on disk — run \`dreamteamer compile\` and re-run.`);
2462
- // AN IDEMPOTENT WRITE IS A SUCCESS — a re-run of an "apply my schema" script, or a retry after a
2463
- // partial failure, asks for what is already there. Say so plainly and stop, without a commit; but
2464
- // still through the compile, so a broken workspace fails exactly as the gate fails it.
2465
- const already = doc.fields?.[fieldName];
2466
- if (already !== undefined && canonical(already) === canonical(field)) {
2467
- compileGated(ws, store);
2468
- return { collection, field: fieldName, file: dest, overlay, value: already, unchanged: true };
2469
- }
2470
- const gate = writeGated(ws, store, [dest], `dreamteamer: ${collection} ${verb}`, () => {
2471
- doc.fields = placeField(doc.fields ?? {}, fieldName, field);
2472
- fs.mkdirSync(path.dirname(dest), { recursive: true });
2473
- fs.writeFileSync(dest, writeSource(previousText, doc));
2474
- });
2475
- return { collection, field: fieldName, file: dest, overlay, value: field, commits: gate.commits };
2476
- }
2477
-
2478
- /**
2479
- * Clear one field's values from every record of a collection — the other half of removing it.
2480
- *
2481
- * A removed field whose values stay in the files leaves the collection READABLE AND UNWRITABLE: the
2482
- * key is now an unknown field, `check` reports it and the store refuses the next write to that
2483
- * record. So the op that creates the staleness cleans it up, in the same write and the same commit.
2484
- * A mirror is a field like any other here: its values live in this collection's records.
2485
- *
2486
- * ⚠ THIS DELETES DATA, deliberately: removing a field is an explicit destructive schema act, it runs
2487
- * inside the gate's commit, so the previous values are one `git show HEAD~1` away, and the COUNT is
2488
- * returned and printed — a silent deletion and a reported one are different acts.
2489
- *
2490
- * ⚠ THE BODY FIELD needs none of this. With the field gone the descriptor names no body, so the
2491
- * prose is not parsed into `fields` at all and stays in the file as Markdown no field claims.
2492
- */
2493
- function clearFieldValues(store, collection, fieldName) {
2494
- const d = store.descriptors.get(collection);
2495
- // a binary record has no serialised fields, and a compiled-source collection is a build artifact
2496
- if (!d || !store.canRewrite(collection)) return { files: [], undo: () => {}, records: 0 };
2497
- const bf = bodyFieldOf(d);
2498
- const files = [], undos = [];
2499
- for (const [, file] of store.ids(collection)) {
2500
- let fields;
2501
- try { fields = parseRecord(file, d, bf); } catch { continue; } // `check` reports a bad record
2502
- if (!(fieldName in fields)) continue;
2503
- const previous = fs.readFileSync(file, 'utf8');
2504
- delete fields[fieldName];
2505
- atomicWrite(file, serialize(d, fields, previous));
2506
- files.push(file);
2507
- undos.push(() => atomicWrite(file, previous));
2508
- }
2509
- return { files, undo: () => { for (const u of [...undos].reverse()) u(); }, records: files.length };
2510
- }
2511
-
2512
- /** The positions in the edited source that are the field's OWN presentation — removing the field is
2513
- * an explicit act, and pruning these is what it means. Everything else naming it is refused. */
2514
- const PRUNED_WITH_THE_FIELD = /^display\.(list\.(columns|sort|options\.[a-z_]+)|record\.(badge|color_by)|form\.sections\[\d+\])$/;
2515
-
2516
- /** Prune the field's own presentation from one parsed source, dropping what the prune empties. */
2517
- function pruneFieldPresentation(doc, fieldName) {
2518
- const display = doc.display;
2519
- if (!display || typeof display !== 'object') return;
2520
- const list = display.list;
2521
- if (list) {
2522
- if (Array.isArray(list.columns)) {
2523
- list.columns = list.columns.filter((c) => c !== fieldName);
2524
- if (!list.columns.length) delete list.columns;
2525
- }
2526
- if (typeof list.sort === 'string' && list.sort.replace(/^-/, '') === fieldName) delete list.sort;
2527
- if (list.options && typeof list.options === 'object') {
2528
- for (const k of OPTION_FIELD_KEYS) if (list.options[k] === fieldName) delete list.options[k];
2529
- for (const k of OPTION_FIELD_LISTS) {
2530
- if (!Array.isArray(list.options[k])) continue;
2531
- list.options[k] = list.options[k].filter((c) => c !== fieldName);
2532
- if (!list.options[k].length) delete list.options[k];
2533
- }
2534
- if (!Object.keys(list.options).length) delete list.options;
2535
- }
2536
- }
2537
- for (const k of ['badge', 'color_by']) if (display.record?.[k] === fieldName) delete display.record[k];
2538
- if (Array.isArray(display.form?.sections)) {
2539
- display.form.sections = display.form.sections
2540
- .map((sec) => (Array.isArray(sec?.fields) ? { ...sec, fields: sec.fields.filter((f) => f !== fieldName) } : sec))
2541
- .filter((sec) => !Array.isArray(sec?.fields) || sec.fields.length);
2542
- if (!display.form.sections.length) delete display.form.sections;
2543
- }
2544
- // a block the prune left empty is a statement nobody made
2545
- for (const b of Object.keys(display)) if (display[b] && typeof display[b] === 'object' && !Object.keys(display[b]).length) delete display[b];
2546
- if (!Object.keys(display).length) delete doc.display;
2547
- }
2548
-
2549
- /** What `rm-field` would do, counted without writing: the values it clears, the presentation it
2550
- * prunes, and every position elsewhere that still names the field — which it refuses on. */
2551
- export function removeFieldPlan(ws, store, collection, fieldName, { moduleId } = {}) {
2552
- const { file } = declaringSource(ws, store, collection, fieldName, moduleId, 'rm-field');
2553
- const rel = path.relative(ws.root, file);
2554
- if (readYaml(file)?.fields?.[fieldName] === undefined) throw new Error(`${rel} does not declare ${collection}.${fieldName} — it is declared by ${declaringModules(ws, store, collection).join(', ')}; drop --module, or name the module whose source declares it`);
2555
- // the same walk a rename makes, to a name nothing can hold: every position it reaches names the field
2556
- const { positions } = fieldRenameWalk(ws, store, collection, fieldName, `${fieldName}\u0000`, { records: false });
2557
- const own = (p) => p.rel === rel && (p.at === `fields.${fieldName}` || PRUNED_WITH_THE_FIELD.test(p.at));
2558
- // another source declaring the field keeps it alive — an override removed from an overlay, say —
2559
- // so nothing naming it dangles and its values stay
2560
- const survives = positions.some((p) => p.rel !== rel && p.at === `fields.${fieldName}`);
2561
- const blocking = survives ? [] : positions.filter((p) => !own(p)).map((p) => ({ ...p, fixed: false, why: p.why ?? 'it would name a field that no longer exists' }));
2562
- const d = store.descriptor(collection);
2563
- let cleared = 0;
2564
- if (!survives && store.canRewrite(collection)) {
2565
- const bf = bodyFieldOf(d);
2566
- for (const [, f] of store.ids(collection)) {
2567
- try { if (fieldName in parseRecord(f, d, bf)) cleared++; } catch { /* `check` reports it */ }
2568
- }
2569
- }
2570
- return {
2571
- collection, field: fieldName, file, positions: positions.filter(own), blocking,
2572
- records: cleared, refs: 0, descriptors: 1, cleared,
2573
- };
2574
- }
2575
-
2576
- export function removeField(ws, store, collection, fieldName, { moduleId, dryRun = false } = {}) {
2577
- const plan = removeFieldPlan(ws, store, collection, fieldName, { moduleId });
2578
- if (dryRun) return { ...plan, dryRun: true };
2579
- // ⚠ A NAME ANOTHER POSITION STILL CARRIES IS REFUSED, not left dangling: compile validates every
2580
- // one of them (rule 6), and a template, a constraint, a mirror or a view naming a field that is
2581
- // gone is a decision about what it should say instead — which is the operator's to make.
2582
- refusePositions(`rm-field ${collection} --name ${fieldName}`, plan.blocking);
2583
- const dest = plan.file;
2584
- const previousText = fs.readFileSync(dest, 'utf8');
2585
- const doc = load(previousText);
2586
- const out = writeGated(ws, store, [dest], `dreamteamer: ${collection} rm-field ${fieldName}`, () => {
2587
- delete doc.fields[fieldName];
2588
- pruneFieldPresentation(doc, fieldName);
2589
- // an overlay whose last field is gone adds nothing to the merge — removing its last field
2590
- // removes the file
2591
- if (doc.overlay === true && !Object.keys(doc.fields).length && Object.keys(doc).every((k) => ['name', 'overlay', 'fields'].includes(k))) fs.rmSync(dest);
2592
- else fs.writeFileSync(dest, writeSource(previousText, doc));
2593
- }, () => {
2594
- const after = new Store(ws); // the runtime as the gate compile just left it
2595
- if (fieldsOf(after.descriptor(collection))[fieldName]) return {};
2596
- const own = clearFieldValues(after, collection, fieldName);
2597
- return { files: own.files, undo: own.undo, cleared: own.records };
2598
- // ⚠ THE ONE OP THAT MAY LOSE A COMMENT: the comment above a field explains THAT field, so
2599
- // removing the field takes it, which is the outcome asked for.
2600
- }, { commentsMayDecrease: true });
2601
- return { collection, removed: fieldName, cleared: out.cleared, commits: out.commits };
2602
- }
2603
-
2604
- /**
2605
- * WHERE A UI-VIEW'S SOURCE ACTUALLY LIVES — asked of the manifest, exactly as `descriptorSourceDir`
2606
- * asks it for a collection, and for the same reason: the guard that matters is "will `npm install`
2607
- * erase this write", not "which module owns it".
2608
- *
2609
- * ⚠ This used to be `workspaceSystemDir` unconditionally, which silently meant a view could only be
2610
- * saved if the WORKSPACE MODULE happened to ship it. Saving one shipped by any other inline module
2611
- * wrote a SECOND file carrying the same id, and compile refuses that by name — so the whole write
2612
- * rolled back and the surface reported `name collision on ui-view "…"` instead of saving. Measured
2613
- * on a three-module workspace: every one of the views shipped by a module OTHER than the workspace
2614
- * module was unsaveable, and the failure said nothing about why.
2615
- *
2616
- * Returns `{ file, shipped }` — where to write, and the workspace-relative source that already
2617
- * exists (null for a new view, which lands in the workspace module as before).
2618
- */
2619
- function uiViewSourceFile(ws, id) {
2620
- const src = readManifest(ws.root)?.entries?.[`ui-views/${id}.ui-view.yaml`]?.sources?.[0];
2621
- // sources are `{path, hash}`; tolerate the pre-0.10 string form, same as compile's staleness check
2622
- const shipped = typeof src === 'string' ? src : src?.path;
2623
- if (!shipped) return { file: path.join(workspaceSystemDir(ws, 'ui-views'), `${id}.ui-view.yaml`), shipped: null };
2624
- return { file: path.join(ws.root, shipped), shipped };
2625
- }
2626
-
2627
- // saved views (M3): a studio-saved view IS a ui-view record — but ui-views are
2628
- // system-stored (sources + compile), so the write goes through the same gate as any
2629
- // other schema op. the studio "save view" button lands here.
2630
- export function saveUiView(ws, store, { id, view, moduleId }) {
2631
- if (!id || !/^[a-z0-9][a-z0-9-/]*$/.test(id)) throw new Error(`invalid ui-view id "${id}" — lowercase slug required`);
2632
- // §5: `add` on a system collection takes `--module`. It used to be dropped by the parser and then
2633
- // assigned into the VIEW as a field called `module` — `dt add ui-views … --module core` wrote
2634
- // `module: core` into the yaml, compiled clean, and self-committed a workspace only `dt check`
2635
- // would later object to. An explicit target module resolves the destination; without one the
2636
- // manifest answers (an existing view is edited where it lives), and the workspace module is the
2637
- // fallback for a new one.
2638
- const target = moduleId ? moduleRecord(store, moduleId) : null;
2639
- if (target && IN_NODE_MODULES(target.fields.path)) {
2640
- throw new Error(`module "${moduleId}" ships from node_modules (${target.fields.path}) — a write there is erased by the next npm install.\n pick a module whose sources are in this workspace (the workspace module is the default).`);
2641
- }
2642
- const { file: dest, shipped } = target
2643
- ? { file: path.join(kindDir(path.join(ws.root, target.fields.path), 'ui-views'), `${id}.ui-view.yaml`), shipped: null }
2644
- : uiViewSourceFile(ws, id);
2645
- // `compiled` is compile's: a view read back from the runtime carries it, and a source never does
2646
- view = Object.fromEntries(Object.entries(view).filter(([k]) => k !== 'compiled' && k !== 'overlay'));
2647
- // A view an installed package ships is never written where npm would erase it, and never refused
2648
- // either: the save becomes an OVERLAY in the workspace module carrying only what differs from the
2649
- // package's source, which compile merges onto it (`overlay: true`, compile.js). A changed column
2650
- // list is a few lines, and every later fix the package ships still reaches the rest of the view.
2651
- if (shipped && IN_NODE_MODULES(shipped)) return saveUiViewOverlay(ws, store, id, view, shipped);
2652
- const existed = fs.existsSync(dest);
2653
- // A module source is where this project writes down WHY a view exists; `dump` cannot keep that.
2654
- const previous = existed ? fs.readFileSync(dest, 'utf8') : null;
2655
- // ⚠ opted OUT of the comment invariant, on the same rule `rm-field` is: this write REPLACES
2656
- // the view, so a key the caller omits is deliberately gone (see the `filter:` case) and the comment
2657
- // explaining that key goes with it. Every key that SURVIVES keeps its comments, which is what the
2658
- // round-trip buys and what the old `dump` could not do.
2659
- const gate = writeGated(ws, store, [dest], `dreamteamer: ui-views ${existed ? 'update' : 'add'} ${id}`, () => {
2660
- fs.mkdirSync(path.dirname(dest), { recursive: true });
2661
- fs.writeFileSync(dest, writeSource(previous, view));
2662
- }, undefined, { commentsMayDecrease: true });
2663
- return { id, file: dest, updated: existed, commits: gate.commits, unchanged: gate.unchanged };
2664
- }
2665
-
2666
- /** The save of a package's view: the workspace module's overlay, rewritten from the package source
2667
- * each time (never stacked on the previous overlay), and removed when the view equals the package's. */
2668
- function saveUiViewOverlay(ws, store, id, view, shipped) {
2669
- const dest = path.join(workspaceSystemDir(ws, 'ui-views'), `${id}.ui-view.yaml`);
2670
- const existed = fs.existsSync(dest);
2671
- const delta = viewOverlayOf(load(fs.readFileSync(path.join(ws.root, shipped), 'utf8')) ?? {}, view);
2672
- const out = { id, file: dest, overlay: true, overlays: shipped };
2673
- if (!Object.keys(delta).length && !existed) return { ...out, updated: false, unchanged: true };
2674
- const previous = existed ? fs.readFileSync(dest, 'utf8') : null;
2675
- const gate = writeGated(ws, store, [dest], `dreamteamer: ui-views overlay ${id}`, () => {
2676
- if (!Object.keys(delta).length) return fs.rmSync(dest);
2677
- fs.mkdirSync(path.dirname(dest), { recursive: true });
2678
- fs.writeFileSync(dest, writeSource(previous, { overlay: true, ...delta }));
2679
- }, undefined, { commentsMayDecrease: true });
2680
- return { ...out, updated: existed, removed: !Object.keys(delta).length || undefined, commits: gate.commits, unchanged: gate.unchanged };
2681
- }
2682
-
2683
- /**
2684
- * `dt set ui-views/<id> module=<m>` — MOVE a view's source to another module, the way `moveCollection`
2685
- * moves a descriptor: the same bytes at the new path (a view's comments are its module's reasoning),
2686
- * the old file gone, one compile gate, one commit per repo it touches — so a move into a linked
2687
- * clone's module commits there, ready to publish with that module.
2688
- */
2689
- export function moveUiView(ws, store, id, toModule, { dryRun = false } = {}) {
2690
- const { shipped } = uiViewSourceFile(ws, id);
2691
- if (!shipped) throw new Error(`ui-view "${id}" does not exist`);
2692
- if (IN_NODE_MODULES(shipped)) {
2693
- throw new Error(`ui-view "${id}" is shipped by an installed package (${shipped}) — it moves with its package, not from here.\n save it under a new name, then move that one.`);
2694
- }
2695
- const to = moduleRecord(store, toModule); // throws with the known-module list
2696
- if (IN_NODE_MODULES(to.fields.path)) {
2697
- throw new Error(`module "${toModule}" ships from node_modules (${to.fields.path}) — a write there is erased by the next npm install.\n pick a module whose sources are in this workspace.`);
2698
- }
2699
- const owner = moduleRows(store).filter((r) => shipped.startsWith(`${r.fields.path}/`)).sort((a, b) => b.fields.path.length - a.fields.path.length)[0];
2700
- const src = path.join(ws.root, shipped);
2701
- const dest = path.join(kindDir(path.join(ws.root, to.fields.path), 'ui-views'), `${id}.ui-view.yaml`);
2702
- const plan = { id, from: owner?.id ?? null, to: toModule, file: path.relative(ws.root, dest) };
2703
- if (path.resolve(dest) === path.resolve(src)) return { ...plan, moved: false };
2704
- if (fs.existsSync(dest)) throw new Error(`${plan.file} already exists — move or remove it first; nothing was moved`);
2705
- if (dryRun) return { ...plan, moved: false, dryRun: true };
2706
- const bytes = fs.readFileSync(src);
2707
- let moved = false;
2708
- const out = gatedTreeOp(ws, store, {
2709
- subject: `dreamteamer: ui-views set ${id} module=${toModule}`,
2710
- paths: [shipped, plan.file],
2711
- mutate: () => {
2712
- fs.mkdirSync(path.dirname(dest), { recursive: true });
2713
- fs.writeFileSync(dest, bytes);
2714
- fs.rmSync(src);
2715
- moved = true;
2716
- },
2717
- undo: () => {
2718
- if (moved && fs.existsSync(dest)) fs.rmSync(dest);
2719
- fs.mkdirSync(path.dirname(src), { recursive: true });
2720
- fs.writeFileSync(src, bytes);
2721
- },
2722
- });
2723
- return { ...plan, moved: true, commits: out.commits };
2724
- }
2725
-
2726
- export function removeUiView(ws, store, id) {
2727
- // Same source resolution as the save above — an inline module's view is under this repo's git
2728
- // history like everything else, so deleting it is one revertable commit. Refusing it while
2729
- // ALLOWING a save to the same file would be an asymmetry with nothing behind it.
2730
- const { file: dest, shipped } = uiViewSourceFile(ws, id);
2731
- if (shipped && /(^|\/)node_modules\//.test(shipped))
2732
- throw new Error(`ui-view "${id}" is shipped by an installed package (${shipped}) — removing the file would be undone by the next npm install.\n disable it instead: add "ui-views/${id}" to dreamteamer.disable in package.json.`);
2733
- if (!fs.existsSync(dest)) throw new Error(`ui-view "${id}" does not exist`);
2734
- const gate = writeGated(ws, store, [dest], `dreamteamer: ui-views rm ${id}`, () => fs.rmSync(dest), undefined, { commentsMayDecrease: true });
2735
- return { removed: id, commits: gate.commits };
2736
- }
2737
-
2738
- // ---- the identity entities: skills, agents, commands, command-bindings, mixins ----------------
2739
- // §3.1's last row. These are FLAT at a module root and stay flat (decision 274) — their ids are
2740
- // single segments, and namespacing them was cut with the wave that considered it.
2741
- //
2742
- // `add` is a SCAFFOLD for skills only, and refused with the path for the rest. That asymmetry is not
2743
- // arbitrary: a skill's minimum-that-compiles is two frontmatter keys and an empty body, which a verb
2744
- // can write honestly. An agent, a command, a binding and a mixin are all PROSE or PREDICATES —
2745
- // the value is entirely in what a human writes, and a verb that scaffolds one produces a file whose
2746
- // only content is the fact that a verb made it.
2747
-
2748
- /** kind → {suffix, folder} — one table, because five verbs read it and a sixth spelling of "where
2749
- * does a command live" is how a kind the engine stopped knowing sat in a module for two days
2750
- * (decision 156). */
2751
- const ENTITY_SHAPE = {
2752
- skills: { suffix: 'SKILL.md', folder: true },
2753
- agents: { suffix: '.agent.md', folder: false },
2754
- commands: { suffix: '.command.md', folder: false },
2755
- 'command-bindings': { suffix: '.command-binding.yaml', folder: false },
2756
- mixins: { suffix: '.mixin.yaml', folder: false },
2757
- };
2758
-
2759
- /** The shape of one kind — the table above, else DERIVED from the compiled descriptor, which is how
2760
- * a kind an extension contributes (`proofs`) gets `rm · rename · set` without this file naming it:
2761
- * `storage.suffix` + the format's extension, one file per id. */
2762
- function entityShape(ws, kind) {
2763
- if (ENTITY_SHAPE[kind]) return ENTITY_SHAPE[kind];
2764
- const d = loadDescriptors(ws.root).get(kind);
2765
- const storage = storageOf(d);
2766
- if (!isRuntime(d) || !storage.suffix) throw new Error(`"${kind}" is not an entity kind this workspace compiles`);
2767
- return { suffix: `.${storage.suffix}${EXT[storage.format] ?? '.md'}`, folder: storage.shape === 'folder' };
2768
- }
2769
-
2770
- /** The source file (or folder) ONE entity is compiled from, asked of the manifest — the same
2771
- * question `uiViewSourceFile` asks, for the five other kinds. */
2772
- function entitySource(ws, kind, id) {
2773
- const shape = entityShape(ws, kind);
2774
- const key = shape.folder ? `${kind}/${id}/SKILL.md` : `${kind}/${id}${shape.suffix}`;
2775
- const src = readManifest(ws.root)?.entries?.[key]?.sources?.[0];
2776
- const shipped = typeof src === 'string' ? src : src?.path;
2777
- if (!shipped) return { file: null, dir: null, shipped: null };
2778
- const file = path.join(ws.root, shipped);
2779
- return { file, dir: shape.folder ? path.dirname(file) : file, shipped };
2780
- }
2781
-
2782
- /** Refuse a write into an installed package, with `disable` as the remedy — the message every other
2783
- * op in this file already gives, in one place. */
2784
- function refuseNpmEntity(kind, id, shipped) {
2785
- if (!shipped || !IN_NODE_MODULES(shipped)) return;
2786
- throw new Error(`${kind.replace(/s$/, '')} "${id}" is shipped by an installed package (${shipped}) — a write there is erased by the next \`npm install\`.\n disable it instead: add "${kind}/${id}" to dreamteamer.disable in package.json.`);
2787
- }
2788
-
2789
- const ENTITY_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
2790
-
2791
- export function createSkill(ws, store, { name, description, moduleId }) {
2792
- if (!name || name === true) throw new Error('missing skill name — dreamteamer add skills --name <id> --description "…"');
2793
- if (!ENTITY_ID.test(name)) throw new Error(`invalid skill id "${name}" — lowercase alphanumeric with single hyphens (it is a folder name and the frontmatter \`name\` at once).`);
2794
- if (typeof description !== 'string' || !description.trim()) {
2795
- // ⚠ REQUIRED, not defaulted. claude-code discovers skills natively and shows the description
2796
- // as the trigger; the orientation block indexes it for every other harness. A skill with no
2797
- // description is loadable by nobody and shows up as a bare id in the one place an agent looks.
2798
- throw new Error('--description is required: it is the sentence that says WHEN to load this skill, and it is all any harness shows. An undescribed skill is undiscoverable.');
2799
- }
2800
- if (store.descriptors.has('skills') && store.ids('skills').has(name)) {
2801
- throw new Error(`skill "${name}" already exists — dt get skills/${name}`);
2802
- }
2803
- const root = moduleId ? path.join(ws.root, moduleRecord(store, moduleId).fields.path) : null;
2804
- if (root && IN_NODE_MODULES(path.relative(ws.root, root))) {
2805
- throw new Error(`module "${moduleId}" ships from node_modules — a write there is erased by the next \`npm install\`.`);
2806
- }
2807
- // ⚠ THE MODULE ROOT IS RETURNED, not left to the caller to slice back out of `file`. The caller
2808
- // prints a path under it (the `no proof yet` nudge), and deriving that by cutting at `/skills/`
2809
- // is wrong in both layouts this function already handles: the ROOT layout writes
2810
- // `skills/<id>/SKILL.md` with no module segment at all, and the pre-flatten one writes
2811
- // `system/skills/…`. Here the answer is known exactly, in one line.
2812
- const wm = ws.pkg.dreamteamer?.workspace_module;
2813
- const modRoot = root ?? (wm ? path.join(ws.root, 'modules', wm) : ws.root);
2814
- const dir = path.join(root ? kindDir(root, 'skills') : workspaceSystemDir(ws, 'skills'), name);
2815
- const file = path.join(dir, 'SKILL.md');
2816
- if (fs.existsSync(file)) throw new Error(`${path.relative(ws.root, file)} already exists`);
2817
- // THE MINIMUM THAT COMPILES, and nothing more: two frontmatter keys and an empty body. A
2818
- // scaffold that guesses at sections is a file whose only content is that a verb made it.
2819
- const text = `---\nname: ${name}\ndescription: ${JSON.stringify(description)}\n---\n\n`;
2820
- const out = gatedTreeOp(ws, store, {
2821
- subject: `dreamteamer: skills add ${name}`,
2822
- paths: [path.relative(ws.root, file)],
2823
- mutate: () => {
2824
- fs.mkdirSync(dir, { recursive: true });
2825
- fs.writeFileSync(file, text);
2826
- },
2827
- undo: () => fs.rmSync(dir, { recursive: true, force: true }),
2828
- });
2829
- return { id: name, file, moduleRoot: path.relative(ws.root, modRoot) || '.', commits: out.commits };
2830
- }
2831
-
2832
- /** `add` on a kind nobody can scaffold honestly — refused WITH THE PATH, because "hand-authored"
2833
- * without the filename is a refusal the reader has to go research. */
2834
- export function refuseHandAuthored(ws, store, kind, id, moduleId) {
2835
- const shape = entityShape(ws, kind);
2836
- const root = moduleId ? moduleRecord(store, moduleId).fields.path : path.join('modules', ws.pkg.dreamteamer?.workspace_module ?? 'default');
2837
- const where = path.join(root, kind, `${id || '<id>'}${shape.suffix}`);
2838
- const one = kind.replace(/s$/, '');
2839
- throw new Error(`${/^[aeiou]/.test(one) ? 'an' : 'a'} ${one} is hand-authored — its whole value is what you write in it, and a scaffold would produce a file whose only content is that a verb made it.\n write ${where}, then run \`dreamteamer compile\`.\n edit an existing one with: dreamteamer set ${kind}/<id> <key>=<value>`);
2840
- }
2841
-
2842
- export function removeEntity(ws, store, kind, id) {
2843
- const { dir, shipped } = entitySource(ws, kind, id);
2844
- if (!shipped) throw new Error(`${kind.replace(/s$/, '')} "${id}" does not exist — dt list ${kind}`);
2845
- refuseNpmEntity(kind, id, shipped);
2846
- // ⚠ STASH, DO NOT DELETE, UNTIL THE COMMIT LANDS — `gatedTreeOp`'s `undo` has to be able to put a
2847
- // whole folder back, and a `rmSync` cannot be undone. Same reasoning as `removeModule`.
2848
- const stash = path.join(ws.root, '.dreamteamer', `.rm-${kind}-${id}`);
2849
- fs.rmSync(stash, { recursive: true, force: true });
2850
- try {
2851
- const out = gatedTreeOp(ws, store, {
2852
- subject: `dreamteamer: ${kind} rm ${id}`,
2853
- paths: [path.relative(ws.root, dir)],
2854
- mutate: () => {
2855
- fs.mkdirSync(path.dirname(stash), { recursive: true });
2856
- fs.renameSync(dir, stash);
2857
- },
2858
- undo: () => { if (fs.existsSync(stash)) fs.renameSync(stash, dir); },
2859
- });
2860
- return { removed: id, file: dir, commits: out.commits };
2861
- } finally {
2862
- fs.rmSync(stash, { recursive: true, force: true });
2863
- }
2864
- }
2865
-
2866
- export function renameEntity(ws, store, kind, oldId, newId) {
2867
- if (!newId || newId === true) throw new Error(`missing new id — dreamteamer rename ${kind}/${oldId} <new-id>`);
2868
- if (oldId === newId) return { renamed: false, id: newId };
2869
- if (!ENTITY_ID.test(newId)) throw new Error(`invalid ${kind.replace(/s$/, '')} id "${newId}" — lowercase alphanumeric with single hyphens.`);
2870
- const shape = entityShape(ws, kind);
2871
- const { dir, file, shipped } = entitySource(ws, kind, oldId);
2872
- if (!shipped) throw new Error(`${kind.replace(/s$/, '')} "${oldId}" does not exist — dt list ${kind}`);
2873
- refuseNpmEntity(kind, oldId, shipped);
2874
- const newDir = shape.folder
2875
- ? path.join(path.dirname(dir), newId)
2876
- : path.join(path.dirname(file), `${newId}${shape.suffix}`);
2877
- if (fs.existsSync(newDir)) throw new Error(`${path.relative(ws.root, newDir)} already exists`);
2878
- const entityFile = shape.folder ? path.join(newDir, 'SKILL.md') : newDir;
2879
- const isYaml = shape.suffix.endsWith('.yaml');
2880
- let before = null;
2881
- const out = gatedTreeOp(ws, store, {
2882
- subject: `dreamteamer: ${kind} rename ${oldId} → ${newId}`,
2883
- paths: [path.relative(ws.root, shape.folder ? dir : file), path.relative(ws.root, newDir)],
2884
- mutate: () => {
2885
- fs.renameSync(shape.folder ? dir : file, newDir);
2886
- // ⚠ THE FRONTMATTER `name` IS PART OF THE ID. compile reads the FILENAME for the entity id
2887
- // and the frontmatter for what the harness shows, and letting them disagree is how a skill
2888
- // answers to one name in the tree and another in the session that loads it. A YAML entity
2889
- // (a binding, a template) carries no `name` key, so there is nothing to move.
2890
- before = fs.readFileSync(entityFile, 'utf8');
2891
- if (!isYaml) fs.writeFileSync(entityFile, setFrontmatterKey(before, 'name', newId));
2892
- },
2893
- undo: () => {
2894
- if (before !== null && fs.existsSync(entityFile)) fs.writeFileSync(entityFile, before);
2895
- if (fs.existsSync(newDir)) fs.renameSync(newDir, shape.folder ? dir : file);
2896
- },
2897
- });
2898
- return { renamed: true, id: newId, commits: out.commits };
2899
- }
2900
-
2901
- export function setEntityFrontmatter(ws, store, kind, id, changes) {
2902
- const shape = entityShape(ws, kind);
2903
- const { dir, file, shipped } = entitySource(ws, kind, id);
2904
- if (!shipped) throw new Error(`${kind.replace(/s$/, '')} "${id}" does not exist — dt list ${kind}`);
2905
- refuseNpmEntity(kind, id, shipped);
2906
- // ⚠ THE DESCRIPTOR IS THE AUTHORITY, and the engine was disagreeing with itself: `dt set
2907
- // skills/<id> descripton="oops"` wrote the typo, compiled, SELF-COMMITTED — and then `dt check`
2908
- // failed on the very workspace the self-commit exists to keep valid, because the `skills`
2909
- // descriptor declares a closed set of properties and check validates against it. "Frontmatter is
2910
- // an open document" was the wrong half to believe: if a key is not in the descriptor, `check`
2911
- // will reject it, so `set` refuses it first. Its two siblings already read this way
2912
- // (`setCollectionScalars`, `setModule`), and a body field is not settable from the CLI at all.
2913
- const props = fieldsOf(store.descriptors.get(kind));
2914
- const settable = (k) => props[k] && !props[k].body && !props[k].derived && !props[k].virtual;
2915
- const unknown = Object.keys(changes).find((k) => !settable(k));
2916
- if (unknown) throw new Error(`"${unknown}" is not a settable key of ${kind} — declared: ${Object.keys(props).filter(settable).join(', ')}. \`dreamteamer check\` rejects anything else, so this is refused before it is committed.`);
2917
- const target = shape.folder ? path.join(dir, 'SKILL.md') : file;
2918
- // A YAML source (a binding, a template) is a whole document; a markdown one has frontmatter and
2919
- // prose. `writeSource` round-trips both — the difference is only which text it is handed.
2920
- const isYaml = shape.suffix.endsWith('.yaml');
2921
- const previousText = fs.readFileSync(target, 'utf8');
2922
- const changed = [];
2923
- const gate = writeGated(ws, store, [target], `dreamteamer: ${kind} set ${id} ${Object.keys(changes).join(' ')}`, () => {
2924
- if (isYaml) {
2925
- const doc = load(previousText) ?? {};
2926
- for (const [k, v] of Object.entries(changes)) {
2927
- if (v === '' || v === null) delete doc[k];
2928
- else doc[k] = v;
2929
- changed.push(k);
2930
- }
2931
- fs.writeFileSync(target, writeSource(previousText, doc));
2932
- } else {
2933
- let text = previousText;
2934
- for (const [k, v] of Object.entries(changes)) {
2935
- text = setFrontmatterKey(text, k, v === '' ? null : v);
2936
- changed.push(k);
2937
- }
2938
- fs.writeFileSync(target, text);
2939
- }
2940
- }, undefined, { commentsMayDecrease: true });
2941
- return { id, file: target, changed, commits: gate.commits, unchanged: gate.unchanged };
2942
- }
2943
-
2944
- /**
2945
- * One frontmatter key, set (or removed with `null`), with the BODY untouched.
2946
- *
2947
- * ⚠ Round-tripped through `writeSource` over the frontmatter block ALONE, and the body re-attached
2948
- * verbatim. Re-dumping a whole markdown file is how a skill's prose gets re-wrapped by a verb that
2949
- * was asked to change one word of its description — and a skill's prose is the entire artifact.
2950
- */
2951
- function setFrontmatterKey(text, key, value) {
2952
- const m = /^---\r?\n([\s\S]*?)\r?\n---(\r?\n[\s\S]*)?$/.exec(text);
2953
- if (!m) throw new Error('no YAML frontmatter — a markdown entity starts with a `---` block, and this file does not.');
2954
- const doc = load(m[1]) ?? {};
2955
- if (value === null) delete doc[key];
2956
- else doc[key] = value;
2957
- const front = writeSource(m[1], doc).replace(/\n+$/, '');
2958
- return `---\n${front}\n---${m[2] ?? '\n'}`;
2959
- }