@warpgogol/forge 7.0.0 → 8.0.2

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 (396) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/bin/cli.js +6 -12
  3. package/bin/resolve-entry.js +24 -0
  4. package/dist/os/compass/comment-safety.d.ts +83 -0
  5. package/dist/os/compass/comment-safety.d.ts.map +1 -0
  6. package/dist/os/compass/comment-safety.js +305 -0
  7. package/dist/os/compass/comment-safety.js.map +1 -0
  8. package/dist/os/compass/compass.module.d.ts.map +1 -1
  9. package/dist/os/compass/compass.module.js +47 -4
  10. package/dist/os/compass/compass.module.js.map +1 -1
  11. package/dist/os/compass/handlers/compass-change-summary-handler.d.ts +2 -1
  12. package/dist/os/compass/handlers/compass-change-summary-handler.d.ts.map +1 -1
  13. package/dist/os/compass/handlers/compass-change-summary-handler.js +34 -10
  14. package/dist/os/compass/handlers/compass-change-summary-handler.js.map +1 -1
  15. package/dist/os/compass/handlers/compass-docs-scaffold.d.ts.map +1 -1
  16. package/dist/os/compass/handlers/compass-docs-scaffold.js +54 -17
  17. package/dist/os/compass/handlers/compass-docs-scaffold.js.map +1 -1
  18. package/dist/os/compass/handlers/compass-header-scaffold-handler.d.ts +14 -0
  19. package/dist/os/compass/handlers/compass-header-scaffold-handler.d.ts.map +1 -0
  20. package/dist/os/compass/handlers/compass-header-scaffold-handler.js +261 -0
  21. package/dist/os/compass/handlers/compass-header-scaffold-handler.js.map +1 -0
  22. package/dist/os/compass/handlers/compass-header-scaffold.d.ts +31 -0
  23. package/dist/os/compass/handlers/compass-header-scaffold.d.ts.map +1 -0
  24. package/dist/os/compass/handlers/compass-header-scaffold.js +739 -0
  25. package/dist/os/compass/handlers/compass-header-scaffold.js.map +1 -0
  26. package/dist/os/compass/handlers/compass-inventory-handler.d.ts.map +1 -1
  27. package/dist/os/compass/handlers/compass-inventory-handler.js +8 -4
  28. package/dist/os/compass/handlers/compass-inventory-handler.js.map +1 -1
  29. package/dist/os/compass/handlers/compass-inventory.d.ts +6 -0
  30. package/dist/os/compass/handlers/compass-inventory.d.ts.map +1 -1
  31. package/dist/os/compass/handlers/compass-inventory.js +28 -13
  32. package/dist/os/compass/handlers/compass-inventory.js.map +1 -1
  33. package/dist/os/compass/handlers/compass-migrate-handler.d.ts.map +1 -1
  34. package/dist/os/compass/handlers/compass-migrate-handler.js +12 -26
  35. package/dist/os/compass/handlers/compass-migrate-handler.js.map +1 -1
  36. package/dist/os/compass/handlers/compass-migrate.d.ts +15 -2
  37. package/dist/os/compass/handlers/compass-migrate.d.ts.map +1 -1
  38. package/dist/os/compass/handlers/compass-migrate.js +58 -20
  39. package/dist/os/compass/handlers/compass-migrate.js.map +1 -1
  40. package/dist/os/compass/handlers/git-revision.d.ts +10 -0
  41. package/dist/os/compass/handlers/git-revision.d.ts.map +1 -1
  42. package/dist/os/compass/handlers/git-revision.js +58 -4
  43. package/dist/os/compass/handlers/git-revision.js.map +1 -1
  44. package/dist/os/compass/handlers/summary-record.d.ts +20 -5
  45. package/dist/os/compass/handlers/summary-record.d.ts.map +1 -1
  46. package/dist/os/compass/handlers/summary-record.js +175 -44
  47. package/dist/os/compass/handlers/summary-record.js.map +1 -1
  48. package/dist/os/compass/index.d.ts +1 -0
  49. package/dist/os/compass/index.d.ts.map +1 -1
  50. package/dist/os/compass/index.js +2 -0
  51. package/dist/os/compass/index.js.map +1 -1
  52. package/dist/os/compass/policy.d.ts +9 -0
  53. package/dist/os/compass/policy.d.ts.map +1 -1
  54. package/dist/os/compass/policy.js +11 -2
  55. package/dist/os/compass/policy.js.map +1 -1
  56. package/dist/os/core/core.module.js +1 -1
  57. package/dist/os/core/handlers/package-health.d.ts.map +1 -1
  58. package/dist/os/core/handlers/package-health.js +1 -6
  59. package/dist/os/core/handlers/package-health.js.map +1 -1
  60. package/dist/os/queue/types.d.ts +2 -0
  61. package/dist/os/queue/types.d.ts.map +1 -1
  62. package/dist/os/queue/types.js +3 -1
  63. package/dist/os/queue/types.js.map +1 -1
  64. package/dist/os/rfc/acceptance.d.ts.map +1 -1
  65. package/dist/os/rfc/acceptance.js +51 -1
  66. package/dist/os/rfc/acceptance.js.map +1 -1
  67. package/dist/os/rfc/decision-log.d.ts.map +1 -1
  68. package/dist/os/rfc/decision-log.js +21 -3
  69. package/dist/os/rfc/decision-log.js.map +1 -1
  70. package/dist/os/rfc/dna-trace.d.ts +2 -0
  71. package/dist/os/rfc/dna-trace.d.ts.map +1 -1
  72. package/dist/os/rfc/dna-trace.js +13 -4
  73. package/dist/os/rfc/dna-trace.js.map +1 -1
  74. package/dist/os/rfc/handlers/implement-stamp-origin.d.ts +37 -0
  75. package/dist/os/rfc/handlers/implement-stamp-origin.d.ts.map +1 -0
  76. package/dist/os/rfc/handlers/implement-stamp-origin.js +118 -0
  77. package/dist/os/rfc/handlers/implement-stamp-origin.js.map +1 -0
  78. package/dist/os/rfc/handlers/implement-stamp.d.ts +41 -1
  79. package/dist/os/rfc/handlers/implement-stamp.d.ts.map +1 -1
  80. package/dist/os/rfc/handlers/implement-stamp.js +594 -81
  81. package/dist/os/rfc/handlers/implement-stamp.js.map +1 -1
  82. package/dist/os/rfc/handlers/rfc-evidence-sync.d.ts +42 -0
  83. package/dist/os/rfc/handlers/rfc-evidence-sync.d.ts.map +1 -0
  84. package/dist/os/rfc/handlers/rfc-evidence-sync.js +147 -0
  85. package/dist/os/rfc/handlers/rfc-evidence-sync.js.map +1 -0
  86. package/dist/os/rfc/handlers/validate-rules.d.ts +9 -1
  87. package/dist/os/rfc/handlers/validate-rules.d.ts.map +1 -1
  88. package/dist/os/rfc/handlers/validate-rules.js +60 -8
  89. package/dist/os/rfc/handlers/validate-rules.js.map +1 -1
  90. package/dist/os/rfc/reachable-symbol.d.ts +17 -0
  91. package/dist/os/rfc/reachable-symbol.d.ts.map +1 -0
  92. package/dist/os/rfc/reachable-symbol.js +376 -0
  93. package/dist/os/rfc/reachable-symbol.js.map +1 -0
  94. package/dist/os/rfc/rfc.module.d.ts.map +1 -1
  95. package/dist/os/rfc/rfc.module.js +89 -5
  96. package/dist/os/rfc/rfc.module.js.map +1 -1
  97. package/dist/os/rfc/types.d.ts +81 -12
  98. package/dist/os/rfc/types.d.ts.map +1 -1
  99. package/dist/os/rfc/types.js +15 -10
  100. package/dist/os/rfc/types.js.map +1 -1
  101. package/dist/os/rfc/verification-evidence.d.ts +10 -1
  102. package/dist/os/rfc/verification-evidence.d.ts.map +1 -1
  103. package/dist/os/rfc/verification-evidence.js +175 -10
  104. package/dist/os/rfc/verification-evidence.js.map +1 -1
  105. package/dist/os/rfc/verification-origin.d.ts +58 -0
  106. package/dist/os/rfc/verification-origin.d.ts.map +1 -0
  107. package/dist/os/rfc/verification-origin.js +346 -0
  108. package/dist/os/rfc/verification-origin.js.map +1 -0
  109. package/dist/os/rfc/verification-refresh.d.ts.map +1 -1
  110. package/dist/os/rfc/verification-refresh.js +11 -1
  111. package/dist/os/rfc/verification-refresh.js.map +1 -1
  112. package/dist/os/rfc/verify-workspace.d.ts +23 -0
  113. package/dist/os/rfc/verify-workspace.d.ts.map +1 -0
  114. package/dist/os/rfc/verify-workspace.js +278 -0
  115. package/dist/os/rfc/verify-workspace.js.map +1 -0
  116. package/dist/os/session/handlers/metrics-rfc.d.ts.map +1 -1
  117. package/dist/os/session/handlers/metrics-rfc.js +3 -0
  118. package/dist/os/session/handlers/metrics-rfc.js.map +1 -1
  119. package/dist/os/spec/spec-status.d.ts.map +1 -1
  120. package/dist/os/spec/spec-status.js +5 -23
  121. package/dist/os/spec/spec-status.js.map +1 -1
  122. package/dist/os/spec/spec-validate.d.ts.map +1 -1
  123. package/dist/os/spec/spec-validate.js +30 -9
  124. package/dist/os/spec/spec-validate.js.map +1 -1
  125. package/dist/os/workflow/handlers.d.ts +0 -4
  126. package/dist/os/workflow/handlers.d.ts.map +1 -1
  127. package/dist/os/workflow/handlers.js +9 -36
  128. package/dist/os/workflow/handlers.js.map +1 -1
  129. package/dist/os/workflow/index.d.ts +2 -2
  130. package/dist/os/workflow/index.d.ts.map +1 -1
  131. package/dist/os/workflow/index.js +1 -1
  132. package/dist/os/workflow/index.js.map +1 -1
  133. package/dist/os/workflow/types.d.ts +0 -19
  134. package/dist/os/workflow/types.d.ts.map +1 -1
  135. package/dist/os/workflow/types.js +0 -2
  136. package/dist/os/workflow/types.js.map +1 -1
  137. package/dist/os/workflow/workflow.module.d.ts.map +1 -1
  138. package/dist/os/workflow/workflow.module.js +6 -15
  139. package/dist/os/workflow/workflow.module.js.map +1 -1
  140. package/dist/src/config/forge-config.d.ts +5 -0
  141. package/dist/src/config/forge-config.d.ts.map +1 -1
  142. package/dist/src/config/forge-config.js +5 -2
  143. package/dist/src/config/forge-config.js.map +1 -1
  144. package/dist/src/onboarding/agents-generate.js +1 -1
  145. package/dist/src/onboarding/doctor.js +3 -3
  146. package/dist/src/onboarding/doctor.js.map +1 -1
  147. package/dist/src/onboarding/init.js +2 -2
  148. package/dist/src/onboarding/nested-agents-templates.js +1 -1
  149. package/dist/src/onboarding/prettierignore.js +1 -1
  150. package/dist/src/onboarding/upgrade.js +2 -2
  151. package/dist/src/onboarding/workspace-discovery.js +1 -1
  152. package/dist/src/profiles/profile-schema.d.ts +2 -0
  153. package/dist/src/profiles/profile-schema.d.ts.map +1 -1
  154. package/dist/src/profiles/profile-schema.js +1 -0
  155. package/dist/src/profiles/profile-schema.js.map +1 -1
  156. package/dist/src/profiles/stack-profile.d.ts +1 -0
  157. package/dist/src/profiles/stack-profile.d.ts.map +1 -1
  158. package/dist/src/types.d.ts +23 -0
  159. package/dist/src/types.d.ts.map +1 -1
  160. package/dist/src/types.js +2 -1
  161. package/dist/src/types.js.map +1 -1
  162. package/docs/reference/cli.md +0 -1
  163. package/docs/reference/programmatic-api.md +1 -1
  164. package/os/adr/handlers/validate.test.ts +14 -0
  165. package/os/compass/comment-safety.ts +331 -0
  166. package/os/compass/compass.module.ts +50 -4
  167. package/os/compass/handlers/compass-change-summary-handler.ts +41 -11
  168. package/os/compass/handlers/compass-docs-scaffold.ts +59 -17
  169. package/os/compass/handlers/compass-game-extensions.test.ts +3 -7
  170. package/os/compass/handlers/compass-header-scaffold-handler.ts +352 -0
  171. package/os/compass/handlers/compass-header-scaffold.ts +847 -0
  172. package/os/compass/handlers/compass-inventory-handler.ts +9 -4
  173. package/os/compass/handlers/compass-inventory.ts +29 -13
  174. package/os/compass/handlers/compass-migrate-handler.ts +13 -27
  175. package/os/compass/handlers/compass-migrate.ts +77 -21
  176. package/os/compass/handlers/git-revision.ts +59 -4
  177. package/os/compass/handlers/resolve-scan-root-package.test.ts +14 -0
  178. package/os/compass/handlers/resolve-scan-root-workpiece.test.ts +14 -0
  179. package/os/compass/handlers/summary-record.ts +194 -41
  180. package/os/compass/handlers/tests/compass-audit-plan.test.ts +6 -0
  181. package/os/compass/handlers/tests/compass-audit-record.test.ts +6 -0
  182. package/os/compass/handlers/tests/compass-audit-validate.test.ts +6 -0
  183. package/os/compass/handlers/tests/compass-change-summary-handler.test.ts +131 -0
  184. package/os/compass/handlers/tests/compass-docs-validate.test.ts +6 -0
  185. package/os/compass/handlers/tests/compass-header-scaffold.test.ts +896 -0
  186. package/os/compass/handlers/tests/compass-ledger-scope.test.ts +6 -0
  187. package/os/compass/handlers/tests/compass-migrate.test.ts +87 -9
  188. package/os/compass/handlers/tests/compass-policy.test.ts +1 -1
  189. package/os/compass/handlers/tests/compass-text-safety.test.ts +271 -0
  190. package/os/compass/handlers/tests/compass-v2-contract.test.ts +52 -3
  191. package/os/compass/handlers/tests/summary-record.test.ts +324 -3
  192. package/os/compass/index.ts +15 -0
  193. package/os/compass/policy.ts +27 -2
  194. package/os/core/core.module.ts +1 -1
  195. package/os/core/handlers/invariant-engine.test.ts +3 -1
  196. package/os/core/handlers/note-frontmatter-validate.test.ts +6 -1
  197. package/os/core/handlers/note-link-validate.test.ts +6 -1
  198. package/os/core/handlers/note-orphan-detect.test.ts +6 -1
  199. package/os/core/handlers/package-health.test.ts +6 -0
  200. package/os/core/handlers/package-health.ts +1 -6
  201. package/os/mission/handlers/archive.test.ts +14 -0
  202. package/os/naming/naming-convention.test.ts +14 -0
  203. package/os/queue/decision-ledger.test.ts +27 -4
  204. package/os/queue/queue-validate.test.ts +14 -0
  205. package/os/queue/types.ts +3 -1
  206. package/os/rfc/acceptance-reachable.test.ts +146 -0
  207. package/os/rfc/acceptance.test.ts +25 -0
  208. package/os/rfc/acceptance.ts +51 -1
  209. package/os/rfc/decision-log.ts +22 -4
  210. package/os/rfc/dna-trace.ts +17 -5
  211. package/os/rfc/frontmatter-io.test.ts +14 -0
  212. package/os/rfc/handlers/implement-stamp-acceptance-verification.test.ts +81 -0
  213. package/os/rfc/handlers/implement-stamp-binding.test.ts +79 -0
  214. package/os/rfc/handlers/implement-stamp-origin.test.ts +132 -0
  215. package/os/rfc/handlers/implement-stamp-origin.ts +154 -0
  216. package/os/rfc/handlers/implement-stamp-stale.test.ts +20 -2
  217. package/os/rfc/handlers/implement-stamp.ts +714 -87
  218. package/os/rfc/handlers/lifecycle.test.ts +14 -0
  219. package/os/rfc/handlers/rfc-evidence-sync.ts +221 -0
  220. package/os/rfc/handlers/validate-rules-rfc0997.test.ts +14 -0
  221. package/os/rfc/handlers/validate-rules-rfc1006.test.ts +14 -0
  222. package/os/rfc/handlers/validate-rules-rfc1330.test.ts +120 -0
  223. package/os/rfc/handlers/validate-rules-rfc1334.test.ts +65 -0
  224. package/os/rfc/handlers/validate-rules.test.ts +14 -0
  225. package/os/rfc/handlers/validate-rules.ts +80 -7
  226. package/os/rfc/handlers/validate.test.ts +4 -3
  227. package/os/rfc/reachable-symbol.ts +441 -0
  228. package/os/rfc/rfc-0000-template.md +3 -0
  229. package/os/rfc/rfc-create-concurrent.test.ts +6 -0
  230. package/os/rfc/rfc-create-hint.test.ts +6 -0
  231. package/os/rfc/rfc-read-only-no-side-effects.test.ts +6 -0
  232. package/os/rfc/rfc.module.ts +95 -5
  233. package/os/rfc/types.ts +106 -12
  234. package/os/rfc/verification-emit-check.test.ts +14 -0
  235. package/os/rfc/verification-emit-freshness.test.ts +415 -0
  236. package/os/rfc/verification-emit.test.ts +14 -0
  237. package/os/rfc/verification-evidence.ts +230 -10
  238. package/os/rfc/verification-normalize.test.ts +14 -0
  239. package/os/rfc/verification-origin.test.ts +236 -0
  240. package/os/rfc/verification-origin.ts +417 -0
  241. package/os/rfc/verification-refresh.test.ts +14 -0
  242. package/os/rfc/verification-refresh.ts +12 -1
  243. package/os/rfc/verifier/rfc-1333/imp12-binding.acceptance.test.ts +78 -0
  244. package/os/rfc/verifier/rfc-1333/imp12-gate.acceptance.test.ts +81 -0
  245. package/os/rfc/verifier/rfc-1333/skills-and-types.acceptance.test.ts +50 -0
  246. package/os/rfc/verifier/rfc-1333/verify-workspace.acceptance.test.ts +103 -0
  247. package/os/rfc/verify-workspace.test.ts +122 -0
  248. package/os/rfc/verify-workspace.ts +342 -0
  249. package/os/session/handlers/metrics-rfc.ts +3 -0
  250. package/os/spec/spec-status.test.ts +130 -0
  251. package/os/spec/spec-status.ts +5 -18
  252. package/os/spec/spec-validate.test.ts +76 -1
  253. package/os/spec/spec-validate.ts +26 -7
  254. package/os/workflow/handlers.ts +8 -42
  255. package/os/workflow/index.ts +1 -4
  256. package/os/workflow/types.ts +0 -22
  257. package/os/workflow/workflow.module.ts +6 -16
  258. package/package.json +1 -1
  259. package/skills/_shared/agent-operating-model.md +1 -1
  260. package/skills/_shared/fo-pipeline-conventions.md +1 -0
  261. package/skills/fo/fo-add-tests/SKILL.md +14 -0
  262. package/skills/fo/fo-fix/SKILL.md +2 -1
  263. package/skills/fo/fo-handoff/SKILL.md +1 -1
  264. package/skills/fo/fo-idea-create-rfc/acceptance-criteria-standard.md +8 -0
  265. package/skills/fo/fo-idea-i-just-want-to-see-the-result/SKILL.md +4 -2
  266. package/skills/fo/fo-idea-implement/SKILL.md +68 -53
  267. package/skills/fo/fo-idea-plan/SKILL.md +3 -1
  268. package/skills/fo/fo-review/SKILL.md +12 -0
  269. package/skills/fo/fo-session-save/learned-principles.md +13 -0
  270. package/skills/fo/fo-step-commit/SKILL.md +1 -1
  271. package/src/bin-entry.test.ts +37 -0
  272. package/src/compass/contract-registry.test.ts +14 -0
  273. package/src/compass/types.test.ts +14 -0
  274. package/src/config/__tests__/resolve-terminology.test.ts +14 -0
  275. package/src/config/forge-config.test.ts +14 -0
  276. package/src/config/forge-config.ts +7 -2
  277. package/src/forge-module.test.ts +14 -0
  278. package/src/knowledge/__tests__/promote.test.ts +14 -0
  279. package/src/knowledge/__tests__/serialize.test.ts +14 -0
  280. package/src/knowledge/__tests__/sync.test.ts +4 -1
  281. package/src/knowledge/budgets.test.ts +14 -0
  282. package/src/knowledge/compact.test.ts +14 -0
  283. package/src/knowledge/parse.test.ts +14 -0
  284. package/src/knowledge/schema.test.ts +14 -0
  285. package/src/migration-adapters/__tests__/ignored-files.test.ts +14 -0
  286. package/src/migration-adapters/__tests__/registry.test.ts +14 -0
  287. package/src/migration-adapters/__tests__/types.test.ts +14 -0
  288. package/src/onboarding/__tests__/workspace-discovery.test.ts +14 -0
  289. package/src/onboarding/agents-generate.ts +1 -1
  290. package/src/onboarding/compass-docs/semantic-layer-block.test.ts +6 -0
  291. package/src/onboarding/create.test.ts +14 -0
  292. package/src/onboarding/doctor-token-check.test.ts +3 -0
  293. package/src/onboarding/doctor.test.ts +14 -0
  294. package/src/onboarding/doctor.ts +3 -3
  295. package/src/onboarding/init.test.ts +14 -0
  296. package/src/onboarding/init.ts +2 -2
  297. package/src/onboarding/nested-agents-templates.ts +1 -1
  298. package/src/onboarding/prettierignore.ts +1 -1
  299. package/src/onboarding/scaffold.test.ts +14 -0
  300. package/src/onboarding/site-workshop-profile.test.ts +3 -0
  301. package/src/onboarding/upgrade.test.ts +14 -0
  302. package/src/onboarding/upgrade.ts +2 -2
  303. package/src/onboarding/workspace-discovery.ts +1 -1
  304. package/src/pipeline-status.test.ts +14 -0
  305. package/src/plugin/forge-plugin-manifest.test.ts +14 -0
  306. package/src/profiles/__tests__/profile-schema.test.ts +14 -0
  307. package/src/profiles/__tests__/stack-profile.test.ts +14 -0
  308. package/src/profiles/__tests__/terminology-utils.test.ts +14 -0
  309. package/src/profiles/profile-schema.ts +1 -0
  310. package/src/tests/acceptance-criteria.test.ts +14 -0
  311. package/src/tests/acceptance-probe-kinds.test.ts +14 -0
  312. package/src/tests/adr-implement-stamp.test.ts +14 -0
  313. package/src/tests/agents-generate-domain.test.ts +3 -0
  314. package/src/tests/agents-generate.test.ts +3 -0
  315. package/src/tests/bindings-schema.test.ts +2 -0
  316. package/src/tests/budgets.test.ts +14 -0
  317. package/src/tests/compact.test.ts +14 -0
  318. package/src/tests/compass-docs-flag.test.ts +6 -0
  319. package/src/tests/compass-docs-scaffold.test.ts +6 -0
  320. package/src/tests/compass-docs-validate-scope.test.ts +6 -0
  321. package/src/tests/contract-registry.test.ts +14 -0
  322. package/src/tests/create.test.ts +3 -0
  323. package/src/tests/discover-pack-skills.test.ts +14 -0
  324. package/src/tests/doctor-autonomy.test.ts +3 -0
  325. package/src/tests/doctor-bindings.test.ts +6 -1
  326. package/src/tests/doctor-dist-freshness.test.ts +26 -2
  327. package/src/tests/doctor-domain.test.ts +6 -1
  328. package/src/tests/doctor-fix.test.ts +3 -0
  329. package/src/tests/doctor-nested-agents.test.ts +3 -0
  330. package/src/tests/doctor-profile-id-known.test.ts +3 -0
  331. package/src/tests/doctor-skills-unmanaged.test.ts +3 -0
  332. package/src/tests/doctor-version-sync.test.ts +4 -1
  333. package/src/tests/editable-generated-region.test.ts +6 -3
  334. package/src/tests/exploration-handlers.test.ts +14 -0
  335. package/src/tests/file-size-lint.test.ts +6 -1
  336. package/src/tests/forge-autonomy-validate.test.ts +3 -1
  337. package/src/tests/forge-config.test.ts +6 -1
  338. package/src/tests/forge-validate-compass-docs.test.ts +6 -0
  339. package/src/tests/fs-atomic.test.ts +14 -0
  340. package/src/tests/fs.test.ts +14 -0
  341. package/src/tests/generated-marker.test.ts +14 -0
  342. package/src/tests/hash.test.ts +14 -0
  343. package/src/tests/implement-stamp.test.ts +476 -10
  344. package/src/tests/init-bindings.test.ts +6 -1
  345. package/src/tests/knowledge-parse.test.ts +14 -0
  346. package/src/tests/knowledge-pbt.test.ts +14 -0
  347. package/src/tests/markdown-table.test.ts +6 -3
  348. package/src/tests/memory-compact.test.ts +3 -0
  349. package/src/tests/memory-scaffold.test.ts +6 -1
  350. package/src/tests/metrics-rfc-1053.test.ts +14 -0
  351. package/src/tests/migration-adapters.test.ts +3 -0
  352. package/src/tests/package-files.test.ts +4 -1
  353. package/src/tests/package-health-lint-surface.test.ts +3 -0
  354. package/src/tests/pinned-check.test.ts +14 -0
  355. package/src/tests/pinned-init.test.ts +14 -0
  356. package/src/tests/pinned-validate.test.ts +14 -0
  357. package/src/tests/plugin-manifest.test.ts +14 -0
  358. package/src/tests/prettierignore-manage.test.ts +3 -0
  359. package/src/tests/profile-schema.test.ts +6 -1
  360. package/src/tests/profile-validate.test.ts +6 -1
  361. package/src/tests/program-lease.test.ts +3 -0
  362. package/src/tests/program-paths-extended.test.ts +3 -0
  363. package/src/tests/program-paths.test.ts +3 -0
  364. package/src/tests/program-property.test.ts +3 -0
  365. package/src/tests/program-schemas.test.ts +3 -0
  366. package/src/tests/program-spec-node.test.ts +3 -0
  367. package/src/tests/promote.test.ts +14 -0
  368. package/src/tests/public-surface.test.ts +6 -1
  369. package/src/tests/registry.test.ts +14 -0
  370. package/src/tests/rfc-evidence-sync.test.ts +347 -0
  371. package/src/tests/rfc-implement-stamp-governance.test.ts +403 -0
  372. package/src/tests/scaffold-project.test.ts +3 -0
  373. package/src/tests/session-handlers.test.ts +14 -0
  374. package/src/tests/session-pbt.test.ts +14 -0
  375. package/src/tests/skill-agents-sync.test.ts +3 -4
  376. package/src/tests/skill-schema.test.ts +14 -0
  377. package/src/tests/skill-sync-marker.test.ts +3 -0
  378. package/src/tests/skill-validate-knowledge.test.ts +14 -0
  379. package/src/tests/skill-validate.test.ts +14 -0
  380. package/src/tests/stack-profile.test.ts +6 -1
  381. package/src/tests/string-utils.test.ts +14 -0
  382. package/src/tests/upgrade.test.ts +6 -1
  383. package/src/tests/werkstatt-lock.test.ts +14 -0
  384. package/src/tests/workspace-discovery-domain.test.ts +6 -1
  385. package/src/tests/workspace-discovery.test.ts +6 -1
  386. package/src/types.test.ts +14 -0
  387. package/src/types.ts +30 -1
  388. package/src/utils/__tests__/fs-idempotent.test.ts +17 -0
  389. package/src/utils/__tests__/fs-trash.test.ts +17 -0
  390. package/src/utils/fs-atomic.test.ts +17 -0
  391. package/src/utils/fs-trash-sync.test.ts +17 -0
  392. package/src/utils/fs.test.ts +17 -0
  393. package/src/utils/generated-marker.test.ts +17 -0
  394. package/src/utils/hash.test.ts +17 -0
  395. package/src/utils/string-utils.test.ts +17 -0
  396. package/src/validators/__tests__/note-orphan-detect.test.ts +14 -0
@@ -0,0 +1,739 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>
4
+ compass.header.scaffold — pure codemod core (RFC-1318). Authors and repairs
5
+ Compass v2 headers under machine-enforced invariants: append-only merge of
6
+ existing content, closed-block guarantee on every emission, derived-or-sentinel
7
+ purposes, fixture-string safety, header-scoped comment anchors, high-risk
8
+ deference, deterministic repair of known malformation shapes.
9
+ </purpose>
10
+ <non-goals>
11
+ <item>Do not walk the filesystem or write — the handler owns discovery, dirty-target checks, and writes.</item>
12
+ <item>Do not rewrite surviving authored content — the merge only inserts missing blocks/items; weak prose stays for agents.</item>
13
+ <item>Do not strip forbidden v1 blocks or reorder blocks — compass.migrate owns the transformer role.</item>
14
+ </non-goals>
15
+ </MODULE_CONTRACT>
16
+ <CHANGE_SUMMARY>
17
+ <item>RFC-1318: add compass.header.scaffold codemod for mechanical header sweeps</item>
18
+ <item>RFC-1318</item>
19
+ <item>RFC-1323: write-time comment-terminator safety — shared comment-safety seam, authored CS-08 reject, injected neutralization, header-region scan</item>
20
+ <item>RFC-1323: review pass — still-open enclosing-style detection, per-file pre-pass parity, scaffold never-throws, docs.scaffold raw-leaf assert, trim per-file skip, CS-08 always-error severity</item>
21
+ </CHANGE_SUMMARY>
22
+ */
23
+ import { COMPASS_TAGS, TODO_ITEM, blockSpan, collectAiInvariants, hasUnclosedTag, inHeaderRegion, } from "./compass-migrate.js";
24
+ import { EXPORTED_SYMBOL_RE, deriveFileTokens, getRelativeSegments, getWorkspaceRelativeSegments, } from "./compass-inventory.js";
25
+ import { commentStyleCandidates, commentStyleFor, getLineCommentPrefix, assertCompassCommentSafe, CompassCommentSafetyError, } from "../comment-safety.js";
26
+ const SENTINEL_PURPOSE = "TODO(compass): describe this file's role — automatic derivation found no usable signal.";
27
+ const SENTINEL_NONGOAL = "TODO(compass): record the boundary this file must not take on.";
28
+ const TAG_LINE_CAP = 10;
29
+ function firstTagIndex(source) {
30
+ let best = -1;
31
+ for (const tag of COMPASS_TAGS) {
32
+ const i = source.indexOf(`<${tag}>`);
33
+ if (i >= 0 && (best < 0 || i < best))
34
+ best = i;
35
+ }
36
+ return best;
37
+ }
38
+ /**
39
+ * Locate the comment that carries the Compass header — the comment whose open
40
+ * precedes the first compass tag in the header region without a close between
41
+ * them. Repair anchors at the header comment's own terminator, never a close
42
+ * marker below it (fixture blocks or later comments must not absorb the boundary).
43
+ */
44
+ /**
45
+ * A comment opener counts as a header carrier only when nothing but
46
+ * whitespace precedes it on its line — an opener inside a string literal or
47
+ * mid-expression is fixture material, not a comment (SCAFFOLD-01).
48
+ */
49
+ function atLineStart(source, index) {
50
+ const lineStart = source.lastIndexOf("\n", index - 1) + 1;
51
+ return source.slice(lineStart, index).trim() === "";
52
+ }
53
+ /**
54
+ * Line-start openers still sit inside fixtures when they live inside a
55
+ * multi-line template literal (odd unescaped-backtick count) or a fenced
56
+ * code block (odd ```-fence count) — neither is a real comment.
57
+ */
58
+ function insideLiteral(source, open, style) {
59
+ const before = source.slice(0, open);
60
+ if (style === "block") {
61
+ return (before.match(/(?<!\\)`/g) ?? []).length % 2 === 1;
62
+ }
63
+ if (style === "html") {
64
+ const fences = before
65
+ .split("\n")
66
+ .filter((l) => l.trimStart().startsWith("```") || l.trimStart().startsWith("~~~")).length;
67
+ return fences % 2 === 1;
68
+ }
69
+ if (style === "line") {
70
+ // GDScript/tres docstrings: an odd triple-quote count puts the run inside
71
+ // a string literal, not a comment block.
72
+ return (before.match(/"""/g) ?? []).length % 2 === 1;
73
+ }
74
+ return false;
75
+ }
76
+ function findHeaderSpanInStyle(source, tagIdx, style, path) {
77
+ if (style === "block") {
78
+ const open = source.lastIndexOf("/*", tagIdx);
79
+ if (open < 0 || !atLineStart(source, open) || insideLiteral(source, open, style))
80
+ return null;
81
+ if (source.slice(open, tagIdx).includes("*/"))
82
+ return null;
83
+ const close = source.indexOf("*/", tagIdx);
84
+ if (close < 0)
85
+ return null;
86
+ return { start: open, end: close + 2, closeStart: close, style };
87
+ }
88
+ if (style === "html") {
89
+ const open = source.lastIndexOf("<!--", tagIdx);
90
+ if (open < 0 || !atLineStart(source, open) || insideLiteral(source, open, style))
91
+ return null;
92
+ if (source.slice(open, tagIdx).includes("-->"))
93
+ return null;
94
+ const close = source.indexOf("-->", tagIdx);
95
+ if (close < 0)
96
+ return null;
97
+ return { start: open, end: close + 3, closeStart: close, style };
98
+ }
99
+ // line style — a contiguous run of prefixed lines around the tag's line.
100
+ const prefix = (getLineCommentPrefix(path) ?? "# ").trimEnd();
101
+ const lines = source.split("\n");
102
+ const offsets = [];
103
+ let off = 0;
104
+ for (const line of lines) {
105
+ offsets.push(off);
106
+ off += line.length + 1;
107
+ }
108
+ let tagLine = -1;
109
+ for (let i = 0; i < lines.length; i += 1) {
110
+ if (offsets[i] <= tagIdx && tagIdx < offsets[i] + lines[i].length + 1) {
111
+ tagLine = i;
112
+ break;
113
+ }
114
+ }
115
+ if (tagLine < 0 || !lines[tagLine].trimStart().startsWith(prefix))
116
+ return null;
117
+ let first = tagLine;
118
+ while (first > 0 && lines[first - 1].trimStart().startsWith(prefix))
119
+ first -= 1;
120
+ if (insideLiteral(source, offsets[first], style))
121
+ return null;
122
+ let last = tagLine;
123
+ while (last + 1 < lines.length && lines[last + 1].trimStart().startsWith(prefix))
124
+ last += 1;
125
+ const end = offsets[last] + lines[last].length;
126
+ return { start: offsets[first], end, closeStart: end, style };
127
+ }
128
+ function findHeaderSpan(source, path) {
129
+ const tagIdx = firstTagIndex(source);
130
+ if (tagIdx < 0 || !inHeaderRegion(source, tagIdx))
131
+ return null;
132
+ for (const style of commentStyleCandidates(path)) {
133
+ const span = findHeaderSpanInStyle(source, tagIdx, style, path);
134
+ if (span)
135
+ return span;
136
+ }
137
+ return null;
138
+ }
139
+ /** Lines carrying literal compass tags — the SCAFFOLD-01 evidence list. */
140
+ function tagLines(source) {
141
+ const out = [];
142
+ for (const [index, line] of source.split("\n").entries()) {
143
+ if (/<\/?(?:MODULE_CONTRACT|KEY_DECISIONS|CHANGE_SUMMARY|non-goals|purpose)\b/.test(line)) {
144
+ out.push(`L${index + 1}: ${line.trim().slice(0, 120)}`);
145
+ if (out.length >= TAG_LINE_CAP)
146
+ break;
147
+ }
148
+ }
149
+ return out;
150
+ }
151
+ function firstDescribeTitle(source) {
152
+ return /\bdescribe(?:\.(?:skip|only|todo|each|concurrent|runIf|skipIf))?\s*\(\s*["'`]([^"'`]+)["'`]/.exec(source)?.[1];
153
+ }
154
+ function exportedSymbols(source) {
155
+ const names = [];
156
+ for (const m of source.matchAll(EXPORTED_SYMBOL_RE))
157
+ names.push(m[1]);
158
+ return names;
159
+ }
160
+ function stemPhrase(path) {
161
+ const filename = path.split("/").filter(Boolean).pop() ?? "";
162
+ const dot = filename.lastIndexOf(".");
163
+ const raw = dot > 0 ? filename.slice(0, dot) : filename;
164
+ return raw
165
+ .replace(/\.(test|spec)$/i, "")
166
+ .replace(/[[\]]/g, " ")
167
+ .replace(/[-_.]+/g, " ")
168
+ .trim();
169
+ }
170
+ /** The PURPOSE-02 bar: ≥10 words and ≥1 file-derived token in the text. */
171
+ function purposeMeetsBar(text, tokens) {
172
+ const words = text
173
+ .toLowerCase()
174
+ .split(/[^a-z0-9]+/)
175
+ .filter(Boolean);
176
+ if (words.length < 10)
177
+ return false;
178
+ const wordSet = new Set(words);
179
+ return [...tokens].some((t) => wordSet.has(t));
180
+ }
181
+ function derivePurpose(input) {
182
+ const { pathFromRoot, source, isTest } = input;
183
+ const tokens = deriveFileTokens(pathFromRoot, source);
184
+ const stem = stemPhrase(pathFromRoot);
185
+ if (isTest) {
186
+ const title = firstDescribeTitle(source);
187
+ if (title) {
188
+ const clean = title.replace(/[<>]/g, "");
189
+ const text = `Unit tests for ${clean} — covers the ${stem} suite surface and its observable contract.`;
190
+ if (purposeMeetsBar(text, tokens))
191
+ return { text, sentinel: false };
192
+ }
193
+ }
194
+ else {
195
+ const symbols = exportedSymbols(source)
196
+ .slice(0, 3)
197
+ .map((s) => s.replace(/[<>]/g, ""));
198
+ if (symbols.length > 0) {
199
+ const text = `Provides ${symbols.join(", ")} for the ${stem} module surface consumed by callers of this layer.`;
200
+ if (purposeMeetsBar(text, tokens))
201
+ return { text, sentinel: false };
202
+ }
203
+ }
204
+ return { text: SENTINEL_PURPOSE, sentinel: true };
205
+ }
206
+ function contractBlock(purposeText, nonGoalItems) {
207
+ const goals = nonGoalItems.map((item) => ` <item>${item}</item>`).join("\n");
208
+ return [
209
+ "<MODULE_CONTRACT>",
210
+ `<purpose>${purposeText}</purpose>`,
211
+ "<non-goals>",
212
+ goals,
213
+ "</non-goals>",
214
+ "</MODULE_CONTRACT>",
215
+ ].join("\n");
216
+ }
217
+ function keyDecisionsBlock(items) {
218
+ return ["<KEY_DECISIONS>", ...items.map((i) => ` <item>${i}</item>`), "</KEY_DECISIONS>"].join("\n");
219
+ }
220
+ function wrapHeader(blocks, style, path) {
221
+ const body = blocks.join("\n");
222
+ // RFC-1323: authored/derived text must not carry the style's comment
223
+ // terminator — a terminator-bearing derived purpose is a scaffold bug and
224
+ // fails closed (COMPASS-CS-08) rather than writing a corrupted header.
225
+ assertCompassCommentSafe(body, style, { file: path, block: "header" });
226
+ if (style === "html")
227
+ return `<!--\n${body}\n-->`;
228
+ if (style === "line") {
229
+ const prefix = getLineCommentPrefix(path) ?? "# ";
230
+ return body
231
+ .split("\n")
232
+ .map((l) => prefix + l)
233
+ .join("\n");
234
+ }
235
+ return `/*\n${body}\n*/`;
236
+ }
237
+ /**
238
+ * Comment style for a NEW header. .astro gets `/* *\u002f` inside a `---`
239
+ * frontmatter fence but `<!-- -->` when the file has none — literal block
240
+ * markers in the template region would render as text.
241
+ */
242
+ function insertStyleFor(path, source) {
243
+ const start = source.charCodeAt(0) === 0xfeff ? 1 : 0;
244
+ if (path.endsWith(".astro") && !source.startsWith("---", start))
245
+ return "html";
246
+ return commentStyleFor(path);
247
+ }
248
+ /**
249
+ * Offset where a new header lands — after BOM, shebang, astro frontmatter,
250
+ * markdown YAML frontmatter, and directive prologue. For .astro the offset is
251
+ * INSIDE the frontmatter fence (block comment); for .md it is after the fence
252
+ * (frontmatter stays first, then the `<!-- -->` header).
253
+ */
254
+ function insertionOffset(source, path) {
255
+ let i = 0;
256
+ if (source.charCodeAt(0) === 0xfeff)
257
+ i = 1;
258
+ if (source.startsWith("#!", i)) {
259
+ const nl = source.indexOf("\n", i);
260
+ i = nl < 0 ? source.length : nl + 1;
261
+ }
262
+ if (path.endsWith(".astro") && source.startsWith("---", i)) {
263
+ const openEnd = source.indexOf("\n", i);
264
+ if (openEnd >= 0)
265
+ return openEnd + 1;
266
+ }
267
+ if (path.endsWith(".md") && source.startsWith("---", i)) {
268
+ // The closing fence must be a --- only line — `----` rules or body
269
+ // horizontal rules are not frontmatter terminators.
270
+ const close = source.slice(i + 3).search(/\r?\n---[^\S\r\n]*(?:\r?\n|$)/);
271
+ if (close >= 0) {
272
+ const nlLen = source[i + 3 + close] === "\r" ? 2 : 1;
273
+ const fenceStart = i + 3 + close + nlLen;
274
+ const afterClose = source.indexOf("\n", fenceStart);
275
+ i = afterClose < 0 ? source.length : afterClose + 1;
276
+ }
277
+ }
278
+ for (;;) {
279
+ const m = /^[^\S\r\n]*["']use [\w-]+["'][^\S\r\n]*;?[^\S\r\n]*(?:\r?\n|$)/.exec(source.slice(i));
280
+ if (!m)
281
+ break;
282
+ i += m[0].length;
283
+ }
284
+ while (source[i] === "\n" || source[i] === "\r")
285
+ i += 1;
286
+ return i;
287
+ }
288
+ /** Offset of the start of the line containing `index`. */
289
+ function lineStartOf(source, index) {
290
+ return source.lastIndexOf("\n", index - 1) + 1;
291
+ }
292
+ function applyEdits(source, edits, guard) {
293
+ const sorted = [...edits].sort((a, b) => b.start - a.start || (b.order ?? 0) - (a.order ?? 0));
294
+ // RFC-1323: every inserted payload is asserted against the header's own
295
+ // style — seeded/re-emitted item text (e.g. @ai-invariant lines captured
296
+ // from // comments) can carry a terminator that means nothing there but
297
+ // truncates the block/html header it lands in.
298
+ if (guard) {
299
+ for (const e of sorted) {
300
+ assertCompassCommentSafe(e.text, guard.style, { file: guard.file, block: "header" });
301
+ }
302
+ }
303
+ let out = source;
304
+ for (const e of sorted)
305
+ out = out.slice(0, e.start) + e.text + out.slice(e.end);
306
+ return out;
307
+ }
308
+ function skipped(reason, source, diagnostic) {
309
+ return {
310
+ disposition: "skipped",
311
+ source,
312
+ repairs: [],
313
+ skipReason: reason,
314
+ ...(diagnostic ? { diagnostic } : {}),
315
+ };
316
+ }
317
+ /**
318
+ * Pure per-file transform. Returns the (possibly) rewritten source plus a
319
+ * disposition — never throws; unrepairable shapes report SCAFFOLD-02, and
320
+ * authored text carrying a comment terminator reports COMPASS-CS-08 — both
321
+ * with the original source.
322
+ */
323
+ export function scaffoldFile(input, policy) {
324
+ try {
325
+ return scaffoldFileImpl(input, policy);
326
+ }
327
+ catch (err) {
328
+ if (err instanceof CompassCommentSafetyError) {
329
+ return skipped("unsafe text", input.source, {
330
+ ruleId: "COMPASS-CS-08",
331
+ message: `${err.message} — file left untouched`,
332
+ });
333
+ }
334
+ throw err;
335
+ }
336
+ }
337
+ function scaffoldFileImpl(input, policy) {
338
+ const { source, pathFromRoot, riskClass, keyDecisionsRequired } = input;
339
+ const tagIdx = firstTagIndex(source);
340
+ const span = findHeaderSpan(source, pathFromRoot);
341
+ // Fixture-string safety — markup candidates outside a header comment are
342
+ // string-literal/code-borne tags; dynamic tag construction is agent work.
343
+ // An unterminated comment opener swallowing the tags is a malformation
344
+ // (SCAFFOLD-02), not a fixture.
345
+ if (!span && tagIdx >= 0) {
346
+ const unterminated = [
347
+ ["/*", "*/"],
348
+ ["<!--", "-->"],
349
+ ].some(([opener, closer]) => {
350
+ const open = source.lastIndexOf(opener, tagIdx);
351
+ return (open >= 0 &&
352
+ atLineStart(source, open) &&
353
+ !insideLiteral(source, open, opener === "/*" ? "block" : "html") &&
354
+ !source.slice(open, tagIdx).includes(closer) &&
355
+ source.indexOf(closer, tagIdx) < 0);
356
+ });
357
+ if (unterminated) {
358
+ return skipped("unrepairable malformation", source, {
359
+ ruleId: "SCAFFOLD-02",
360
+ message: "unterminated comment carries compass tags — file left untouched",
361
+ });
362
+ }
363
+ const lines = tagLines(source);
364
+ return skipped("fixture-string markup", source, {
365
+ ruleId: "SCAFFOLD-01",
366
+ message: `markup candidates outside a header comment — literal lines: ${lines.join(" | ")}`,
367
+ });
368
+ }
369
+ // High-risk deference — a new header on a high-risk file requires an
370
+ // @ai-invariant the codemod cannot invent; authorship stays agent work.
371
+ const aiInvariants = collectAiInvariants(source, policy);
372
+ if (!span && riskClass === "high" && aiInvariants.length === 0) {
373
+ return skipped("high-risk file requires an @ai-invariant — header authorship stays agent work", source);
374
+ }
375
+ // ── Insert path: no header anywhere ───────────────────────────────────────
376
+ if (!span) {
377
+ const purpose = derivePurpose(input);
378
+ const blocks = [
379
+ contractBlock(purpose.text, [SENTINEL_NONGOAL]),
380
+ ...(keyDecisionsRequired
381
+ ? [keyDecisionsBlock(aiInvariants.length > 0 ? aiInvariants : [TODO_ITEM])]
382
+ : []),
383
+ "<CHANGE_SUMMARY>\n</CHANGE_SUMMARY>",
384
+ ];
385
+ const style = insertStyleFor(pathFromRoot, source);
386
+ const header = wrapHeader(blocks, style, pathFromRoot);
387
+ const at = insertionOffset(source, pathFromRoot);
388
+ // Never glue the header onto a partial last line (EOF shebang, frontmatter
389
+ // fence without trailing newline, terminal 'use client').
390
+ const pad = at > 0 && source[at - 1] !== "\n" ? "\n" : "";
391
+ const next = `${source.slice(0, at)}${pad}${header}\n\n${source.slice(at)}`;
392
+ if (!closesCleanly(next, pathFromRoot)) {
393
+ return skipped("unrepairable malformation", source, {
394
+ ruleId: "SCAFFOLD-02",
395
+ message: "composed header failed the closed-block parse-back — file left untouched",
396
+ });
397
+ }
398
+ return {
399
+ disposition: purpose.sentinel ? "sentinel" : "inserted",
400
+ source: next,
401
+ repairs: ["inserted-header", ...(purpose.sentinel ? ["sentinel-purpose"] : [])],
402
+ };
403
+ }
404
+ // ── Repair path: append-only merge inside the header comment ──────────────
405
+ // Staged edits: every stage recomputes positions against the post-edit text
406
+ // so coordinates never mix bases.
407
+ let next = source;
408
+ const repairs = [];
409
+ let usedSentinel = false;
410
+ const prefixFor = (s) => s.style === "line" ? (getLineCommentPrefix(pathFromRoot) ?? "# ") : "";
411
+ const reheader = () => {
412
+ const s = findHeaderSpan(next, pathFromRoot);
413
+ return s ? { span: s, text: next.slice(s.start, s.end) } : null;
414
+ };
415
+ const lineWrap = (block, s) => {
416
+ const prefix = prefixFor(s);
417
+ return prefix === ""
418
+ ? block
419
+ : block
420
+ .split("\n")
421
+ .map((l) => prefix + l)
422
+ .join("\n");
423
+ };
424
+ // Line-style spans may only be edited at line boundaries — a mid-line
425
+ // insert either splits the prefix run or glues text onto a comment line.
426
+ // insertAt: before the line containing absPos. appendAt: past the run's
427
+ // end for line style (closeStart === end there), before the comment
428
+ // terminator otherwise. Line-style text needs a leading "\n".
429
+ const insertAt = (absPos, h) => prefixFor(h.span) !== "" ? lineStartOf(next, absPos) : absPos;
430
+ const appendAt = (h) => prefixFor(h.span) !== "" ? h.span.end : h.span.closeStart;
431
+ const appendText = (block, s) => prefixFor(s) !== "" ? `\n${block}` : `${block}\n`;
432
+ const stageGuard = () => ({
433
+ disposition: "skipped",
434
+ source,
435
+ repairs: [],
436
+ skipReason: "unrepairable malformation",
437
+ diagnostic: {
438
+ ruleId: "SCAFFOLD-02",
439
+ message: "header comment lost between repair stages — file left untouched",
440
+ },
441
+ });
442
+ // Stage 1 — close any compass tag left open inside the header. The close
443
+ // anchors before the next sibling tag's open (a swallowed sibling) or
444
+ // before the header comment's own terminator. All anchor positions are
445
+ // header-relative and shift by h.span.start exactly once.
446
+ {
447
+ const h = reheader();
448
+ if (!h)
449
+ return stageGuard();
450
+ const prefix = prefixFor(h.span);
451
+ const closeEdits = [];
452
+ for (const tag of COMPASS_TAGS) {
453
+ if (!hasUnclosedTag(h.text, tag))
454
+ continue;
455
+ const openAt = h.text.indexOf(`<${tag}>`);
456
+ const later = COMPASS_TAGS.slice(COMPASS_TAGS.indexOf(tag) + 1)
457
+ .map((t) => h.text.indexOf(`<${t}>`, openAt + 1))
458
+ .filter((i) => i >= 0)
459
+ .sort((a, b) => a - b);
460
+ let at;
461
+ let closeLine;
462
+ if (later.length > 0 && prefix !== "") {
463
+ // Anchor at the sibling tag's line start — a mid-line insert would
464
+ // split the contiguous prefix run line comments depend on.
465
+ at = h.text.lastIndexOf("\n", later[0] - 1) + 1;
466
+ closeLine = `${prefix}</${tag}>\n`;
467
+ }
468
+ else if (later.length > 0) {
469
+ at = later[0];
470
+ closeLine = `</${tag}>\n`;
471
+ }
472
+ else if (prefix !== "") {
473
+ // End of the prefix run — open a fresh line rather than gluing onto
474
+ // the last comment line's tail.
475
+ at = h.span.end - h.span.start;
476
+ closeLine = `\n${prefix}</${tag}>`;
477
+ }
478
+ else {
479
+ at = h.span.closeStart - h.span.start;
480
+ closeLine = `</${tag}>\n`;
481
+ }
482
+ closeEdits.push({ start: h.span.start + at, end: h.span.start + at, text: closeLine });
483
+ repairs.push(`closed-${tag.toLowerCase().replace(/_/g, "-")}`);
484
+ }
485
+ next = applyEdits(next, closeEdits, { style: h.span.style, file: pathFromRoot });
486
+ }
487
+ // Stage 2 — contract-level repairs: missing contract, missing/unclosed
488
+ // purpose, missing/unclosed/item-less non-goals.
489
+ {
490
+ const h = reheader();
491
+ if (!h)
492
+ return stageGuard();
493
+ const edits = [];
494
+ const contract = blockSpan(h.text, "MODULE_CONTRACT");
495
+ if (!contract) {
496
+ // The header comment carries stray tags but no contract — compose one
497
+ // inside the comment. Canonical order puts MODULE_CONTRACT first, so it
498
+ // anchors before the earliest stray block (or at the run's end).
499
+ const purpose = derivePurpose(input);
500
+ usedSentinel = purpose.sentinel;
501
+ const insertion = lineWrap(contractBlock(purpose.text, [SENTINEL_NONGOAL]), h.span);
502
+ const strayIdx = ["<KEY_DECISIONS>", "<CHANGE_SUMMARY>"]
503
+ .map((t) => h.text.indexOf(t))
504
+ .filter((i) => i >= 0)
505
+ .sort((a, b) => a - b)[0];
506
+ if (strayIdx !== undefined) {
507
+ const at = insertAt(h.span.start + strayIdx, h);
508
+ edits.push({ start: at, end: at, text: `${insertion}\n` });
509
+ }
510
+ else {
511
+ const at = appendAt(h);
512
+ edits.push({ start: at, end: at, text: appendText(insertion, h.span) });
513
+ }
514
+ repairs.push("inserted-module-contract");
515
+ }
516
+ else {
517
+ const contractText = h.text.slice(contract.start, contract.end);
518
+ const base = h.span.start + contract.start;
519
+ if (!contractText.includes("<purpose>")) {
520
+ const purpose = derivePurpose(input);
521
+ usedSentinel = purpose.sentinel;
522
+ const openEnd = base + "<MODULE_CONTRACT>".length;
523
+ edits.push({
524
+ start: openEnd,
525
+ end: openEnd,
526
+ text: `\n${lineWrap(`<purpose>${purpose.text}</purpose>`, h.span)}`,
527
+ order: 20,
528
+ });
529
+ repairs.push(purpose.sentinel ? "sentinel-purpose" : "inserted-purpose");
530
+ }
531
+ else if (!contractText.includes("</purpose>")) {
532
+ // An unclosed <purpose> swallows its siblings — close it before the
533
+ // next inner tag or the contract close, whichever comes first.
534
+ const purposeOpen = contractText.indexOf("<purpose>");
535
+ const following = ["<non-goals>", "</MODULE_CONTRACT>"]
536
+ .map((t) => contractText.indexOf(t, purposeOpen + 1))
537
+ .filter((i) => i >= 0)
538
+ .sort((a, b) => a - b);
539
+ // `following` is contractText-relative; contract.end is h.text-relative.
540
+ const absAt = following.length > 0 ? base + following[0] : h.span.start + contract.end;
541
+ // Same-line siblings (`# <purpose>t <non-goals>`) close inline —
542
+ // a line-start insert would emit the close before its own open and
543
+ // a prefixed insert would split the line leaving a bare tag tail.
544
+ const purposeAbs = base + purposeOpen;
545
+ const sameLine = prefixFor(h.span) !== "" && lineStartOf(next, absAt) === lineStartOf(next, purposeAbs);
546
+ const anchor = sameLine ? absAt : insertAt(absAt, h);
547
+ edits.push({
548
+ start: anchor,
549
+ end: anchor,
550
+ text: sameLine ? `</purpose> ` : `${lineWrap("</purpose>", h.span)}\n`,
551
+ order: 10,
552
+ });
553
+ repairs.push("closed-purpose");
554
+ }
555
+ const ng = contractText.indexOf("<non-goals>");
556
+ if (ng < 0) {
557
+ const anchor = insertAt(base + contractText.indexOf("</MODULE_CONTRACT>"), h);
558
+ edits.push({
559
+ start: anchor,
560
+ end: anchor,
561
+ text: `${lineWrap(`<non-goals>\n <item>${SENTINEL_NONGOAL}</item>\n</non-goals>`, h.span)}\n`,
562
+ order: 30,
563
+ });
564
+ repairs.push("inserted-non-goals");
565
+ }
566
+ else {
567
+ let ngEnd = contractText.indexOf("</non-goals>", ng);
568
+ if (ngEnd < 0) {
569
+ const anchor = insertAt(base + contractText.indexOf("</MODULE_CONTRACT>"), h);
570
+ edits.push({
571
+ start: anchor,
572
+ end: anchor,
573
+ text: `${lineWrap("</non-goals>", h.span)}\n`,
574
+ order: 40,
575
+ });
576
+ repairs.push("closed-non-goals");
577
+ ngEnd = contractText.indexOf("</MODULE_CONTRACT>");
578
+ }
579
+ const inner = contractText.slice(ng + "<non-goals>".length, ngEnd);
580
+ const itemOpens = (inner.match(/<item>/g) ?? []).length;
581
+ const itemCloses = (inner.match(/<\/item>/g) ?? []).length;
582
+ if (itemOpens === 0) {
583
+ const bareLines = inner
584
+ .split("\n")
585
+ .map((l) => l.trim().replace(/^[#;]+\s?/, ""))
586
+ .filter((l) => l.length > 0 && !l.startsWith("*") && !l.startsWith("//"));
587
+ const items = bareLines.length > 0 ? bareLines : [SENTINEL_NONGOAL];
588
+ const ngPrefix = prefixFor(h.span);
589
+ if (ngPrefix !== "") {
590
+ // Line style: replace whole prefixed lines — the line after
591
+ // <non-goals> through the line before </non-goals>.
592
+ const innerStart = next.indexOf("\n", base + ng) + 1;
593
+ const innerEnd = lineStartOf(next, base + ngEnd);
594
+ if (innerStart > 0 && innerStart <= innerEnd) {
595
+ edits.push({
596
+ start: innerStart,
597
+ end: innerEnd,
598
+ text: items.map((i) => `${ngPrefix} <item>${i}</item>\n`).join(""),
599
+ });
600
+ repairs.push("non-goals-items");
601
+ }
602
+ }
603
+ else {
604
+ edits.push({
605
+ start: base + ng + "<non-goals>".length,
606
+ end: base + ngEnd,
607
+ text: `\n${items.map((i) => ` <item>${i}</item>`).join("\n")}\n`,
608
+ });
609
+ repairs.push("non-goals-items");
610
+ }
611
+ }
612
+ else if (itemOpens !== itemCloses) {
613
+ // Same-line `<item>…</non-goals>` closes inline — a line-start
614
+ // insert would emit the close before its own open.
615
+ const itemOpenAbs = base + ng + "<non-goals>".length + inner.lastIndexOf("<item>");
616
+ const itemAbsEnd = base + ngEnd;
617
+ const sameLine = prefixFor(h.span) !== "" &&
618
+ lineStartOf(next, itemAbsEnd) === lineStartOf(next, itemOpenAbs);
619
+ const anchor = sameLine ? itemAbsEnd : insertAt(itemAbsEnd, h);
620
+ edits.push({
621
+ start: anchor,
622
+ end: anchor,
623
+ text: sameLine ? `</item> ` : `${lineWrap("</item>", h.span)}\n`,
624
+ order: 10,
625
+ });
626
+ repairs.push("closed-item");
627
+ }
628
+ }
629
+ }
630
+ next = applyEdits(next, edits, { style: h.span.style, file: pathFromRoot });
631
+ }
632
+ // Stage 3 — KEY_DECISIONS required by layer/risk but absent.
633
+ {
634
+ const h = reheader();
635
+ if (!h)
636
+ return stageGuard();
637
+ if (keyDecisionsRequired && !h.text.includes("<KEY_DECISIONS>")) {
638
+ if (riskClass === "high" && aiInvariants.length === 0) {
639
+ return skipped("high-risk file requires an @ai-invariant — header authorship stays agent work", source);
640
+ }
641
+ const kd = lineWrap(keyDecisionsBlock(aiInvariants.length > 0 ? aiInvariants : [TODO_ITEM]), h.span);
642
+ const mc = blockSpan(h.text, "MODULE_CONTRACT");
643
+ if (mc) {
644
+ next = applyEdits(next, [
645
+ {
646
+ start: h.span.start + mc.end,
647
+ end: h.span.start + mc.end,
648
+ text: `\n${kd}`,
649
+ },
650
+ ], { style: h.span.style, file: pathFromRoot });
651
+ }
652
+ else {
653
+ const at = appendAt(h);
654
+ next = applyEdits(next, [{ start: at, end: at, text: appendText(kd, h.span) }], {
655
+ style: h.span.style,
656
+ file: pathFromRoot,
657
+ });
658
+ }
659
+ repairs.push("inserted-key-decisions");
660
+ }
661
+ }
662
+ // Stage 4 — CHANGE_SUMMARY absent entirely (unclosed was repaired in stage 1).
663
+ {
664
+ const h = reheader();
665
+ if (!h)
666
+ return stageGuard();
667
+ if (!h.text.includes("<CHANGE_SUMMARY>")) {
668
+ const cs = lineWrap("<CHANGE_SUMMARY>\n</CHANGE_SUMMARY>", h.span);
669
+ const anchor = blockSpan(h.text, "KEY_DECISIONS")?.end ?? blockSpan(h.text, "MODULE_CONTRACT")?.end;
670
+ if (anchor !== undefined) {
671
+ next = applyEdits(next, [
672
+ {
673
+ start: h.span.start + anchor,
674
+ end: h.span.start + anchor,
675
+ text: `\n${cs}`,
676
+ },
677
+ ], { style: h.span.style, file: pathFromRoot });
678
+ }
679
+ else {
680
+ const at = appendAt(h);
681
+ next = applyEdits(next, [{ start: at, end: at, text: appendText(cs, h.span) }], {
682
+ style: h.span.style,
683
+ file: pathFromRoot,
684
+ });
685
+ }
686
+ repairs.push("inserted-change-summary");
687
+ }
688
+ }
689
+ if (next === source) {
690
+ return { disposition: "unchanged", source, repairs: [] };
691
+ }
692
+ if (!closesCleanly(next, pathFromRoot)) {
693
+ return skipped("unrepairable malformation", source, {
694
+ ruleId: "SCAFFOLD-02",
695
+ message: "repaired header failed the closed-block parse-back — file left untouched",
696
+ });
697
+ }
698
+ return {
699
+ disposition: usedSentinel ? "sentinel" : "repaired",
700
+ source: next,
701
+ repairs: [...new Set(repairs)],
702
+ };
703
+ }
704
+ /**
705
+ * Every compass tag present in the header comment closes inside it — inner
706
+ * tags included, so "unchanged" stays aligned with what compass.validate
707
+ * reports (its extractor requires close tags too).
708
+ */
709
+ function closesCleanly(source, path) {
710
+ const span = findHeaderSpan(source, path);
711
+ if (!span)
712
+ return false;
713
+ const header = source.slice(span.start, span.end);
714
+ for (const tag of COMPASS_TAGS) {
715
+ if (hasUnclosedTag(header, tag))
716
+ return false;
717
+ }
718
+ const contract = blockSpan(header, "MODULE_CONTRACT");
719
+ if (!contract)
720
+ return false;
721
+ const contractText = header.slice(contract.start, contract.end);
722
+ if (!contractText.includes("<purpose>") || !contractText.includes("</purpose>"))
723
+ return false;
724
+ const ng = blockSpan(contractText, "non-goals");
725
+ if (!ng)
726
+ return false;
727
+ const ngText = contractText.slice(ng.start, ng.end);
728
+ const itemOpens = (ngText.match(/<item>/g) ?? []).length;
729
+ const itemCloses = (ngText.match(/<\/item>/g) ?? []).length;
730
+ if (itemOpens === 0 || itemOpens !== itemCloses)
731
+ return false;
732
+ return header.includes("<CHANGE_SUMMARY>");
733
+ }
734
+ /** Workspace-relative path for an explicit --files target (mirrors migrate's toTarget). */
735
+ export function explicitWorkspaceRelativePath(absPath, workspaceRoot, policy) {
736
+ const segments = getRelativeSegments(absPath, workspaceRoot);
737
+ return getWorkspaceRelativeSegments(segments, policy).join("/");
738
+ }
739
+ //# sourceMappingURL=compass-header-scaffold.js.map