@warpgogol/forge 7.0.0 → 8.0.4

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 (455) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/bin/cli.js +6 -12
  3. package/bin/cli.ts +3 -2
  4. package/bin/resolve-entry.js +24 -0
  5. package/dist/bin/cli.js +3 -2
  6. package/dist/bin/cli.js.map +1 -1
  7. package/dist/os/authority/authority.module.d.ts +3 -0
  8. package/dist/os/authority/authority.module.d.ts.map +1 -0
  9. package/dist/os/authority/authority.module.js +169 -0
  10. package/dist/os/authority/authority.module.js.map +1 -0
  11. package/dist/os/authority/handlers/delegate-revoke.d.ts +15 -0
  12. package/dist/os/authority/handlers/delegate-revoke.d.ts.map +1 -0
  13. package/dist/os/authority/handlers/delegate-revoke.js +91 -0
  14. package/dist/os/authority/handlers/delegate-revoke.js.map +1 -0
  15. package/dist/os/authority/handlers/delegate.d.ts +14 -0
  16. package/dist/os/authority/handlers/delegate.d.ts.map +1 -0
  17. package/dist/os/authority/handlers/delegate.js +134 -0
  18. package/dist/os/authority/handlers/delegate.js.map +1 -0
  19. package/dist/os/authority/handlers/delegation-list.d.ts +12 -0
  20. package/dist/os/authority/handlers/delegation-list.d.ts.map +1 -0
  21. package/dist/os/authority/handlers/delegation-list.js +54 -0
  22. package/dist/os/authority/handlers/delegation-list.js.map +1 -0
  23. package/dist/os/authority/handlers/delegation-validate.d.ts +11 -0
  24. package/dist/os/authority/handlers/delegation-validate.d.ts.map +1 -0
  25. package/dist/os/authority/handlers/delegation-validate.js +132 -0
  26. package/dist/os/authority/handlers/delegation-validate.js.map +1 -0
  27. package/dist/os/authority/helpers.d.ts +36 -0
  28. package/dist/os/authority/helpers.d.ts.map +1 -0
  29. package/dist/os/authority/helpers.js +83 -0
  30. package/dist/os/authority/helpers.js.map +1 -0
  31. package/dist/os/authority/index.d.ts +2 -0
  32. package/dist/os/authority/index.d.ts.map +1 -0
  33. package/dist/os/authority/index.js +14 -0
  34. package/dist/os/authority/index.js.map +1 -0
  35. package/dist/os/compass/comment-safety.d.ts +83 -0
  36. package/dist/os/compass/comment-safety.d.ts.map +1 -0
  37. package/dist/os/compass/comment-safety.js +305 -0
  38. package/dist/os/compass/comment-safety.js.map +1 -0
  39. package/dist/os/compass/compass.module.d.ts.map +1 -1
  40. package/dist/os/compass/compass.module.js +47 -4
  41. package/dist/os/compass/compass.module.js.map +1 -1
  42. package/dist/os/compass/handlers/compass-change-summary-handler.d.ts +2 -1
  43. package/dist/os/compass/handlers/compass-change-summary-handler.d.ts.map +1 -1
  44. package/dist/os/compass/handlers/compass-change-summary-handler.js +34 -10
  45. package/dist/os/compass/handlers/compass-change-summary-handler.js.map +1 -1
  46. package/dist/os/compass/handlers/compass-docs-scaffold.d.ts.map +1 -1
  47. package/dist/os/compass/handlers/compass-docs-scaffold.js +54 -17
  48. package/dist/os/compass/handlers/compass-docs-scaffold.js.map +1 -1
  49. package/dist/os/compass/handlers/compass-header-scaffold-handler.d.ts +14 -0
  50. package/dist/os/compass/handlers/compass-header-scaffold-handler.d.ts.map +1 -0
  51. package/dist/os/compass/handlers/compass-header-scaffold-handler.js +261 -0
  52. package/dist/os/compass/handlers/compass-header-scaffold-handler.js.map +1 -0
  53. package/dist/os/compass/handlers/compass-header-scaffold.d.ts +31 -0
  54. package/dist/os/compass/handlers/compass-header-scaffold.d.ts.map +1 -0
  55. package/dist/os/compass/handlers/compass-header-scaffold.js +739 -0
  56. package/dist/os/compass/handlers/compass-header-scaffold.js.map +1 -0
  57. package/dist/os/compass/handlers/compass-inventory-handler.d.ts.map +1 -1
  58. package/dist/os/compass/handlers/compass-inventory-handler.js +8 -4
  59. package/dist/os/compass/handlers/compass-inventory-handler.js.map +1 -1
  60. package/dist/os/compass/handlers/compass-inventory.d.ts +6 -0
  61. package/dist/os/compass/handlers/compass-inventory.d.ts.map +1 -1
  62. package/dist/os/compass/handlers/compass-inventory.js +28 -13
  63. package/dist/os/compass/handlers/compass-inventory.js.map +1 -1
  64. package/dist/os/compass/handlers/compass-migrate-handler.d.ts.map +1 -1
  65. package/dist/os/compass/handlers/compass-migrate-handler.js +12 -26
  66. package/dist/os/compass/handlers/compass-migrate-handler.js.map +1 -1
  67. package/dist/os/compass/handlers/compass-migrate.d.ts +15 -2
  68. package/dist/os/compass/handlers/compass-migrate.d.ts.map +1 -1
  69. package/dist/os/compass/handlers/compass-migrate.js +58 -20
  70. package/dist/os/compass/handlers/compass-migrate.js.map +1 -1
  71. package/dist/os/compass/handlers/git-revision.d.ts +10 -0
  72. package/dist/os/compass/handlers/git-revision.d.ts.map +1 -1
  73. package/dist/os/compass/handlers/git-revision.js +58 -4
  74. package/dist/os/compass/handlers/git-revision.js.map +1 -1
  75. package/dist/os/compass/handlers/summary-record.d.ts +20 -5
  76. package/dist/os/compass/handlers/summary-record.d.ts.map +1 -1
  77. package/dist/os/compass/handlers/summary-record.js +175 -44
  78. package/dist/os/compass/handlers/summary-record.js.map +1 -1
  79. package/dist/os/compass/index.d.ts +1 -0
  80. package/dist/os/compass/index.d.ts.map +1 -1
  81. package/dist/os/compass/index.js +2 -0
  82. package/dist/os/compass/index.js.map +1 -1
  83. package/dist/os/compass/policy.d.ts +9 -0
  84. package/dist/os/compass/policy.d.ts.map +1 -1
  85. package/dist/os/compass/policy.js +11 -2
  86. package/dist/os/compass/policy.js.map +1 -1
  87. package/dist/os/core/core.module.js +1 -1
  88. package/dist/os/core/handlers/package-health.d.ts.map +1 -1
  89. package/dist/os/core/handlers/package-health.js +1 -6
  90. package/dist/os/core/handlers/package-health.js.map +1 -1
  91. package/dist/os/queue/types.d.ts +2 -0
  92. package/dist/os/queue/types.d.ts.map +1 -1
  93. package/dist/os/queue/types.js +3 -1
  94. package/dist/os/queue/types.js.map +1 -1
  95. package/dist/os/rfc/acceptance.d.ts.map +1 -1
  96. package/dist/os/rfc/acceptance.js +51 -1
  97. package/dist/os/rfc/acceptance.js.map +1 -1
  98. package/dist/os/rfc/decision-log.d.ts.map +1 -1
  99. package/dist/os/rfc/decision-log.js +21 -3
  100. package/dist/os/rfc/decision-log.js.map +1 -1
  101. package/dist/os/rfc/dna-trace.d.ts +2 -0
  102. package/dist/os/rfc/dna-trace.d.ts.map +1 -1
  103. package/dist/os/rfc/dna-trace.js +13 -4
  104. package/dist/os/rfc/dna-trace.js.map +1 -1
  105. package/dist/os/rfc/handlers/implement-stamp-origin.d.ts +37 -0
  106. package/dist/os/rfc/handlers/implement-stamp-origin.d.ts.map +1 -0
  107. package/dist/os/rfc/handlers/implement-stamp-origin.js +118 -0
  108. package/dist/os/rfc/handlers/implement-stamp-origin.js.map +1 -0
  109. package/dist/os/rfc/handlers/implement-stamp.d.ts +41 -1
  110. package/dist/os/rfc/handlers/implement-stamp.d.ts.map +1 -1
  111. package/dist/os/rfc/handlers/implement-stamp.js +594 -81
  112. package/dist/os/rfc/handlers/implement-stamp.js.map +1 -1
  113. package/dist/os/rfc/handlers/rfc-evidence-sync.d.ts +42 -0
  114. package/dist/os/rfc/handlers/rfc-evidence-sync.d.ts.map +1 -0
  115. package/dist/os/rfc/handlers/rfc-evidence-sync.js +147 -0
  116. package/dist/os/rfc/handlers/rfc-evidence-sync.js.map +1 -0
  117. package/dist/os/rfc/handlers/validate-rules.d.ts +9 -1
  118. package/dist/os/rfc/handlers/validate-rules.d.ts.map +1 -1
  119. package/dist/os/rfc/handlers/validate-rules.js +90 -9
  120. package/dist/os/rfc/handlers/validate-rules.js.map +1 -1
  121. package/dist/os/rfc/reachable-symbol.d.ts +17 -0
  122. package/dist/os/rfc/reachable-symbol.d.ts.map +1 -0
  123. package/dist/os/rfc/reachable-symbol.js +376 -0
  124. package/dist/os/rfc/reachable-symbol.js.map +1 -0
  125. package/dist/os/rfc/rfc.module.d.ts.map +1 -1
  126. package/dist/os/rfc/rfc.module.js +89 -5
  127. package/dist/os/rfc/rfc.module.js.map +1 -1
  128. package/dist/os/rfc/types.d.ts +89 -12
  129. package/dist/os/rfc/types.d.ts.map +1 -1
  130. package/dist/os/rfc/types.js +17 -10
  131. package/dist/os/rfc/types.js.map +1 -1
  132. package/dist/os/rfc/verification-evidence.d.ts +10 -1
  133. package/dist/os/rfc/verification-evidence.d.ts.map +1 -1
  134. package/dist/os/rfc/verification-evidence.js +175 -10
  135. package/dist/os/rfc/verification-evidence.js.map +1 -1
  136. package/dist/os/rfc/verification-origin.d.ts +58 -0
  137. package/dist/os/rfc/verification-origin.d.ts.map +1 -0
  138. package/dist/os/rfc/verification-origin.js +346 -0
  139. package/dist/os/rfc/verification-origin.js.map +1 -0
  140. package/dist/os/rfc/verification-refresh.d.ts.map +1 -1
  141. package/dist/os/rfc/verification-refresh.js +11 -1
  142. package/dist/os/rfc/verification-refresh.js.map +1 -1
  143. package/dist/os/rfc/verify-workspace.d.ts +23 -0
  144. package/dist/os/rfc/verify-workspace.d.ts.map +1 -0
  145. package/dist/os/rfc/verify-workspace.js +278 -0
  146. package/dist/os/rfc/verify-workspace.js.map +1 -0
  147. package/dist/os/session/handlers/metrics-rfc.d.ts.map +1 -1
  148. package/dist/os/session/handlers/metrics-rfc.js +3 -0
  149. package/dist/os/session/handlers/metrics-rfc.js.map +1 -1
  150. package/dist/os/session/handlers/save.d.ts.map +1 -1
  151. package/dist/os/session/handlers/save.js +41 -10
  152. package/dist/os/session/handlers/save.js.map +1 -1
  153. package/dist/os/spec/spec-status.d.ts.map +1 -1
  154. package/dist/os/spec/spec-status.js +5 -23
  155. package/dist/os/spec/spec-status.js.map +1 -1
  156. package/dist/os/spec/spec-validate.d.ts.map +1 -1
  157. package/dist/os/spec/spec-validate.js +30 -9
  158. package/dist/os/spec/spec-validate.js.map +1 -1
  159. package/dist/os/workflow/handlers.d.ts +0 -4
  160. package/dist/os/workflow/handlers.d.ts.map +1 -1
  161. package/dist/os/workflow/handlers.js +9 -36
  162. package/dist/os/workflow/handlers.js.map +1 -1
  163. package/dist/os/workflow/index.d.ts +2 -2
  164. package/dist/os/workflow/index.d.ts.map +1 -1
  165. package/dist/os/workflow/index.js +1 -1
  166. package/dist/os/workflow/index.js.map +1 -1
  167. package/dist/os/workflow/types.d.ts +0 -19
  168. package/dist/os/workflow/types.d.ts.map +1 -1
  169. package/dist/os/workflow/types.js +0 -2
  170. package/dist/os/workflow/types.js.map +1 -1
  171. package/dist/os/workflow/workflow.module.d.ts.map +1 -1
  172. package/dist/os/workflow/workflow.module.js +6 -15
  173. package/dist/os/workflow/workflow.module.js.map +1 -1
  174. package/dist/src/authority/delegations.d.ts +108 -0
  175. package/dist/src/authority/delegations.d.ts.map +1 -0
  176. package/dist/src/authority/delegations.js +217 -0
  177. package/dist/src/authority/delegations.js.map +1 -0
  178. package/dist/src/authority/index.d.ts +3 -0
  179. package/dist/src/authority/index.d.ts.map +1 -0
  180. package/dist/src/authority/index.js +17 -0
  181. package/dist/src/authority/index.js.map +1 -0
  182. package/dist/src/authority/signing.d.ts +8 -0
  183. package/dist/src/authority/signing.d.ts.map +1 -0
  184. package/dist/src/authority/signing.js +72 -0
  185. package/dist/src/authority/signing.js.map +1 -0
  186. package/dist/src/config/forge-config.d.ts +5 -0
  187. package/dist/src/config/forge-config.d.ts.map +1 -1
  188. package/dist/src/config/forge-config.js +5 -2
  189. package/dist/src/config/forge-config.js.map +1 -1
  190. package/dist/src/onboarding/agents-generate.js +1 -1
  191. package/dist/src/onboarding/doctor.js +3 -3
  192. package/dist/src/onboarding/doctor.js.map +1 -1
  193. package/dist/src/onboarding/init.js +2 -2
  194. package/dist/src/onboarding/nested-agents-templates.js +1 -1
  195. package/dist/src/onboarding/prettierignore.js +1 -1
  196. package/dist/src/onboarding/upgrade.js +2 -2
  197. package/dist/src/onboarding/workspace-discovery.js +1 -1
  198. package/dist/src/profiles/profile-schema.d.ts +2 -0
  199. package/dist/src/profiles/profile-schema.d.ts.map +1 -1
  200. package/dist/src/profiles/profile-schema.js +1 -0
  201. package/dist/src/profiles/profile-schema.js.map +1 -1
  202. package/dist/src/profiles/stack-profile.d.ts +1 -0
  203. package/dist/src/profiles/stack-profile.d.ts.map +1 -1
  204. package/dist/src/types.d.ts +23 -0
  205. package/dist/src/types.d.ts.map +1 -1
  206. package/dist/src/types.js +2 -1
  207. package/dist/src/types.js.map +1 -1
  208. package/docs/reference/cli.md +0 -1
  209. package/docs/reference/programmatic-api.md +1 -1
  210. package/os/adr/handlers/validate.test.ts +14 -0
  211. package/os/authority/authority.module.ts +183 -0
  212. package/os/authority/authority.test.ts +328 -0
  213. package/os/authority/handlers/delegate-revoke.ts +123 -0
  214. package/os/authority/handlers/delegate.ts +190 -0
  215. package/os/authority/handlers/delegation-list.ts +80 -0
  216. package/os/authority/handlers/delegation-validate.ts +231 -0
  217. package/os/authority/helpers.ts +111 -0
  218. package/os/authority/index.ts +14 -0
  219. package/os/compass/comment-safety.ts +331 -0
  220. package/os/compass/compass.module.ts +50 -4
  221. package/os/compass/handlers/compass-change-summary-handler.ts +41 -11
  222. package/os/compass/handlers/compass-docs-scaffold.ts +59 -17
  223. package/os/compass/handlers/compass-game-extensions.test.ts +3 -7
  224. package/os/compass/handlers/compass-header-scaffold-handler.ts +352 -0
  225. package/os/compass/handlers/compass-header-scaffold.ts +847 -0
  226. package/os/compass/handlers/compass-inventory-handler.ts +9 -4
  227. package/os/compass/handlers/compass-inventory.ts +29 -13
  228. package/os/compass/handlers/compass-migrate-handler.ts +13 -27
  229. package/os/compass/handlers/compass-migrate.ts +77 -21
  230. package/os/compass/handlers/git-revision.ts +59 -4
  231. package/os/compass/handlers/resolve-scan-root-package.test.ts +14 -0
  232. package/os/compass/handlers/resolve-scan-root-workpiece.test.ts +14 -0
  233. package/os/compass/handlers/summary-record.ts +194 -41
  234. package/os/compass/handlers/tests/compass-audit-plan.test.ts +6 -0
  235. package/os/compass/handlers/tests/compass-audit-record.test.ts +6 -0
  236. package/os/compass/handlers/tests/compass-audit-validate.test.ts +6 -0
  237. package/os/compass/handlers/tests/compass-change-summary-handler.test.ts +131 -0
  238. package/os/compass/handlers/tests/compass-docs-validate.test.ts +6 -0
  239. package/os/compass/handlers/tests/compass-header-scaffold.test.ts +896 -0
  240. package/os/compass/handlers/tests/compass-ledger-scope.test.ts +6 -0
  241. package/os/compass/handlers/tests/compass-migrate.test.ts +87 -9
  242. package/os/compass/handlers/tests/compass-policy.test.ts +1 -1
  243. package/os/compass/handlers/tests/compass-text-safety.test.ts +271 -0
  244. package/os/compass/handlers/tests/compass-v2-contract.test.ts +52 -3
  245. package/os/compass/handlers/tests/summary-record.test.ts +324 -3
  246. package/os/compass/index.ts +15 -0
  247. package/os/compass/policy.ts +27 -2
  248. package/os/core/core.module.ts +1 -1
  249. package/os/core/handlers/invariant-engine.test.ts +3 -1
  250. package/os/core/handlers/note-frontmatter-validate.test.ts +6 -1
  251. package/os/core/handlers/note-link-validate.test.ts +6 -1
  252. package/os/core/handlers/note-orphan-detect.test.ts +6 -1
  253. package/os/core/handlers/package-health.test.ts +6 -0
  254. package/os/core/handlers/package-health.ts +1 -6
  255. package/os/mission/handlers/archive.test.ts +14 -0
  256. package/os/naming/naming-convention.test.ts +14 -0
  257. package/os/queue/decision-ledger.test.ts +27 -4
  258. package/os/queue/queue-validate.test.ts +14 -0
  259. package/os/queue/types.ts +3 -1
  260. package/os/rfc/acceptance-reachable.test.ts +146 -0
  261. package/os/rfc/acceptance.test.ts +25 -0
  262. package/os/rfc/acceptance.ts +51 -1
  263. package/os/rfc/decision-log.ts +22 -4
  264. package/os/rfc/dna-trace.ts +17 -5
  265. package/os/rfc/frontmatter-io.test.ts +14 -0
  266. package/os/rfc/handlers/implement-stamp-acceptance-verification.test.ts +81 -0
  267. package/os/rfc/handlers/implement-stamp-binding.test.ts +79 -0
  268. package/os/rfc/handlers/implement-stamp-origin.test.ts +132 -0
  269. package/os/rfc/handlers/implement-stamp-origin.ts +154 -0
  270. package/os/rfc/handlers/implement-stamp-stale.test.ts +20 -2
  271. package/os/rfc/handlers/implement-stamp.ts +714 -87
  272. package/os/rfc/handlers/lifecycle.test.ts +14 -0
  273. package/os/rfc/handlers/rfc-evidence-sync.ts +221 -0
  274. package/os/rfc/handlers/validate-rules-rfc0997.test.ts +14 -0
  275. package/os/rfc/handlers/validate-rules-rfc1006.test.ts +14 -0
  276. package/os/rfc/handlers/validate-rules-rfc1330.test.ts +120 -0
  277. package/os/rfc/handlers/validate-rules-rfc1334.test.ts +65 -0
  278. package/os/rfc/handlers/validate-rules.test.ts +14 -0
  279. package/os/rfc/handlers/validate-rules.ts +122 -13
  280. package/os/rfc/handlers/validate.test.ts +4 -3
  281. package/os/rfc/reachable-symbol.ts +441 -0
  282. package/os/rfc/rfc-0000-template.md +3 -0
  283. package/os/rfc/rfc-create-concurrent.test.ts +6 -0
  284. package/os/rfc/rfc-create-hint.test.ts +6 -0
  285. package/os/rfc/rfc-read-only-no-side-effects.test.ts +6 -0
  286. package/os/rfc/rfc.module.ts +95 -5
  287. package/os/rfc/types.ts +116 -12
  288. package/os/rfc/verification-emit-check.test.ts +14 -0
  289. package/os/rfc/verification-emit-freshness.test.ts +415 -0
  290. package/os/rfc/verification-emit.test.ts +14 -0
  291. package/os/rfc/verification-evidence.ts +230 -10
  292. package/os/rfc/verification-normalize.test.ts +14 -0
  293. package/os/rfc/verification-origin.test.ts +236 -0
  294. package/os/rfc/verification-origin.ts +417 -0
  295. package/os/rfc/verification-refresh.test.ts +14 -0
  296. package/os/rfc/verification-refresh.ts +12 -1
  297. package/os/rfc/verifier/rfc-1333/imp12-binding.acceptance.test.ts +78 -0
  298. package/os/rfc/verifier/rfc-1333/imp12-gate.acceptance.test.ts +81 -0
  299. package/os/rfc/verifier/rfc-1333/skills-and-types.acceptance.test.ts +50 -0
  300. package/os/rfc/verifier/rfc-1333/verify-workspace.acceptance.test.ts +103 -0
  301. package/os/rfc/verify-workspace.test.ts +122 -0
  302. package/os/rfc/verify-workspace.ts +342 -0
  303. package/os/session/handlers/metrics-rfc.ts +3 -0
  304. package/os/session/handlers/save.ts +43 -9
  305. package/os/spec/spec-status.test.ts +130 -0
  306. package/os/spec/spec-status.ts +5 -18
  307. package/os/spec/spec-validate.test.ts +76 -1
  308. package/os/spec/spec-validate.ts +26 -7
  309. package/os/workflow/handlers.ts +8 -42
  310. package/os/workflow/index.ts +1 -4
  311. package/os/workflow/types.ts +0 -22
  312. package/os/workflow/workflow.module.ts +6 -16
  313. package/package.json +13 -1
  314. package/skills/_shared/agent-operating-model.md +1 -1
  315. package/skills/_shared/fo-pipeline-conventions.md +1 -0
  316. package/skills/fo/fo-add-tests/SKILL.md +14 -0
  317. package/skills/fo/fo-fix/SKILL.md +2 -1
  318. package/skills/fo/fo-handoff/SKILL.md +1 -1
  319. package/skills/fo/fo-idea-create-rfc/acceptance-criteria-standard.md +8 -0
  320. package/skills/fo/fo-idea-i-just-want-to-see-the-result/SKILL.md +4 -2
  321. package/skills/fo/fo-idea-implement/SKILL.md +68 -53
  322. package/skills/fo/fo-idea-plan/SKILL.md +3 -1
  323. package/skills/fo/fo-review/SKILL.md +12 -0
  324. package/skills/fo/fo-session-save/learned-principles.md +13 -0
  325. package/skills/fo/fo-step-commit/SKILL.md +1 -1
  326. package/src/authority/delegations.ts +267 -0
  327. package/src/authority/index.ts +38 -0
  328. package/src/authority/signing.ts +73 -0
  329. package/src/bin-entry.test.ts +37 -0
  330. package/src/compass/contract-registry.test.ts +14 -0
  331. package/src/compass/types.test.ts +14 -0
  332. package/src/config/__tests__/resolve-terminology.test.ts +14 -0
  333. package/src/config/forge-config.test.ts +14 -0
  334. package/src/config/forge-config.ts +7 -2
  335. package/src/forge-module.test.ts +14 -0
  336. package/src/knowledge/__tests__/promote.test.ts +14 -0
  337. package/src/knowledge/__tests__/serialize.test.ts +14 -0
  338. package/src/knowledge/__tests__/sync.test.ts +4 -1
  339. package/src/knowledge/budgets.test.ts +14 -0
  340. package/src/knowledge/compact.test.ts +14 -0
  341. package/src/knowledge/parse.test.ts +14 -0
  342. package/src/knowledge/schema.test.ts +14 -0
  343. package/src/migration-adapters/__tests__/ignored-files.test.ts +14 -0
  344. package/src/migration-adapters/__tests__/registry.test.ts +14 -0
  345. package/src/migration-adapters/__tests__/types.test.ts +14 -0
  346. package/src/onboarding/__tests__/workspace-discovery.test.ts +14 -0
  347. package/src/onboarding/agents-generate.ts +1 -1
  348. package/src/onboarding/compass-docs/semantic-layer-block.test.ts +6 -0
  349. package/src/onboarding/create.test.ts +14 -0
  350. package/src/onboarding/doctor-token-check.test.ts +3 -0
  351. package/src/onboarding/doctor.test.ts +14 -0
  352. package/src/onboarding/doctor.ts +3 -3
  353. package/src/onboarding/init.test.ts +14 -0
  354. package/src/onboarding/init.ts +2 -2
  355. package/src/onboarding/nested-agents-templates.ts +1 -1
  356. package/src/onboarding/prettierignore.ts +1 -1
  357. package/src/onboarding/scaffold.test.ts +14 -0
  358. package/src/onboarding/site-workshop-profile.test.ts +3 -0
  359. package/src/onboarding/upgrade.test.ts +14 -0
  360. package/src/onboarding/upgrade.ts +2 -2
  361. package/src/onboarding/workspace-discovery.ts +1 -1
  362. package/src/pipeline-status.test.ts +14 -0
  363. package/src/plugin/forge-plugin-manifest.test.ts +14 -0
  364. package/src/profiles/__tests__/profile-schema.test.ts +14 -0
  365. package/src/profiles/__tests__/stack-profile.test.ts +14 -0
  366. package/src/profiles/__tests__/terminology-utils.test.ts +14 -0
  367. package/src/profiles/profile-schema.ts +1 -0
  368. package/src/tests/acceptance-criteria.test.ts +14 -0
  369. package/src/tests/acceptance-probe-kinds.test.ts +14 -0
  370. package/src/tests/adr-implement-stamp.test.ts +14 -0
  371. package/src/tests/agents-generate-domain.test.ts +3 -0
  372. package/src/tests/agents-generate.test.ts +3 -0
  373. package/src/tests/bindings-schema.test.ts +2 -0
  374. package/src/tests/budgets.test.ts +14 -0
  375. package/src/tests/compact.test.ts +14 -0
  376. package/src/tests/compass-docs-flag.test.ts +6 -0
  377. package/src/tests/compass-docs-scaffold.test.ts +6 -0
  378. package/src/tests/compass-docs-validate-scope.test.ts +6 -0
  379. package/src/tests/contract-registry.test.ts +14 -0
  380. package/src/tests/create.test.ts +3 -0
  381. package/src/tests/discover-pack-skills.test.ts +14 -0
  382. package/src/tests/doctor-autonomy.test.ts +3 -0
  383. package/src/tests/doctor-bindings.test.ts +6 -1
  384. package/src/tests/doctor-dist-freshness.test.ts +26 -2
  385. package/src/tests/doctor-domain.test.ts +6 -1
  386. package/src/tests/doctor-fix.test.ts +3 -0
  387. package/src/tests/doctor-nested-agents.test.ts +3 -0
  388. package/src/tests/doctor-profile-id-known.test.ts +3 -0
  389. package/src/tests/doctor-skills-unmanaged.test.ts +3 -0
  390. package/src/tests/doctor-version-sync.test.ts +4 -1
  391. package/src/tests/editable-generated-region.test.ts +6 -3
  392. package/src/tests/exploration-handlers.test.ts +14 -0
  393. package/src/tests/file-size-lint.test.ts +6 -1
  394. package/src/tests/forge-autonomy-validate.test.ts +3 -1
  395. package/src/tests/forge-config.test.ts +6 -1
  396. package/src/tests/forge-validate-compass-docs.test.ts +6 -0
  397. package/src/tests/fs-atomic.test.ts +14 -0
  398. package/src/tests/fs.test.ts +14 -0
  399. package/src/tests/generated-marker.test.ts +14 -0
  400. package/src/tests/hash.test.ts +14 -0
  401. package/src/tests/implement-stamp.test.ts +476 -10
  402. package/src/tests/init-bindings.test.ts +6 -1
  403. package/src/tests/knowledge-parse.test.ts +14 -0
  404. package/src/tests/knowledge-pbt.test.ts +14 -0
  405. package/src/tests/markdown-table.test.ts +6 -3
  406. package/src/tests/memory-compact.test.ts +3 -0
  407. package/src/tests/memory-scaffold.test.ts +6 -1
  408. package/src/tests/metrics-rfc-1053.test.ts +14 -0
  409. package/src/tests/migration-adapters.test.ts +3 -0
  410. package/src/tests/package-files.test.ts +4 -1
  411. package/src/tests/package-health-lint-surface.test.ts +3 -0
  412. package/src/tests/pinned-check.test.ts +14 -0
  413. package/src/tests/pinned-init.test.ts +14 -0
  414. package/src/tests/pinned-validate.test.ts +14 -0
  415. package/src/tests/plugin-manifest.test.ts +14 -0
  416. package/src/tests/prettierignore-manage.test.ts +3 -0
  417. package/src/tests/profile-schema.test.ts +6 -1
  418. package/src/tests/profile-validate.test.ts +6 -1
  419. package/src/tests/program-lease.test.ts +3 -0
  420. package/src/tests/program-paths-extended.test.ts +3 -0
  421. package/src/tests/program-paths.test.ts +3 -0
  422. package/src/tests/program-property.test.ts +3 -0
  423. package/src/tests/program-schemas.test.ts +3 -0
  424. package/src/tests/program-spec-node.test.ts +3 -0
  425. package/src/tests/promote.test.ts +14 -0
  426. package/src/tests/public-surface.test.ts +6 -1
  427. package/src/tests/registry.test.ts +14 -0
  428. package/src/tests/rfc-evidence-sync.test.ts +347 -0
  429. package/src/tests/rfc-implement-stamp-governance.test.ts +403 -0
  430. package/src/tests/rfc-validate-delegation.test.ts +178 -0
  431. package/src/tests/scaffold-project.test.ts +3 -0
  432. package/src/tests/session-handlers.test.ts +79 -0
  433. package/src/tests/session-pbt.test.ts +14 -0
  434. package/src/tests/skill-agents-sync.test.ts +3 -4
  435. package/src/tests/skill-schema.test.ts +14 -0
  436. package/src/tests/skill-sync-marker.test.ts +3 -0
  437. package/src/tests/skill-validate-knowledge.test.ts +14 -0
  438. package/src/tests/skill-validate.test.ts +14 -0
  439. package/src/tests/stack-profile.test.ts +6 -1
  440. package/src/tests/string-utils.test.ts +14 -0
  441. package/src/tests/upgrade.test.ts +6 -1
  442. package/src/tests/werkstatt-lock.test.ts +14 -0
  443. package/src/tests/workspace-discovery-domain.test.ts +6 -1
  444. package/src/tests/workspace-discovery.test.ts +6 -1
  445. package/src/types.test.ts +14 -0
  446. package/src/types.ts +30 -1
  447. package/src/utils/__tests__/fs-idempotent.test.ts +17 -0
  448. package/src/utils/__tests__/fs-trash.test.ts +17 -0
  449. package/src/utils/fs-atomic.test.ts +17 -0
  450. package/src/utils/fs-trash-sync.test.ts +17 -0
  451. package/src/utils/fs.test.ts +17 -0
  452. package/src/utils/generated-marker.test.ts +17 -0
  453. package/src/utils/hash.test.ts +17 -0
  454. package/src/utils/string-utils.test.ts +17 -0
  455. package/src/validators/__tests__/note-orphan-detect.test.ts +14 -0
@@ -12,23 +12,19 @@ verification evidence, and atomically mutates RFC frontmatter.
12
12
  </non-goals>
13
13
  </MODULE_CONTRACT>
14
14
  <CHANGE_SUMMARY>
15
- <item>RFC-1097: step 6 — compass.migrate codemod run
16
-
17
- Mechanical v1 to v2 header migration across the workspace: 942 files rewritten — CHANGE_SUMMARY windows collapsed into history, forbidden v1 blocks stripped, KEY_DECISIONS seeded from @ai-invariant comments (5 files) or TODO placeholders (103 files), blocks reordered to canonical order.</item>
18
- <item>RFC-1097: sweep — packages/forge + services clean
19
-
20
- Sweep batch 2: real KEY_DECISIONS on 10 files, expanded purposes (CONTRACT-02/PURPOSE-02), headers on mission/index + gen-upstreams, sanitizeItemText in summary.record (literal Compass tags corrupted history), excludedPaths for wrangler types, test-fixtures testPattern. forge+services now 0 diagnostics under --mode error.</item>
21
- <item>Session-retro 2026-10-08: auto-detect picks the sole implement/feat-prefixed candidate among multi-commit references (RFC-IMP-03 no longer blocks full pipelines); ambiguous sets keep blocking with annotated candidate list + earliest-candidate suggestion.</item>
22
- <item>RFC-1249: wire werkstatt.commands.validate into packages.check + retire CMD-OUTPUT debt</item>
23
- <item>RFC-1271: review wave — deep probe normalization, malformed-envelope fail-closed, post-stamp re-emit, honest repair hints</item>
24
- <history>RFC-0268, RFC-0476, RFC-0756, RFC-0795, RFC-0997, RFC-1053, RFC-IMP-07</history>
15
+ <item>RFC-1322: fo-review fix pass — io-injected resolver hardening (empty/dir/escape paths fail closed, line-range strip, probes-less envelope guard), shared IMP-06/09 evaluator, dry-run JSON fields, helpers exported per plan</item>
16
+ <item>RFC-1322: evidence annotation extraction takes the last occurrence — prose mentions no longer shadow the annotation</item>
17
+ <item>RFC-1330: origin gates wired into the shared evidence evaluator; non-blocking warnings surfaced in results.</item>
18
+ <item>RFC-1333: steps 1-3 — report contract, rfc.verify.workspace export, RFC-IMP-12 gate, RFC-IMP-11 blocking</item>
19
+ <item>RFC-1333: CX-1/CX-2 fixes — docs/** binding, waiver covers a missing report, IMP-12 for probe-less RFCs; merge-aware fail-closed binding.</item>
20
+ <history>RFC-0268, RFC-0476, RFC-0756, RFC-0795, RFC-0997, RFC-1053, RFC-1097, RFC-1249, RFC-1271, RFC-1306, RFC-1310, RFC-1321, RFC-1322, RFC-IMP-07</history>
25
21
  </CHANGE_SUMMARY>
26
22
  */
27
23
 
28
24
  import { execFile, writeFileSync } from "../../../src/utils/sync-fs.ts";
29
25
  import { ambientIo, resolveIo } from "../../../src/utils/io.ts";
30
26
 
31
- import { join, dirname } from "node:path";
27
+ import { join, dirname, relative, resolve, sep } from "node:path";
32
28
 
33
29
  import { writeFileAtomic } from "../../../src/utils/fs-atomic.ts";
34
30
  import { parse as yamlParse } from "yaml";
@@ -43,7 +39,23 @@ import {
43
39
  import { evaluateAcceptanceCriteria } from "./validate-rules.ts";
44
40
  import { toIsoDate } from "./shared.ts";
45
41
  import { byteHashHex, normalizeProbes, runRfcVerificationEmit } from "../verification-evidence.ts";
46
- import { RFC_DIR, RFC_METADATA_CUTOFF, RFC_PROBE_BINDING_CUTOFF } from "../types.ts";
42
+ import {
43
+ RFC_DIR,
44
+ RFC_METADATA_CUTOFF,
45
+ RFC_ORIGIN_CUTOFF,
46
+ RFC_PROBE_BINDING_CUTOFF,
47
+ } from "../types.ts";
48
+ import {
49
+ createOriginGit,
50
+ deriveProbeOrigins,
51
+ gitEnvForCwd,
52
+ hasVerifierTrailers,
53
+ } from "../verification-origin.ts";
54
+ import {
55
+ ACCEPTANCE_REPORTS_DIR,
56
+ evaluateAcceptanceVerificationGate,
57
+ evaluateOriginGates,
58
+ } from "./implement-stamp-origin.ts";
47
59
  import type {
48
60
  RfcStatus,
49
61
  RfcImplementStampViolation,
@@ -51,6 +63,7 @@ import type {
51
63
  AcceptanceProbe,
52
64
  VerificationEvidence,
53
65
  } from "../types.ts";
66
+ import type { WorkspaceIO } from "../../../src/types.ts";
54
67
 
55
68
  // Ambient default for helper fns without a context param — handlers override
56
69
  // with `const io = resolveIo(context.io)` inside their own scope.
@@ -72,13 +85,18 @@ const IMPLEMENTATION_SUBJECT_RE = /^(implement|feat)(\([^)]*\))?!?:/i;
72
85
 
73
86
  function execGit(workspaceRoot: string, args: string[]): Promise<string> {
74
87
  return new Promise((resolve) => {
75
- execFile("git", args, { cwd: workspaceRoot, timeout: 10000 }, (err, stdout) => {
76
- if (err) {
77
- resolve("");
78
- return;
79
- }
80
- resolve(stdout.trim());
81
- });
88
+ execFile(
89
+ "git",
90
+ args,
91
+ { cwd: workspaceRoot, timeout: 30000, env: gitEnvForCwd() },
92
+ (err, stdout) => {
93
+ if (err) {
94
+ resolve("");
95
+ return;
96
+ }
97
+ resolve(stdout.trim());
98
+ },
99
+ );
82
100
  });
83
101
  }
84
102
 
@@ -96,7 +114,7 @@ async function commitReachableFromHead(workspaceRoot: string, commitSha: string)
96
114
  execFile(
97
115
  "git",
98
116
  ["merge-base", "--is-ancestor", commitSha, "HEAD"],
99
- { cwd: workspaceRoot, timeout: 10000 },
117
+ { cwd: workspaceRoot, timeout: 30000, env: gitEnvForCwd() },
100
118
  (err) => {
101
119
  resolve(!err);
102
120
  },
@@ -113,6 +131,7 @@ async function autoDetectImplementationCommit(
113
131
  const hashes = await execGit(workspaceRoot, [
114
132
  "log",
115
133
  "--fixed-strings",
134
+ "--regexp-ignore-case",
116
135
  "--no-merges",
117
136
  `--grep=${rfcId}`,
118
137
  "--format=%H",
@@ -126,6 +145,7 @@ async function autoDetectImplementationCommit(
126
145
  const details = await execGit(workspaceRoot, [
127
146
  "log",
128
147
  "--fixed-strings",
148
+ "--regexp-ignore-case",
129
149
  "--no-merges",
130
150
  `--grep=${rfcId}`,
131
151
  "--format=%h %s",
@@ -144,6 +164,39 @@ async function autoDetectImplementationCommit(
144
164
  return { multiple: candidates };
145
165
  }
146
166
 
167
+ /**
168
+ * RFC-1310 STAMP-GOV-01: provenance, not mere reference — the commit carries
169
+ * an `X-RFC:`/`X-ADR:` trailer naming the id (ecosystem.commit --rfc/--adr)
170
+ * or its diff adds a CHANGE_SUMMARY `<item>` naming the id (the injection
171
+ * itself, e.g. commits made before the trailer existed).
172
+ */
173
+ async function commitCarriesGovernanceProvenance(
174
+ workspaceRoot: string,
175
+ commitSha: string,
176
+ rfcId: string,
177
+ ): Promise<boolean> {
178
+ const idUpper = rfcId.toUpperCase();
179
+ // RFC-1321 review-r2: same (?!\d) boundary as commitReferencesRfc —
180
+ // X-RFC: RFC-00011 must not satisfy provenance for RFC-0001.
181
+ const idRe = new RegExp(`${idUpper.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?!\\d)`);
182
+ const commitMsg = await execGit(workspaceRoot, ["log", "-1", "--format=%B", commitSha]);
183
+ if (
184
+ commitMsg.split("\n").some((l) => /^X-(?:RFC|ADR):\s*\S/i.test(l) && idRe.test(l.toUpperCase()))
185
+ ) {
186
+ return true;
187
+ }
188
+ const diff = await execGit(workspaceRoot, ["show", "-U0", "--format=", commitSha]);
189
+ return diff
190
+ .split("\n")
191
+ .some(
192
+ (l) =>
193
+ l.startsWith("+") &&
194
+ !l.startsWith("+++") &&
195
+ l.includes("<item>") &&
196
+ idRe.test(l.toUpperCase()),
197
+ );
198
+ }
199
+
147
200
  async function commitReferencesRfc(
148
201
  workspaceRoot: string,
149
202
  commitSha: string,
@@ -151,7 +204,11 @@ async function commitReferencesRfc(
151
204
  ): Promise<boolean> {
152
205
  // Check the commit message and the diff for the RFC ID
153
206
  const commitMsg = await execGit(workspaceRoot, ["log", "-1", "--format=%B", commitSha]);
154
- if (commitMsg.includes(rfcId)) return true;
207
+ // RFC-1321: governance ids compare case-insensitively — `--id rfc-1310` must
208
+ // satisfy an `RFC-1310` subject (the RFC-IMP-03 false-fail). The (?!\d)
209
+ // boundary keeps RFC-0001 from matching RFC-00011.
210
+ const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
211
+ if (new RegExp(`${esc(rfcId.toUpperCase())}(?!\\d)`).test(commitMsg.toUpperCase())) return true;
155
212
 
156
213
  // Also check if the commit touched a file whose name contains the RFC id
157
214
  const changedFiles = await execGit(workspaceRoot, [
@@ -161,7 +218,7 @@ async function commitReferencesRfc(
161
218
  commitSha,
162
219
  ]);
163
220
  const slug = rfcId.toLowerCase();
164
- if (changedFiles.toLowerCase().includes(slug)) return true;
221
+ if (new RegExp(`${esc(slug)}(?!\\d)`).test(changedFiles.toLowerCase())) return true;
165
222
 
166
223
  return false;
167
224
  }
@@ -271,6 +328,383 @@ function mutateFrontmatter(
271
328
  return content;
272
329
  }
273
330
 
331
+ // ─── RFC-1322: --check-criteria ──────────────────────────────────────────────
332
+
333
+ /** Extract the inline `(evidence: ...)` annotation text from a criterion line. */
334
+ function extractEvidenceAnnotation(line: string): string | undefined {
335
+ // The authoritative annotation is the LAST occurrence — criterion prose may
336
+ // reference the literal `(evidence: ...)` syntax mid-sentence (RFC-1322's own
337
+ // AC-1/AC-2 do), and taking the first match would certify `...` as evidence.
338
+ const matches = [...line.matchAll(/\(evidence:\s*(.+?)\)/g)];
339
+ return matches.at(-1)?.[1]?.trim();
340
+ }
341
+
342
+ /**
343
+ * The AC-N identifier of a checklist line, or a truncated line excerpt when it
344
+ * carries no id — STAMP-CHECK-01 diagnostics and criteriaAutoChecked key on it.
345
+ */
346
+ function criterionLabelOf(line: string): string {
347
+ const id = line.match(/- \[[ x]\]\s*(AC-\d+):/)?.[1];
348
+ if (id) return id;
349
+ const trimmed = line.trim();
350
+ return trimmed.length > 72 ? `${trimmed.slice(0, 69)}…` : trimmed;
351
+ }
352
+
353
+ /**
354
+ * Resolvable-annotation contract (RFC-1322 — deliberately stricter than V-37,
355
+ * which validates the `probe:` binding only and lets `file:` annotations fall
356
+ * through unvalidated): `test:<path>`, `file:<path>`, and `<path>:<line>`
357
+ * resolve when the path exists on disk as a FILE; `probe:AC-N` resolves when
358
+ * the evidence envelope carries a probe record bound to AC-N with ok === true.
359
+ * Every other form is unresolvable — the stamp certifies, so it resolves
360
+ * evidence, not just references. An empty or directory target never resolves
361
+ * (an empty `test:`/`file:` joins onto workspaceRoot, whose directory always
362
+ * exists — that would blank-check the criterion the gate exists to protect),
363
+ * and `..` segments that escape the workspace root are refused.
364
+ */
365
+ export async function resolveCriterionEvidence(
366
+ annotation: string,
367
+ envelope: VerificationEvidence | null,
368
+ workspaceRoot: string,
369
+ io: WorkspaceIO,
370
+ ): Promise<boolean> {
371
+ const statFile = async (filePath: string): Promise<boolean> => {
372
+ if (filePath === "") return false;
373
+ const resolved = resolve(workspaceRoot, filePath);
374
+ if (resolved !== workspaceRoot && !resolved.startsWith(workspaceRoot + sep)) {
375
+ return false;
376
+ }
377
+ try {
378
+ return (await io.stat(resolved)).isFile;
379
+ } catch {
380
+ return false;
381
+ }
382
+ };
383
+ if (annotation.startsWith("probe:")) {
384
+ const refId = annotation.slice("probe:".length).trim();
385
+ return (envelope?.probes ?? []).some((r) => r.probe?.criterion === refId && r.ok === true);
386
+ }
387
+ if (annotation.startsWith("test:") || annotation.startsWith("file:")) {
388
+ // A trailing :line / :line-range rides the annotation, not the path.
389
+ const filePath = annotation
390
+ .slice(annotation.indexOf(":") + 1)
391
+ .trim()
392
+ .replace(/:\d+(?:-\d+)?$/, "");
393
+ return statFile(filePath);
394
+ }
395
+ if (/^[^:]+:\d+(?:-\d+)?$/.test(annotation)) {
396
+ const filePath = annotation.slice(0, annotation.lastIndexOf(":")).trim();
397
+ return statFile(filePath);
398
+ }
399
+ return false;
400
+ }
401
+
402
+ /**
403
+ * The committed envelope needs an in-process refresh when it is absent,
404
+ * malformed, lacks the hash fields IMP-09 binds, or its hashes diverge from
405
+ * the committed RFC bytes / acceptance list — the same comparisons IMP-09
406
+ * performs, evaluated pre-write so the auto-check pass sees probe: evidence.
407
+ */
408
+ export function envelopeNeedsRefresh(
409
+ evidenceCheck: {
410
+ exists: boolean;
411
+ malformed: boolean;
412
+ envelope: VerificationEvidence | null;
413
+ },
414
+ rfcMarkdown: string,
415
+ acceptance: unknown,
416
+ ): boolean {
417
+ if (!evidenceCheck.exists || evidenceCheck.malformed || !evidenceCheck.envelope) {
418
+ return true;
419
+ }
420
+ const env = evidenceCheck.envelope;
421
+ if (!env.rfcFileHash || !env.acceptanceHash) return true;
422
+ const currentFileHash = byteHashHex(rfcMarkdown);
423
+ const currentAcceptanceHash = byteHashHex(
424
+ normalizeProbes(Array.isArray(acceptance) ? (acceptance as AcceptanceProbe[]) : []),
425
+ );
426
+ return env.rfcFileHash !== currentFileHash || env.acceptanceHash !== currentAcceptanceHash;
427
+ }
428
+
429
+ /** RFC-1333: committed acceptance reports for an RFC (frontmatter only). */
430
+ export async function readAcceptanceReports(
431
+ workspaceRoot: string,
432
+ rfcId: string,
433
+ ): Promise<Array<{ path: string; frontmatter: Record<string, unknown> }>> {
434
+ const dir = join(ACCEPTANCE_REPORTS_DIR, rfcId.toLowerCase());
435
+ const listed = await execGit(workspaceRoot, ["ls-files", "--", dir]);
436
+ const out: Array<{ path: string; frontmatter: Record<string, unknown> }> = [];
437
+ for (const path of listed.split("\n").filter((p) => p.endsWith(".md"))) {
438
+ const text = await execGit(workspaceRoot, ["show", `HEAD:${path}`]);
439
+ // CRLF checkouts and BOMs must not turn a real report into "no evidence".
440
+ const m = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---/.exec(text);
441
+ if (!m) continue;
442
+ try {
443
+ const fm = yamlParse(m[1]!) as Record<string, unknown>;
444
+ if (fm && typeof fm === "object") out.push({ path, frontmatter: fm });
445
+ } catch {
446
+ // Unparseable report frontmatter is not evidence.
447
+ }
448
+ }
449
+ return out;
450
+ }
451
+
452
+ /** RFC-1333: candidate..HEAD may contain only verifier-trailer or docs-only commits. */
453
+ export async function candidateBoundToHead(workspaceRoot: string, sha: string): Promise<boolean> {
454
+ const isAnc = await new Promise<boolean>((done) =>
455
+ execFile(
456
+ "git",
457
+ ["merge-base", "--is-ancestor", sha, "HEAD"],
458
+ { cwd: workspaceRoot, env: gitEnvForCwd() },
459
+ (err) => done(!err),
460
+ ),
461
+ );
462
+ if (!isAnc) return false;
463
+ // --first-parent -m: a merge reports its full first-parent diff, so code
464
+ // brought in by a merge cannot pass as an empty "docs-only" commit.
465
+ const log = await execGit(workspaceRoot, [
466
+ "log",
467
+ "--first-parent",
468
+ "-m",
469
+ "--format=%x1e%B%x1f",
470
+ "--name-only",
471
+ `${sha}..HEAD`,
472
+ ]);
473
+ const count = Number(
474
+ (await execGit(workspaceRoot, ["rev-list", "--count", `${sha}..HEAD`])) || "0",
475
+ );
476
+ const chunks = log.split("\x1e").filter((c) => c.includes("\x1f"));
477
+ // Fail closed: commits exist but their log could not be read.
478
+ if (count > 0 && chunks.length === 0) return false;
479
+ for (const chunk of chunks) {
480
+ const [body = "", files = ""] = chunk.split("\x1f");
481
+ const touched = files
482
+ .split("\n")
483
+ .map((l) => l.trim())
484
+ .filter(Boolean);
485
+ const docsOnly = touched.every((f) => f.startsWith("docs/"));
486
+ if (!docsOnly && !hasVerifierTrailers(body)) return false;
487
+ }
488
+ return true;
489
+ }
490
+
491
+ /**
492
+ * RFC-IMP-06 (probe-bearing RFCs need a passing envelope) + RFC-IMP-09
493
+ * (committed envelope must hash-match the committed bytes — RFC-1271) as one
494
+ * evaluator. The default path runs it pre-lock; --check-criteria runs it
495
+ * in-lock against the envelope its emit-if-needed pass may have just
496
+ * refreshed. One ruleset, two invocation orders — the paths cannot diverge.
497
+ */
498
+ async function evaluateStampEvidenceGates(opts: {
499
+ evidenceCheck: {
500
+ exists: boolean;
501
+ overall: string;
502
+ envelope: VerificationEvidence | null;
503
+ malformed: boolean;
504
+ };
505
+ requiresEvidence: boolean;
506
+ hasProbes: boolean;
507
+ targetId: string;
508
+ rfcFilePath: string;
509
+ acceptance: unknown;
510
+ io: WorkspaceIO;
511
+ /** RFC-1330: origin gates need the frontmatter and git access. */
512
+ frontmatter: Record<string, unknown>;
513
+ workspaceRoot: string;
514
+ /** RFC-1333: operator waiver for a missing report or non-subagent isolation. */
515
+ waiverReason?: string;
516
+ }): Promise<{
517
+ violations: RfcImplementStampViolation[];
518
+ warnings: RfcImplementStampViolation[];
519
+ evidenceRelPath?: string;
520
+ }> {
521
+ const { evidenceCheck, requiresEvidence, hasProbes, targetId, rfcFilePath, acceptance } = opts;
522
+ const violations: RfcImplementStampViolation[] = [];
523
+ const warnings: RfcImplementStampViolation[] = [];
524
+ let evidenceRelPath: string | undefined;
525
+
526
+ // ── RFC-IMP-10 / RFC-IMP-11: git-derived origin gates (RFC-1330) ─────────
527
+ // Derived fresh at stamp time (head = HEAD) — the committed envelope's
528
+ // origin records are volatile context and may predate later commits.
529
+ if (hasProbes && String(opts.frontmatter["createdAt"] ?? "") >= RFC_ORIGIN_CUTOFF) {
530
+ const probes = acceptance as AcceptanceProbe[];
531
+ const origins = await deriveProbeOrigins({
532
+ git: createOriginGit(opts.workspaceRoot),
533
+ rfcRelPath: relative(opts.workspaceRoot, rfcFilePath),
534
+ frontmatter: opts.frontmatter,
535
+ probes,
536
+ });
537
+ const gate = evaluateOriginGates({
538
+ targetId,
539
+ frontmatter: opts.frontmatter,
540
+ body: await opts.io.readFile(rfcFilePath),
541
+ probes,
542
+ origins,
543
+ });
544
+ violations.push(...gate.errors);
545
+ warnings.push(...gate.warnings);
546
+ }
547
+
548
+ // RFC-IMP-12 applies to every post-cutoff HIGH-tier RFC, probe-bearing or not.
549
+ // ── RFC-IMP-12: acceptance-verification report (RFC-1333) ─────────────
550
+ const acc = await evaluateAcceptanceVerificationGate({
551
+ targetId,
552
+ frontmatter: opts.frontmatter,
553
+ reports: await readAcceptanceReports(opts.workspaceRoot, targetId),
554
+ isCandidateBound: (sha) => candidateBoundToHead(opts.workspaceRoot, sha),
555
+ waiverReason: opts.waiverReason,
556
+ });
557
+ violations.push(...acc.errors);
558
+ warnings.push(...acc.warnings);
559
+
560
+ // ── RFC-IMP-06: probe-bearing post-cutoff RFCs need a passing envelope ────
561
+ if (requiresEvidence) {
562
+ if (!evidenceCheck.exists || evidenceCheck.overall !== "pass") {
563
+ violations.push({
564
+ rule: "RFC-IMP-06",
565
+ message: `RFC ${targetId} declares acceptance probes but evidence file is missing or overall is not "pass" (got "${evidenceCheck.overall}"). Run: site-kernel run rfc.verification.emit --id ${targetId}`,
566
+ });
567
+ } else {
568
+ evidenceRelPath = join(VERIFICATION_DIR, `${targetId.toLowerCase()}.generated.yaml`);
569
+ }
570
+ }
571
+
572
+ // ── RFC-IMP-09: stale evidence gate (RFC-1271) ────────────────────────────
573
+ // Hashes are recomputed from the working tree; combined with RFC-IMP-04
574
+ // (the RFC file must be committed-clean to stamp) the compared bytes are
575
+ // effectively the committed bytes — deliberate, keeps the gate honest
576
+ // without a second git read.
577
+ if (evidenceCheck.exists) {
578
+ if (evidenceCheck.malformed || !evidenceCheck.envelope) {
579
+ violations.push({
580
+ rule: "RFC-IMP-09",
581
+ message: `RFC ${targetId} evidence envelope is malformed (unreadable YAML or non-object content). Re-run: site-kernel run rfc.verification.emit --id ${targetId}, then commit the envelope — or delete the stale envelope file.`,
582
+ });
583
+ } else if (!hasProbes) {
584
+ violations.push({
585
+ rule: "RFC-IMP-09",
586
+ message: `RFC ${targetId} has a committed evidence envelope but no acceptance: list — probes were deleted after emission, which is a criteria change. Either restore the probes and re-run: site-kernel run rfc.verification.emit --id ${targetId}, then commit the envelope — or delete the stale envelope file (rfc.verification.emit skips probe-less RFCs, so re-emit alone cannot clear this).`,
587
+ });
588
+ } else {
589
+ const rfcMarkdown = await opts.io.readFile(rfcFilePath);
590
+ const currentFileHash = byteHashHex(rfcMarkdown);
591
+ const currentAcceptanceHash = byteHashHex(normalizeProbes(acceptance as AcceptanceProbe[]));
592
+ const env = evidenceCheck.envelope;
593
+ if (!env.rfcFileHash || !env.acceptanceHash) {
594
+ violations.push({
595
+ rule: "RFC-IMP-09",
596
+ message: `RFC ${targetId} evidence envelope lacks hash fields (pre-RFC-0330 format). Re-run: site-kernel run rfc.verification.emit --id ${targetId}, then commit the envelope.`,
597
+ });
598
+ } else if (
599
+ env.rfcFileHash !== currentFileHash ||
600
+ env.acceptanceHash !== currentAcceptanceHash
601
+ ) {
602
+ const staleFields = [
603
+ env.rfcFileHash !== currentFileHash ? "rfcFileHash" : "",
604
+ env.acceptanceHash !== currentAcceptanceHash ? "acceptanceHash" : "",
605
+ ]
606
+ .filter(Boolean)
607
+ .join(" + ");
608
+ violations.push({
609
+ rule: "RFC-IMP-09",
610
+ message: `RFC ${targetId} evidence is stale: ${staleFields} mismatch — the RFC file or its acceptance list changed after emission. Re-run: site-kernel run rfc.verification.emit --id ${targetId}, then commit the envelope.`,
611
+ });
612
+ }
613
+ }
614
+ }
615
+
616
+ return { violations, warnings, evidenceRelPath };
617
+ }
618
+
619
+ interface AutoCheckOutcome {
620
+ /** Trimmed unchecked lines whose evidence resolved — flip targets. */
621
+ flippable: string[];
622
+ /** Criterion labels of flippable lines — the criteriaAutoChecked surface. */
623
+ flippedIds: string[];
624
+ /** Unresolvable/absent annotations — STAMP-CHECK-01 payloads. */
625
+ failures: Array<{ criterion: string; annotation: string }>;
626
+ /**
627
+ * Dry-run only: `probe:` annotations that cannot resolve because the
628
+ * envelope would be refreshed first. Not failures — the real run resolves
629
+ * them against the freshly emitted envelope.
630
+ */
631
+ pendingRefresh: string[];
632
+ }
633
+
634
+ /** In-memory auto-check pass over the unchecked criteria of the committed body. */
635
+ async function autoCheckCriteria(opts: {
636
+ uncheckedLines: string[];
637
+ envelope: VerificationEvidence | null;
638
+ /** False in dry-run when the envelope would be re-emitted before resolving. */
639
+ probesUsable: boolean;
640
+ workspaceRoot: string;
641
+ io: WorkspaceIO;
642
+ }): Promise<AutoCheckOutcome> {
643
+ const outcome: AutoCheckOutcome = {
644
+ flippable: [],
645
+ flippedIds: [],
646
+ failures: [],
647
+ pendingRefresh: [],
648
+ };
649
+ for (const line of opts.uncheckedLines) {
650
+ const label = criterionLabelOf(line);
651
+ const annotation = extractEvidenceAnnotation(line);
652
+ if (!annotation) {
653
+ outcome.failures.push({
654
+ criterion: label,
655
+ annotation: "<no (evidence: ...) annotation>",
656
+ });
657
+ continue;
658
+ }
659
+ if (!opts.probesUsable && annotation.startsWith("probe:")) {
660
+ // Store the trimmed line so the post-flip gate can exclude pending
661
+ // criteria from the residual-unchecked check (they flip post-emit in
662
+ // the real run); labels derive via criterionLabelOf when reported.
663
+ outcome.pendingRefresh.push(line);
664
+ continue;
665
+ }
666
+ if (await resolveCriterionEvidence(annotation, opts.envelope, opts.workspaceRoot, opts.io)) {
667
+ outcome.flippable.push(line);
668
+ outcome.flippedIds.push(label);
669
+ } else {
670
+ outcome.failures.push({ criterion: label, annotation });
671
+ }
672
+ }
673
+ return outcome;
674
+ }
675
+
676
+ /**
677
+ * Flip `- [ ]` → `- [x]` for the given unchecked criterion lines inside the
678
+ * source's `## Acceptance criteria` section only — fenced code blocks are
679
+ * skipped so a section example inside ``` fences never becomes a flip target
680
+ * (the same guard the section extractors apply), and `## Document readiness`
681
+ * DR-N items are out of scope by construction.
682
+ */
683
+ export function flipCriteriaInSource(
684
+ source: string,
685
+ uncheckedTargets: ReadonlySet<string>,
686
+ ): string {
687
+ const lines = source.split("\n");
688
+ let inFence = false;
689
+ let inSection = false;
690
+ for (let i = 0; i < lines.length; i++) {
691
+ const line = lines[i]!;
692
+ if (/^```/.test(line)) {
693
+ inFence = !inFence;
694
+ continue;
695
+ }
696
+ if (inFence) continue;
697
+ if (/^## /.test(line)) {
698
+ inSection = /^## Acceptance criteria\s*$/.test(line);
699
+ continue;
700
+ }
701
+ if (inSection && /^\s*- \[ \]/.test(line) && uncheckedTargets.has(line.trim())) {
702
+ lines[i] = line.replace(/- \[ \]/, "- [x]");
703
+ }
704
+ }
705
+ return lines.join("\n");
706
+ }
707
+
274
708
  // ─── Main handler ────────────────────────────────────────────────────────────
275
709
 
276
710
  export async function runRfcImplementStamp(
@@ -281,7 +715,12 @@ export async function runRfcImplementStamp(
281
715
  const { workspaceRoot, logger, outputFormat, dryRun } = context;
282
716
  const rfcDirPath = join(workspaceRoot, RFC_DIR);
283
717
 
284
- const targetId = input.flags["id"] as string | undefined;
718
+ // RFC-1321: canonicalize the governance id at parse — every stored surface
719
+ // (result rfcId, post-stamp re-emit flags, metrics ids) carries the
720
+ // canonical uppercase spelling regardless of flag casing. A non-string flag
721
+ // (repeated --id forms an array) degrades to absent rather than crashing.
722
+ const rawId = input.flags["id"];
723
+ const targetId = typeof rawId === "string" ? rawId.toUpperCase() : undefined;
285
724
  let implementationCommit = input.flags["implementation-commit"] as string | undefined;
286
725
 
287
726
  // ── Flag validation ───────────────────────────────────────────────────────
@@ -291,6 +730,10 @@ export async function runRfcImplementStamp(
291
730
 
292
731
  const violations: RfcImplementStampViolation[] = [];
293
732
  const isDryRun = dryRun || input.flags["dry-run"] === true;
733
+ // RFC-1322: the stamp performs the checkbox flips itself — but only for
734
+ // criteria whose (evidence: ...) annotation resolves — and refreshes a
735
+ // missing/stale envelope in-process before the gates evaluate it.
736
+ const checkCriteria = input.flags["check-criteria"] === true;
294
737
 
295
738
  // ── Find the target RFC ───────────────────────────────────────────────────
296
739
  const files = await listRfcFiles(rfcDirPath);
@@ -333,15 +776,52 @@ export async function runRfcImplementStamp(
333
776
  return stampFailResult(violations, isDryRun, outputFormat, logger);
334
777
  }
335
778
 
779
+ // ── RFC-1306: --sync runs the evidence-resync chain before stamping ────────
780
+ // Positioned after the target RFC resolves (so --id is real) and before any
781
+ // criteria/commit/evidence read, so the IMP-06/09 gates see fresh artifacts.
782
+ // The chain is delegated by name through the kernel host's invoke port — the
783
+ // standalone forge CLI has no host and fails closed like rfc.evidence.sync.
784
+ if (input.flags["sync"] === true) {
785
+ if (!context.invoke) {
786
+ violations.push({
787
+ rule: "EVIDENCE-SYNC-01",
788
+ message:
789
+ "--sync requires the werkstatt kernel host (context.invoke is absent). Run via `pnpm exec werkstatt run rfc.implement.stamp --id <id> --sync`, or resync manually.",
790
+ });
791
+ return stampFailResult(violations, isDryRun, outputFormat, logger);
792
+ }
793
+ let syncReport: Awaited<ReturnType<NonNullable<typeof context.invoke>>>;
794
+ try {
795
+ syncReport = await context.invoke("rfc.evidence.sync", { id: targetId });
796
+ } catch (err) {
797
+ violations.push({
798
+ rule: "EVIDENCE-SYNC-02",
799
+ message: `rfc.evidence.sync threw before stamping: ${err instanceof Error ? err.message : String(err)}. Resolve the failing step and re-run the stamp.`,
800
+ });
801
+ return stampFailResult(violations, isDryRun, outputFormat, logger);
802
+ }
803
+ if (syncReport.exitCode !== 0) {
804
+ violations.push({
805
+ rule: "EVIDENCE-SYNC-02",
806
+ message: `rfc.evidence.sync failed before stamping${syncReport.summary ? `: ${syncReport.summary}` : ""}. Resolve the failing step and re-run the stamp.`,
807
+ });
808
+ return stampFailResult(violations, isDryRun, outputFormat, logger);
809
+ }
810
+ logger.info(`[rfc.implement.stamp] --sync: ${syncReport.summary ?? "resync chain completed"}`);
811
+ }
812
+
336
813
  // ── RFC-IMP-02: criterion checks (V-26/V-27 semantics) ────────────────────
814
+ // Under --check-criteria both branches defer: unchecked lines become flip
815
+ // candidates for the auto-check pass, and checkedWithoutEvidence re-runs on
816
+ // the post-flip body — a flipped line always keeps its annotation.
337
817
  const criteriaEval = evaluateAcceptanceCriteria(body);
338
- if (criteriaEval.totalUnchecked > 0) {
818
+ if (!checkCriteria && criteriaEval.totalUnchecked > 0) {
339
819
  violations.push({
340
820
  rule: "RFC-IMP-02",
341
821
  message: `${criteriaEval.totalUnchecked} acceptance criteria are unchecked. All criteria must be checked before stamping: ${criteriaEval.uncheckedLines.join("; ")}`,
342
822
  });
343
823
  }
344
- if (criteriaEval.checkedWithoutEvidence.length > 0) {
824
+ if (!checkCriteria && criteriaEval.checkedWithoutEvidence.length > 0) {
345
825
  violations.push({
346
826
  rule: "RFC-IMP-02",
347
827
  message: `${criteriaEval.checkedWithoutEvidence.length} checked criteria lack inline (evidence: ...) annotation: ${criteriaEval.checkedWithoutEvidence.join("; ")}`,
@@ -371,10 +851,14 @@ export async function runRfcImplementStamp(
371
851
  }
372
852
 
373
853
  // ── RFC-0756: auto-detect implementation commit when --implementation-commit is omitted ──
854
+ // RFC-1310 STAMP-GOV-01: auto-detect candidates join the provenance scan
855
+ // set — a trailer on any implementation-shaped commit counts.
856
+ const provenanceCandidateShas: string[] = [];
374
857
  if (!implementationCommit) {
375
858
  const detected = await autoDetectImplementationCommit(workspaceRoot, targetId);
376
859
  if ("sha" in detected) {
377
860
  implementationCommit = detected.sha;
861
+ provenanceCandidateShas.push(detected.sha);
378
862
  } else if ("none" in detected) {
379
863
  violations.push({
380
864
  rule: "RFC-IMP-03",
@@ -384,6 +868,7 @@ export async function runRfcImplementStamp(
384
868
  // Auto-resolve when exactly one candidate looks like an implementation
385
869
  // commit — a multi-commit RFC pipeline (audit → plan → implement → docs →
386
870
  // review) references the id at every step, but only one step implements.
871
+ provenanceCandidateShas.push(...detected.multiple.map((c) => c.sha));
387
872
  const implCandidates = detected.multiple.filter((c) =>
388
873
  IMPLEMENTATION_SUBJECT_RE.test(c.message),
389
874
  );
@@ -445,6 +930,29 @@ export async function runRfcImplementStamp(
445
930
  rule: "RFC-IMP-03",
446
931
  message: `Implementation commit ${implementationCommit} does not reference ${targetId} in its message or changed files.`,
447
932
  });
933
+ } else {
934
+ // ── RFC-1310 STAMP-GOV-01: commit-time governance provenance ──────
935
+ // A subject mention is not provenance — the implementation commit
936
+ // (or an auto-detected sibling candidate) must carry the X-RFC
937
+ // trailer or an injected CHANGE_SUMMARY item, else the stamp would
938
+ // certify a provenance-broken implementation (DNA-59).
939
+ const scanShas = [...new Set([implementationCommit, ...provenanceCandidateShas])];
940
+ logger.info(
941
+ `[rfc.implement.stamp] STAMP-GOV-01 scanning ${scanShas.length} commit(s): ${scanShas.join(", ")}`,
942
+ );
943
+ let provenance = false;
944
+ for (const sha of scanShas) {
945
+ if (await commitCarriesGovernanceProvenance(workspaceRoot, sha, targetId)) {
946
+ provenance = true;
947
+ break;
948
+ }
949
+ }
950
+ if (!provenance) {
951
+ violations.push({
952
+ rule: "STAMP-GOV-01",
953
+ message: `Implementation commit(s) for ${targetId} carry no governance provenance (no X-RFC: ${targetId} trailer, no injected CHANGE_SUMMARY item) — scanned: ${scanShas.join(", ")}. Retro-fix: hand-edit CHANGE_SUMMARY <item>${targetId}: …</item> entries into the touched files' headers in the worktree, then land a follow-up ecosystem.commit --rfc ${targetId} --message "docs(${targetId.toLowerCase()}): retrofit governance provenance" and re-stamp.`,
954
+ });
955
+ }
448
956
  }
449
957
  }
450
958
  }
@@ -457,67 +965,39 @@ export async function runRfcImplementStamp(
457
965
  const rfcFilePath = join(rfcDirPath, targetFile);
458
966
 
459
967
  let evidenceRelPath: string | undefined;
968
+ // RFC-1330/1333: non-blocking stamp findings (waived RFC-IMP-12: missing report or isolation).
969
+ const stampWarnings: RfcImplementStampViolation[] = [];
970
+ const waiverFlag = input.flags["waive-independent-verification"];
971
+ const waiverReason =
972
+ typeof waiverFlag === "string" && waiverFlag.trim() ? waiverFlag.trim() : undefined;
460
973
 
461
974
  // RFC-1271: the envelope is fetched unconditionally — a committed envelope
462
975
  // must also be evaluated when hasProbes is now false, because probe
463
976
  // deletion IS a criteria change and would otherwise slip past
464
977
  // requiresEvidence entirely (RFC-IMP-08 exempts policy/deprecation kinds).
465
- const evidenceCheck = await checkExistingEvidence(workspaceRoot, targetId);
466
-
467
- if (requiresEvidence) {
468
- if (!evidenceCheck.exists || evidenceCheck.overall !== "pass") {
469
- violations.push({
470
- rule: "RFC-IMP-06",
471
- message: `RFC ${targetId} declares acceptance probes but evidence file is missing or overall is not "pass" (got "${evidenceCheck.overall}"). Run: site-kernel run rfc.verification.emit --id ${targetId}`,
472
- });
473
- } else {
474
- const slug = targetId.toLowerCase();
475
- evidenceRelPath = join(VERIFICATION_DIR, `${slug}.generated.yaml`);
476
- }
477
- }
478
-
479
- // ── RFC-IMP-09: stale evidence gate (RFC-1271) ────────────────────────────
480
- // Hashes are recomputed from the working tree; combined with RFC-IMP-04
481
- // (the RFC file must be committed-clean to stamp) the compared bytes are
482
- // effectively the committed bytes — deliberate, keeps the gate honest
483
- // without a second git read. Fires before any frontmatter mutation.
484
- if (evidenceCheck.exists) {
485
- if (evidenceCheck.malformed || !evidenceCheck.envelope) {
486
- violations.push({
487
- rule: "RFC-IMP-09",
488
- message: `RFC ${targetId} evidence envelope is malformed (unreadable YAML or non-object content). Re-run: site-kernel run rfc.verification.emit --id ${targetId}, then commit the envelope — or delete the stale envelope file.`,
489
- });
490
- } else if (!hasProbes) {
491
- violations.push({
492
- rule: "RFC-IMP-09",
493
- message: `RFC ${targetId} has a committed evidence envelope but no acceptance: list — probes were deleted after emission, which is a criteria change. Either restore the probes and re-run: site-kernel run rfc.verification.emit --id ${targetId}, then commit the envelope — or delete the stale envelope file (rfc.verification.emit skips probe-less RFCs, so re-emit alone cannot clear this).`,
494
- });
495
- } else {
496
- const rfcMarkdown = await io.readFile(rfcFilePath);
497
- const currentFileHash = byteHashHex(rfcMarkdown);
498
- const currentAcceptanceHash = byteHashHex(normalizeProbes(acceptance as AcceptanceProbe[]));
499
- const env = evidenceCheck.envelope;
500
- if (!env.rfcFileHash || !env.acceptanceHash) {
501
- violations.push({
502
- rule: "RFC-IMP-09",
503
- message: `RFC ${targetId} evidence envelope lacks hash fields (pre-RFC-0330 format). Re-run: site-kernel run rfc.verification.emit --id ${targetId}, then commit the envelope.`,
504
- });
505
- } else if (
506
- env.rfcFileHash !== currentFileHash ||
507
- env.acceptanceHash !== currentAcceptanceHash
508
- ) {
509
- const staleFields = [
510
- env.rfcFileHash !== currentFileHash ? "rfcFileHash" : "",
511
- env.acceptanceHash !== currentAcceptanceHash ? "acceptanceHash" : "",
512
- ]
513
- .filter(Boolean)
514
- .join(" + ");
515
- violations.push({
516
- rule: "RFC-IMP-09",
517
- message: `RFC ${targetId} evidence is stale: ${staleFields} mismatch — the RFC file or its acceptance list changed after emission. Re-run: site-kernel run rfc.verification.emit --id ${targetId}, then commit the envelope.`,
518
- });
519
- }
520
- }
978
+ // let — --check-criteria re-reads the envelope after the emit-if-needed pass.
979
+ let evidenceCheck = await checkExistingEvidence(workspaceRoot, targetId);
980
+
981
+ // Default path: IMP-06 + IMP-09 fire pre-lock via the shared evaluator —
982
+ // under --check-criteria the same ruleset runs inside the lock, after the
983
+ // emit-if-needed pass may have refreshed the envelope.
984
+ if (!checkCriteria) {
985
+ const gates = await evaluateStampEvidenceGates({
986
+ evidenceCheck,
987
+ requiresEvidence,
988
+ hasProbes,
989
+ targetId,
990
+ rfcFilePath,
991
+ acceptance,
992
+ io,
993
+ frontmatter: fm,
994
+ workspaceRoot,
995
+ waiverReason,
996
+ });
997
+ violations.push(...gates.violations);
998
+ stampWarnings.push(...gates.warnings);
999
+ for (const w of gates.warnings) logger.warn(`${w.rule}: ${w.message}`);
1000
+ if (gates.evidenceRelPath) evidenceRelPath = gates.evidenceRelPath;
521
1001
  }
522
1002
 
523
1003
  // ── RFC-IMP-08: minimum-one-probe gate (RFC-0997) ─────────────────────────
@@ -538,6 +1018,9 @@ export async function runRfcImplementStamp(
538
1018
  }
539
1019
 
540
1020
  // ── RFC-IMP-05: acquire RFC-specific exclusive lock ───────────────────────
1021
+ // Under --check-criteria the lock must precede the FIRST write — which is
1022
+ // the emit-if-needed envelope refresh, not the stamp mutation — so all
1023
+ // envelope-independent gates above abort before this point.
541
1024
  const { acquired, lockPath } = await acquireRfcLock(workspaceRoot, targetId);
542
1025
  if (!acquired) {
543
1026
  violations.push({
@@ -550,16 +1033,146 @@ export async function runRfcImplementStamp(
550
1033
  try {
551
1034
  // ── Atomic mutation ──────────────────────────────────────────────────────
552
1035
  const rfcSource = await io.readFile(rfcFilePath);
1036
+ // RFC-1322: the mutation-bound source — under --check-criteria it carries
1037
+ // the auto-check flips; without the flag it is the committed file text.
1038
+ let stampSource = rfcSource;
1039
+ let criteriaAutoChecked: string[] | undefined;
1040
+ let criteriaPendingRefresh: string[] = [];
1041
+ let evidenceWouldRefresh = false;
1042
+ let effectiveCriteriaChecked = criteriaEval.totalChecked;
1043
+
1044
+ if (checkCriteria) {
1045
+ // Emit-if-needed (RFC-1322 order step 4): a missing, malformed, or
1046
+ // hash-stale envelope is refreshed in-process through the same direct
1047
+ // runRfcVerificationEmit call the post-stamp re-emit uses — on the
1048
+ // committed bytes, so IMP-09 keeps evaluating a real file state. The
1049
+ // freshness precheck (RFC-1320) gates this emit exactly as a manual one.
1050
+ const needsEmit = hasProbes && envelopeNeedsRefresh(evidenceCheck, rfcSource, acceptance);
1051
+ evidenceWouldRefresh = needsEmit;
1052
+ if (needsEmit && !isDryRun) {
1053
+ let emitOk = false;
1054
+ let emitSummary = "";
1055
+ try {
1056
+ const emitResult = await runRfcVerificationEmit(
1057
+ { argv: [], flags: { id: targetId } },
1058
+ context,
1059
+ );
1060
+ emitOk = emitResult.exitCode === 0;
1061
+ emitSummary = emitResult.summary ?? "";
1062
+ } catch (emitErr) {
1063
+ violations.push({
1064
+ rule: "EVIDENCE-SYNC-02",
1065
+ message: `pre-stamp evidence emit for ${targetId} threw: ${emitErr instanceof Error ? emitErr.message : String(emitErr)}. Resolve the failing step and re-run the stamp.`,
1066
+ });
1067
+ return stampFailResult(violations, isDryRun, outputFormat, logger);
1068
+ }
1069
+ if (!emitOk) {
1070
+ violations.push({
1071
+ rule: "EVIDENCE-SYNC-02",
1072
+ message: `pre-stamp evidence emit for ${targetId} failed${emitSummary ? `: ${emitSummary}` : ""}. Resolve the failing step and re-run the stamp.`,
1073
+ });
1074
+ return stampFailResult(violations, isDryRun, outputFormat, logger);
1075
+ }
1076
+ logger.info(`[rfc.implement.stamp] --check-criteria: refreshed stale/missing envelope`);
1077
+ evidenceCheck = await checkExistingEvidence(workspaceRoot, targetId);
1078
+ }
1079
+
1080
+ // Auto-check pass (RFC-1322 order step 5, in-memory): each unchecked
1081
+ // criterion resolves its (evidence: ...) annotation; unresolvable ones
1082
+ // abort before any RFC mutation. In dry-run with a pending refresh the
1083
+ // probe: annotations are not yet resolvable — pending, not failures.
1084
+ const auto = await autoCheckCriteria({
1085
+ uncheckedLines: criteriaEval.uncheckedLines,
1086
+ envelope: evidenceCheck.envelope,
1087
+ probesUsable: !(isDryRun && needsEmit),
1088
+ workspaceRoot,
1089
+ io,
1090
+ });
1091
+ criteriaAutoChecked = auto.flippedIds;
1092
+ criteriaPendingRefresh = auto.pendingRefresh.map(criterionLabelOf);
1093
+ if (auto.failures.length > 0) {
1094
+ violations.push({
1095
+ rule: "STAMP-CHECK-01",
1096
+ message:
1097
+ `${auto.failures.length} unchecked acceptance criteria lack resolvable (evidence: ...) annotations — ` +
1098
+ `supply a resolvable reference (test:<path>, file:<path>, <path>:<line>, or probe:AC-N bound to a passing envelope probe): ` +
1099
+ auto.failures.map((f) => `${f.criterion} [${f.annotation}]`).join("; "),
1100
+ });
1101
+ }
1102
+
1103
+ if (auto.flippable.length > 0) {
1104
+ stampSource = flipCriteriaInSource(rfcSource, new Set(auto.flippable));
1105
+ }
1106
+
1107
+ // Post-flip criteria gates on the mutation-bound bytes (step 6): a
1108
+ // still-unchecked line means the flip failed to land — fail closed
1109
+ // rather than write a partially checked document; checked lines must
1110
+ // keep their annotation (a flipped line always does). Dry-run pending
1111
+ // criteria (probe: awaiting the skipped emit) are excluded — the real
1112
+ // run resolves them against the refreshed envelope.
1113
+ const pendingSet = new Set(auto.pendingRefresh);
1114
+ const postFlipEval = evaluateAcceptanceCriteria(stampSource);
1115
+ const residualUnchecked = postFlipEval.uncheckedLines.filter((l) => !pendingSet.has(l));
1116
+ if (residualUnchecked.length > 0) {
1117
+ violations.push({
1118
+ rule: "RFC-IMP-02",
1119
+ message: `${residualUnchecked.length} acceptance criteria remain unchecked after the --check-criteria pass: ${residualUnchecked.join("; ")}`,
1120
+ });
1121
+ }
1122
+ if (postFlipEval.checkedWithoutEvidence.length > 0) {
1123
+ violations.push({
1124
+ rule: "RFC-IMP-02",
1125
+ message: `${postFlipEval.checkedWithoutEvidence.length} checked criteria lack inline (evidence: ...) annotation: ${postFlipEval.checkedWithoutEvidence.join("; ")}`,
1126
+ });
1127
+ }
1128
+ effectiveCriteriaChecked = postFlipEval.totalChecked;
1129
+
1130
+ // IMP-06 + IMP-09 against the (possibly just-refreshed) envelope via
1131
+ // the shared evaluator — skipped in dry-run when a refresh would run,
1132
+ // since committed-bytes verdicts are not predictive of the post-emit
1133
+ // state the real stamp evaluates.
1134
+ if (!(isDryRun && needsEmit)) {
1135
+ const gates = await evaluateStampEvidenceGates({
1136
+ evidenceCheck,
1137
+ requiresEvidence,
1138
+ hasProbes,
1139
+ targetId,
1140
+ rfcFilePath,
1141
+ acceptance,
1142
+ io,
1143
+ frontmatter: fm,
1144
+ workspaceRoot,
1145
+ waiverReason,
1146
+ });
1147
+ violations.push(...gates.violations);
1148
+ stampWarnings.push(...gates.warnings);
1149
+ for (const w of gates.warnings) logger.warn(`${w.rule}: ${w.message}`);
1150
+ if (gates.evidenceRelPath) evidenceRelPath = gates.evidenceRelPath;
1151
+ }
1152
+
1153
+ if (violations.length > 0) {
1154
+ return stampFailResult(violations, isDryRun, outputFormat, logger);
1155
+ }
1156
+ }
553
1157
 
554
1158
  const today = toIsoDate(new Date());
555
1159
  const stampedAt = new Date().toISOString();
556
- const mutatedSource = mutateFrontmatter(rfcSource, "implemented", today, today);
1160
+ const mutatedSource = mutateFrontmatter(stampSource, "implemented", today, today);
557
1161
 
558
1162
  if (isDryRun) {
559
1163
  if (outputFormat === "pretty") {
560
1164
  logger.success(`[dry-run] ${targetId} would be stamped as implemented`);
561
1165
  logger.info(` implementation commit: ${implementationCommit}`);
562
- logger.info(` criteria checked: ${criteriaEval.totalChecked}`);
1166
+ logger.info(` criteria checked: ${effectiveCriteriaChecked}`);
1167
+ if (criteriaAutoChecked && criteriaAutoChecked.length > 0) {
1168
+ logger.info(` criteria auto-checked: ${criteriaAutoChecked.join(", ")}`);
1169
+ }
1170
+ if (criteriaPendingRefresh.length > 0) {
1171
+ logger.info(` criteria pending envelope refresh: ${criteriaPendingRefresh.join(", ")}`);
1172
+ }
1173
+ if (evidenceWouldRefresh) {
1174
+ logger.info(` evidence envelope would be refreshed (missing or stale)`);
1175
+ }
563
1176
  if (evidenceRelPath) {
564
1177
  logger.info(` evidence: ${evidenceRelPath}`);
565
1178
  }
@@ -568,11 +1181,19 @@ export async function runRfcImplementStamp(
568
1181
  data: {
569
1182
  command: "rfc.implement.stamp",
570
1183
  status: "pass",
1184
+ ...(stampWarnings.length > 0 ? { warnings: stampWarnings } : {}),
571
1185
  data: {
572
1186
  rfcId: targetId,
573
1187
  implementationCommit: implementationCommit!,
574
1188
  stampedAt,
575
- criteriaChecked: criteriaEval.totalChecked,
1189
+ criteriaChecked: effectiveCriteriaChecked,
1190
+ ...(checkCriteria
1191
+ ? {
1192
+ criteriaAutoChecked: criteriaAutoChecked ?? [],
1193
+ criteriaPendingRefresh,
1194
+ evidenceWouldRefresh,
1195
+ }
1196
+ : {}),
576
1197
  ...(evidenceRelPath ? { evidencePath: evidenceRelPath } : {}),
577
1198
  },
578
1199
  violations: [],
@@ -582,7 +1203,8 @@ export async function runRfcImplementStamp(
582
1203
  };
583
1204
  }
584
1205
 
585
- // Write the mutated RFC file atomically
1206
+ // Write the mutated RFC file atomically — under --check-criteria this
1207
+ // single write carries the checkbox flips AND the frontmatter mutation.
586
1208
  await writeFileAtomic(rfcFilePath, mutatedSource);
587
1209
 
588
1210
  // ── RFC-1053: Generate per-RFC metrics (non-fatal, guarded by !isDryRun) ─
@@ -629,7 +1251,10 @@ export async function runRfcImplementStamp(
629
1251
  if (outputFormat === "pretty") {
630
1252
  logger.success(`${targetId} stamped as implemented`);
631
1253
  logger.info(` implementation commit: ${implementationCommit}`);
632
- logger.info(` criteria checked: ${criteriaEval.totalChecked}`);
1254
+ logger.info(` criteria checked: ${effectiveCriteriaChecked}`);
1255
+ if (criteriaAutoChecked && criteriaAutoChecked.length > 0) {
1256
+ logger.info(` criteria auto-checked: ${criteriaAutoChecked.join(", ")}`);
1257
+ }
633
1258
  if (evidenceRelPath) {
634
1259
  logger.info(` evidence: ${evidenceRelPath}`);
635
1260
  }
@@ -640,11 +1265,13 @@ export async function runRfcImplementStamp(
640
1265
  data: {
641
1266
  command: "rfc.implement.stamp",
642
1267
  status: "pass",
1268
+ ...(stampWarnings.length > 0 ? { warnings: stampWarnings } : {}),
643
1269
  data: {
644
1270
  rfcId: targetId,
645
1271
  implementationCommit: implementationCommit!,
646
1272
  stampedAt,
647
- criteriaChecked: criteriaEval.totalChecked,
1273
+ criteriaChecked: effectiveCriteriaChecked,
1274
+ ...(checkCriteria ? { criteriaAutoChecked: criteriaAutoChecked ?? [] } : {}),
648
1275
  ...(evidenceRelPath ? { evidencePath: evidenceRelPath } : {}),
649
1276
  ...(hasProbes ? { evidenceReEmitted } : {}),
650
1277
  ...(metricsPath ? { metricsPath } : {}),