@ybotok/loam 0.2.0-alpha.5 → 0.2.0-alpha.7

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 (303) hide show
  1. package/CHANGELOG.md +1063 -0
  2. package/MIGRATING-from-OpenSpec.md +7 -4
  3. package/QUICKSTART.md +8 -3
  4. package/README.md +13 -7
  5. package/ROADMAP.md +285 -11
  6. package/SCHEMA.md +566 -45
  7. package/WORKFLOW.md +23 -10
  8. package/dist/commands/adopt/render.js +47 -8
  9. package/dist/commands/adopt/render.js.map +1 -1
  10. package/dist/commands/archive/plan/landscape.js +45 -1
  11. package/dist/commands/archive/plan/landscape.js.map +1 -1
  12. package/dist/commands/archive/plan/model/extending.js +85 -0
  13. package/dist/commands/archive/plan/model/extending.js.map +1 -0
  14. package/dist/commands/archive/run.js +53 -23
  15. package/dist/commands/archive/run.js.map +1 -1
  16. package/dist/commands/context/print.js +11 -1
  17. package/dist/commands/context/print.js.map +1 -1
  18. package/dist/commands/doctor.js +46 -0
  19. package/dist/commands/doctor.js.map +1 -1
  20. package/dist/commands/explore.js +12 -2
  21. package/dist/commands/explore.js.map +1 -1
  22. package/dist/commands/list/views.js +5 -1
  23. package/dist/commands/list/views.js.map +1 -1
  24. package/dist/commands/seed/commit.js +34 -1
  25. package/dist/commands/seed/commit.js.map +1 -1
  26. package/dist/commands/seed/plan.js +158 -13
  27. package/dist/commands/seed/plan.js.map +1 -1
  28. package/dist/commands/seed/seed.js +7 -2
  29. package/dist/commands/seed/seed.js.map +1 -1
  30. package/dist/commands/show/feature.js +2 -1
  31. package/dist/commands/show/feature.js.map +1 -1
  32. package/dist/commands/show/marks.js +3 -5
  33. package/dist/commands/show/marks.js.map +1 -1
  34. package/dist/commands/show/service.js +39 -18
  35. package/dist/commands/show/service.js.map +1 -1
  36. package/dist/commands/subsystem/edit.js +4 -2
  37. package/dist/commands/subsystem/edit.js.map +1 -1
  38. package/dist/commands/subsystem/move.js +55 -17
  39. package/dist/commands/subsystem/move.js.map +1 -1
  40. package/dist/commands/subsystem/sync.js +238 -87
  41. package/dist/commands/subsystem/sync.js.map +1 -1
  42. package/dist/commands/subsystem/txn/exclude.js +132 -0
  43. package/dist/commands/subsystem/txn/exclude.js.map +1 -0
  44. package/dist/commands/subsystem/txn/report.js +174 -0
  45. package/dist/commands/subsystem/txn/report.js.map +1 -0
  46. package/dist/commands/subsystem/txn/txn.js +126 -22
  47. package/dist/commands/subsystem/txn/txn.js.map +1 -1
  48. package/dist/commands/subsystem/txn/views.js +159 -19
  49. package/dist/commands/subsystem/txn/views.js.map +1 -1
  50. package/dist/commands/validate/arch-coverage.js +16 -9
  51. package/dist/commands/validate/arch-coverage.js.map +1 -1
  52. package/dist/commands/validate/checks/fleet-shape.js +30 -77
  53. package/dist/commands/validate/checks/fleet-shape.js.map +1 -1
  54. package/dist/commands/validate/checks/health-deps.js +9 -6
  55. package/dist/commands/validate/checks/health-deps.js.map +1 -1
  56. package/dist/commands/validate/checks/vocabulary.js +4 -19
  57. package/dist/commands/validate/checks/vocabulary.js.map +1 -1
  58. package/dist/commands/validate/feature.js +1 -1
  59. package/dist/commands/validate/feature.js.map +1 -1
  60. package/dist/commands/validate/fleet/census.js +37 -13
  61. package/dist/commands/validate/fleet/census.js.map +1 -1
  62. package/dist/commands/validate/fleet/landscape.js +131 -120
  63. package/dist/commands/validate/fleet/landscape.js.map +1 -1
  64. package/dist/commands/validate/fleet/load.js +66 -0
  65. package/dist/commands/validate/fleet/load.js.map +1 -1
  66. package/dist/commands/validate/fleet/map/attest.js +102 -0
  67. package/dist/commands/validate/fleet/map/attest.js.map +1 -0
  68. package/dist/commands/validate/fleet/map/bindings.js +109 -0
  69. package/dist/commands/validate/fleet/map/bindings.js.map +1 -0
  70. package/dist/commands/validate/fleet/map/consumers.js +219 -0
  71. package/dist/commands/validate/fleet/map/consumers.js.map +1 -0
  72. package/dist/commands/validate/fleet/map/isolation.js +116 -0
  73. package/dist/commands/validate/fleet/map/isolation.js.map +1 -0
  74. package/dist/commands/validate/fleet/map/usecases.js +56 -0
  75. package/dist/commands/validate/fleet/map/usecases.js.map +1 -0
  76. package/dist/commands/validate/fleet/scorecard/scorecard.js.map +1 -1
  77. package/dist/commands/validate/fleet/usecases/steps.js +49 -17
  78. package/dist/commands/validate/fleet/usecases/steps.js.map +1 -1
  79. package/dist/commands/validate/fleet/views/fleet-project.js +217 -0
  80. package/dist/commands/validate/fleet/views/fleet-project.js.map +1 -0
  81. package/dist/commands/validate/fleet/views/ids.js +45 -15
  82. package/dist/commands/validate/fleet/views/ids.js.map +1 -1
  83. package/dist/commands/validate/fleet/views/projects.js +258 -70
  84. package/dist/commands/validate/fleet/views/projects.js.map +1 -1
  85. package/dist/commands/validate/fleet/views/root-documents.js +99 -0
  86. package/dist/commands/validate/fleet/views/root-documents.js.map +1 -0
  87. package/dist/commands/validate/fleet/views/stale.js +32 -15
  88. package/dist/commands/validate/fleet/views/stale.js.map +1 -1
  89. package/dist/commands/validate/service/model/diverged.js +226 -0
  90. package/dist/commands/validate/service/model/diverged.js.map +1 -0
  91. package/dist/commands/validate/service/model/grade.js +163 -0
  92. package/dist/commands/validate/service/model/grade.js.map +1 -0
  93. package/dist/commands/validate/service/service.js +110 -34
  94. package/dist/commands/validate/service/service.js.map +1 -1
  95. package/dist/commands/validate/service/specs.js +39 -5
  96. package/dist/commands/validate/service/specs.js.map +1 -1
  97. package/dist/commands/validate/service/spine.js +41 -3
  98. package/dist/commands/validate/service/spine.js.map +1 -1
  99. package/dist/commands/validate/service/usecases/tags.js +113 -0
  100. package/dist/commands/validate/service/usecases/tags.js.map +1 -0
  101. package/dist/commands/validate/service/usecases/usecases.js +209 -0
  102. package/dist/commands/validate/service/usecases/usecases.js.map +1 -0
  103. package/dist/commands/validate/validate.js +10 -24
  104. package/dist/commands/validate/validate.js.map +1 -1
  105. package/dist/core/agent/agents-md/artifacts.js +1 -0
  106. package/dist/core/agent/agents-md/artifacts.js.map +1 -1
  107. package/dist/core/agent/agents-md/command-map.js +19 -5
  108. package/dist/core/agent/agents-md/command-map.js.map +1 -1
  109. package/dist/core/agent/agents-md/cycle.js +24 -9
  110. package/dist/core/agent/agents-md/cycle.js.map +1 -1
  111. package/dist/core/agent/agents-md/map/lenses/context.js +4 -3
  112. package/dist/core/agent/agents-md/map/lenses/context.js.map +1 -1
  113. package/dist/core/agent/agents-md/map/subsystem.js +70 -17
  114. package/dist/core/agent/agents-md/map/subsystem.js.map +1 -1
  115. package/dist/core/agent/agents-md/map/usecases.js +45 -3
  116. package/dist/core/agent/agents-md/map/usecases.js.map +1 -1
  117. package/dist/core/agent/agents-md/refusals.js +5 -3
  118. package/dist/core/agent/agents-md/refusals.js.map +1 -1
  119. package/dist/core/agent/agents-md.js +26 -7
  120. package/dist/core/agent/agents-md.js.map +1 -1
  121. package/dist/core/agent/support/report.js +39 -5
  122. package/dist/core/agent/support/report.js.map +1 -1
  123. package/dist/core/agent/workflows/adopt.js +123 -14
  124. package/dist/core/agent/workflows/adopt.js.map +1 -1
  125. package/dist/core/agent/workflows/check.js +34 -20
  126. package/dist/core/agent/workflows/check.js.map +1 -1
  127. package/dist/core/agent/workflows/closing.js +3 -1
  128. package/dist/core/agent/workflows/closing.js.map +1 -1
  129. package/dist/core/agent/workflows/reference/spine.js +12 -6
  130. package/dist/core/agent/workflows/reference/spine.js.map +1 -1
  131. package/dist/core/brief/brief.js +88 -19
  132. package/dist/core/brief/brief.js.map +1 -1
  133. package/dist/core/brief/checks.js +133 -7
  134. package/dist/core/brief/checks.js.map +1 -1
  135. package/dist/core/brief/landscape.js +212 -129
  136. package/dist/core/brief/landscape.js.map +1 -1
  137. package/dist/core/brief/map/extend.js +81 -0
  138. package/dist/core/brief/map/extend.js.map +1 -0
  139. package/dist/core/brief/map/owed.js +284 -0
  140. package/dist/core/brief/map/owed.js.map +1 -0
  141. package/dist/core/brief/targets.js +94 -29
  142. package/dist/core/brief/targets.js.map +1 -1
  143. package/dist/core/brief/unchecked.js +13 -3
  144. package/dist/core/brief/unchecked.js.map +1 -1
  145. package/dist/core/c4/likec4.js +23 -1
  146. package/dist/core/c4/likec4.js.map +1 -1
  147. package/dist/core/c4/parsed/deployment.js +5 -3
  148. package/dist/core/c4/parsed/deployment.js.map +1 -1
  149. package/dist/core/c4/parsed/view-ids.js +39 -1
  150. package/dist/core/c4/parsed/view-ids.js.map +1 -1
  151. package/dist/core/c4/prefetch/fleet.js +142 -0
  152. package/dist/core/c4/prefetch/fleet.js.map +1 -0
  153. package/dist/core/c4/project/architecture.js +77 -7
  154. package/dist/core/c4/project/architecture.js.map +1 -1
  155. package/dist/core/c4/project/batch.js +140 -0
  156. package/dist/core/c4/project/batch.js.map +1 -0
  157. package/dist/core/c4/project/documents.js +12 -6
  158. package/dist/core/c4/project/documents.js.map +1 -1
  159. package/dist/core/c4/project/load.js +85 -42
  160. package/dist/core/c4/project/load.js.map +1 -1
  161. package/dist/core/c4/project/staged.js +53 -15
  162. package/dist/core/c4/project/staged.js.map +1 -1
  163. package/dist/core/c4/resolve/attested.js +0 -0
  164. package/dist/core/c4/resolve/attested.js.map +1 -0
  165. package/dist/core/c4/resolve/service.js +8 -17
  166. package/dist/core/c4/resolve/service.js.map +1 -1
  167. package/dist/core/c4/resolve/steps.js +18 -0
  168. package/dist/core/c4/resolve/steps.js.map +1 -1
  169. package/dist/core/c4/root-project/exclude.js +352 -0
  170. package/dist/core/c4/root-project/exclude.js.map +1 -0
  171. package/dist/core/c4/service-model/documents.js +47 -0
  172. package/dist/core/c4/service-model/documents.js.map +1 -0
  173. package/dist/core/c4/service-model/fleet/extending.js +82 -0
  174. package/dist/core/c4/service-model/fleet/extending.js.map +1 -0
  175. package/dist/core/c4/service-model/load.js +165 -0
  176. package/dist/core/c4/service-model/load.js.map +1 -0
  177. package/dist/core/c4/service-model/renderer.js +128 -0
  178. package/dist/core/c4/service-model/renderer.js.map +1 -0
  179. package/dist/core/c4/service-model/shape.js +126 -0
  180. package/dist/core/c4/service-model/shape.js.map +1 -0
  181. package/dist/core/c4/service-model/slice.js +188 -0
  182. package/dist/core/c4/service-model/slice.js.map +1 -0
  183. package/dist/core/c4/source-scan.js +26 -0
  184. package/dist/core/c4/source-scan.js.map +1 -1
  185. package/dist/core/c4/splice/authored-source.js +60 -13
  186. package/dist/core/c4/splice/authored-source.js.map +1 -1
  187. package/dist/core/c4/splice/contract.js.map +1 -1
  188. package/dist/core/c4/splice/identity/declared.js +87 -0
  189. package/dist/core/c4/splice/identity/declared.js.map +1 -0
  190. package/dist/core/c4/splice/identity/edges.js +17 -0
  191. package/dist/core/c4/splice/identity/edges.js.map +1 -1
  192. package/dist/core/c4/splice/identity/existing.js +80 -0
  193. package/dist/core/c4/splice/identity/existing.js.map +1 -0
  194. package/dist/core/c4/splice/identity/interior.js +80 -0
  195. package/dist/core/c4/splice/identity/interior.js.map +1 -0
  196. package/dist/core/c4/splice/identity/owner.js +50 -0
  197. package/dist/core/c4/splice/identity/owner.js.map +1 -0
  198. package/dist/core/c4/splice/landscape-merge.js +154 -100
  199. package/dist/core/c4/splice/landscape-merge.js.map +1 -1
  200. package/dist/core/c4/splice/model/merge.js +140 -0
  201. package/dist/core/c4/splice/model/merge.js.map +1 -0
  202. package/dist/core/c4/splice/placement.js +14 -4
  203. package/dist/core/c4/splice/placement.js.map +1 -1
  204. package/dist/core/c4/workspace.js +2 -1
  205. package/dist/core/c4/workspace.js.map +1 -1
  206. package/dist/core/coherence/coherence.js +7 -0
  207. package/dist/core/coherence/coherence.js.map +1 -1
  208. package/dist/core/delta/delta.js +9 -0
  209. package/dist/core/delta/delta.js.map +1 -1
  210. package/dist/core/deployment/delta.js +16 -10
  211. package/dist/core/deployment/delta.js.map +1 -1
  212. package/dist/core/diff/base-state.js +21 -5
  213. package/dist/core/diff/base-state.js.map +1 -1
  214. package/dist/core/diff/victims.js +10 -1
  215. package/dist/core/diff/victims.js.map +1 -1
  216. package/dist/core/docs.js +29 -24
  217. package/dist/core/docs.js.map +1 -1
  218. package/dist/core/doctor/config.js +7 -3
  219. package/dist/core/doctor/config.js.map +1 -1
  220. package/dist/core/doctor/doctor.js +36 -8
  221. package/dist/core/doctor/doctor.js.map +1 -1
  222. package/dist/core/doctor/report.js.map +1 -1
  223. package/dist/core/doctor/reports/scan.js +242 -0
  224. package/dist/core/doctor/reports/scan.js.map +1 -0
  225. package/dist/core/explain/refusals.js +1 -1
  226. package/dist/core/explain/refusals.js.map +1 -1
  227. package/dist/core/explore/explore.js +44 -9
  228. package/dist/core/explore/explore.js.map +1 -1
  229. package/dist/core/fleet-context.js +47 -0
  230. package/dist/core/fleet-context.js.map +1 -1
  231. package/dist/core/gate/checks.js +5 -1
  232. package/dist/core/gate/checks.js.map +1 -1
  233. package/dist/core/gate/partners.js +65 -26
  234. package/dist/core/gate/partners.js.map +1 -1
  235. package/dist/core/kernel/ids/fqn/ancestors.js +65 -0
  236. package/dist/core/kernel/ids/fqn/ancestors.js.map +1 -0
  237. package/dist/core/pack/living.js +47 -13
  238. package/dist/core/pack/living.js.map +1 -1
  239. package/dist/core/pack/pack.js +9 -6
  240. package/dist/core/pack/pack.js.map +1 -1
  241. package/dist/core/projection/arch-slice.js +2 -2
  242. package/dist/core/projection/arch-slice.js.map +1 -1
  243. package/dist/core/repo/paths.js +45 -38
  244. package/dist/core/repo/paths.js.map +1 -1
  245. package/dist/core/repo/tree/render/body.js +45 -6
  246. package/dist/core/repo/tree/render/body.js.map +1 -1
  247. package/dist/core/repo/tree/render/projects.js +93 -35
  248. package/dist/core/repo/tree/render/projects.js.map +1 -1
  249. package/dist/core/repo/tree/render/service/header.js +125 -0
  250. package/dist/core/repo/tree/render/service/header.js.map +1 -0
  251. package/dist/core/repo/tree/render/service/peers.js +28 -0
  252. package/dist/core/repo/tree/render/service/peers.js.map +1 -0
  253. package/dist/core/repo/tree/render/service/view-id.js +67 -0
  254. package/dist/core/repo/tree/render/service/view-id.js.map +1 -0
  255. package/dist/core/repo/tree/render/service/views.js +78 -0
  256. package/dist/core/repo/tree/render/service/views.js.map +1 -0
  257. package/dist/core/repo/tree/render/stale.js +20 -4
  258. package/dist/core/repo/tree/render/stale.js.map +1 -1
  259. package/dist/core/repo/tree/render/views.js +149 -32
  260. package/dist/core/repo/tree/render/views.js.map +1 -1
  261. package/dist/core/repo/tree/walk.js +45 -2
  262. package/dist/core/repo/tree/walk.js.map +1 -1
  263. package/dist/core/scaffold/landscape.js +219 -9
  264. package/dist/core/scaffold/landscape.js.map +1 -1
  265. package/dist/core/staging/writes.js.map +1 -1
  266. package/dist/core/usecases/delta/claims.js +1 -0
  267. package/dist/core/usecases/delta/claims.js.map +1 -1
  268. package/dist/core/usecases/delta/overlay.js +4 -0
  269. package/dist/core/usecases/delta/overlay.js.map +1 -1
  270. package/dist/core/usecases/fleet.js +18 -6
  271. package/dist/core/usecases/fleet.js.map +1 -1
  272. package/dist/core/usecases/operations.js +7 -0
  273. package/dist/core/usecases/operations.js.map +1 -1
  274. package/dist/core/usecases/service/exclude.js +119 -0
  275. package/dist/core/usecases/service/exclude.js.map +1 -0
  276. package/dist/core/usecases/service/flows.js +161 -0
  277. package/dist/core/usecases/service/flows.js.map +1 -0
  278. package/dist/core/verify/checklist.js +42 -10
  279. package/dist/core/verify/checklist.js.map +1 -1
  280. package/dist/core/vocabulary/issue.js.map +1 -1
  281. package/dist/core/vocabulary/maturity.js +51 -1
  282. package/dist/core/vocabulary/maturity.js.map +1 -1
  283. package/examples/README.md +30 -8
  284. package/examples/docs/architecture/landscape.likec4 +47 -0
  285. package/examples/docs/architecture/services.likec4 +70 -0
  286. package/examples/docs/architecture/subsystems.likec4 +3 -0
  287. package/examples/docs/architecture/usecases/order-notification.likec4 +5 -2
  288. package/examples/docs/likec4.config.json +0 -1
  289. package/examples/docs/services/checkout-web/model.likec4 +39 -56
  290. package/examples/docs/services/order-service/arch.spec.md +13 -6
  291. package/examples/docs/services/order-service/model.likec4 +58 -70
  292. package/examples/docs/services/payment-service/arch.spec.md +7 -4
  293. package/examples/docs/services/payment-service/model.likec4 +38 -39
  294. package/examples/docs/services/platform/identity-service/arch.spec.md +7 -4
  295. package/examples/docs/services/platform/identity-service/model.likec4 +35 -37
  296. package/examples/docs/services/platform/notification-service/health.yaml +8 -3
  297. package/examples/docs/services/platform/notification-service/model.likec4 +43 -64
  298. package/package.json +1 -1
  299. package/examples/docs/services/checkout-web/likec4.config.json +0 -4
  300. package/examples/docs/services/order-service/likec4.config.json +0 -4
  301. package/examples/docs/services/payment-service/likec4.config.json +0 -4
  302. package/examples/docs/services/platform/identity-service/likec4.config.json +0 -4
  303. package/examples/docs/services/platform/notification-service/likec4.config.json +0 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"merge.js","sourceRoot":"","sources":["../../../../../src/core/c4/splice/model/merge.ts"],"names":[],"mappings":"AA4BA,OAAO,EAAE,SAAS,EAAsC,MAAM,sBAAsB,CAAC;AACrF,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAAE,oBAAoB,EAAuB,MAAM,gBAAgB,CAAC;AAC3E,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAUrE,mGAAmG;AACnG,MAAM,UAAU,WAAW,CAAC,GAAsB;IAChD,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,GAAG,CAAC;IAChD,MAAM,EAAE,KAAK,EAAE,GAAG,SAAS,CAAC;IAC5B,MAAM,IAAI,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC;IAClC,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;QAClB,MAAM,IAAI,oBAAoB,CAAC,wEAAwE,CAAC,CAAC;IAC3G,CAAC;IACD,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC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C,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,IAAI,CAAC,CAAC;AAC5D,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,SAAS,cAAc,CAAC,IAAY;IAClC,IAAI,SAAS,CAAC,IAAI,CAAC,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAC1C,MAAM,GAAG,GAAG,IAAI,KAAK,EAAE,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IAC3D,OAAO,GAAG,IAAI,GAAG,GAAG,cAAc,CAAC;AACrC,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,IAAI,CAAC,OAAe,EAAE,IAAY;IACzC,MAAM,IAAI,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;IAChC,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;QAClB,MAAM,IAAI,oBAAoB,CAC5B,yCAAyC,IAAI,yEAAyE,CACvH,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,qGAAqG;AACrG,SAAS,WAAW,CAAC,IAAY,EAAE,KAAa;IAC9C,MAAM,SAAS,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,KAAK,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACxD,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;IAC5C,OAAO,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;AAC/C,CAAC","sourcesContent":["/**\n * The other half of the archive's C4 merge: what a feature adds INSIDE a\n * service, spliced into the service's own extending `model.likec4`.\n *\n * `../landscape-merge.ts` routes the additions (`../identity/owner.ts` states\n * the rule) and this carries them over, by the same discipline: authored source,\n * byte for byte,\n * with the feature's own tag stripped and the indentation rebased — never a\n * re-serialization of the parsed model, which keeps only the fields loam models.\n *\n * PLACEMENT IS SIMPLER HERE, and deliberately so. The map groups additions by\n * service because every service writes into it and concurrent archives must\n * merge in git; a service model has ONE service in it, so there is no\n * neighborhood to join. An element lands inside the `extend <fqn> { … }` block\n * that owns its parent — or inside its parent's own block when the model\n * already declares that container — and a model with no `extend` block for the\n * fqn gains one at the end of its `model { }` block, as a model with no `model\n * { }` block at all gains that. A relationship lands after the last top-level\n * relationship of that block, or last in it.\n *\n * WHAT THIS DOES NOT DO IS PROVE THE RESULT. The landscape merge parses its own\n * output because a landscape is a self-contained document; an extending model\n * is not — it is read beside the `architecture/` project, and staging that set\n * means touching the docs repo. So the parse net lives with the caller\n * (`commands/archive/plan/model/extending.ts`), which is also the side that\n * holds the merged MAP the model must be proven against.\n */\nimport type { Elem } from \"../../likec4.js\";\nimport { scanModel, type ScannedModel, type ScannedRel } from \"../../source-scan.js\";\nimport { matchLineEndings, spliceSource } from \"../authored-source.js\";\nimport { LandscapeSpliceError, type ModelAdditions } from \"../contract.js\";\nimport { relStatementKey } from \"../identity/edges.js\";\nimport { closeSpot, nestedInsert, spotAfter } from \"../placement.js\";\n\nexport interface ModelMergeRequest {\n /** One model's share of the merge, as `planLandscapeMerge` routed it. */\n additions: ModelAdditions;\n /** delta.likec4 as authored — the bytes the additions are spliced from. */\n deltaText: string;\n featureId: string;\n}\n\n/** The merged model source. Refuses (never guesses) when the delta or the model cannot be read. */\nexport function spliceModel(req: ModelMergeRequest): string {\n const { additions, deltaText, featureId } = req;\n const { model } = additions;\n const scan = scanModel(deltaText);\n if (scan === null) {\n throw new LandscapeSpliceError(\"delta.likec4 has no model block — nothing to splice the additions from\");\n }\n const byId = new Map(scan.elements.map((e) => [e.id, e]));\n const pool = new Map<string, ScannedRel[]>();\n for (const s of scan.rels) {\n const k = relStatementKey(s);\n pool.set(k, [...(pool.get(k) ?? []), s]);\n }\n\n let content = withModelBlock(model.text);\n let live = read(content, model.path);\n // The delta ranges already carried over, so a child whose parent is itself\n // new is recognised as riding inside the parent's text — the same rule the\n // landscape merge states, and the reason `node` inside a new `cache` is never\n // spliced twice.\n const spliced: Array<{ start: number; end: number }> = [];\n const rides = (start: number, end: number): boolean =>\n spliced.some((r) => start >= r.start && end <= r.end);\n const applyAt = (at: number, insert: string): void => {\n content = content.slice(0, at) + insert + content.slice(at);\n live = read(content, model.path);\n };\n\n // Ancestors first, exactly as the landscape merge orders them: a spliced\n // parent covers its children before they are seen.\n const depth = (id: string): number => id.split(\".\").length;\n const ordered = [...additions.els].sort(\n (a, b) => depth(a.id) - depth(b.id) || (byId.get(a.id)?.start ?? 0) - (byId.get(b.id)?.start ?? 0),\n );\n for (const e of ordered) {\n const src = byId.get(e.id);\n if (src === undefined) {\n throw new LandscapeSpliceError(\n `cannot locate '${e.id}' in delta.likec4 — the model merge splices authored source, and this declaration was not found`,\n );\n }\n if (rides(src.start, src.end)) continue;\n const [at, insert] = elementInsert({\n content,\n live,\n block: (indent) => spliceSource(deltaText, src, { featureId, indent }),\n parent: parentIdOf(e),\n });\n applyAt(at, insert);\n spliced.push({ start: src.start, end: src.end });\n }\n\n for (const r of additions.rels) {\n const s = pool.get(relStatementKey(r))?.shift();\n if (s === undefined) {\n throw new LandscapeSpliceError(\n `cannot locate the '${r.source} -> ${r.target}' relationship in delta.likec4 — the model merge splices authored source, and no matching declaration was found`,\n );\n }\n if (rides(s.start, s.end)) continue;\n const base = blockIndent(content, live.close);\n // Top-level in the model block: an edge written inside an `extend` block is\n // that block's, and anchoring after it would splice into someone's body.\n const top = live.rels.filter((x) => !live.elements.some((el) => x.start > el.start && x.start < el.end));\n const anchor = top.at(-1);\n const spot = anchor === undefined ? closeSpot(content, live.close) : spotAfter(content, live.close, anchor.end);\n const block = spliceSource(deltaText, s, { featureId, indent: `${base} ` });\n applyAt(spot.at, spot.bare ? `\\n${block}\\n` : `${block}\\n`);\n }\n // The delta's newlines are not necessarily this model's, and a merge that left\n // both conventions in one file is noise in every editor and every diff — the\n // same correction the landscape merge makes, from the same helper\n // (verification 2026-09-04, W-CRLF).\n return matchLineEndings(model.text, content);\n}\n\n/** The parent an addition nests under. Routing only ever sends nested ids here. */\nfunction parentIdOf(e: Elem): string {\n return e.id.slice(0, e.id.lastIndexOf(\".\"));\n}\n\ninterface ElementInsert {\n content: string;\n live: ScannedModel;\n /** The authored block at a given indent — computed late, because the indent depends on where it lands. */\n block: (indent: string) => string;\n parent: string;\n}\n\n/**\n * Where one element's block goes, as `(offset, text)`.\n *\n * Two arms, and the second is the one that makes a freshly adopted service\n * work: a model that has never named this container's parent has no `extend`\n * block for it, so the merge writes one rather than refusing. A parent the\n * merged project will not resolve is caught by the caller's parse net, which is\n * the only reader that can see the map and the model together.\n */\nfunction elementInsert(req: ElementInsert): [number, string] {\n const { content, live, block, parent } = req;\n const declared = live.elements.find((x) => x.id === parent);\n if (declared !== undefined) {\n const nested = nestedInsert(content, declared, block(`${declared.indent} `));\n return [nested.at, nested.insert];\n }\n const base = blockIndent(content, live.close);\n const body = `${base} extend ${parent} {\\n${block(`${base} `)}\\n${base} }`;\n const spot = closeSpot(content, live.close);\n return [spot.at, spot.bare ? `\\n${body}\\n` : `${body}\\n`];\n}\n\n/**\n * The model, with a `model { }` block appended when the file has none.\n *\n * `../../service-model/shape.ts` answers `extending` for an empty file, a\n * views-only file and a tags-only `specification { }` — three shapes it calls\n * legal on purpose — so routing hands those models a nested addition, and\n * refusing there took a whole legal shape away from `loam archive` for a\n * document the merge is perfectly able to author (review of E1: before the\n * routing existed, the same delta merged onto the map). It is the call\n * `elementInsert` already makes one level down — a model that has never named\n * the parent gains the `extend` block rather than refusing — and the caller's\n * parse net proves the result either way.\n */\nfunction withModelBlock(text: string): string {\n if (scanModel(text) !== null) return text;\n const pad = text === \"\" || text.endsWith(\"\\n\") ? \"\" : \"\\n\";\n return `${text}${pad}model {\\n}\\n`;\n}\n\n/**\n * The model's `model { }` block, re-scanned after every splice so each addition\n * lands in the text the previous one left — the landscape merge's rule, for the\n * same reason: placement composes per statement, not per archive.\n *\n * `withModelBlock` guarantees the FIRST read finds one, so a null here means a\n * splice destroyed the block it was writing into: mechanical, so it refuses at\n * plan time with nothing written, exactly as the parse nets do.\n */\nfunction read(content: string, path: string): ScannedModel {\n const scan = scanModel(content);\n if (scan === null) {\n throw new LandscapeSpliceError(\n `merging this feature's additions left ${path} without a model block — nothing was written; re-run after reporting it`,\n );\n }\n return scan;\n}\n\n/** The indentation of the line the model block's closing brace sits on, or \"\" when it shares one. */\nfunction blockIndent(text: string, close: number): string {\n const lineStart = text.lastIndexOf(\"\\n\", close - 1) + 1;\n const before = text.slice(lineStart, close);\n return /^[ \\t]*$/.test(before) ? before : \"\";\n}\n"]}
@@ -3,7 +3,12 @@ import { elementService, serviceOf } from "../resolve/service.js";
3
3
  import { relSortKey } from "./identity/edges.js";
4
4
  /** The model's top-level statements in document order, joined to the parsed elements for services. */
5
5
  export function topStatements(scan, els) {
6
- const topEls = scan.elements.filter((e) => !e.id.includes("."));
6
+ // An `extend <fqn>` frame is never a top-level declaration of THIS document —
7
+ // it reopens one another document owns — so it anchors nothing and displaces
8
+ // nothing. Undotted fqns are the reason the tag is checked rather than the
9
+ // dot: `extend paymentService { }` would otherwise read as a declaration of
10
+ // `paymentService` here.
11
+ const topEls = scan.elements.filter((e) => e.extend !== true && !e.id.includes("."));
7
12
  const bound = new Map(els.map((e) => [e.id, elementService(e)]));
8
13
  const stmts = topEls.map((e) => ({
9
14
  kind: "element",
@@ -159,14 +164,19 @@ function beforeSpot(text, before) {
159
164
  return { at: ls, bare: false };
160
165
  return { at: before.start, bare: true };
161
166
  }
162
- /** The line following the statement that ends at `end` — clamped to the closing brace's own spot. */
163
- function spotAfter(text, close, end) {
167
+ /**
168
+ * The line following the statement that ends at `end` — clamped to the closing
169
+ * brace's own spot. Exported for the service-model splice (`./model/merge.ts`),
170
+ * which asks the same two questions of a `model { }` block it does not group by
171
+ * service: after this statement, or last thing in the block.
172
+ */
173
+ export function spotAfter(text, close, end) {
164
174
  const nl = text.indexOf("\n", end);
165
175
  const at = nl === -1 ? text.length : nl + 1;
166
176
  return at > close ? closeSpot(text, close) : { at, bare: false };
167
177
  }
168
178
  /** The last resort: directly before the model's closing brace. */
169
- function closeSpot(text, close) {
179
+ export function closeSpot(text, close) {
170
180
  const ls = lineStartAt(text, close);
171
181
  if (/^[ \t]*$/.test(text.slice(ls, close)))
172
182
  return { at: ls, bare: false };
@@ -1 +1 @@
1
- {"version":3,"file":"placement.js","sourceRoot":"","sources":["../../../../src/core/c4/splice/placement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAElE,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAwEjD,sGAAsG;AACtG,MAAM,UAAU,aAAa,CAAC,IAAkB,EAAE,GAAW;IAC3D,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;IAChE,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACjE,MAAM,KAAK,GAAc,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QAC1C,IAAI,EAAE,SAAkB;QACxB,EAAE,EAAE,CAAC,CAAC,EAAE;QACR,GAAG,EAAE,EAAE;QACP,QAAQ,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;QACnC,KAAK,EAAE,CAAC,CAAC,KAAK;QACd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AU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;QAAE,OAAO,EAAE,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;IAC3E,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;AACnC,CAAC;AAED,SAAS,WAAW,CAAC,IAAY,EAAE,EAAU;IAC3C,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;AAC5C,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,IAAY,EAAE,MAAsB,EAAE,KAAa;IAC9E,IAAI,MAAM,CAAC,QAAQ,KAAK,CAAC,CAAC,EAAE,CAAC;QAC3B,OAAO,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,KAAK,KAAK,MAAM,CAAC,MAAM,GAAG,EAAE,CAAC;IACvE,CAAC;IACD,MAAM,SAAS,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,MAAM,CAAC,SAAS,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IACnE,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC;QAC7D,OAAO,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,KAAK,IAAI,EAAE,CAAC;IACjD,CAAC;IACD,0EAA0E;IAC1E,OAAO,EAAE,EAAE,EAAE,MAAM,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,KAAK,KAAK,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC;AAC1E,CAAC","sourcesContent":["import { type Elem } from \"../likec4.js\";\nimport { elementService, serviceOf } from \"../resolve/service.js\";\nimport type { ScannedElement, ScannedModel } from \"../source-scan.js\";\nimport { relSortKey } from \"./identity/edges.js\";\n\n/* ------------------------------------------------------------------ */\n/* Landscape placement — where a top-level addition lands */\n/* ------------------------------------------------------------------ */\n\n/**\n * The placement scheme, in full. It never moves an authored byte — placement\n * only chooses where NEW spliced blocks go — and it is deterministic in a\n * stronger sense: archiving feature A then feature B (touching different\n * services) yields the SAME final bytes as B then A, which is what lets two\n * concurrent archive PRs merge in git instead of colliding on one shared\n * append point.\n *\n * - An ELEMENT whose service already has top-level elements in the model\n * (the elementService join — binding first, title as the fallback) lands\n * immediately after the last of them: it joins its service's neighborhood.\n * Two features touching the SAME service therefore land adjacently, and\n * their concurrent PRs still conflict — expected, and documented\n * (SCHEMA.md sends that conflict to the PR flow).\n * - An element opening a NEW service lands in the trailing region before the\n * model's closing brace: skip the trailing relationship run, then walk left\n * per same-service RUN, past every run whose leading id is\n * lexicographically greater — an insertion sort of neighborhood heads\n * against whatever is already there, which is what makes the region's\n * final order independent of archive order (see the note on elementSpot:\n * per-statement comparison was order-dependent).\n * - A RELATIONSHIP lands after the last top-level relationship touching its\n * SOURCE's service (either endpoint counts), then past the anchor's own\n * CLUSTER members with a smaller sort key — two edges anchored to the same\n * statement must order by key, not by which archived first. With no such\n * neighborhood it falls to the trailing region, cluster-head-key-sorted\n * the same insertion-sort way, after the trailing elements.\n *\n * LikeC4 reference resolution is not order-dependent, so a relationship\n * placed before an element it names still parses; the in-memory parse net in\n * landscape-merge.ts's planLandscapeMerge stays as the backstop regardless.\n */\nexport interface Spot {\n /** Offset into the living text: a line start, or a point inside a shared line. */\n at: number;\n /** True when `at` shares its line with other text (the closing brace, or a displaced statement) — the block must bring its own newlines. */\n bare: boolean;\n}\n\n/** A top-level statement of the living model, with everything placement asks of it. */\nexport interface TopStmt {\n kind: \"element\" | \"rel\";\n /** Element: its id. */\n id: string;\n /** Relationship: its placement sort key (relSortKey). */\n key: string;\n /** The service(s) this statement resolves to — one for an element, both endpoints for a rel. */\n services: string[];\n start: number;\n end: number;\n}\n\n/**\n * The living model as placement reads it: the text being spliced into, its\n * top-level statement layout, and the model block's closing brace. One value\n * because every spot is computed against all three at the same instant — a\n * layout paired with text a splice has since moved would place against a\n * document that no longer exists (see `modelRegion` in landscape-merge.ts's\n * planLandscapeMerge).\n */\nexport interface ModelRegion {\n text: string;\n stmts: TopStmt[];\n close: number;\n}\n\n/** The model's top-level statements in document order, joined to the parsed elements for services. */\nexport function topStatements(scan: ScannedModel, els: Elem[]): TopStmt[] {\n const topEls = scan.elements.filter((e) => !e.id.includes(\".\"));\n const bound = new Map(els.map((e) => [e.id, elementService(e)]));\n const stmts: TopStmt[] = topEls.map((e) => ({\n kind: \"element\" as const,\n id: e.id,\n key: \"\",\n services: [bound.get(e.id) ?? e.id],\n start: e.start,\n end: e.end,\n }));\n for (const r of scan.rels) {\n // A rel declared inside an element's body is not a top-level statement —\n // anchoring after it would splice into the parent's block.\n if (topEls.some((e) => r.start > e.start && r.start < e.end)) continue;\n stmts.push({\n kind: \"rel\",\n id: \"\",\n key: relSortKey(els, r),\n // Deliberately no `known` fleet set here: this resolution only decides\n // WHERE in the file a statement anchors, both sides of every comparison\n // resolve through the same call, and the merged document is re-parsed\n // before anything is written — a wrong grouping is cosmetic, never a\n // wrong merge.\n services: [serviceOf(els, r.source), serviceOf(els, r.target)],\n start: r.start,\n end: r.end,\n });\n }\n return stmts.sort((a, b) => a.start - b.start);\n}\n\n\n/**\n * The trailing walks move in PLACEMENT UNITS, never single statements. A unit\n * is a service neighborhood: a contiguous run of top-level elements resolving\n * to one service, or a contiguous cluster of relationships grown around the\n * statements touching one — keyed by its LEADING statement's id/key. Anchored\n * inserts extend a neighborhood without changing its head, so the insertion\n * sort the trailing region maintains is over neighborhood heads, which\n * archive order cannot reshuffle. Comparing per statement instead let an\n * anchored insert legally sit a LOWER id/key after a higher one (its anchor\n * decides where it lives, not its own sort key), and a later trailing walk\n * then stopped at different statements depending on which archive had run\n * first — order-DEPENDENT bytes for features touching disjoint services, the\n * exact regime the scheme guarantees.\n */\nexport function elementSpot(region: ModelRegion, id: string, service: string): Spot {\n const { text, stmts, close } = region;\n let anchor: TopStmt | undefined;\n for (const s of stmts) {\n if (s.kind === \"element\" && s.services.includes(service)) anchor = s;\n }\n if (anchor !== undefined) return spotAfter(text, close, anchor.end);\n let i = stmts.length - 1;\n let before: TopStmt | undefined;\n while (i >= 0 && stmts[i]!.kind === \"rel\") {\n before = stmts[i];\n i -= 1;\n }\n while (i >= 0 && stmts[i]!.kind === \"element\") {\n // The same-service run ending here is one unit: skip it whole or stop\n // before it whole — an anchored member may carry any id, the run's\n // LEADING id is its sort key.\n let j = i;\n while (j > 0 && stmts[j - 1]!.kind === \"element\" && stmts[j - 1]!.services[0] === stmts[i]!.services[0]) j -= 1;\n if (!(stmts[j]!.id > id)) break;\n before = stmts[j];\n i = j - 1;\n }\n return before !== undefined ? beforeSpot(text, before) : closeSpot(text, close);\n}\n\n/**\n * Each top-level statement's cluster, as the index of the cluster's leading\n * statement. A relationship whose SOURCE's service some earlier relationship\n * in the same contiguous stretch already touches is an anchored join — it\n * belongs to that neighborhood wherever its own key would sort. One whose\n * source's service nothing before it touches opens a new cluster; sharing\n * only a TARGET does not join (every trailing edge into a busy hub would\n * otherwise dissolve into one giant cluster, and the trailing sort with it).\n * Recomputed from bytes alone, so the next archive sees the same units this\n * one placed.\n */\nfunction relClusterHeads(stmts: TopStmt[]): number[] {\n const heads = stmts.map((_, i) => i);\n let head = -1;\n let services: Set<string> | null = null;\n for (let i = 0; i < stmts.length; i += 1) {\n const s = stmts[i]!;\n if (s.kind !== \"rel\") {\n head = -1;\n services = null;\n continue;\n }\n if (services !== null && services.has(s.services[0]!)) {\n for (const svc of s.services) services.add(svc);\n } else {\n head = i;\n services = new Set(s.services);\n }\n heads[i] = head;\n }\n return heads;\n}\n\nexport function relSpot(region: ModelRegion, sourceService: string, key: string): Spot {\n const { text, stmts, close } = region;\n const heads = relClusterHeads(stmts);\n let anchorAt = -1;\n for (let i = 0; i < stmts.length; i += 1) {\n const s = stmts[i]!;\n if (s.kind === \"rel\" && s.services.includes(sourceService)) anchorAt = i;\n }\n if (anchorAt !== -1) {\n // Past the anchor, order among the cluster's OWN members is by key — two\n // edges anchored to the same statement must order by key, not by which\n // archived first — but the walk never leaves the cluster: the next\n // cluster is another neighborhood's, and stepping over it would depend\n // on which archive put it there.\n let last = stmts[anchorAt]!;\n for (let j = anchorAt + 1; j < stmts.length; j += 1) {\n const s = stmts[j]!;\n if (s.kind !== \"rel\" || heads[j] !== heads[anchorAt] || s.key >= key) break;\n last = s;\n }\n return spotAfter(text, close, last.end);\n }\n let i = stmts.length - 1;\n let before: TopStmt | undefined;\n while (i >= 0 && stmts[i]!.kind === \"rel\") {\n const j = heads[i]!;\n if (!(stmts[j]!.key > key)) break;\n before = stmts[j];\n i = j - 1;\n }\n return before !== undefined ? beforeSpot(text, before) : closeSpot(text, close);\n}\n\n/**\n * Insertion before an existing statement: at the start of its line when only\n * whitespace precedes it there, at the statement itself — bare, displacing it\n * onto a fresh line — when other text shares the line (a statement written on\n * the `model {` line, say). The unguarded line start spliced the block BEFORE\n * the model keyword, and the parse net refused a perfectly legal landscape.\n */\nfunction beforeSpot(text: string, before: TopStmt): Spot {\n const ls = lineStartAt(text, before.start);\n if (/^[ \\t]*$/.test(text.slice(ls, before.start))) return { at: ls, bare: false };\n return { at: before.start, bare: true };\n}\n\n/** The line following the statement that ends at `end` — clamped to the closing brace's own spot. */\nfunction spotAfter(text: string, close: number, end: number): Spot {\n const nl = text.indexOf(\"\\n\", end);\n const at = nl === -1 ? text.length : nl + 1;\n return at > close ? closeSpot(text, close) : { at, bare: false };\n}\n\n/** The last resort: directly before the model's closing brace. */\nfunction closeSpot(text: string, close: number): Spot {\n const ls = lineStartAt(text, close);\n if (/^[ \\t]*$/.test(text.slice(ls, close))) return { at: ls, bare: false };\n return { at: close, bare: true };\n}\n\nfunction lineStartAt(text: string, at: number): number {\n return text.lastIndexOf(\"\\n\", at - 1) + 1;\n}\n\n/**\n * Where a child block enters an existing living parent: before the closing\n * brace of the parent's body, on its own line at the parent's inner indent —\n * and a parent that never had a body gains one around the child.\n */\nexport function nestedInsert(text: string, parent: ScannedElement, block: string): { at: number; insert: string } {\n if (parent.bodyOpen === -1) {\n return { at: parent.end, insert: ` {\\n${block}\\n${parent.indent}}` };\n }\n const lineStart = text.lastIndexOf(\"\\n\", parent.bodyClose - 1) + 1;\n if (/^[ \\t]*$/.test(text.slice(lineStart, parent.bodyClose))) {\n return { at: lineStart, insert: `${block}\\n` };\n }\n // `{ ... }` on one line — break the brace onto its own line to make room.\n return { at: parent.bodyClose, insert: `\\n${block}\\n${parent.indent}` };\n}\n"]}
1
+ {"version":3,"file":"placement.js","sourceRoot":"","sources":["../../../../src/core/c4/splice/placement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAElE,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAwEjD,sGAAsG;AACtG,MAAM,UAAU,aAAa,CAAC,IAAkB,EAAE,GAAW;IAC3D,8EAA8E;IAC9E,6EAA6E;IAC7E,2EAA2E;IAC3E,4EAA4E;IAC5E,yBAAyB;IACzB,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;IACrF,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACjE,MAAM,KAAK,GAAc,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QAC1C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O,EAAE,EAAE,EAAE,MAAM,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,KAAK,KAAK,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC;AAC1E,CAAC","sourcesContent":["import { type Elem } from \"../likec4.js\";\nimport { elementService, serviceOf } from \"../resolve/service.js\";\nimport type { ScannedElement, ScannedModel } from \"../source-scan.js\";\nimport { relSortKey } from \"./identity/edges.js\";\n\n/* ------------------------------------------------------------------ */\n/* Landscape placement — where a top-level addition lands */\n/* ------------------------------------------------------------------ */\n\n/**\n * The placement scheme, in full. It never moves an authored byte — placement\n * only chooses where NEW spliced blocks go — and it is deterministic in a\n * stronger sense: archiving feature A then feature B (touching different\n * services) yields the SAME final bytes as B then A, which is what lets two\n * concurrent archive PRs merge in git instead of colliding on one shared\n * append point.\n *\n * - An ELEMENT whose service already has top-level elements in the model\n * (the elementService join — binding first, title as the fallback) lands\n * immediately after the last of them: it joins its service's neighborhood.\n * Two features touching the SAME service therefore land adjacently, and\n * their concurrent PRs still conflict — expected, and documented\n * (SCHEMA.md sends that conflict to the PR flow).\n * - An element opening a NEW service lands in the trailing region before the\n * model's closing brace: skip the trailing relationship run, then walk left\n * per same-service RUN, past every run whose leading id is\n * lexicographically greater — an insertion sort of neighborhood heads\n * against whatever is already there, which is what makes the region's\n * final order independent of archive order (see the note on elementSpot:\n * per-statement comparison was order-dependent).\n * - A RELATIONSHIP lands after the last top-level relationship touching its\n * SOURCE's service (either endpoint counts), then past the anchor's own\n * CLUSTER members with a smaller sort key — two edges anchored to the same\n * statement must order by key, not by which archived first. With no such\n * neighborhood it falls to the trailing region, cluster-head-key-sorted\n * the same insertion-sort way, after the trailing elements.\n *\n * LikeC4 reference resolution is not order-dependent, so a relationship\n * placed before an element it names still parses; the in-memory parse net in\n * landscape-merge.ts's planLandscapeMerge stays as the backstop regardless.\n */\nexport interface Spot {\n /** Offset into the living text: a line start, or a point inside a shared line. */\n at: number;\n /** True when `at` shares its line with other text (the closing brace, or a displaced statement) — the block must bring its own newlines. */\n bare: boolean;\n}\n\n/** A top-level statement of the living model, with everything placement asks of it. */\nexport interface TopStmt {\n kind: \"element\" | \"rel\";\n /** Element: its id. */\n id: string;\n /** Relationship: its placement sort key (relSortKey). */\n key: string;\n /** The service(s) this statement resolves to — one for an element, both endpoints for a rel. */\n services: string[];\n start: number;\n end: number;\n}\n\n/**\n * The living model as placement reads it: the text being spliced into, its\n * top-level statement layout, and the model block's closing brace. One value\n * because every spot is computed against all three at the same instant — a\n * layout paired with text a splice has since moved would place against a\n * document that no longer exists (see `modelRegion` in landscape-merge.ts's\n * planLandscapeMerge).\n */\nexport interface ModelRegion {\n text: string;\n stmts: TopStmt[];\n close: number;\n}\n\n/** The model's top-level statements in document order, joined to the parsed elements for services. */\nexport function topStatements(scan: ScannedModel, els: Elem[]): TopStmt[] {\n // An `extend <fqn>` frame is never a top-level declaration of THIS document —\n // it reopens one another document owns — so it anchors nothing and displaces\n // nothing. Undotted fqns are the reason the tag is checked rather than the\n // dot: `extend paymentService { }` would otherwise read as a declaration of\n // `paymentService` here.\n const topEls = scan.elements.filter((e) => e.extend !== true && !e.id.includes(\".\"));\n const bound = new Map(els.map((e) => [e.id, elementService(e)]));\n const stmts: TopStmt[] = topEls.map((e) => ({\n kind: \"element\" as const,\n id: e.id,\n key: \"\",\n services: [bound.get(e.id) ?? e.id],\n start: e.start,\n end: e.end,\n }));\n for (const r of scan.rels) {\n // A rel declared inside an element's body is not a top-level statement —\n // anchoring after it would splice into the parent's block.\n if (topEls.some((e) => r.start > e.start && r.start < e.end)) continue;\n stmts.push({\n kind: \"rel\",\n id: \"\",\n key: relSortKey(els, r),\n // Deliberately no `known` fleet set here: this resolution only decides\n // WHERE in the file a statement anchors, both sides of every comparison\n // resolve through the same call, and the merged document is re-parsed\n // before anything is written — a wrong grouping is cosmetic, never a\n // wrong merge.\n services: [serviceOf(els, r.source), serviceOf(els, r.target)],\n start: r.start,\n end: r.end,\n });\n }\n return stmts.sort((a, b) => a.start - b.start);\n}\n\n\n/**\n * The trailing walks move in PLACEMENT UNITS, never single statements. A unit\n * is a service neighborhood: a contiguous run of top-level elements resolving\n * to one service, or a contiguous cluster of relationships grown around the\n * statements touching one — keyed by its LEADING statement's id/key. Anchored\n * inserts extend a neighborhood without changing its head, so the insertion\n * sort the trailing region maintains is over neighborhood heads, which\n * archive order cannot reshuffle. Comparing per statement instead let an\n * anchored insert legally sit a LOWER id/key after a higher one (its anchor\n * decides where it lives, not its own sort key), and a later trailing walk\n * then stopped at different statements depending on which archive had run\n * first — order-DEPENDENT bytes for features touching disjoint services, the\n * exact regime the scheme guarantees.\n */\nexport function elementSpot(region: ModelRegion, id: string, service: string): Spot {\n const { text, stmts, close } = region;\n let anchor: TopStmt | undefined;\n for (const s of stmts) {\n if (s.kind === \"element\" && s.services.includes(service)) anchor = s;\n }\n if (anchor !== undefined) return spotAfter(text, close, anchor.end);\n let i = stmts.length - 1;\n let before: TopStmt | undefined;\n while (i >= 0 && stmts[i]!.kind === \"rel\") {\n before = stmts[i];\n i -= 1;\n }\n while (i >= 0 && stmts[i]!.kind === \"element\") {\n // The same-service run ending here is one unit: skip it whole or stop\n // before it whole — an anchored member may carry any id, the run's\n // LEADING id is its sort key.\n let j = i;\n while (j > 0 && stmts[j - 1]!.kind === \"element\" && stmts[j - 1]!.services[0] === stmts[i]!.services[0]) j -= 1;\n if (!(stmts[j]!.id > id)) break;\n before = stmts[j];\n i = j - 1;\n }\n return before !== undefined ? beforeSpot(text, before) : closeSpot(text, close);\n}\n\n/**\n * Each top-level statement's cluster, as the index of the cluster's leading\n * statement. A relationship whose SOURCE's service some earlier relationship\n * in the same contiguous stretch already touches is an anchored join — it\n * belongs to that neighborhood wherever its own key would sort. One whose\n * source's service nothing before it touches opens a new cluster; sharing\n * only a TARGET does not join (every trailing edge into a busy hub would\n * otherwise dissolve into one giant cluster, and the trailing sort with it).\n * Recomputed from bytes alone, so the next archive sees the same units this\n * one placed.\n */\nfunction relClusterHeads(stmts: TopStmt[]): number[] {\n const heads = stmts.map((_, i) => i);\n let head = -1;\n let services: Set<string> | null = null;\n for (let i = 0; i < stmts.length; i += 1) {\n const s = stmts[i]!;\n if (s.kind !== \"rel\") {\n head = -1;\n services = null;\n continue;\n }\n if (services !== null && services.has(s.services[0]!)) {\n for (const svc of s.services) services.add(svc);\n } else {\n head = i;\n services = new Set(s.services);\n }\n heads[i] = head;\n }\n return heads;\n}\n\nexport function relSpot(region: ModelRegion, sourceService: string, key: string): Spot {\n const { text, stmts, close } = region;\n const heads = relClusterHeads(stmts);\n let anchorAt = -1;\n for (let i = 0; i < stmts.length; i += 1) {\n const s = stmts[i]!;\n if (s.kind === \"rel\" && s.services.includes(sourceService)) anchorAt = i;\n }\n if (anchorAt !== -1) {\n // Past the anchor, order among the cluster's OWN members is by key — two\n // edges anchored to the same statement must order by key, not by which\n // archived first — but the walk never leaves the cluster: the next\n // cluster is another neighborhood's, and stepping over it would depend\n // on which archive put it there.\n let last = stmts[anchorAt]!;\n for (let j = anchorAt + 1; j < stmts.length; j += 1) {\n const s = stmts[j]!;\n if (s.kind !== \"rel\" || heads[j] !== heads[anchorAt] || s.key >= key) break;\n last = s;\n }\n return spotAfter(text, close, last.end);\n }\n let i = stmts.length - 1;\n let before: TopStmt | undefined;\n while (i >= 0 && stmts[i]!.kind === \"rel\") {\n const j = heads[i]!;\n if (!(stmts[j]!.key > key)) break;\n before = stmts[j];\n i = j - 1;\n }\n return before !== undefined ? beforeSpot(text, before) : closeSpot(text, close);\n}\n\n/**\n * Insertion before an existing statement: at the start of its line when only\n * whitespace precedes it there, at the statement itself — bare, displacing it\n * onto a fresh line — when other text shares the line (a statement written on\n * the `model {` line, say). The unguarded line start spliced the block BEFORE\n * the model keyword, and the parse net refused a perfectly legal landscape.\n */\nfunction beforeSpot(text: string, before: TopStmt): Spot {\n const ls = lineStartAt(text, before.start);\n if (/^[ \\t]*$/.test(text.slice(ls, before.start))) return { at: ls, bare: false };\n return { at: before.start, bare: true };\n}\n\n/**\n * The line following the statement that ends at `end` — clamped to the closing\n * brace's own spot. Exported for the service-model splice (`./model/merge.ts`),\n * which asks the same two questions of a `model { }` block it does not group by\n * service: after this statement, or last thing in the block.\n */\nexport function spotAfter(text: string, close: number, end: number): Spot {\n const nl = text.indexOf(\"\\n\", end);\n const at = nl === -1 ? text.length : nl + 1;\n return at > close ? closeSpot(text, close) : { at, bare: false };\n}\n\n/** The last resort: directly before the model's closing brace. */\nexport function closeSpot(text: string, close: number): Spot {\n const ls = lineStartAt(text, close);\n if (/^[ \\t]*$/.test(text.slice(ls, close))) return { at: ls, bare: false };\n return { at: close, bare: true };\n}\n\nfunction lineStartAt(text: string, at: number): number {\n return text.lastIndexOf(\"\\n\", at - 1) + 1;\n}\n\n/**\n * Where a child block enters an existing living parent: before the closing\n * brace of the parent's body, on its own line at the parent's inner indent —\n * and a parent that never had a body gains one around the child.\n */\nexport function nestedInsert(text: string, parent: ScannedElement, block: string): { at: number; insert: string } {\n if (parent.bodyOpen === -1) {\n return { at: parent.end, insert: ` {\\n${block}\\n${parent.indent}}` };\n }\n const lineStart = text.lastIndexOf(\"\\n\", parent.bodyClose - 1) + 1;\n if (/^[ \\t]*$/.test(text.slice(lineStart, parent.bodyClose))) {\n return { at: lineStart, insert: `${block}\\n` };\n }\n // `{ ... }` on one line — break the brace onto its own line to make room.\n return { at: parent.bodyClose, insert: `\\n${block}\\n${parent.indent}` };\n}\n"]}
@@ -43,7 +43,7 @@ import { basename, join, resolve } from "node:path";
43
43
  import { LikeC4 } from "likec4";
44
44
  import { flattenModel } from "./likec4.js";
45
45
  import { readDynamicViews } from "./parsed/dynamic-views.js";
46
- import { readViewIds } from "./parsed/view-ids.js";
46
+ import { readGlobalStyleIds, readViewIds } from "./parsed/view-ids.js";
47
47
  import { readSpecification } from "./parsed/specification.js";
48
48
  import { readDeployment } from "./parsed/deployment.js";
49
49
  /**
@@ -153,6 +153,7 @@ export async function loadBatch(paths) {
153
153
  specification: readSpecification(model.specification),
154
154
  views: readDynamicViews(model),
155
155
  viewIds: readViewIds(model),
156
+ globalStyles: readGlobalStyleIds(model),
156
157
  deployment: readDeployment(model),
157
158
  ...flattenModel(model),
158
159
  });
@@ -1 +1 @@
1
- {"version":3,"file":"workspace.js","sourceRoot":"","sources":["../../../src/core/c4/workspace.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,YAAY,EAAwD,MAAM,aAAa,CAAC;AACjG,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAQxD;;;;;;;GAOG;AACH,KAAK,UAAU,KAAK,CAAC,IAAY,EAAE,OAAiB;IAClD,MAAM,KAAK,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC7C,0EAA0E;IAC1E,yEAAyE;IACzE,0EAA0E;IAC1E,0EAA0E;IAC1E,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,CAAC,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,EAAE,IAAI,CAAC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,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IACnD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Batch loader: many self-contained `.likec4` documents through ONE\n * LikeC4/Langium workspace.\n *\n * `loadFile` pays a fresh workspace per call — ~100ms even warm — which is what\n * made `validate --all` O(documents) workspace spins (13.7s median over the\n * 120-service benchmark fixture, docs/BENCHMARKS.md). This module copies every\n * document into a mkdtemp workspace as one single-file PROJECT each (a\n * `likec4.config.json` per folder), calls `LikeC4.fromWorkspace` once, splits\n * `getErrors()` per document, and flattens each clean project through the same\n * `flattenModel` the per-file path uses. Parity — byte-identical error\n * messages/lines and identical elements/relationships — is pinned by\n * test/likec4-batch-parity.test.ts, which is also the tripwire for the exact\n * likec4 version pin: multi-project workspaces are public API, but this use of\n * them is not documented, so an upgrade must fail that suite before it lands.\n *\n * Isolation is load-bearing, not cosmetic: `fromSource` gives each document a\n * workspace of its own, so an author-written `import ... from 'name'` can never\n * resolve. In a shared workspace it COULD — a sibling project is one lucky name\n * away — so every folder carries one crypto-random per-invocation hex token in\n * its project name. A document cannot import what it cannot name, and the\n * parity suite pins that a guessed sibling name errors identically in both\n * modes.\n *\n * Callers own the failure story: a document that cannot be staged (unreadable,\n * missing) is silently DROPPED from the result so the caller's ordinary\n * per-path load reproduces today's error, and a batch-infrastructure failure\n * (tmpdir denied — the sandboxed-runner class ROADMAP documents) rejects the\n * whole call for the caller to catch and degrade. FleetContext.prefetchLikeC4\n * does exactly that: findings can never change because a workspace could not be\n * created, only the speed can.\n *\n * This file took core/c4/ to exactly five files, and the seam that note\n * predicted is now open: `./project/load.ts` loads a DIRECTORY as one project,\n * which is the opposite isolation contract and belongs beside this one rather\n * than inside it.\n */\nimport { randomBytes } from \"node:crypto\";\nimport { inOrder } from \"../kernel/concurrency.js\";\nimport { copyFile, mkdir, mkdtemp, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { basename, join, resolve } from \"node:path\";\nimport { LikeC4 } from \"likec4\";\nimport { flattenModel, type LikeC4Error, type LoadedDoc, type ReadableModel } from \"./likec4.js\";\nimport { readDynamicViews } from \"./parsed/dynamic-views.js\";\nimport { readViewIds } from \"./parsed/view-ids.js\";\nimport { readSpecification } from \"./parsed/specification.js\";\nimport { readDeployment } from \"./parsed/deployment.js\";\n\n/** A staged document: the real path it came from, and its workspace project. */\ninterface StagedDoc {\n path: string;\n project: string;\n}\n\n/**\n * Stage every readable document as its own single-file project. A copy failure\n * removes the half-made folder and drops the path — an empty project must not\n * reach the workspace scan, and the caller's per-path load owns the error. The\n * copy is `copyFile` (raw bytes), not read/decode/write: BOM, CRLF and even\n * non-UTF-8 bytes reach LikeC4's own reader exactly as they would from the\n * original file on disk.\n */\nasync function stage(root: string, targets: string[]): Promise<StagedDoc[]> {\n const token = randomBytes(8).toString(\"hex\");\n // Concurrent, capped, in input order (kernel/concurrency's contract): the\n // per-document folders share nothing, and on a network-mounted docs repo\n // the sequential form paid three round-trips per document. Nulls mark the\n // drops so indices — and with them the p<i> project names — stay aligned.\n const results = await inOrder([...targets.entries()], async ([i, path]) => {\n const project = `p${i}_${token}`;\n const folder = join(root, project);\n try {\n await mkdir(folder);\n await writeFile(join(folder, \"likec4.config.json\"), JSON.stringify({ name: project }), \"utf8\");\n await copyFile(path, join(folder, basename(path)));\n return { path, project };\n } catch {\n await rm(folder, { recursive: true, force: true });\n return null;\n }\n });\n return results.filter((r): r is StagedDoc => r !== null);\n}\n\n/**\n * `getErrors()` split per document, each error's `sourceFsPath` rewritten from\n * the workspace copy to the document's real absolute path.\n *\n * Grouping keys on the unique `p<i>_<token>` path SEGMENT, never on a\n * tmp-root prefix compare: darwin hands back realpathed workspace paths\n * (`/var/...` becomes `/private/var/...`) in some environments and the literal\n * mkdtemp path in others, and a prefix compare silently attributes every error\n * to nobody in exactly one of those two worlds. The segment survives both.\n */\nfunction groupErrors(likec4: LikeC4, staged: StagedDoc[]): Map<string, LikeC4Error[]> {\n const pathOf = new Map(staged.map((doc) => [doc.project, doc.path]));\n const grouped = new Map<string, LikeC4Error[]>();\n for (const err of likec4.getErrors()) {\n const project = err.sourceFsPath.split(/[\\\\/]/).find((segment) => pathOf.has(segment));\n if (project === undefined) {\n // An error this walk cannot attribute would otherwise be DROPPED — and a\n // dropped error grades its document clean, which is failing open in the\n // fleet gate. Unreachable at the pinned likec4 version (every corpus\n // error carries its project folder in sourceFsPath), so the one place a\n // dependency upgrade could break the attribution is the one place that\n // must reject the whole batch: the caller degrades to per-path loads,\n // where the error reappears.\n throw new Error(`unattributable LikeC4 error in batch workspace: ${err.message}`);\n }\n const list = grouped.get(project) ?? [];\n list.push({ ...err, sourceFsPath: pathOf.get(project) });\n grouped.set(project, list);\n }\n return grouped;\n}\n\n/**\n * Load and validate many self-contained `.likec4` documents in one workspace.\n * Returns `resolve(path)` → LoadedDoc; paths are deduped through the same\n * resolution, and a path that could not be staged is absent from the result.\n *\n * A document with errors keeps `loadSource`'s exact rule — empty elements and\n * relationships, WITHOUT calling `parsedModel`: the parsed stage succeeds even\n * over unresolved references, so the \"errors mean no model\" boundary is loam's\n * to apply, not LikeC4's. A clean document is flattened from\n * `parsedModel(project)` — parsed, never computed: the computed stage RESOLVES\n * every view against the model — which loam never wants, because it reads a\n * view's DECLARATIONS and never a view's resolved contents (docs/DESIGN.md\n * rule 26) — and which is superlinear in edge count (see loadSource).\n */\nexport async function loadBatch(paths: string[]): Promise<Map<string, LoadedDoc>> {\n const targets = [...new Set(paths.map((path) => resolve(path)))];\n const out = new Map<string, LoadedDoc>();\n if (targets.length === 0) return out;\n const root = await mkdtemp(join(tmpdir(), \"loam-c4-\"));\n try {\n const staged = await stage(root, targets);\n if (staged.length === 0) return out;\n // One workspace for the whole batch — the entire point. The logger is\n // disabled exactly as in loadSource: diagnostics are returned per document,\n // not written out-of-band to stderr (core never prints).\n const likec4 = await LikeC4.fromWorkspace(root, { logger: false });\n try {\n const grouped = groupErrors(likec4, staged);\n for (const { path, project } of staged) {\n const errors = grouped.get(project) ?? [];\n if (errors.length > 0) {\n out.set(path, { errors, elements: [], relationships: [] });\n } else {\n const model = (await likec4.parsedModel(project)) as ReadableModel;\n // The specification travels with the batch loader too, and must: this\n // is the loader `validate --all` reads the landscape through, so a\n // kind-tag check wired only into `loadSource` would be a check the\n // fleet gate — the one run it exists for — never actually ran.\n out.set(path, {\n errors,\n specification: readSpecification(model.specification),\n views: readDynamicViews(model),\n viewIds: readViewIds(model),\n deployment: readDeployment(model),\n ...flattenModel(model),\n });\n }\n }\n } finally {\n await likec4.dispose();\n }\n return out;\n } finally {\n // The workspace is this invocation's alone; nothing else may observe it.\n // A kill between mkdtemp and here can strand a loam-c4-* dir in OS tmp —\n // never in the docs repo — which docs/DESIGN.md records as accepted.\n await rm(root, { recursive: true, force: true });\n }\n}\n"]}
1
+ {"version":3,"file":"workspace.js","sourceRoot":"","sources":["../../../src/core/c4/workspace.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,YAAY,EAAwD,MAAM,aAAa,CAAC;AACjG,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACvE,OAAO,EAA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N,aAAa,EAAE,iBAAiB,CAAC,KAAK,CAAC,aAAa,CAAC;wBACrD,KAAK,EAAE,gBAAgB,CAAC,KAAK,CAAC;wBAC9B,OAAO,EAAE,WAAW,CAAC,KAAK,CAAC;wBAC3B,YAAY,EAAE,kBAAkB,CAAC,KAAK,CAAC;wBACvC,UAAU,EAAE,cAAc,CAAC,KAAK,CAAC;wBACjC,GAAG,YAAY,CAAC,KAAK,CAAC;qBACvB,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;QACH,CAAC;gBAAS,CAAC;YACT,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;QACzB,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC;YAAS,CAAC;QACT,yEAAyE;QACzE,yEAAyE;QACzE,qEAAqE;QACrE,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IACnD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Batch loader: many self-contained `.likec4` documents through ONE\n * LikeC4/Langium workspace.\n *\n * `loadFile` pays a fresh workspace per call — ~100ms even warm — which is what\n * made `validate --all` O(documents) workspace spins (13.7s median over the\n * 120-service benchmark fixture, docs/BENCHMARKS.md). This module copies every\n * document into a mkdtemp workspace as one single-file PROJECT each (a\n * `likec4.config.json` per folder), calls `LikeC4.fromWorkspace` once, splits\n * `getErrors()` per document, and flattens each clean project through the same\n * `flattenModel` the per-file path uses. Parity — byte-identical error\n * messages/lines and identical elements/relationships — is pinned by\n * test/likec4-batch-parity.test.ts, which is also the tripwire for the exact\n * likec4 version pin: multi-project workspaces are public API, but this use of\n * them is not documented, so an upgrade must fail that suite before it lands.\n *\n * Isolation is load-bearing, not cosmetic: `fromSource` gives each document a\n * workspace of its own, so an author-written `import ... from 'name'` can never\n * resolve. In a shared workspace it COULD — a sibling project is one lucky name\n * away — so every folder carries one crypto-random per-invocation hex token in\n * its project name. A document cannot import what it cannot name, and the\n * parity suite pins that a guessed sibling name errors identically in both\n * modes.\n *\n * Callers own the failure story: a document that cannot be staged (unreadable,\n * missing) is silently DROPPED from the result so the caller's ordinary\n * per-path load reproduces today's error, and a batch-infrastructure failure\n * (tmpdir denied — the sandboxed-runner class ROADMAP documents) rejects the\n * whole call for the caller to catch and degrade. FleetContext.prefetchLikeC4\n * does exactly that: findings can never change because a workspace could not be\n * created, only the speed can.\n *\n * This file took core/c4/ to exactly five files, and the seam that note\n * predicted is now open: `./project/load.ts` loads a DIRECTORY as one project,\n * which is the opposite isolation contract and belongs beside this one rather\n * than inside it.\n */\nimport { randomBytes } from \"node:crypto\";\nimport { inOrder } from \"../kernel/concurrency.js\";\nimport { copyFile, mkdir, mkdtemp, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { basename, join, resolve } from \"node:path\";\nimport { LikeC4 } from \"likec4\";\nimport { flattenModel, type LikeC4Error, type LoadedDoc, type ReadableModel } from \"./likec4.js\";\nimport { readDynamicViews } from \"./parsed/dynamic-views.js\";\nimport { readGlobalStyleIds, readViewIds } from \"./parsed/view-ids.js\";\nimport { readSpecification } from \"./parsed/specification.js\";\nimport { readDeployment } from \"./parsed/deployment.js\";\n\n/** A staged document: the real path it came from, and its workspace project. */\ninterface StagedDoc {\n path: string;\n project: string;\n}\n\n/**\n * Stage every readable document as its own single-file project. A copy failure\n * removes the half-made folder and drops the path — an empty project must not\n * reach the workspace scan, and the caller's per-path load owns the error. The\n * copy is `copyFile` (raw bytes), not read/decode/write: BOM, CRLF and even\n * non-UTF-8 bytes reach LikeC4's own reader exactly as they would from the\n * original file on disk.\n */\nasync function stage(root: string, targets: string[]): Promise<StagedDoc[]> {\n const token = randomBytes(8).toString(\"hex\");\n // Concurrent, capped, in input order (kernel/concurrency's contract): the\n // per-document folders share nothing, and on a network-mounted docs repo\n // the sequential form paid three round-trips per document. Nulls mark the\n // drops so indices — and with them the p<i> project names — stay aligned.\n const results = await inOrder([...targets.entries()], async ([i, path]) => {\n const project = `p${i}_${token}`;\n const folder = join(root, project);\n try {\n await mkdir(folder);\n await writeFile(join(folder, \"likec4.config.json\"), JSON.stringify({ name: project }), \"utf8\");\n await copyFile(path, join(folder, basename(path)));\n return { path, project };\n } catch {\n await rm(folder, { recursive: true, force: true });\n return null;\n }\n });\n return results.filter((r): r is StagedDoc => r !== null);\n}\n\n/**\n * `getErrors()` split per document, each error's `sourceFsPath` rewritten from\n * the workspace copy to the document's real absolute path.\n *\n * Grouping keys on the unique `p<i>_<token>` path SEGMENT, never on a\n * tmp-root prefix compare: darwin hands back realpathed workspace paths\n * (`/var/...` becomes `/private/var/...`) in some environments and the literal\n * mkdtemp path in others, and a prefix compare silently attributes every error\n * to nobody in exactly one of those two worlds. The segment survives both.\n */\nfunction groupErrors(likec4: LikeC4, staged: StagedDoc[]): Map<string, LikeC4Error[]> {\n const pathOf = new Map(staged.map((doc) => [doc.project, doc.path]));\n const grouped = new Map<string, LikeC4Error[]>();\n for (const err of likec4.getErrors()) {\n const project = err.sourceFsPath.split(/[\\\\/]/).find((segment) => pathOf.has(segment));\n if (project === undefined) {\n // An error this walk cannot attribute would otherwise be DROPPED — and a\n // dropped error grades its document clean, which is failing open in the\n // fleet gate. Unreachable at the pinned likec4 version (every corpus\n // error carries its project folder in sourceFsPath), so the one place a\n // dependency upgrade could break the attribution is the one place that\n // must reject the whole batch: the caller degrades to per-path loads,\n // where the error reappears.\n throw new Error(`unattributable LikeC4 error in batch workspace: ${err.message}`);\n }\n const list = grouped.get(project) ?? [];\n list.push({ ...err, sourceFsPath: pathOf.get(project) });\n grouped.set(project, list);\n }\n return grouped;\n}\n\n/**\n * Load and validate many self-contained `.likec4` documents in one workspace.\n * Returns `resolve(path)` → LoadedDoc; paths are deduped through the same\n * resolution, and a path that could not be staged is absent from the result.\n *\n * A document with errors keeps `loadSource`'s exact rule — empty elements and\n * relationships, WITHOUT calling `parsedModel`: the parsed stage succeeds even\n * over unresolved references, so the \"errors mean no model\" boundary is loam's\n * to apply, not LikeC4's. A clean document is flattened from\n * `parsedModel(project)` — parsed, never computed: the computed stage RESOLVES\n * every view against the model — which loam never wants, because it reads a\n * view's DECLARATIONS and never a view's resolved contents (docs/DESIGN.md\n * rule 26) — and which is superlinear in edge count (see loadSource).\n */\nexport async function loadBatch(paths: string[]): Promise<Map<string, LoadedDoc>> {\n const targets = [...new Set(paths.map((path) => resolve(path)))];\n const out = new Map<string, LoadedDoc>();\n if (targets.length === 0) return out;\n const root = await mkdtemp(join(tmpdir(), \"loam-c4-\"));\n try {\n const staged = await stage(root, targets);\n if (staged.length === 0) return out;\n // One workspace for the whole batch — the entire point. The logger is\n // disabled exactly as in loadSource: diagnostics are returned per document,\n // not written out-of-band to stderr (core never prints).\n const likec4 = await LikeC4.fromWorkspace(root, { logger: false });\n try {\n const grouped = groupErrors(likec4, staged);\n for (const { path, project } of staged) {\n const errors = grouped.get(project) ?? [];\n if (errors.length > 0) {\n out.set(path, { errors, elements: [], relationships: [] });\n } else {\n const model = (await likec4.parsedModel(project)) as ReadableModel;\n // The specification travels with the batch loader too, and must: this\n // is the loader `validate --all` reads the landscape through, so a\n // kind-tag check wired only into `loadSource` would be a check the\n // fleet gate — the one run it exists for — never actually ran.\n out.set(path, {\n errors,\n specification: readSpecification(model.specification),\n views: readDynamicViews(model),\n viewIds: readViewIds(model),\n globalStyles: readGlobalStyleIds(model),\n deployment: readDeployment(model),\n ...flattenModel(model),\n });\n }\n }\n } finally {\n await likec4.dispose();\n }\n return out;\n } finally {\n // The workspace is this invocation's alone; nothing else may observe it.\n // A kill between mkdtemp and here can strand a loam-c4-* dir in OS tmp —\n // never in the docs repo — which docs/DESIGN.md records as accepted.\n await rm(root, { recursive: true, force: true });\n }\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { loadFile } from "../c4/likec4.js";
3
3
  import { elementService, serviceResolver } from "../c4/resolve/service.js";
4
+ import { extendingModels } from "../c4/service-model/fleet/extending.js";
4
5
  import { serviceIdProblem } from "../kernel/ids/service.js";
5
6
  import { deltaShapeIssues } from "../delta/delta.js";
6
7
  import { featurePaths } from "../repo/paths.js";
@@ -50,6 +51,12 @@ export async function featureCoherence(request) {
50
51
  // overlay states: one memoised read does not justify an edge from
51
52
  // `core/deployment/` to `fleet-context`.
52
53
  ...(context === undefined ? {} : { load: (path) => context.loadLikeC4(path) }),
54
+ // The fleet's extending models, so the preview is the map the archive would
55
+ // really leave: a nested addition is routed into the service's own model,
56
+ // never onto the map. Read here for the same reason `load` is passed here —
57
+ // this module holds the context and `core/deployment/` does not — and as a
58
+ // thunk, so a feature with no `deployment/` directory pays nothing for it.
59
+ models: () => extendingModels(docsDir, context),
53
60
  });
54
61
  if (topology.kind === "unreadable") {
55
62
  issues.push({
@@ -1 +1 @@
1
- {"version":3,"file":"coherence.js","sourceRoot":"","sources":["../../../src/core/coherence/coherence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAuC,MAAM,iBAAiB,CAAC;AAChF,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAErD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACzF,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAExD,OAAO,EAAE,iBAAiB,EAAmB,MAAM,eAAe,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,eAA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AC,CAAC,OAAO,KAAK,SAAS;YAAE,SAAS;QACtC,MAAM,OAAO,GAAG,gBAAgB,CAAC,CAAC,CAAC,OAAO,EAAE,8BAA8B,CAAC,CAAC;QAC5E,IAAI,OAAO,KAAK,IAAI;YAAE,SAAS;QAC/B,MAAM,CAAC,IAAI,CAAC;YACV,QAAQ,EAAE,OAAO;YACjB,IAAI,EAAE,4BAA4B;YAClC,OAAO,EAAE,CAAC,CAAC,OAAO;YAClB,OAAO,EACL,IAAI,CAAC,CAAC,KAAK,MAAM,CAAC,CAAC,EAAE,OAAO,OAAO,GAAG;gBACtC,kCAAkC,CAAC,CAAC,OAAO,yDAAyD;gBACpG,sBAAsB,CAAC,CAAC,OAAO,uEAAuE;SACzG,CAAC,CAAC;IACL,CAAC;IAED,2EAA2E;IAC3E,oEAAoE;IACpE,uEAAuE;IACvE,kEAAkE;IAClE,iEAAiE;IACjE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,cAAc,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;IAExF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { loadFile, type Elem, type LoadedDoc, type Rel } from \"../c4/likec4.js\";\nimport { elementService, serviceResolver } from \"../c4/resolve/service.js\";\nimport { serviceIdProblem } from \"../kernel/ids/service.js\";\nimport { deltaShapeIssues } from \"../delta/delta.js\";\nimport type { Issue } from \"../vocabulary/issue.js\";\nimport { featurePaths } from \"../repo/paths.js\";\nimport { featureSpecServices } from \"../repo/repo.js\";\nimport { enumeratedServiceIds, enumeratedServiceIndex } from \"../repo/service-target.js\";\nimport { serviceOperationIds } from \"../openapi/doc.js\";\nimport type { FleetContext } from \"../fleet-context.js\";\nimport { declaredByService, type DeltaScope } from \"./declared.js\";\nimport { coherenceLookups } from \"./lookups.js\";\nimport { eventCoherence } from \"./events/events.js\";\nimport { authoringIssues } from \"./authoring/scaffold.js\";\nimport { glossaryDeltaIssues } from \"../glossary/delta.js\";\nimport { flowDeltaIssues } from \"../usecases/delta/flows.js\";\nimport { deploymentDeltaIssues, readFeatureDeployments } from \"../deployment/delta.js\";\nimport type { DocsDir, FeatureDir } from \"../kernel/ids/dirs.js\";\n\n\n/**\n * Cross-axis consistency for a feature: do C4 (architecture), requirements (behaviour),\n * and OpenAPI (contract) agree? Errors are hard (would corrupt the living docs on archive);\n * warnings surface softer misalignments.\n *\n * `preloadedDelta` is the feature's already-parsed delta.likec4, when the caller\n * has it — loading a LikeC4 document spins up a fresh Langium workspace, the\n * dominant per-feature cost, and validate/archive have both parsed the same file\n * moments earlier. Standalone calls omit it and nothing changes: the file is\n * loaded here, exactly as before.\n */\n\n/** How a caller names the feature being graded, and what it already has in hand. */\nexport interface CoherenceRequest {\n docsDir: DocsDir;\n featureDir: FeatureDir;\n featureId: string;\n /** The delta LikeC4 document, when the caller already parsed it. */\n preloadedDelta?: LoadedDoc;\n context?: FleetContext;\n}\n\nexport async function featureCoherence(request: CoherenceRequest): Promise<Issue[]> {\n const { docsDir, featureDir, featureId, preloadedDelta, context } = request;\n const scope: DeltaScope = { docsDir, featureDir, featureId };\n // Delta shape first: a diff that does not apply to the living spec explains\n // everything downstream, and it is the one breach that is silent without a check.\n const issues: Issue[] = await deltaShapeIssues(docsDir, featureDir, featureId, context);\n\n // The vocabulary axis, and it is asked first because it is cheap and\n // independent: one `existsSync` for a feature with no glossary/, and nothing\n // downstream reads its answer. A term this feature introduces that the living\n // glossary already defines is the one thing that can go wrong on a create-only\n // merge, and it must be caught before the copy, not after.\n issues.push(...(await glossaryDeltaIssues(docsDir, featureDir)));\n\n // The use-case axis, and it is asked here for the vocabulary axis's reasons\n // exactly: one walk over a directory that is usually absent, nothing\n // downstream reads its answer, and a create-only merge has one thing that can\n // go wrong. A flow this feature introduces that the living `architecture/`\n // already holds must be caught before the copy, not after it has replaced an\n // authored hop sequence.\n issues.push(...(await flowDeltaIssues(docsDir, featureDir)));\n issues.push(...(await deploymentDeltaIssues(docsDir, featureDir)));\n\n // And the topology's second question, which the collision check above cannot\n // ask: does the document READ against the map this feature's own merge would\n // leave behind. It matters more literally here than one axis over — a feature\n // that stands a service up in a new cluster declares that service in its\n // `delta.likec4` and instances it in the topology, so the element the document\n // names exists only post-merge — and without it the archive copies an\n // unreadable document into `architecture/` for the next reader's\n // `loam validate --all` to fail on, against a file they did not write.\n const topology = await readFeatureDeployments({\n docsDir,\n featureDir,\n featureId,\n // A function rather than the context itself, for the reason the use-case\n // overlay states: one memoised read does not justify an edge from\n // `core/deployment/` to `fleet-context`.\n ...(context === undefined ? {} : { load: (path: string) => context.loadLikeC4(path) }),\n });\n if (topology.kind === \"unreadable\") {\n issues.push({\n severity: \"error\",\n code: \"deployment.doc-invalid\",\n subject: featureId,\n // The opening sentence does not say whose file is at fault, on the\n // `usecase.flow-invalid` message's reasoning: the corpus is the feature's\n // `deployment/` PLUS the living `architecture/` documents it extends, so\n // the failing path can be a living one — a landscape that no longer\n // parses, a topology somebody else wrote. Every message carries its own\n // path, so a reader can place it.\n message:\n `this feature's deployment document(s) could not be read against the map its own merge would leave behind, ` +\n `so the archive would land an architecture/ nothing has checked. The corpus is the feature's deployment/ AND ` +\n `the living architecture/ documents it extends, so the fault may be in either — each message names its file. ` +\n `${topology.errors.length} problem(s): ${topology.errors.join(\"; \")}`,\n });\n }\n\n // --- C4 delta ---\n let elements: Elem[] = [];\n let taggedEls: Elem[] = [];\n let taggedRels: Rel[] = [];\n const deltaPath = featurePaths(featureDir).delta;\n if (existsSync(deltaPath)) {\n const res = preloadedDelta ?? (context === undefined ? await loadFile(deltaPath) : await context.loadLikeC4(deltaPath));\n if (res.errors.length > 0) {\n // An unreadable architecture axis can prove nothing — it must never count as coherent.\n issues.push({\n severity: \"error\",\n code: \"delta.invalid\",\n message: `delta.likec4 has ${res.errors.length} parse error(s) — architecture axis unreadable (run \\`loam validate --feature ${featureId}\\`)`,\n });\n } else {\n elements = res.elements;\n taggedEls = res.elements.filter((e) => e.tags.includes(featureId));\n taggedRels = res.relationships.filter((r) => r.tags.includes(featureId));\n // Every rule below filters by the feature tag, so a delta whose author\n // forgot the tags entirely passes every check and archives while merging\n // nothing. Whole-file only: once ANYTHING is tagged, deciding that an\n // untagged edge \"looks intended\" would be guessing.\n if (\n (res.elements.length > 0 || res.relationships.length > 0) &&\n taggedEls.length === 0 &&\n taggedRels.length === 0\n ) {\n issues.push({\n severity: \"error\",\n code: \"delta.nothing-tagged\",\n message: `delta.likec4 declares elements/relationships but none are tagged #${featureId}; loam cannot see untagged changes`,\n });\n }\n }\n }\n // --- per-service specs (requirement operations) + openapi deltas ---\n const svcNames = await featureSpecServices(featureDir, context);\n\n // Every axis below joins on the service id, so endpoints resolve through the\n // element's `metadata { service }` binding — never through what the box is\n // called. The enumerated fleet — `services/` plus this feature's own\n // `specs/` directories, the same union `enumeratedTarget` probes below —\n // rides into the resolver so a delta that models CONTAINERS joins correctly:\n // without it, an edge into `payment.api` resolves to a service called \"api\"\n // that has never existed, and every check below grades the edge against an\n // absent service instead of the one that owns the container. An unenumerable\n // services/ falls back to the feature's own names — every living probe would\n // have found nothing there anyway.\n const fleetIds = await enumeratedServiceIds(docsDir, context);\n const svcOf = serviceResolver(elements, new Set<string>([...fleetIds, ...svcNames]));\n\n // Which elements the landscape merge would SPLICE: the tagged ones and\n // everything nested inside their blocks. Defined here because two checks\n // share it — the scaffold gate just below, and the binding-grammar check\n // near the end of this function — and the merge carries a tagged element's\n // authored block over byte for byte, children included, so a scope narrower\n // than the splice lets a nested child's text ride through unread.\n const taggedIds = taggedEls.map((el) => el.id);\n const ridesWithTag = (el: Elem): boolean =>\n el.tags.includes(featureId) || taggedIds.some((id) => el.id.startsWith(`${id}.`));\n\n // The scaffold gate: placeholder text and an unwritten intent are legal\n // documents whose merge would publish content nobody authored — the exact\n // template strings `loam new` wrote (authoring/scaffold.ts owns the list).\n issues.push(\n ...(await authoringIssues({ featureDir, featureId, splicedEls: elements.filter(ridesWithTag), svcNames, context })),\n );\n const {\n reqOps, removingOps, featureApiOps, unreadableApis,\n } = await declaredByService(scope, svcNames, issues, context);\n const {\n governedByLivingSpec, edgeConsumers, requirementConsumers, definedElsewhere,\n deprecatedInLiving, undeprecatedByFeature,\n } = coherenceLookups(scope, context);\n\n for (const [svc, retiring] of removingOps) {\n for (const op of retiring) {\n const consumers = [...(await edgeConsumers(svc, op)), ...(await requirementConsumers(svc, op))];\n if (consumers.length === 0) continue;\n issues.push({\n severity: \"error\",\n code: \"openapi.remove-op-consumed\",\n subject: svc,\n message: `${svc}: this feature retires '${op}', but the living fleet still consumes it — ${consumers.join(\"; \")}. Retire the consumer in the same feature (drop the edge from architecture/landscape.likec4, or the requirement that names it), or archive with --approve to break it deliberately.`,\n });\n }\n }\n\n // E1: Spec -> API — every operation a requirement governs must exist in that service's OpenAPI.\n for (const [svc, ops] of reqOps) {\n // The union below reads the feature's own contract; unreadable means the\n // op may well be defined in the file nobody could open, and `op-undefined`\n // would point the author at the requirement when the truth is the YAML.\n // `openapi.invalid` (declared.ts) already gates; one breach, one finding.\n if (unreadableApis.has(svc)) continue;\n const available = await serviceOperationIds(docsDir, svc, featureDir, context);\n for (const op of ops) {\n if (available.includes(op)) continue;\n const other = await definedElsewhere(svc, op);\n if (other !== undefined) {\n issues.push({ severity: \"warn\", code: \"spec-api.op-pending\", message: `requirement in ${svc} governs '${op}', defined by in-flight ${other} — archive it first` });\n continue;\n }\n issues.push({ severity: \"error\", code: \"spec-api.op-undefined\", message: `requirement in ${svc} governs '${op}', not defined in ${svc}'s OpenAPI` });\n }\n }\n\n // The declared→enumerated bridge for edge TARGETS. `svcOf` answers with\n // whatever the document wrote — `metadata { service '../../x' }` parses in\n // LikeC4 without one error — and every living lookup below joins its answer\n // into `services/<target>/` or `specs/<target>/`. So a target resolves\n // through the enumerations first (the fleet's `services/` plus this\n // feature's own `specs/`, where a service it introduces lives), and a name\n // neither knows skips the lookups — no ops, not governed, not deprecated —\n // grading exactly as an absent service, spelled with the declared name.\n const enumeratedTarget = enumeratedServiceIndex(docsDir, svcNames, context);\n\n // E2 / W1 / W4: C4 edges vs API + requirements.\n for (const r of taggedRels) {\n if (r.op === undefined) {\n if ((r.title ?? \"\").toLowerCase().startsWith(\"call\")) {\n issues.push({ severity: \"warn\", code: \"c4.op-link-missing\", message: `edge ${svcOf(r.source)} → ${svcOf(r.target)} (\"${r.title}\") has no operation link (metadata { op })` });\n }\n continue;\n }\n const target = svcOf(r.target);\n const pathable = await enumeratedTarget(target);\n // Same suspension as E1, but only for the verdicts that READ a contract:\n // does the op exist, is it being removed, is it deprecated (whose\n // un-deprecation escape reads the feature contract too). Each of those\n // would be an opinion about a file nobody could open. The governance\n // question below is deliberately NOT suspended — it joins the edge against\n // requirement documents alone, so the broken YAML could never change its\n // answer, and silencing it deferred a real warning for no reason.\n const contractUnreadable = pathable !== undefined && unreadableApis.has(pathable);\n const available =\n pathable === undefined || contractUnreadable\n ? []\n : await serviceOperationIds(docsDir, pathable, featureDir, context);\n if (contractUnreadable) {\n // openapi.invalid (declared.ts) already gates; one breach, one finding.\n } else if (pathable !== undefined && removingOps.get(pathable)?.has(r.op) === true) {\n issues.push({ severity: \"error\", code: \"c4-api.op-removing\", message: `${svcOf(r.source)} builds new consumption on '${r.op}', which this feature removes from ${target}` });\n } else if (!available.includes(r.op)) {\n const other = await definedElsewhere(target, r.op);\n if (other !== undefined) {\n issues.push({ severity: \"warn\", code: \"c4-api.op-pending\", message: `${svcOf(r.source)} calls '${r.op}' on ${target}, defined by in-flight ${other} — archive it first` });\n } else {\n issues.push({ severity: \"error\", code: \"c4-api.op-undefined\", message: `${svcOf(r.source)} calls '${r.op}' on ${target}, but ${target}'s OpenAPI does not define it (contract broken)` });\n }\n }\n // Governed by THIS target's requirements, not by anybody's. An operationId\n // is unique only inside one contract, so the fleet-wide set this used to\n // ask meant a `getStatus` governed in service A silenced the question for\n // service B's entirely unrelated `getStatus` — the warning went quiet for\n // the edge that needed it, and only in repos where some other service\n // happened to reuse the name. The living half on the same line has always\n // joined per service (`governedByLivingSpec(target, …)`); this is the delta\n // half asking it the same way.\n if (pathable === undefined || (!(reqOps.get(pathable) ?? []).includes(r.op) && !(await governedByLivingSpec(pathable, r.op)))) {\n issues.push({ severity: \"warn\", code: \"c4.op-ungoverned\", message: `'${r.op}' is called by ${svcOf(r.source)} but no requirement governs it` });\n }\n // Lifecycle: this NEW tagged edge builds consumption on an operation the\n // living provider contract already marks deprecated. Advisory, never an\n // archive gate — the edge is legal and the contract holds — but new\n // consumption of a dying op deserves an eye before it ships. Quiet when\n // the feature's own openapi delta drops the flag: that state is the fix\n // in progress, not new consumption of a dying op.\n if (!contractUnreadable && pathable !== undefined && (await deprecatedInLiving(pathable, r.op)) && !(await undeprecatedByFeature(pathable, r.op))) {\n issues.push({ severity: \"warn\", code: \"c4-api.op-deprecated\", message: `${svcOf(r.source)} builds new consumption on '${r.op}', which ${target}'s living OpenAPI marks deprecated — prefer the replacement operation` });\n }\n }\n\n // W2: API -> C4 — every operation the feature adds should be consumed by some edge.\n const consumed = new Set(taggedRels.map((r) => r.op).filter((o): o is string => o !== undefined));\n for (const op of featureApiOps) {\n if (!consumed.has(op)) {\n issues.push({ severity: \"warn\", code: \"api.op-unconsumed\", message: `operation '${op}' is added but no architecture edge consumes it (provider-only or unmodeled)` });\n }\n }\n\n // W3: a new service should carry a requirement delta.\n for (const e of taggedEls) {\n const svc: string = elementService(e);\n if (e.kind === \"softwareSystem\" && !svcNames.some((n) => n === svc)) {\n issues.push({ severity: \"warn\", code: \"service.no-requirement-delta\", message: `new service ${svc} has no requirement delta under specs/` });\n }\n }\n\n // An explicit `metadata { service '<id>' }` binding, held to the same grammar\n // every `--service` flag is — on the tagged elements AND everything nested\n // inside their blocks. The scope is the splice's, not the tag's: the\n // landscape merge carries a tagged element's authored block over byte for\n // byte, children included (landscape-merge.ts's rides() exists exactly so a\n // child travels inside its parent's text), so an untagged container's\n // binding reaches the living map as surely as its tagged parent's — and\n // checking only the tagged elements themselves let it ride through unread.\n // The binding is the one name the archive TRUSTS: the merge splices it into\n // the living map verbatim, and the new-service scan probes\n // `services/<binding>/` with it — where `metadata { service '../outside-svc' }`,\n // which LikeC4 parses without a murmur, collapses the probe right out of\n // services/, and the spliced map fails the very next `validate --all`\n // (`landscape.binding-unknown`). Explicit bindings only, on purpose: a prose\n // title with no binding is legal C4, and a title becomes a path only through\n // `specs/<svc>/`, whose own grammar check (`delta.service-id-invalid`)\n // guards that route. `ridesWithTag` itself is defined up beside the scaffold\n // gate, which shares the splice's scope for the same reason.\n for (const e of elements.filter(ridesWithTag)) {\n if (e.service === undefined) continue;\n const problem = serviceIdProblem(e.service, \"metadata { service } binding\");\n if (problem === null) continue;\n issues.push({\n severity: \"error\",\n code: \"c4.service-binding-invalid\",\n subject: e.service,\n message:\n `'${e.title}' (${e.id}) — ${problem} ` +\n `\\`loam archive\\` would splice '${e.service}' into the living landscape.likec4 exactly as written, ` +\n `and probe services/${e.service}/ with it. Bind the element to the services/<id>/ directory it means.`,\n });\n }\n\n // The event axis — the same three-way agreement the operation checks above\n // grade, joined on the message name instead of the operationId: the\n // feature's asyncapi deltas (pins, markers, justification), the tagged\n // edges' publishes/consumes metadata, and the requirement deltas'\n // Publishes:/Consumes: lines (./events/events.ts owns the walk).\n issues.push(...(await eventCoherence({ scope, svcNames, taggedRels, svcOf, context })));\n\n return issues;\n}\n"]}
1
+ {"version":3,"file":"coherence.js","sourceRoot":"","sources":["../../../src/core/coherence/coherence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAuC,MAAM,iBAAiB,CAAC;AAChF,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,eAAe,EAAE,MAAM,wCAAwC,CAAC;AACzE,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0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AK,EAAE,QAAQ,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;IAExF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { loadFile, type Elem, type LoadedDoc, type Rel } from \"../c4/likec4.js\";\nimport { elementService, serviceResolver } from \"../c4/resolve/service.js\";\nimport { extendingModels } from \"../c4/service-model/fleet/extending.js\";\nimport { serviceIdProblem } from \"../kernel/ids/service.js\";\nimport { deltaShapeIssues } from \"../delta/delta.js\";\nimport type { Issue } from \"../vocabulary/issue.js\";\nimport { featurePaths } from \"../repo/paths.js\";\nimport { featureSpecServices } from \"../repo/repo.js\";\nimport { enumeratedServiceIds, enumeratedServiceIndex } from \"../repo/service-target.js\";\nimport { serviceOperationIds } from \"../openapi/doc.js\";\nimport type { FleetContext } from \"../fleet-context.js\";\nimport { declaredByService, type DeltaScope } from \"./declared.js\";\nimport { coherenceLookups } from \"./lookups.js\";\nimport { eventCoherence } from \"./events/events.js\";\nimport { authoringIssues } from \"./authoring/scaffold.js\";\nimport { glossaryDeltaIssues } from \"../glossary/delta.js\";\nimport { flowDeltaIssues } from \"../usecases/delta/flows.js\";\nimport { deploymentDeltaIssues, readFeatureDeployments } from \"../deployment/delta.js\";\nimport type { DocsDir, FeatureDir } from \"../kernel/ids/dirs.js\";\n\n\n/**\n * Cross-axis consistency for a feature: do C4 (architecture), requirements (behaviour),\n * and OpenAPI (contract) agree? Errors are hard (would corrupt the living docs on archive);\n * warnings surface softer misalignments.\n *\n * `preloadedDelta` is the feature's already-parsed delta.likec4, when the caller\n * has it — loading a LikeC4 document spins up a fresh Langium workspace, the\n * dominant per-feature cost, and validate/archive have both parsed the same file\n * moments earlier. Standalone calls omit it and nothing changes: the file is\n * loaded here, exactly as before.\n */\n\n/** How a caller names the feature being graded, and what it already has in hand. */\nexport interface CoherenceRequest {\n docsDir: DocsDir;\n featureDir: FeatureDir;\n featureId: string;\n /** The delta LikeC4 document, when the caller already parsed it. */\n preloadedDelta?: LoadedDoc;\n context?: FleetContext;\n}\n\nexport async function featureCoherence(request: CoherenceRequest): Promise<Issue[]> {\n const { docsDir, featureDir, featureId, preloadedDelta, context } = request;\n const scope: DeltaScope = { docsDir, featureDir, featureId };\n // Delta shape first: a diff that does not apply to the living spec explains\n // everything downstream, and it is the one breach that is silent without a check.\n const issues: Issue[] = await deltaShapeIssues(docsDir, featureDir, featureId, context);\n\n // The vocabulary axis, and it is asked first because it is cheap and\n // independent: one `existsSync` for a feature with no glossary/, and nothing\n // downstream reads its answer. A term this feature introduces that the living\n // glossary already defines is the one thing that can go wrong on a create-only\n // merge, and it must be caught before the copy, not after.\n issues.push(...(await glossaryDeltaIssues(docsDir, featureDir)));\n\n // The use-case axis, and it is asked here for the vocabulary axis's reasons\n // exactly: one walk over a directory that is usually absent, nothing\n // downstream reads its answer, and a create-only merge has one thing that can\n // go wrong. A flow this feature introduces that the living `architecture/`\n // already holds must be caught before the copy, not after it has replaced an\n // authored hop sequence.\n issues.push(...(await flowDeltaIssues(docsDir, featureDir)));\n issues.push(...(await deploymentDeltaIssues(docsDir, featureDir)));\n\n // And the topology's second question, which the collision check above cannot\n // ask: does the document READ against the map this feature's own merge would\n // leave behind. It matters more literally here than one axis over — a feature\n // that stands a service up in a new cluster declares that service in its\n // `delta.likec4` and instances it in the topology, so the element the document\n // names exists only post-merge — and without it the archive copies an\n // unreadable document into `architecture/` for the next reader's\n // `loam validate --all` to fail on, against a file they did not write.\n const topology = await readFeatureDeployments({\n docsDir,\n featureDir,\n featureId,\n // A function rather than the context itself, for the reason the use-case\n // overlay states: one memoised read does not justify an edge from\n // `core/deployment/` to `fleet-context`.\n ...(context === undefined ? {} : { load: (path: string) => context.loadLikeC4(path) }),\n // The fleet's extending models, so the preview is the map the archive would\n // really leave: a nested addition is routed into the service's own model,\n // never onto the map. Read here for the same reason `load` is passed here —\n // this module holds the context and `core/deployment/` does not — and as a\n // thunk, so a feature with no `deployment/` directory pays nothing for it.\n models: () => extendingModels(docsDir, context),\n });\n if (topology.kind === \"unreadable\") {\n issues.push({\n severity: \"error\",\n code: \"deployment.doc-invalid\",\n subject: featureId,\n // The opening sentence does not say whose file is at fault, on the\n // `usecase.flow-invalid` message's reasoning: the corpus is the feature's\n // `deployment/` PLUS the living `architecture/` documents it extends, so\n // the failing path can be a living one — a landscape that no longer\n // parses, a topology somebody else wrote. Every message carries its own\n // path, so a reader can place it.\n message:\n `this feature's deployment document(s) could not be read against the map its own merge would leave behind, ` +\n `so the archive would land an architecture/ nothing has checked. The corpus is the feature's deployment/ AND ` +\n `the living architecture/ documents it extends, so the fault may be in either — each message names its file. ` +\n `${topology.errors.length} problem(s): ${topology.errors.join(\"; \")}`,\n });\n }\n\n // --- C4 delta ---\n let elements: Elem[] = [];\n let taggedEls: Elem[] = [];\n let taggedRels: Rel[] = [];\n const deltaPath = featurePaths(featureDir).delta;\n if (existsSync(deltaPath)) {\n const res = preloadedDelta ?? (context === undefined ? await loadFile(deltaPath) : await context.loadLikeC4(deltaPath));\n if (res.errors.length > 0) {\n // An unreadable architecture axis can prove nothing — it must never count as coherent.\n issues.push({\n severity: \"error\",\n code: \"delta.invalid\",\n message: `delta.likec4 has ${res.errors.length} parse error(s) — architecture axis unreadable (run \\`loam validate --feature ${featureId}\\`)`,\n });\n } else {\n elements = res.elements;\n taggedEls = res.elements.filter((e) => e.tags.includes(featureId));\n taggedRels = res.relationships.filter((r) => r.tags.includes(featureId));\n // Every rule below filters by the feature tag, so a delta whose author\n // forgot the tags entirely passes every check and archives while merging\n // nothing. Whole-file only: once ANYTHING is tagged, deciding that an\n // untagged edge \"looks intended\" would be guessing.\n if (\n (res.elements.length > 0 || res.relationships.length > 0) &&\n taggedEls.length === 0 &&\n taggedRels.length === 0\n ) {\n issues.push({\n severity: \"error\",\n code: \"delta.nothing-tagged\",\n message: `delta.likec4 declares elements/relationships but none are tagged #${featureId}; loam cannot see untagged changes`,\n });\n }\n }\n }\n // --- per-service specs (requirement operations) + openapi deltas ---\n const svcNames = await featureSpecServices(featureDir, context);\n\n // Every axis below joins on the service id, so endpoints resolve through the\n // element's `metadata { service }` binding — never through what the box is\n // called. The enumerated fleet — `services/` plus this feature's own\n // `specs/` directories, the same union `enumeratedTarget` probes below —\n // rides into the resolver so a delta that models CONTAINERS joins correctly:\n // without it, an edge into `payment.api` resolves to a service called \"api\"\n // that has never existed, and every check below grades the edge against an\n // absent service instead of the one that owns the container. An unenumerable\n // services/ falls back to the feature's own names — every living probe would\n // have found nothing there anyway.\n const fleetIds = await enumeratedServiceIds(docsDir, context);\n const svcOf = serviceResolver(elements, new Set<string>([...fleetIds, ...svcNames]));\n\n // Which elements the landscape merge would SPLICE: the tagged ones and\n // everything nested inside their blocks. Defined here because two checks\n // share it — the scaffold gate just below, and the binding-grammar check\n // near the end of this function — and the merge carries a tagged element's\n // authored block over byte for byte, children included, so a scope narrower\n // than the splice lets a nested child's text ride through unread.\n const taggedIds = taggedEls.map((el) => el.id);\n const ridesWithTag = (el: Elem): boolean =>\n el.tags.includes(featureId) || taggedIds.some((id) => el.id.startsWith(`${id}.`));\n\n // The scaffold gate: placeholder text and an unwritten intent are legal\n // documents whose merge would publish content nobody authored — the exact\n // template strings `loam new` wrote (authoring/scaffold.ts owns the list).\n issues.push(\n ...(await authoringIssues({ featureDir, featureId, splicedEls: elements.filter(ridesWithTag), svcNames, context })),\n );\n const {\n reqOps, removingOps, featureApiOps, unreadableApis,\n } = await declaredByService(scope, svcNames, issues, context);\n const {\n governedByLivingSpec, edgeConsumers, requirementConsumers, definedElsewhere,\n deprecatedInLiving, undeprecatedByFeature,\n } = coherenceLookups(scope, context);\n\n for (const [svc, retiring] of removingOps) {\n for (const op of retiring) {\n const consumers = [...(await edgeConsumers(svc, op)), ...(await requirementConsumers(svc, op))];\n if (consumers.length === 0) continue;\n issues.push({\n severity: \"error\",\n code: \"openapi.remove-op-consumed\",\n subject: svc,\n message: `${svc}: this feature retires '${op}', but the living fleet still consumes it — ${consumers.join(\"; \")}. Retire the consumer in the same feature (drop the edge from architecture/landscape.likec4, or the requirement that names it), or archive with --approve to break it deliberately.`,\n });\n }\n }\n\n // E1: Spec -> API — every operation a requirement governs must exist in that service's OpenAPI.\n for (const [svc, ops] of reqOps) {\n // The union below reads the feature's own contract; unreadable means the\n // op may well be defined in the file nobody could open, and `op-undefined`\n // would point the author at the requirement when the truth is the YAML.\n // `openapi.invalid` (declared.ts) already gates; one breach, one finding.\n if (unreadableApis.has(svc)) continue;\n const available = await serviceOperationIds(docsDir, svc, featureDir, context);\n for (const op of ops) {\n if (available.includes(op)) continue;\n const other = await definedElsewhere(svc, op);\n if (other !== undefined) {\n issues.push({ severity: \"warn\", code: \"spec-api.op-pending\", message: `requirement in ${svc} governs '${op}', defined by in-flight ${other} — archive it first` });\n continue;\n }\n issues.push({ severity: \"error\", code: \"spec-api.op-undefined\", message: `requirement in ${svc} governs '${op}', not defined in ${svc}'s OpenAPI` });\n }\n }\n\n // The declared→enumerated bridge for edge TARGETS. `svcOf` answers with\n // whatever the document wrote — `metadata { service '../../x' }` parses in\n // LikeC4 without one error — and every living lookup below joins its answer\n // into `services/<target>/` or `specs/<target>/`. So a target resolves\n // through the enumerations first (the fleet's `services/` plus this\n // feature's own `specs/`, where a service it introduces lives), and a name\n // neither knows skips the lookups — no ops, not governed, not deprecated —\n // grading exactly as an absent service, spelled with the declared name.\n const enumeratedTarget = enumeratedServiceIndex(docsDir, svcNames, context);\n\n // E2 / W1 / W4: C4 edges vs API + requirements.\n for (const r of taggedRels) {\n if (r.op === undefined) {\n if ((r.title ?? \"\").toLowerCase().startsWith(\"call\")) {\n issues.push({ severity: \"warn\", code: \"c4.op-link-missing\", message: `edge ${svcOf(r.source)} → ${svcOf(r.target)} (\"${r.title}\") has no operation link (metadata { op })` });\n }\n continue;\n }\n const target = svcOf(r.target);\n const pathable = await enumeratedTarget(target);\n // Same suspension as E1, but only for the verdicts that READ a contract:\n // does the op exist, is it being removed, is it deprecated (whose\n // un-deprecation escape reads the feature contract too). Each of those\n // would be an opinion about a file nobody could open. The governance\n // question below is deliberately NOT suspended — it joins the edge against\n // requirement documents alone, so the broken YAML could never change its\n // answer, and silencing it deferred a real warning for no reason.\n const contractUnreadable = pathable !== undefined && unreadableApis.has(pathable);\n const available =\n pathable === undefined || contractUnreadable\n ? []\n : await serviceOperationIds(docsDir, pathable, featureDir, context);\n if (contractUnreadable) {\n // openapi.invalid (declared.ts) already gates; one breach, one finding.\n } else if (pathable !== undefined && removingOps.get(pathable)?.has(r.op) === true) {\n issues.push({ severity: \"error\", code: \"c4-api.op-removing\", message: `${svcOf(r.source)} builds new consumption on '${r.op}', which this feature removes from ${target}` });\n } else if (!available.includes(r.op)) {\n const other = await definedElsewhere(target, r.op);\n if (other !== undefined) {\n issues.push({ severity: \"warn\", code: \"c4-api.op-pending\", message: `${svcOf(r.source)} calls '${r.op}' on ${target}, defined by in-flight ${other} — archive it first` });\n } else {\n issues.push({ severity: \"error\", code: \"c4-api.op-undefined\", message: `${svcOf(r.source)} calls '${r.op}' on ${target}, but ${target}'s OpenAPI does not define it (contract broken)` });\n }\n }\n // Governed by THIS target's requirements, not by anybody's. An operationId\n // is unique only inside one contract, so the fleet-wide set this used to\n // ask meant a `getStatus` governed in service A silenced the question for\n // service B's entirely unrelated `getStatus` — the warning went quiet for\n // the edge that needed it, and only in repos where some other service\n // happened to reuse the name. The living half on the same line has always\n // joined per service (`governedByLivingSpec(target, …)`); this is the delta\n // half asking it the same way.\n if (pathable === undefined || (!(reqOps.get(pathable) ?? []).includes(r.op) && !(await governedByLivingSpec(pathable, r.op)))) {\n issues.push({ severity: \"warn\", code: \"c4.op-ungoverned\", message: `'${r.op}' is called by ${svcOf(r.source)} but no requirement governs it` });\n }\n // Lifecycle: this NEW tagged edge builds consumption on an operation the\n // living provider contract already marks deprecated. Advisory, never an\n // archive gate — the edge is legal and the contract holds — but new\n // consumption of a dying op deserves an eye before it ships. Quiet when\n // the feature's own openapi delta drops the flag: that state is the fix\n // in progress, not new consumption of a dying op.\n if (!contractUnreadable && pathable !== undefined && (await deprecatedInLiving(pathable, r.op)) && !(await undeprecatedByFeature(pathable, r.op))) {\n issues.push({ severity: \"warn\", code: \"c4-api.op-deprecated\", message: `${svcOf(r.source)} builds new consumption on '${r.op}', which ${target}'s living OpenAPI marks deprecated — prefer the replacement operation` });\n }\n }\n\n // W2: API -> C4 — every operation the feature adds should be consumed by some edge.\n const consumed = new Set(taggedRels.map((r) => r.op).filter((o): o is string => o !== undefined));\n for (const op of featureApiOps) {\n if (!consumed.has(op)) {\n issues.push({ severity: \"warn\", code: \"api.op-unconsumed\", message: `operation '${op}' is added but no architecture edge consumes it (provider-only or unmodeled)` });\n }\n }\n\n // W3: a new service should carry a requirement delta.\n for (const e of taggedEls) {\n const svc: string = elementService(e);\n if (e.kind === \"softwareSystem\" && !svcNames.some((n) => n === svc)) {\n issues.push({ severity: \"warn\", code: \"service.no-requirement-delta\", message: `new service ${svc} has no requirement delta under specs/` });\n }\n }\n\n // An explicit `metadata { service '<id>' }` binding, held to the same grammar\n // every `--service` flag is — on the tagged elements AND everything nested\n // inside their blocks. The scope is the splice's, not the tag's: the\n // landscape merge carries a tagged element's authored block over byte for\n // byte, children included (landscape-merge.ts's rides() exists exactly so a\n // child travels inside its parent's text), so an untagged container's\n // binding reaches the living map as surely as its tagged parent's — and\n // checking only the tagged elements themselves let it ride through unread.\n // The binding is the one name the archive TRUSTS: the merge splices it into\n // the living map verbatim, and the new-service scan probes\n // `services/<binding>/` with it — where `metadata { service '../outside-svc' }`,\n // which LikeC4 parses without a murmur, collapses the probe right out of\n // services/, and the spliced map fails the very next `validate --all`\n // (`landscape.binding-unknown`). Explicit bindings only, on purpose: a prose\n // title with no binding is legal C4, and a title becomes a path only through\n // `specs/<svc>/`, whose own grammar check (`delta.service-id-invalid`)\n // guards that route. `ridesWithTag` itself is defined up beside the scaffold\n // gate, which shares the splice's scope for the same reason.\n for (const e of elements.filter(ridesWithTag)) {\n if (e.service === undefined) continue;\n const problem = serviceIdProblem(e.service, \"metadata { service } binding\");\n if (problem === null) continue;\n issues.push({\n severity: \"error\",\n code: \"c4.service-binding-invalid\",\n subject: e.service,\n message:\n `'${e.title}' (${e.id}) — ${problem} ` +\n `\\`loam archive\\` would splice '${e.service}' into the living landscape.likec4 exactly as written, ` +\n `and probe services/${e.service}/ with it. Bind the element to the services/<id>/ directory it means.`,\n });\n }\n\n // The event axis — the same three-way agreement the operation checks above\n // grade, joined on the message name instead of the operationId: the\n // feature's asyncapi deltas (pins, markers, justification), the tagged\n // edges' publishes/consumes metadata, and the requirement deltas'\n // Publishes:/Consumes: lines (./events/events.ts owns the walk).\n issues.push(...(await eventCoherence({ scope, svcNames, taggedRels, svcOf, context })));\n\n return issues;\n}\n"]}
@@ -46,6 +46,7 @@ import {} from "../document/spec.js";
46
46
  import { featureSpecPaths, SPEC_AXES } from "../repo/paths.js";
47
47
  import { featureUseCasesDir, livingCapabilityPaths } from "../repo/authored/paths.js";
48
48
  import { readCapabilityVocabulary } from "../capabilities/capabilities.js";
49
+ import { extendingModels } from "../c4/service-model/fleet/extending.js";
49
50
  import { flowCoverage } from "../usecases/delta/claims.js";
50
51
  import { enumeratedServiceIds, locateServicePaths } from "../repo/service-target.js";
51
52
  import { featureSpecServices } from "../repo/repo.js";
@@ -180,6 +181,14 @@ export async function deltaShapeIssues(docsDir, featureDir, featureId, context)
180
181
  // does not justify an edge from `core/usecases/` to `fleet-context`, and
181
182
  // the edge would push that package up a DAG level for nothing.
182
183
  ...(context === undefined ? {} : { load: (path) => context.loadLikeC4(path) }),
184
+ // The fleet's extending models, for the merge preview the overlay
185
+ // grades against — read HERE for `vocabulary`'s reason exactly, and as
186
+ // a thunk so the walk pays for it only when a flow is really there.
187
+ // Without it the preview is the pre-routing map and `usecase.flow-invalid`
188
+ // fails open on the one shape it exists for: a hop into
189
+ // `<service-fqn>.<container>`, which the archive routes into that
190
+ // service's own model (verification 2026-09-04, review F8).
191
+ models: () => extendingModels(docsDir, context),
183
192
  })
184
193
  : { kind: "read", kept: [] };
185
194
  if (kept.kind === "unreadable") {
@@ -1 +1 @@
1
- {"version":3,"file":"delta.js","sourceRoot":"","sources":["../../../src/core/delta/delta.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrC,OAAO,EAAqB,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAoB,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AACtF,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAE3E,OAAO,EAAE,YAAY,EAAqB,MAAM,6BAA6B,CAAC;AAC9E,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AACrF,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AACxE,OAAO,EACL,qBAAqB,EACrB,eAAe,GAGhB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAc,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAoB,MAAM,aAAa,CAAC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAC1E,OAAO,EAAE,WAAW,EAAqC,MAAM,YAAY,CAAC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vD,CAAC,CAAC,MAAM,OAAO,CAAC,gBAAgB,CAAC,UAAU,CAAC,CACjD,CAAC;IACF,OAAO;QACL,IAAI;QACJ,MAAM;QACN,MAAM,EAAE;YACN,GAAG,mBAAmB,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC;YACxC,GAAG,oBAAoB,CAAC,KAAK,EAAE,MAAM,CAAC;YACtC,GAAG,CAAC,MAAM,eAAe,CAAC,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;SACxD;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Does the diff apply to the thing it claims to change?\n *\n * A requirement delta is a diff against a living spec, and nothing used to check\n * that it lands. Every failure mode here is silent today: MODIFIED of a\n * requirement that does not exist is merged as a creation, ADDED of one that\n * does exist REPLACES it (scenarios and all) while the author believes they are\n * adding, and a heading that nearly matches the delta grammar parses as plain\n * prose so archive merges nothing at all and says nothing about it.\n *\n * The last of those has a legal-looking cousin: a requirement under an ordinary\n * prose heading (`## Behavior`, `## Error Handling`) is BASE too, and BASE never\n * merges. Upstream OpenSpec deltas are written that way, so the answer is to name\n * what will be lost rather than to start merging prose sections.\n *\n * These run inside the archive gate, because the merge is where the damage lands.\n *\n * TWO CORPORA, ONE ALGEBRA. A feature's delta documents live in two places —\n * `specs/<svc>/{spec,arch.spec}.md` against the service tree, and\n * `capabilities/<id>/spec.md` against the authored business tree — and every\n * grade about a DOCUMENT and its living counterpart applies to both verbatim,\n * with the capability id in `subject` where a service id would be. That is not\n * a coincidence to exploit but the reason the business corpus was given deltas\n * at all: a capability document is a requirements document, so the diff that\n * changes one has exactly the same ways of not landing. A second implementation\n * would be a second set of answers to `delta.added-duplicate`.\n *\n * The exception is the four CROSS-FEATURE warnings — `delta.added-conflict`,\n * `delta.modified-conflict`, `delta.modified-pending`, `delta.removed-pending`\n * — which ask what OTHER features in flight claim. `./claims.ts` indexes the\n * service corpus only and states why; on the business axis those four are\n * silent, which is a missing warning and never a wrong answer.\n *\n * This module is only the walk: which documents get read, in what order, and how\n * each is handed a `DeltaScope`. The checks themselves are in `./document.ts`\n * (a document against itself) and `./select.ts` (the delta against the living\n * text). Their order is load-bearing and stays here, where it can be read in one\n * screen.\n */\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { relative } from \"node:path\";\nimport { type FleetContext } from \"../fleet-context.js\";\nimport { parseRequirements } from \"../document/parse.js\";\nimport { type Requirement } from \"../document/spec.js\";\nimport { featureSpecPaths, SPEC_AXES } from \"../repo/paths.js\";\nimport { featureUseCasesDir, livingCapabilityPaths } from \"../repo/authored/paths.js\";\nimport { readCapabilityVocabulary } from \"../capabilities/capabilities.js\";\n\nimport { flowCoverage, type FlowPromises } from \"../usecases/delta/claims.js\";\nimport { enumeratedServiceIds, locateServicePaths } from \"../repo/service-target.js\";\nimport { featureSpecServices } from \"../repo/repo.js\";\nimport { capabilityDocIssues } from \"../capabilities/delta/doc.js\";\nimport { featureCapabilityDeltas } from \"../capabilities/delta/tree.js\";\nimport {\n removedRealizedIssues,\n uncoveredIssues,\n type CapabilityDeltaDoc,\n type RealizingDoc,\n} from \"../capabilities/delta/uncovered.js\";\nimport { type Issue } from \"../vocabulary/issue.js\";\nimport { claimLookup, type ClaimLookup } from \"./claims.js\";\nimport { deltaDocumentIssues, livingDocumentIssues } from \"./document.js\";\nimport { indexLiving, type DeltaScope, type LivingIndex } from \"./scope.js\";\nimport { selectionIssues } from \"./select.js\";\nimport type { DocsDir, FeatureDir } from \"../kernel/ids/dirs.js\";\n\n/**\n * The business corpus's ONE axis. A capability document carries the promise and\n * nothing else — there is no `arch.spec.md` beside it, because \"how it is\n * built\" is precisely the altitude a capability requirement may not describe\n * (`capability.requirement-service-scoped` is that rule). It has no `key`\n * because it indexes no `ServicePaths`, which is why `DeltaScope.axis` is the\n * narrower `DeltaAxis` and not `SpecAxis`.\n */\nconst CAPABILITY_AXIS = { file: \"spec.md\" };\n\n/**\n * What every document in one feature's walk shares.\n *\n * A record rather than two more parameters because both values are about the\n * WALK and not about the document being graded — `gradeDelta` would otherwise\n * read as a four-argument function whose last two arguments never vary within\n * a run, which is how the next value gets added as a fifth.\n */\ninterface DeltaReads {\n /** What OTHER features in flight claim — lazy, so the common case never scans. */\n claims: ClaimLookup;\n /** The invocation's read index, when the caller threaded one. */\n context?: FleetContext;\n}\n\nexport async function deltaShapeIssues(\n docsDir: DocsDir,\n featureDir: FeatureDir,\n featureId: string,\n context?: FleetContext,\n): Promise<Issue[]> {\n const issues: Issue[] = [];\n const services = await featureSpecServices(featureDir, context);\n // One `existsSync` for a feature that carries no capability delta, which is\n // every feature in a fleet that has not adopted the business axis.\n const capabilities =\n context === undefined ? await featureCapabilityDeltas(featureDir) : await context.featureCapabilityDeltas(featureDir);\n // The flows this feature brings, and one `existsSync` for a feature that\n // brings none — which is every feature in a fleet that has not adopted the\n // axis. The directory, not the documents: what is needed here is whether to\n // pay for the overlay at all, and the walk that lists them happens once,\n // inside it.\n const hasFlows = existsSync(featureUseCasesDir(featureDir));\n // The early return must ask about EVERY corpus. Asking only about services\n // meant a capability-only feature — a business change with no service touched\n // yet, which is exactly what an analyst writes first — was graded by nothing\n // and archived whatever its delta said; asking only about those two would do\n // the same to a feature whose whole content is a cross-service flow, which is\n // the shape an architect answers an analyst with.\n if (services.length === 0 && capabilities.docs.length === 0 && !hasFlows) return issues;\n\n // What OTHER features in flight claim. Only built when a claim has to be\n // checked — the common case never pays for the scan.\n const reads: DeltaReads = {\n claims: claimLookup(docsDir, featureId, context),\n ...(context === undefined ? {} : { context }),\n };\n\n // The two corpora's parsed requirements, kept as the walk produces them so\n // the `Realizes:` join below can be taken without re-reading a byte. That\n // join is the one question neither corpus can answer alone — which service\n // requirement keeps which business promise — and this is the only place in\n // loam where both sides are already open (`capabilities/delta/uncovered.ts`\n // holds the rules; nothing here decides anything).\n const serviceDeltas: RealizingDoc[] = [];\n const capabilityDeltas: CapabilityDeltaDoc[] = [];\n\n // Both requirement-carrying files per service run the same checks — one code\n // path parameterized by filename, the merge's own factoring. `where` names\n // the arch file in messages so a finding cannot be chased into the wrong\n // document; spec.md keeps its historical spelling.\n for (const service of services) {\n for (const axis of SPEC_AXES) {\n const specPath = featureSpecPaths(featureDir, service)[axis.key];\n if (!existsSync(specPath)) continue;\n const scope: DeltaScope = {\n kind: \"service\",\n subject: service,\n axis,\n featureId,\n docsDir,\n specPath,\n where: axis.key === \"spec\" ? service : `${service} (arch.spec.md)`,\n // How the axis's living document is named in messages — spec.md keeps\n // the historical \"living spec\", the arch axis says which file it means.\n livingDoc: axis.key === \"spec\" ? \"living spec\" : \"living arch.spec.md\",\n };\n const graded = await gradeDelta(scope, (await locateServicePaths(docsDir, service, context))[axis.key], reads);\n issues.push(...graded.issues);\n serviceDeltas.push({ service, file: axis.file, reqs: graded.reqs });\n }\n }\n\n for (const doc of capabilities.docs) {\n const scope: DeltaScope = {\n kind: \"capability\",\n subject: doc.id,\n axis: CAPABILITY_AXIS,\n featureId,\n docsDir,\n specPath: doc.spec,\n // `capability <id>`, not `capabilities/<id>` — the second reads as the\n // LIVING directory, and every message this labels is about the FEATURE's\n // delta of it. Sending an author to edit the wrong one of two files with\n // the same name is the whole reason `where` and `livingDoc` are separate.\n where: `capability ${doc.id}`,\n livingDoc: `living capabilities/${doc.id}/spec.md`,\n };\n // Absent is a real and ordinary answer on this axis: the first feature to\n // mention a capability is what creates its living document, so the whole\n // delta grades against `[]` and every requirement in it is legitimately an\n // addition.\n const graded = await gradeDelta(scope, livingCapabilityPaths(docsDir, doc.id).spec, reads);\n issues.push(...graded.issues);\n // The document's own three rules, on the requirements this delta would\n // MERGE — before the merge, where the author can still fix them. See\n // `capabilities/delta/doc.ts` for why grading only the living copy leaves a\n // hole straight through the altitude rule.\n issues.push(\n ...capabilityDocIssues(graded.reqs, {\n where: relative(docsDir, doc.spec).split(/[\\\\/]/).join(\"/\"),\n subject: doc.id,\n }),\n );\n capabilityDeltas.push({ id: doc.id, reqs: graded.reqs, living: graded.living.all });\n }\n\n // The other carrier of a promise, read once and only when this feature\n // actually brings a flow: the `dynamic view`s under `features/<FEAT>/usecases/`,\n // parsed over the map this feature's own merge would leave behind\n // (`core/usecases/delta/overlay.ts`).\n // A feature with no `usecases/` directory is a REAL empty answer, not an\n // ungraded one: there is no flow, so \"no flow keeps this\" is true and the\n // message may say it.\n const kept: FlowPromises = hasFlows\n ? await flowCoverage({\n docsDir,\n featureDir,\n featureId,\n capabilities: capabilityDeltas,\n // Read HERE, through the invocation's index, because this module holds\n // it and `core/usecases/` does not — every other read in this walk does\n // the same, and `core/repo/service-target.ts` prices a fleet\n // enumeration per call at ~13 ms on a 120-service fleet.\n vocabulary: context === undefined ? await readCapabilityVocabulary(docsDir) : await context.capabilities(docsDir),\n known: new Set(await enumeratedServiceIds(docsDir, context)),\n // A function rather than the context itself: one memoised LikeC4 read\n // does not justify an edge from `core/usecases/` to `fleet-context`, and\n // the edge would push that package up a DAG level for nothing.\n ...(context === undefined ? {} : { load: (path: string) => context.loadLikeC4(path) }),\n })\n : { kind: \"read\", kept: [] };\n if (kept.kind === \"unreadable\") {\n // ERROR, and the archive gate's own `NEVER_OVERRIDABLE` keeps `--approve`\n // off it. This is the refusal that stops a flow being copied into\n // `architecture/` and the NEXT reader's `loam validate --all` carrying the\n // failure — including the case the overlay exists for, a hop naming an\n // element the merge does not land. Mechanical, so it is not loam's judgement\n // to override.\n issues.push({\n severity: \"error\",\n code: \"usecase.flow-invalid\",\n subject: featureId,\n // The opening sentence does NOT say whose file is at fault, and that is\n // deliberate: the corpus this reads is the feature's flows PLUS the living\n // `architecture/` documents they are drawn over, so the failing path can\n // be a living one — a landscape that no longer parses, a use case somebody\n // else wrote. Every message carries its own path, so a reader can place\n // it; an opening line that blamed `usecases/` would send them to the wrong\n // file first.\n message:\n `this feature's flows could not be graded against the map its own merge would leave behind, so the archive ` +\n `would land an architecture/ nothing has checked. The corpus is the feature's usecases/ AND the living ` +\n `architecture/ documents they are drawn over, so the fault may be in either — each message names its file. ` +\n `${kept.errors.length} problem(s): ${kept.errors.join(\"; \")}`,\n });\n }\n\n // The `Realizes:` join, both directions, over documents this walk has already\n // parsed. Skipped entirely when the feature carries no capability delta,\n // which is every feature in a fleet that has not adopted the business axis —\n // and the removal half asks for the living corpus only when something is\n // actually retired, so even an adopting fleet pays the fleet-wide read on the\n // features that earn it.\n if (capabilityDeltas.length > 0) {\n // The three arms travel as three, and flattening two of them to `[]` is\n // the one thing this must not do: `capability.uncovered` says in words that\n // no flow keeps the promise, so handing it an empty list for a corpus loam\n // could not read or could not resolve makes it assert a negative it never\n // evaluated — and gate on it. `claims.ts`'s header states the rule; this is\n // where a caller could break it.\n issues.push(\n ...uncoveredIssues(\n capabilityDeltas,\n serviceDeltas,\n kept.kind === \"read\"\n ? { graded: true, kept: kept.kept }\n : { graded: false, why: kept.kind === \"ungraded\" ? kept.why : kept.errors.join(\"; \") },\n ),\n );\n issues.push(\n ...(await removedRealizedIssues({\n capabilities: capabilityDeltas,\n deltas: serviceDeltas,\n living: () => livingRealizers(docsDir, context),\n })),\n );\n }\n\n return issues;\n}\n\n/**\n * Every LIVING service requirements document in the fleet, for the one question\n * that has to ask about services this feature never mentions: does anything out\n * there still realize a capability requirement this feature retires?\n *\n * The same shape and the same cost `openapi.remove-op-consumed` pays through\n * `coherence/lookups.ts` one axis over, and for the same reason — the merge\n * deletes the promise while the `Realizes:` line stays, so the very next\n * `validate --all` reports a breach on a repository whose author was never in\n * this feature. Called behind a thunk (`removedRealizedIssues` invokes it only\n * when something is retired), so a feature that removes nothing never runs it.\n */\nasync function livingRealizers(docsDir: DocsDir, context?: FleetContext): Promise<RealizingDoc[]> {\n const out: RealizingDoc[] = [];\n for (const service of await enumeratedServiceIds(docsDir, context)) {\n const paths = await locateServicePaths(docsDir, service, context);\n for (const axis of SPEC_AXES) {\n const path = paths[axis.key];\n if (!existsSync(path)) continue;\n const reqs =\n context === undefined ? parseRequirements(await readFile(path, \"utf8\")) : await context.readRequirements(path);\n out.push({ service, file: axis.file, reqs });\n }\n }\n return out;\n}\n\n/**\n * One delta document against one living document: the three passes, in the\n * order that makes their messages readable.\n *\n * The order is load-bearing. `deltaDocumentIssues` settles what the delta says\n * about itself, `livingDocumentIssues` settles whether the living text can be\n * selected in at all, and only then does `selectionIssues` compare them — a pin\n * the document pass already refused must not also be reported stale, which\n * would send its author to `loam rebase` for a problem rebase does not fix.\n *\n * The parsed delta requirements come back with the issues because the capability\n * corpus grades them a second way (`capabilityDocIssues`) and re-reading the\n * file to do it would be a second parse of bytes already in hand — and, without\n * a context, a second chance for the two passes to disagree about the document.\n * The LIVING index rides back for the same reason once more: the removal\n * direction of the `Realizes:` join has to resolve a REMOVED spelled by heading\n * into the id it retires, and that id is a fact about the living document.\n */\nasync function gradeDelta(\n scope: DeltaScope,\n livingPath: string,\n reads: DeltaReads,\n): Promise<{ issues: Issue[]; reqs: Requirement[]; living: LivingIndex }> {\n const { claims, context } = reads;\n const raw = context === undefined ? await readFile(scope.specPath, \"utf8\") : await context.readText(scope.specPath);\n const reqs = context === undefined ? parseRequirements(raw) : await context.readRequirements(scope.specPath);\n const living = indexLiving(\n !existsSync(livingPath)\n ? []\n : context === undefined\n ? parseRequirements(await readFile(livingPath, \"utf8\"))\n : await context.readRequirements(livingPath),\n );\n return {\n reqs,\n living,\n issues: [\n ...deltaDocumentIssues(scope, raw, reqs),\n ...livingDocumentIssues(scope, living),\n ...(await selectionIssues(scope, reqs, living, claims)),\n ],\n };\n}\n"]}
1
+ {"version":3,"file":"delta.js","sourceRoot":"","sources":["../../../src/core/delta/delta.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrC,OAAO,EAAqB,MAAM,qBAAqB,CA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IAAI,CAAC;YACxC,GAAG,oBAAoB,CAAC,KAAK,EAAE,MAAM,CAAC;YACtC,GAAG,CAAC,MAAM,eAAe,CAAC,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;SACxD;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Does the diff apply to the thing it claims to change?\n *\n * A requirement delta is a diff against a living spec, and nothing used to check\n * that it lands. Every failure mode here is silent today: MODIFIED of a\n * requirement that does not exist is merged as a creation, ADDED of one that\n * does exist REPLACES it (scenarios and all) while the author believes they are\n * adding, and a heading that nearly matches the delta grammar parses as plain\n * prose so archive merges nothing at all and says nothing about it.\n *\n * The last of those has a legal-looking cousin: a requirement under an ordinary\n * prose heading (`## Behavior`, `## Error Handling`) is BASE too, and BASE never\n * merges. Upstream OpenSpec deltas are written that way, so the answer is to name\n * what will be lost rather than to start merging prose sections.\n *\n * These run inside the archive gate, because the merge is where the damage lands.\n *\n * TWO CORPORA, ONE ALGEBRA. A feature's delta documents live in two places —\n * `specs/<svc>/{spec,arch.spec}.md` against the service tree, and\n * `capabilities/<id>/spec.md` against the authored business tree — and every\n * grade about a DOCUMENT and its living counterpart applies to both verbatim,\n * with the capability id in `subject` where a service id would be. That is not\n * a coincidence to exploit but the reason the business corpus was given deltas\n * at all: a capability document is a requirements document, so the diff that\n * changes one has exactly the same ways of not landing. A second implementation\n * would be a second set of answers to `delta.added-duplicate`.\n *\n * The exception is the four CROSS-FEATURE warnings — `delta.added-conflict`,\n * `delta.modified-conflict`, `delta.modified-pending`, `delta.removed-pending`\n * — which ask what OTHER features in flight claim. `./claims.ts` indexes the\n * service corpus only and states why; on the business axis those four are\n * silent, which is a missing warning and never a wrong answer.\n *\n * This module is only the walk: which documents get read, in what order, and how\n * each is handed a `DeltaScope`. The checks themselves are in `./document.ts`\n * (a document against itself) and `./select.ts` (the delta against the living\n * text). Their order is load-bearing and stays here, where it can be read in one\n * screen.\n */\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { relative } from \"node:path\";\nimport { type FleetContext } from \"../fleet-context.js\";\nimport { parseRequirements } from \"../document/parse.js\";\nimport { type Requirement } from \"../document/spec.js\";\nimport { featureSpecPaths, SPEC_AXES } from \"../repo/paths.js\";\nimport { featureUseCasesDir, livingCapabilityPaths } from \"../repo/authored/paths.js\";\nimport { readCapabilityVocabulary } from \"../capabilities/capabilities.js\";\nimport { extendingModels } from \"../c4/service-model/fleet/extending.js\";\n\nimport { flowCoverage, type FlowPromises } from \"../usecases/delta/claims.js\";\nimport { enumeratedServiceIds, locateServicePaths } from \"../repo/service-target.js\";\nimport { featureSpecServices } from \"../repo/repo.js\";\nimport { capabilityDocIssues } from \"../capabilities/delta/doc.js\";\nimport { featureCapabilityDeltas } from \"../capabilities/delta/tree.js\";\nimport {\n removedRealizedIssues,\n uncoveredIssues,\n type CapabilityDeltaDoc,\n type RealizingDoc,\n} from \"../capabilities/delta/uncovered.js\";\nimport { type Issue } from \"../vocabulary/issue.js\";\nimport { claimLookup, type ClaimLookup } from \"./claims.js\";\nimport { deltaDocumentIssues, livingDocumentIssues } from \"./document.js\";\nimport { indexLiving, type DeltaScope, type LivingIndex } from \"./scope.js\";\nimport { selectionIssues } from \"./select.js\";\nimport type { DocsDir, FeatureDir } from \"../kernel/ids/dirs.js\";\n\n/**\n * The business corpus's ONE axis. A capability document carries the promise and\n * nothing else — there is no `arch.spec.md` beside it, because \"how it is\n * built\" is precisely the altitude a capability requirement may not describe\n * (`capability.requirement-service-scoped` is that rule). It has no `key`\n * because it indexes no `ServicePaths`, which is why `DeltaScope.axis` is the\n * narrower `DeltaAxis` and not `SpecAxis`.\n */\nconst CAPABILITY_AXIS = { file: \"spec.md\" };\n\n/**\n * What every document in one feature's walk shares.\n *\n * A record rather than two more parameters because both values are about the\n * WALK and not about the document being graded — `gradeDelta` would otherwise\n * read as a four-argument function whose last two arguments never vary within\n * a run, which is how the next value gets added as a fifth.\n */\ninterface DeltaReads {\n /** What OTHER features in flight claim — lazy, so the common case never scans. */\n claims: ClaimLookup;\n /** The invocation's read index, when the caller threaded one. */\n context?: FleetContext;\n}\n\nexport async function deltaShapeIssues(\n docsDir: DocsDir,\n featureDir: FeatureDir,\n featureId: string,\n context?: FleetContext,\n): Promise<Issue[]> {\n const issues: Issue[] = [];\n const services = await featureSpecServices(featureDir, context);\n // One `existsSync` for a feature that carries no capability delta, which is\n // every feature in a fleet that has not adopted the business axis.\n const capabilities =\n context === undefined ? await featureCapabilityDeltas(featureDir) : await context.featureCapabilityDeltas(featureDir);\n // The flows this feature brings, and one `existsSync` for a feature that\n // brings none — which is every feature in a fleet that has not adopted the\n // axis. The directory, not the documents: what is needed here is whether to\n // pay for the overlay at all, and the walk that lists them happens once,\n // inside it.\n const hasFlows = existsSync(featureUseCasesDir(featureDir));\n // The early return must ask about EVERY corpus. Asking only about services\n // meant a capability-only feature — a business change with no service touched\n // yet, which is exactly what an analyst writes first — was graded by nothing\n // and archived whatever its delta said; asking only about those two would do\n // the same to a feature whose whole content is a cross-service flow, which is\n // the shape an architect answers an analyst with.\n if (services.length === 0 && capabilities.docs.length === 0 && !hasFlows) return issues;\n\n // What OTHER features in flight claim. Only built when a claim has to be\n // checked — the common case never pays for the scan.\n const reads: DeltaReads = {\n claims: claimLookup(docsDir, featureId, context),\n ...(context === undefined ? {} : { context }),\n };\n\n // The two corpora's parsed requirements, kept as the walk produces them so\n // the `Realizes:` join below can be taken without re-reading a byte. That\n // join is the one question neither corpus can answer alone — which service\n // requirement keeps which business promise — and this is the only place in\n // loam where both sides are already open (`capabilities/delta/uncovered.ts`\n // holds the rules; nothing here decides anything).\n const serviceDeltas: RealizingDoc[] = [];\n const capabilityDeltas: CapabilityDeltaDoc[] = [];\n\n // Both requirement-carrying files per service run the same checks — one code\n // path parameterized by filename, the merge's own factoring. `where` names\n // the arch file in messages so a finding cannot be chased into the wrong\n // document; spec.md keeps its historical spelling.\n for (const service of services) {\n for (const axis of SPEC_AXES) {\n const specPath = featureSpecPaths(featureDir, service)[axis.key];\n if (!existsSync(specPath)) continue;\n const scope: DeltaScope = {\n kind: \"service\",\n subject: service,\n axis,\n featureId,\n docsDir,\n specPath,\n where: axis.key === \"spec\" ? service : `${service} (arch.spec.md)`,\n // How the axis's living document is named in messages — spec.md keeps\n // the historical \"living spec\", the arch axis says which file it means.\n livingDoc: axis.key === \"spec\" ? \"living spec\" : \"living arch.spec.md\",\n };\n const graded = await gradeDelta(scope, (await locateServicePaths(docsDir, service, context))[axis.key], reads);\n issues.push(...graded.issues);\n serviceDeltas.push({ service, file: axis.file, reqs: graded.reqs });\n }\n }\n\n for (const doc of capabilities.docs) {\n const scope: DeltaScope = {\n kind: \"capability\",\n subject: doc.id,\n axis: CAPABILITY_AXIS,\n featureId,\n docsDir,\n specPath: doc.spec,\n // `capability <id>`, not `capabilities/<id>` — the second reads as the\n // LIVING directory, and every message this labels is about the FEATURE's\n // delta of it. Sending an author to edit the wrong one of two files with\n // the same name is the whole reason `where` and `livingDoc` are separate.\n where: `capability ${doc.id}`,\n livingDoc: `living capabilities/${doc.id}/spec.md`,\n };\n // Absent is a real and ordinary answer on this axis: the first feature to\n // mention a capability is what creates its living document, so the whole\n // delta grades against `[]` and every requirement in it is legitimately an\n // addition.\n const graded = await gradeDelta(scope, livingCapabilityPaths(docsDir, doc.id).spec, reads);\n issues.push(...graded.issues);\n // The document's own three rules, on the requirements this delta would\n // MERGE — before the merge, where the author can still fix them. See\n // `capabilities/delta/doc.ts` for why grading only the living copy leaves a\n // hole straight through the altitude rule.\n issues.push(\n ...capabilityDocIssues(graded.reqs, {\n where: relative(docsDir, doc.spec).split(/[\\\\/]/).join(\"/\"),\n subject: doc.id,\n }),\n );\n capabilityDeltas.push({ id: doc.id, reqs: graded.reqs, living: graded.living.all });\n }\n\n // The other carrier of a promise, read once and only when this feature\n // actually brings a flow: the `dynamic view`s under `features/<FEAT>/usecases/`,\n // parsed over the map this feature's own merge would leave behind\n // (`core/usecases/delta/overlay.ts`).\n // A feature with no `usecases/` directory is a REAL empty answer, not an\n // ungraded one: there is no flow, so \"no flow keeps this\" is true and the\n // message may say it.\n const kept: FlowPromises = hasFlows\n ? await flowCoverage({\n docsDir,\n featureDir,\n featureId,\n capabilities: capabilityDeltas,\n // Read HERE, through the invocation's index, because this module holds\n // it and `core/usecases/` does not — every other read in this walk does\n // the same, and `core/repo/service-target.ts` prices a fleet\n // enumeration per call at ~13 ms on a 120-service fleet.\n vocabulary: context === undefined ? await readCapabilityVocabulary(docsDir) : await context.capabilities(docsDir),\n known: new Set(await enumeratedServiceIds(docsDir, context)),\n // A function rather than the context itself: one memoised LikeC4 read\n // does not justify an edge from `core/usecases/` to `fleet-context`, and\n // the edge would push that package up a DAG level for nothing.\n ...(context === undefined ? {} : { load: (path: string) => context.loadLikeC4(path) }),\n // The fleet's extending models, for the merge preview the overlay\n // grades against — read HERE for `vocabulary`'s reason exactly, and as\n // a thunk so the walk pays for it only when a flow is really there.\n // Without it the preview is the pre-routing map and `usecase.flow-invalid`\n // fails open on the one shape it exists for: a hop into\n // `<service-fqn>.<container>`, which the archive routes into that\n // service's own model (verification 2026-09-04, review F8).\n models: () => extendingModels(docsDir, context),\n })\n : { kind: \"read\", kept: [] };\n if (kept.kind === \"unreadable\") {\n // ERROR, and the archive gate's own `NEVER_OVERRIDABLE` keeps `--approve`\n // off it. This is the refusal that stops a flow being copied into\n // `architecture/` and the NEXT reader's `loam validate --all` carrying the\n // failure — including the case the overlay exists for, a hop naming an\n // element the merge does not land. Mechanical, so it is not loam's judgement\n // to override.\n issues.push({\n severity: \"error\",\n code: \"usecase.flow-invalid\",\n subject: featureId,\n // The opening sentence does NOT say whose file is at fault, and that is\n // deliberate: the corpus this reads is the feature's flows PLUS the living\n // `architecture/` documents they are drawn over, so the failing path can\n // be a living one — a landscape that no longer parses, a use case somebody\n // else wrote. Every message carries its own path, so a reader can place\n // it; an opening line that blamed `usecases/` would send them to the wrong\n // file first.\n message:\n `this feature's flows could not be graded against the map its own merge would leave behind, so the archive ` +\n `would land an architecture/ nothing has checked. The corpus is the feature's usecases/ AND the living ` +\n `architecture/ documents they are drawn over, so the fault may be in either — each message names its file. ` +\n `${kept.errors.length} problem(s): ${kept.errors.join(\"; \")}`,\n });\n }\n\n // The `Realizes:` join, both directions, over documents this walk has already\n // parsed. Skipped entirely when the feature carries no capability delta,\n // which is every feature in a fleet that has not adopted the business axis —\n // and the removal half asks for the living corpus only when something is\n // actually retired, so even an adopting fleet pays the fleet-wide read on the\n // features that earn it.\n if (capabilityDeltas.length > 0) {\n // The three arms travel as three, and flattening two of them to `[]` is\n // the one thing this must not do: `capability.uncovered` says in words that\n // no flow keeps the promise, so handing it an empty list for a corpus loam\n // could not read or could not resolve makes it assert a negative it never\n // evaluated — and gate on it. `claims.ts`'s header states the rule; this is\n // where a caller could break it.\n issues.push(\n ...uncoveredIssues(\n capabilityDeltas,\n serviceDeltas,\n kept.kind === \"read\"\n ? { graded: true, kept: kept.kept }\n : { graded: false, why: kept.kind === \"ungraded\" ? kept.why : kept.errors.join(\"; \") },\n ),\n );\n issues.push(\n ...(await removedRealizedIssues({\n capabilities: capabilityDeltas,\n deltas: serviceDeltas,\n living: () => livingRealizers(docsDir, context),\n })),\n );\n }\n\n return issues;\n}\n\n/**\n * Every LIVING service requirements document in the fleet, for the one question\n * that has to ask about services this feature never mentions: does anything out\n * there still realize a capability requirement this feature retires?\n *\n * The same shape and the same cost `openapi.remove-op-consumed` pays through\n * `coherence/lookups.ts` one axis over, and for the same reason — the merge\n * deletes the promise while the `Realizes:` line stays, so the very next\n * `validate --all` reports a breach on a repository whose author was never in\n * this feature. Called behind a thunk (`removedRealizedIssues` invokes it only\n * when something is retired), so a feature that removes nothing never runs it.\n */\nasync function livingRealizers(docsDir: DocsDir, context?: FleetContext): Promise<RealizingDoc[]> {\n const out: RealizingDoc[] = [];\n for (const service of await enumeratedServiceIds(docsDir, context)) {\n const paths = await locateServicePaths(docsDir, service, context);\n for (const axis of SPEC_AXES) {\n const path = paths[axis.key];\n if (!existsSync(path)) continue;\n const reqs =\n context === undefined ? parseRequirements(await readFile(path, \"utf8\")) : await context.readRequirements(path);\n out.push({ service, file: axis.file, reqs });\n }\n }\n return out;\n}\n\n/**\n * One delta document against one living document: the three passes, in the\n * order that makes their messages readable.\n *\n * The order is load-bearing. `deltaDocumentIssues` settles what the delta says\n * about itself, `livingDocumentIssues` settles whether the living text can be\n * selected in at all, and only then does `selectionIssues` compare them — a pin\n * the document pass already refused must not also be reported stale, which\n * would send its author to `loam rebase` for a problem rebase does not fix.\n *\n * The parsed delta requirements come back with the issues because the capability\n * corpus grades them a second way (`capabilityDocIssues`) and re-reading the\n * file to do it would be a second parse of bytes already in hand — and, without\n * a context, a second chance for the two passes to disagree about the document.\n * The LIVING index rides back for the same reason once more: the removal\n * direction of the `Realizes:` join has to resolve a REMOVED spelled by heading\n * into the id it retires, and that id is a fact about the living document.\n */\nasync function gradeDelta(\n scope: DeltaScope,\n livingPath: string,\n reads: DeltaReads,\n): Promise<{ issues: Issue[]; reqs: Requirement[]; living: LivingIndex }> {\n const { claims, context } = reads;\n const raw = context === undefined ? await readFile(scope.specPath, \"utf8\") : await context.readText(scope.specPath);\n const reqs = context === undefined ? parseRequirements(raw) : await context.readRequirements(scope.specPath);\n const living = indexLiving(\n !existsSync(livingPath)\n ? []\n : context === undefined\n ? parseRequirements(await readFile(livingPath, \"utf8\"))\n : await context.readRequirements(livingPath),\n );\n return {\n reqs,\n living,\n issues: [\n ...deltaDocumentIssues(scope, raw, reqs),\n ...livingDocumentIssues(scope, living),\n ...(await selectionIssues(scope, reqs, living, claims)),\n ],\n };\n}\n"]}