@warpgogol/forge 6.3.6 → 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 (405) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +2 -1
  3. package/bin/cli.js +6 -12
  4. package/bin/resolve-entry.js +24 -0
  5. package/dist/os/compass/comment-safety.d.ts +83 -0
  6. package/dist/os/compass/comment-safety.d.ts.map +1 -0
  7. package/dist/os/compass/comment-safety.js +305 -0
  8. package/dist/os/compass/comment-safety.js.map +1 -0
  9. package/dist/os/compass/compass.module.d.ts.map +1 -1
  10. package/dist/os/compass/compass.module.js +47 -4
  11. package/dist/os/compass/compass.module.js.map +1 -1
  12. package/dist/os/compass/handlers/compass-change-summary-handler.d.ts +2 -1
  13. package/dist/os/compass/handlers/compass-change-summary-handler.d.ts.map +1 -1
  14. package/dist/os/compass/handlers/compass-change-summary-handler.js +34 -10
  15. package/dist/os/compass/handlers/compass-change-summary-handler.js.map +1 -1
  16. package/dist/os/compass/handlers/compass-docs-scaffold.d.ts.map +1 -1
  17. package/dist/os/compass/handlers/compass-docs-scaffold.js +54 -17
  18. package/dist/os/compass/handlers/compass-docs-scaffold.js.map +1 -1
  19. package/dist/os/compass/handlers/compass-header-scaffold-handler.d.ts +14 -0
  20. package/dist/os/compass/handlers/compass-header-scaffold-handler.d.ts.map +1 -0
  21. package/dist/os/compass/handlers/compass-header-scaffold-handler.js +261 -0
  22. package/dist/os/compass/handlers/compass-header-scaffold-handler.js.map +1 -0
  23. package/dist/os/compass/handlers/compass-header-scaffold.d.ts +31 -0
  24. package/dist/os/compass/handlers/compass-header-scaffold.d.ts.map +1 -0
  25. package/dist/os/compass/handlers/compass-header-scaffold.js +739 -0
  26. package/dist/os/compass/handlers/compass-header-scaffold.js.map +1 -0
  27. package/dist/os/compass/handlers/compass-inventory-handler.d.ts.map +1 -1
  28. package/dist/os/compass/handlers/compass-inventory-handler.js +8 -4
  29. package/dist/os/compass/handlers/compass-inventory-handler.js.map +1 -1
  30. package/dist/os/compass/handlers/compass-inventory.d.ts +6 -0
  31. package/dist/os/compass/handlers/compass-inventory.d.ts.map +1 -1
  32. package/dist/os/compass/handlers/compass-inventory.js +28 -13
  33. package/dist/os/compass/handlers/compass-inventory.js.map +1 -1
  34. package/dist/os/compass/handlers/compass-migrate-handler.d.ts.map +1 -1
  35. package/dist/os/compass/handlers/compass-migrate-handler.js +12 -26
  36. package/dist/os/compass/handlers/compass-migrate-handler.js.map +1 -1
  37. package/dist/os/compass/handlers/compass-migrate.d.ts +15 -2
  38. package/dist/os/compass/handlers/compass-migrate.d.ts.map +1 -1
  39. package/dist/os/compass/handlers/compass-migrate.js +58 -20
  40. package/dist/os/compass/handlers/compass-migrate.js.map +1 -1
  41. package/dist/os/compass/handlers/git-revision.d.ts +10 -0
  42. package/dist/os/compass/handlers/git-revision.d.ts.map +1 -1
  43. package/dist/os/compass/handlers/git-revision.js +58 -4
  44. package/dist/os/compass/handlers/git-revision.js.map +1 -1
  45. package/dist/os/compass/handlers/summary-record.d.ts +20 -5
  46. package/dist/os/compass/handlers/summary-record.d.ts.map +1 -1
  47. package/dist/os/compass/handlers/summary-record.js +175 -44
  48. package/dist/os/compass/handlers/summary-record.js.map +1 -1
  49. package/dist/os/compass/index.d.ts +1 -0
  50. package/dist/os/compass/index.d.ts.map +1 -1
  51. package/dist/os/compass/index.js +2 -0
  52. package/dist/os/compass/index.js.map +1 -1
  53. package/dist/os/compass/policy.d.ts +9 -0
  54. package/dist/os/compass/policy.d.ts.map +1 -1
  55. package/dist/os/compass/policy.js +11 -2
  56. package/dist/os/compass/policy.js.map +1 -1
  57. package/dist/os/core/core.module.js +1 -1
  58. package/dist/os/core/handlers/package-health.d.ts.map +1 -1
  59. package/dist/os/core/handlers/package-health.js +1 -6
  60. package/dist/os/core/handlers/package-health.js.map +1 -1
  61. package/dist/os/queue/types.d.ts +2 -0
  62. package/dist/os/queue/types.d.ts.map +1 -1
  63. package/dist/os/queue/types.js +3 -1
  64. package/dist/os/queue/types.js.map +1 -1
  65. package/dist/os/rfc/acceptance.d.ts.map +1 -1
  66. package/dist/os/rfc/acceptance.js +66 -2
  67. package/dist/os/rfc/acceptance.js.map +1 -1
  68. package/dist/os/rfc/decision-log.d.ts.map +1 -1
  69. package/dist/os/rfc/decision-log.js +21 -3
  70. package/dist/os/rfc/decision-log.js.map +1 -1
  71. package/dist/os/rfc/dna-trace.d.ts +2 -0
  72. package/dist/os/rfc/dna-trace.d.ts.map +1 -1
  73. package/dist/os/rfc/dna-trace.js +13 -4
  74. package/dist/os/rfc/dna-trace.js.map +1 -1
  75. package/dist/os/rfc/handlers/implement-stamp-origin.d.ts +37 -0
  76. package/dist/os/rfc/handlers/implement-stamp-origin.d.ts.map +1 -0
  77. package/dist/os/rfc/handlers/implement-stamp-origin.js +118 -0
  78. package/dist/os/rfc/handlers/implement-stamp-origin.js.map +1 -0
  79. package/dist/os/rfc/handlers/implement-stamp.d.ts +41 -1
  80. package/dist/os/rfc/handlers/implement-stamp.d.ts.map +1 -1
  81. package/dist/os/rfc/handlers/implement-stamp.js +645 -47
  82. package/dist/os/rfc/handlers/implement-stamp.js.map +1 -1
  83. package/dist/os/rfc/handlers/rfc-evidence-sync.d.ts +42 -0
  84. package/dist/os/rfc/handlers/rfc-evidence-sync.d.ts.map +1 -0
  85. package/dist/os/rfc/handlers/rfc-evidence-sync.js +147 -0
  86. package/dist/os/rfc/handlers/rfc-evidence-sync.js.map +1 -0
  87. package/dist/os/rfc/handlers/validate-rules.d.ts +9 -1
  88. package/dist/os/rfc/handlers/validate-rules.d.ts.map +1 -1
  89. package/dist/os/rfc/handlers/validate-rules.js +71 -10
  90. package/dist/os/rfc/handlers/validate-rules.js.map +1 -1
  91. package/dist/os/rfc/reachable-symbol.d.ts +17 -0
  92. package/dist/os/rfc/reachable-symbol.d.ts.map +1 -0
  93. package/dist/os/rfc/reachable-symbol.js +376 -0
  94. package/dist/os/rfc/reachable-symbol.js.map +1 -0
  95. package/dist/os/rfc/rfc.module.d.ts.map +1 -1
  96. package/dist/os/rfc/rfc.module.js +99 -10
  97. package/dist/os/rfc/rfc.module.js.map +1 -1
  98. package/dist/os/rfc/types.d.ts +112 -14
  99. package/dist/os/rfc/types.d.ts.map +1 -1
  100. package/dist/os/rfc/types.js +27 -10
  101. package/dist/os/rfc/types.js.map +1 -1
  102. package/dist/os/rfc/verification-evidence.d.ts +25 -0
  103. package/dist/os/rfc/verification-evidence.d.ts.map +1 -1
  104. package/dist/os/rfc/verification-evidence.js +244 -13
  105. package/dist/os/rfc/verification-evidence.js.map +1 -1
  106. package/dist/os/rfc/verification-origin.d.ts +58 -0
  107. package/dist/os/rfc/verification-origin.d.ts.map +1 -0
  108. package/dist/os/rfc/verification-origin.js +346 -0
  109. package/dist/os/rfc/verification-origin.js.map +1 -0
  110. package/dist/os/rfc/verification-refresh.d.ts.map +1 -1
  111. package/dist/os/rfc/verification-refresh.js +11 -1
  112. package/dist/os/rfc/verification-refresh.js.map +1 -1
  113. package/dist/os/rfc/verify-workspace.d.ts +23 -0
  114. package/dist/os/rfc/verify-workspace.d.ts.map +1 -0
  115. package/dist/os/rfc/verify-workspace.js +278 -0
  116. package/dist/os/rfc/verify-workspace.js.map +1 -0
  117. package/dist/os/session/handlers/metrics-rfc.d.ts.map +1 -1
  118. package/dist/os/session/handlers/metrics-rfc.js +3 -0
  119. package/dist/os/session/handlers/metrics-rfc.js.map +1 -1
  120. package/dist/os/spec/spec-status.d.ts.map +1 -1
  121. package/dist/os/spec/spec-status.js +5 -23
  122. package/dist/os/spec/spec-status.js.map +1 -1
  123. package/dist/os/spec/spec-validate.d.ts.map +1 -1
  124. package/dist/os/spec/spec-validate.js +30 -9
  125. package/dist/os/spec/spec-validate.js.map +1 -1
  126. package/dist/os/workflow/handlers.d.ts +0 -4
  127. package/dist/os/workflow/handlers.d.ts.map +1 -1
  128. package/dist/os/workflow/handlers.js +9 -36
  129. package/dist/os/workflow/handlers.js.map +1 -1
  130. package/dist/os/workflow/index.d.ts +2 -2
  131. package/dist/os/workflow/index.d.ts.map +1 -1
  132. package/dist/os/workflow/index.js +1 -1
  133. package/dist/os/workflow/index.js.map +1 -1
  134. package/dist/os/workflow/types.d.ts +0 -19
  135. package/dist/os/workflow/types.d.ts.map +1 -1
  136. package/dist/os/workflow/types.js +0 -2
  137. package/dist/os/workflow/types.js.map +1 -1
  138. package/dist/os/workflow/workflow.module.d.ts.map +1 -1
  139. package/dist/os/workflow/workflow.module.js +6 -15
  140. package/dist/os/workflow/workflow.module.js.map +1 -1
  141. package/dist/src/config/forge-config.d.ts +5 -0
  142. package/dist/src/config/forge-config.d.ts.map +1 -1
  143. package/dist/src/config/forge-config.js +5 -2
  144. package/dist/src/config/forge-config.js.map +1 -1
  145. package/dist/src/onboarding/agents-generate.js +1 -1
  146. package/dist/src/onboarding/doctor.js +3 -3
  147. package/dist/src/onboarding/doctor.js.map +1 -1
  148. package/dist/src/onboarding/init.js +2 -2
  149. package/dist/src/onboarding/nested-agents-templates.js +1 -1
  150. package/dist/src/onboarding/prettierignore.js +1 -1
  151. package/dist/src/onboarding/upgrade.js +2 -2
  152. package/dist/src/onboarding/workspace-discovery.js +1 -1
  153. package/dist/src/profiles/profile-schema.d.ts +2 -0
  154. package/dist/src/profiles/profile-schema.d.ts.map +1 -1
  155. package/dist/src/profiles/profile-schema.js +1 -0
  156. package/dist/src/profiles/profile-schema.js.map +1 -1
  157. package/dist/src/profiles/stack-profile.d.ts +1 -0
  158. package/dist/src/profiles/stack-profile.d.ts.map +1 -1
  159. package/dist/src/skill-schema.d.ts +2 -0
  160. package/dist/src/skill-schema.d.ts.map +1 -1
  161. package/dist/src/skill-schema.js +9 -1
  162. package/dist/src/skill-schema.js.map +1 -1
  163. package/dist/src/types.d.ts +23 -0
  164. package/dist/src/types.d.ts.map +1 -1
  165. package/dist/src/types.js +2 -1
  166. package/dist/src/types.js.map +1 -1
  167. package/docs/reference/cli.md +0 -1
  168. package/docs/reference/programmatic-api.md +1 -1
  169. package/os/adr/handlers/validate.test.ts +14 -0
  170. package/os/compass/comment-safety.ts +331 -0
  171. package/os/compass/compass.module.ts +50 -4
  172. package/os/compass/handlers/compass-change-summary-handler.ts +41 -11
  173. package/os/compass/handlers/compass-docs-scaffold.ts +59 -17
  174. package/os/compass/handlers/compass-game-extensions.test.ts +3 -7
  175. package/os/compass/handlers/compass-header-scaffold-handler.ts +352 -0
  176. package/os/compass/handlers/compass-header-scaffold.ts +847 -0
  177. package/os/compass/handlers/compass-inventory-handler.ts +9 -4
  178. package/os/compass/handlers/compass-inventory.ts +29 -13
  179. package/os/compass/handlers/compass-migrate-handler.ts +13 -27
  180. package/os/compass/handlers/compass-migrate.ts +77 -21
  181. package/os/compass/handlers/git-revision.ts +59 -4
  182. package/os/compass/handlers/resolve-scan-root-package.test.ts +14 -0
  183. package/os/compass/handlers/resolve-scan-root-workpiece.test.ts +14 -0
  184. package/os/compass/handlers/summary-record.ts +194 -41
  185. package/os/compass/handlers/tests/compass-audit-plan.test.ts +6 -0
  186. package/os/compass/handlers/tests/compass-audit-record.test.ts +6 -0
  187. package/os/compass/handlers/tests/compass-audit-validate.test.ts +6 -0
  188. package/os/compass/handlers/tests/compass-change-summary-handler.test.ts +131 -0
  189. package/os/compass/handlers/tests/compass-docs-validate.test.ts +6 -0
  190. package/os/compass/handlers/tests/compass-header-scaffold.test.ts +896 -0
  191. package/os/compass/handlers/tests/compass-ledger-scope.test.ts +6 -0
  192. package/os/compass/handlers/tests/compass-migrate.test.ts +87 -9
  193. package/os/compass/handlers/tests/compass-policy.test.ts +1 -1
  194. package/os/compass/handlers/tests/compass-text-safety.test.ts +271 -0
  195. package/os/compass/handlers/tests/compass-v2-contract.test.ts +52 -3
  196. package/os/compass/handlers/tests/summary-record.test.ts +324 -3
  197. package/os/compass/index.ts +15 -0
  198. package/os/compass/policy.ts +27 -2
  199. package/os/core/core.module.ts +1 -1
  200. package/os/core/handlers/invariant-engine.test.ts +3 -1
  201. package/os/core/handlers/note-frontmatter-validate.test.ts +6 -1
  202. package/os/core/handlers/note-link-validate.test.ts +6 -1
  203. package/os/core/handlers/note-orphan-detect.test.ts +6 -1
  204. package/os/core/handlers/package-health.test.ts +6 -0
  205. package/os/core/handlers/package-health.ts +1 -6
  206. package/os/mission/handlers/archive.test.ts +14 -0
  207. package/os/naming/naming-convention.test.ts +14 -0
  208. package/os/queue/decision-ledger.test.ts +27 -4
  209. package/os/queue/queue-validate.test.ts +14 -0
  210. package/os/queue/types.ts +3 -1
  211. package/os/rfc/acceptance-reachable.test.ts +146 -0
  212. package/os/rfc/acceptance.test.ts +136 -0
  213. package/os/rfc/acceptance.ts +71 -2
  214. package/os/rfc/decision-log.ts +22 -4
  215. package/os/rfc/dna-trace.ts +17 -5
  216. package/os/rfc/frontmatter-io.test.ts +14 -0
  217. package/os/rfc/handlers/implement-stamp-acceptance-verification.test.ts +81 -0
  218. package/os/rfc/handlers/implement-stamp-binding.test.ts +79 -0
  219. package/os/rfc/handlers/implement-stamp-origin.test.ts +132 -0
  220. package/os/rfc/handlers/implement-stamp-origin.ts +154 -0
  221. package/os/rfc/handlers/implement-stamp-stale.test.ts +285 -0
  222. package/os/rfc/handlers/implement-stamp.ts +783 -55
  223. package/os/rfc/handlers/lifecycle.test.ts +14 -0
  224. package/os/rfc/handlers/rfc-evidence-sync.ts +221 -0
  225. package/os/rfc/handlers/validate-rules-rfc0997.test.ts +14 -0
  226. package/os/rfc/handlers/validate-rules-rfc1006.test.ts +14 -0
  227. package/os/rfc/handlers/validate-rules-rfc1330.test.ts +120 -0
  228. package/os/rfc/handlers/validate-rules-rfc1334.test.ts +65 -0
  229. package/os/rfc/handlers/validate-rules.test.ts +56 -0
  230. package/os/rfc/handlers/validate-rules.ts +101 -10
  231. package/os/rfc/handlers/validate.test.ts +4 -3
  232. package/os/rfc/reachable-symbol.ts +441 -0
  233. package/os/rfc/rfc-0000-template.md +21 -1
  234. package/os/rfc/rfc-create-concurrent.test.ts +6 -0
  235. package/os/rfc/rfc-create-hint.test.ts +6 -0
  236. package/os/rfc/rfc-read-only-no-side-effects.test.ts +6 -0
  237. package/os/rfc/rfc.module.ts +106 -10
  238. package/os/rfc/types.ts +151 -14
  239. package/os/rfc/verification-emit-check.test.ts +215 -0
  240. package/os/rfc/verification-emit-freshness.test.ts +415 -0
  241. package/os/rfc/verification-emit.test.ts +14 -0
  242. package/os/rfc/verification-evidence.ts +301 -13
  243. package/os/rfc/verification-normalize.test.ts +75 -0
  244. package/os/rfc/verification-origin.test.ts +236 -0
  245. package/os/rfc/verification-origin.ts +417 -0
  246. package/os/rfc/verification-refresh.test.ts +14 -0
  247. package/os/rfc/verification-refresh.ts +12 -1
  248. package/os/rfc/verifier/rfc-1333/imp12-binding.acceptance.test.ts +78 -0
  249. package/os/rfc/verifier/rfc-1333/imp12-gate.acceptance.test.ts +81 -0
  250. package/os/rfc/verifier/rfc-1333/skills-and-types.acceptance.test.ts +50 -0
  251. package/os/rfc/verifier/rfc-1333/verify-workspace.acceptance.test.ts +103 -0
  252. package/os/rfc/verify-workspace.test.ts +122 -0
  253. package/os/rfc/verify-workspace.ts +342 -0
  254. package/os/session/handlers/metrics-rfc.ts +3 -0
  255. package/os/spec/spec-status.test.ts +130 -0
  256. package/os/spec/spec-status.ts +5 -18
  257. package/os/spec/spec-validate.test.ts +76 -1
  258. package/os/spec/spec-validate.ts +26 -7
  259. package/os/workflow/handlers.ts +8 -42
  260. package/os/workflow/index.ts +1 -4
  261. package/os/workflow/types.ts +0 -22
  262. package/os/workflow/workflow.module.ts +6 -16
  263. package/package.json +1 -1
  264. package/skills/_shared/agent-operating-model.md +83 -0
  265. package/skills/_shared/fo-pipeline-conventions.md +1 -0
  266. package/skills/fo/fo-add-tests/SKILL.md +14 -0
  267. package/skills/fo/fo-fix/SKILL.md +2 -1
  268. package/skills/fo/fo-handoff/SKILL.md +1 -1
  269. package/skills/fo/fo-idea/SKILL.md +6 -3
  270. package/skills/fo/fo-idea-create-rfc/acceptance-criteria-standard.md +8 -0
  271. package/skills/fo/fo-idea-i-just-want-to-see-the-result/SKILL.md +4 -2
  272. package/skills/fo/fo-idea-implement/SKILL.md +68 -53
  273. package/skills/fo/fo-idea-plan/SKILL.md +3 -1
  274. package/skills/fo/fo-review/SKILL.md +12 -0
  275. package/skills/fo/fo-session-save/learned-principles.md +13 -0
  276. package/skills/fo/fo-step-commit/SKILL.md +1 -1
  277. package/src/bin-entry.test.ts +37 -0
  278. package/src/compass/contract-registry.test.ts +14 -0
  279. package/src/compass/types.test.ts +14 -0
  280. package/src/config/__tests__/resolve-terminology.test.ts +14 -0
  281. package/src/config/forge-config.test.ts +14 -0
  282. package/src/config/forge-config.ts +7 -2
  283. package/src/forge-module.test.ts +14 -0
  284. package/src/knowledge/__tests__/promote.test.ts +14 -0
  285. package/src/knowledge/__tests__/serialize.test.ts +14 -0
  286. package/src/knowledge/__tests__/sync.test.ts +4 -1
  287. package/src/knowledge/budgets.test.ts +14 -0
  288. package/src/knowledge/compact.test.ts +14 -0
  289. package/src/knowledge/parse.test.ts +14 -0
  290. package/src/knowledge/schema.test.ts +14 -0
  291. package/src/migration-adapters/__tests__/ignored-files.test.ts +14 -0
  292. package/src/migration-adapters/__tests__/registry.test.ts +14 -0
  293. package/src/migration-adapters/__tests__/types.test.ts +14 -0
  294. package/src/onboarding/__tests__/workspace-discovery.test.ts +14 -0
  295. package/src/onboarding/agents-generate.ts +1 -1
  296. package/src/onboarding/compass-docs/semantic-layer-block.test.ts +6 -0
  297. package/src/onboarding/create.test.ts +14 -0
  298. package/src/onboarding/doctor-token-check.test.ts +3 -0
  299. package/src/onboarding/doctor.test.ts +14 -0
  300. package/src/onboarding/doctor.ts +3 -3
  301. package/src/onboarding/init.test.ts +14 -0
  302. package/src/onboarding/init.ts +2 -2
  303. package/src/onboarding/nested-agents-templates.ts +1 -1
  304. package/src/onboarding/prettierignore.ts +1 -1
  305. package/src/onboarding/scaffold.test.ts +14 -0
  306. package/src/onboarding/site-workshop-profile.test.ts +3 -0
  307. package/src/onboarding/templates/behavioral-layer-core.md +8 -0
  308. package/src/onboarding/upgrade.test.ts +14 -0
  309. package/src/onboarding/upgrade.ts +2 -2
  310. package/src/onboarding/workspace-discovery.ts +1 -1
  311. package/src/pipeline-status.test.ts +14 -0
  312. package/src/plugin/forge-plugin-manifest.test.ts +14 -0
  313. package/src/profiles/__tests__/profile-schema.test.ts +14 -0
  314. package/src/profiles/__tests__/stack-profile.test.ts +14 -0
  315. package/src/profiles/__tests__/terminology-utils.test.ts +14 -0
  316. package/src/profiles/profile-schema.ts +1 -0
  317. package/src/skill-schema.ts +9 -1
  318. package/src/tests/acceptance-criteria.test.ts +14 -0
  319. package/src/tests/acceptance-probe-kinds.test.ts +14 -0
  320. package/src/tests/adr-implement-stamp.test.ts +14 -0
  321. package/src/tests/agents-generate-domain.test.ts +3 -0
  322. package/src/tests/agents-generate.test.ts +3 -0
  323. package/src/tests/bindings-schema.test.ts +2 -0
  324. package/src/tests/budgets.test.ts +14 -0
  325. package/src/tests/compact.test.ts +14 -0
  326. package/src/tests/compass-docs-flag.test.ts +6 -0
  327. package/src/tests/compass-docs-scaffold.test.ts +6 -0
  328. package/src/tests/compass-docs-validate-scope.test.ts +6 -0
  329. package/src/tests/contract-registry.test.ts +14 -0
  330. package/src/tests/create.test.ts +3 -0
  331. package/src/tests/discover-pack-skills.test.ts +14 -0
  332. package/src/tests/doctor-autonomy.test.ts +3 -0
  333. package/src/tests/doctor-bindings.test.ts +6 -1
  334. package/src/tests/doctor-dist-freshness.test.ts +26 -2
  335. package/src/tests/doctor-domain.test.ts +6 -1
  336. package/src/tests/doctor-fix.test.ts +3 -0
  337. package/src/tests/doctor-nested-agents.test.ts +3 -0
  338. package/src/tests/doctor-profile-id-known.test.ts +3 -0
  339. package/src/tests/doctor-skills-unmanaged.test.ts +3 -0
  340. package/src/tests/doctor-version-sync.test.ts +4 -1
  341. package/src/tests/editable-generated-region.test.ts +6 -3
  342. package/src/tests/exploration-handlers.test.ts +14 -0
  343. package/src/tests/file-size-lint.test.ts +6 -1
  344. package/src/tests/fixtures/agents-generate-business-before.txt +8 -0
  345. package/src/tests/forge-autonomy-validate.test.ts +3 -1
  346. package/src/tests/forge-config.test.ts +6 -1
  347. package/src/tests/forge-validate-compass-docs.test.ts +6 -0
  348. package/src/tests/fs-atomic.test.ts +14 -0
  349. package/src/tests/fs.test.ts +14 -0
  350. package/src/tests/generated-marker.test.ts +14 -0
  351. package/src/tests/hash.test.ts +14 -0
  352. package/src/tests/implement-stamp.test.ts +476 -10
  353. package/src/tests/init-bindings.test.ts +6 -1
  354. package/src/tests/knowledge-parse.test.ts +14 -0
  355. package/src/tests/knowledge-pbt.test.ts +14 -0
  356. package/src/tests/markdown-table.test.ts +6 -3
  357. package/src/tests/memory-compact.test.ts +3 -0
  358. package/src/tests/memory-scaffold.test.ts +6 -1
  359. package/src/tests/metrics-rfc-1053.test.ts +14 -0
  360. package/src/tests/migration-adapters.test.ts +3 -0
  361. package/src/tests/package-files.test.ts +4 -1
  362. package/src/tests/package-health-lint-surface.test.ts +3 -0
  363. package/src/tests/pinned-check.test.ts +14 -0
  364. package/src/tests/pinned-init.test.ts +14 -0
  365. package/src/tests/pinned-validate.test.ts +14 -0
  366. package/src/tests/plugin-manifest.test.ts +14 -0
  367. package/src/tests/prettierignore-manage.test.ts +3 -0
  368. package/src/tests/profile-schema.test.ts +6 -1
  369. package/src/tests/profile-validate.test.ts +6 -1
  370. package/src/tests/program-lease.test.ts +3 -0
  371. package/src/tests/program-paths-extended.test.ts +3 -0
  372. package/src/tests/program-paths.test.ts +3 -0
  373. package/src/tests/program-property.test.ts +3 -0
  374. package/src/tests/program-schemas.test.ts +3 -0
  375. package/src/tests/program-spec-node.test.ts +3 -0
  376. package/src/tests/promote.test.ts +14 -0
  377. package/src/tests/public-surface.test.ts +6 -1
  378. package/src/tests/registry.test.ts +14 -0
  379. package/src/tests/rfc-evidence-sync.test.ts +347 -0
  380. package/src/tests/rfc-implement-stamp-governance.test.ts +403 -0
  381. package/src/tests/scaffold-project.test.ts +3 -0
  382. package/src/tests/session-handlers.test.ts +14 -0
  383. package/src/tests/session-pbt.test.ts +14 -0
  384. package/src/tests/skill-agents-sync.test.ts +3 -4
  385. package/src/tests/skill-schema.test.ts +53 -0
  386. package/src/tests/skill-sync-marker.test.ts +3 -0
  387. package/src/tests/skill-validate-knowledge.test.ts +14 -0
  388. package/src/tests/skill-validate.test.ts +14 -0
  389. package/src/tests/stack-profile.test.ts +6 -1
  390. package/src/tests/string-utils.test.ts +14 -0
  391. package/src/tests/upgrade.test.ts +6 -1
  392. package/src/tests/werkstatt-lock.test.ts +14 -0
  393. package/src/tests/workspace-discovery-domain.test.ts +6 -1
  394. package/src/tests/workspace-discovery.test.ts +6 -1
  395. package/src/types.test.ts +14 -0
  396. package/src/types.ts +30 -1
  397. package/src/utils/__tests__/fs-idempotent.test.ts +17 -0
  398. package/src/utils/__tests__/fs-trash.test.ts +17 -0
  399. package/src/utils/fs-atomic.test.ts +17 -0
  400. package/src/utils/fs-trash-sync.test.ts +17 -0
  401. package/src/utils/fs.test.ts +17 -0
  402. package/src/utils/generated-marker.test.ts +17 -0
  403. package/src/utils/hash.test.ts +17 -0
  404. package/src/utils/string-utils.test.ts +17 -0
  405. package/src/validators/__tests__/note-orphan-detect.test.ts +14 -0
@@ -12,28 +12,27 @@ verification evidence, and atomically mutates RFC frontmatter.
12
12
  </non-goals>
13
13
  </MODULE_CONTRACT>
14
14
  <CHANGE_SUMMARY>
15
- <item>RFC-1053: integrate generateRfcMetrics after successful stamp (non-fatal, guarded by !isDryRun).</item>
16
- <item>RFC-1097: step 6 — compass.migrate codemod run
17
-
18
- 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>
19
- <item>RFC-1097: sweep — packages/forge + services clean
20
-
21
- 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>
22
- <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>
23
- <item>RFC-1249: wire werkstatt.commands.validate into packages.check + retire CMD-OUTPUT debt</item>
24
- <history>RFC-0268, RFC-0476, RFC-0756, RFC-0795, RFC-0997, 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
  import { execFile, writeFileSync } from "../../../src/utils/sync-fs.js";
28
24
  import { ambientIo, resolveIo } from "../../../src/utils/io.js";
29
- import { join, dirname } from "node:path";
25
+ import { join, dirname, relative, resolve, sep } from "node:path";
30
26
  import { writeFileAtomic } from "../../../src/utils/fs-atomic.js";
31
27
  import { parse as yamlParse } from "yaml";
32
28
  import { generateRfcMetrics } from "../../session/handlers/metrics-rfc.js";
33
29
  import { listRfcFiles, readAndParseRfc, rfcFileMatchesId, loadRfcStatusMap, } from "../frontmatter-io.js";
34
30
  import { evaluateAcceptanceCriteria } from "./validate-rules.js";
35
31
  import { toIsoDate } from "./shared.js";
36
- import { RFC_DIR, RFC_METADATA_CUTOFF, RFC_PROBE_BINDING_CUTOFF } from "../types.js";
32
+ import { byteHashHex, normalizeProbes, runRfcVerificationEmit } from "../verification-evidence.js";
33
+ import { RFC_DIR, RFC_METADATA_CUTOFF, RFC_ORIGIN_CUTOFF, RFC_PROBE_BINDING_CUTOFF, } from "../types.js";
34
+ import { createOriginGit, deriveProbeOrigins, gitEnvForCwd, hasVerifierTrailers, } from "../verification-origin.js";
35
+ import { ACCEPTANCE_REPORTS_DIR, evaluateAcceptanceVerificationGate, evaluateOriginGates, } from "./implement-stamp-origin.js";
37
36
  // Ambient default for helper fns without a context param — handlers override
38
37
  // with `const io = resolveIo(context.io)` inside their own scope.
39
38
  const io = ambientIo;
@@ -45,7 +44,7 @@ const VERIFICATION_DIR = join(RFC_DIR, "verification");
45
44
  const IMPLEMENTATION_SUBJECT_RE = /^(implement|feat)(\([^)]*\))?!?:/i;
46
45
  function execGit(workspaceRoot, args) {
47
46
  return new Promise((resolve) => {
48
- execFile("git", args, { cwd: workspaceRoot, timeout: 10000 }, (err, stdout) => {
47
+ execFile("git", args, { cwd: workspaceRoot, timeout: 30000, env: gitEnvForCwd() }, (err, stdout) => {
49
48
  if (err) {
50
49
  resolve("");
51
50
  return;
@@ -64,7 +63,7 @@ async function commitReachableFromHead(workspaceRoot, commitSha) {
64
63
  // execGit returns "" on error (non-zero exit), trimmed stdout on success
65
64
  // So we need a different approach: check exit code directly
66
65
  return new Promise((resolve) => {
67
- execFile("git", ["merge-base", "--is-ancestor", commitSha, "HEAD"], { cwd: workspaceRoot, timeout: 10000 }, (err) => {
66
+ execFile("git", ["merge-base", "--is-ancestor", commitSha, "HEAD"], { cwd: workspaceRoot, timeout: 30000, env: gitEnvForCwd() }, (err) => {
68
67
  resolve(!err);
69
68
  });
70
69
  });
@@ -73,6 +72,7 @@ async function autoDetectImplementationCommit(workspaceRoot, rfcId) {
73
72
  const hashes = await execGit(workspaceRoot, [
74
73
  "log",
75
74
  "--fixed-strings",
75
+ "--regexp-ignore-case",
76
76
  "--no-merges",
77
77
  `--grep=${rfcId}`,
78
78
  "--format=%H",
@@ -85,6 +85,7 @@ async function autoDetectImplementationCommit(workspaceRoot, rfcId) {
85
85
  const details = await execGit(workspaceRoot, [
86
86
  "log",
87
87
  "--fixed-strings",
88
+ "--regexp-ignore-case",
88
89
  "--no-merges",
89
90
  `--grep=${rfcId}`,
90
91
  "--format=%h %s",
@@ -100,10 +101,37 @@ async function autoDetectImplementationCommit(workspaceRoot, rfcId) {
100
101
  });
101
102
  return { multiple: candidates };
102
103
  }
104
+ /**
105
+ * RFC-1310 STAMP-GOV-01: provenance, not mere reference — the commit carries
106
+ * an `X-RFC:`/`X-ADR:` trailer naming the id (ecosystem.commit --rfc/--adr)
107
+ * or its diff adds a CHANGE_SUMMARY `<item>` naming the id (the injection
108
+ * itself, e.g. commits made before the trailer existed).
109
+ */
110
+ async function commitCarriesGovernanceProvenance(workspaceRoot, commitSha, rfcId) {
111
+ const idUpper = rfcId.toUpperCase();
112
+ // RFC-1321 review-r2: same (?!\d) boundary as commitReferencesRfc —
113
+ // X-RFC: RFC-00011 must not satisfy provenance for RFC-0001.
114
+ const idRe = new RegExp(`${idUpper.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?!\\d)`);
115
+ const commitMsg = await execGit(workspaceRoot, ["log", "-1", "--format=%B", commitSha]);
116
+ if (commitMsg.split("\n").some((l) => /^X-(?:RFC|ADR):\s*\S/i.test(l) && idRe.test(l.toUpperCase()))) {
117
+ return true;
118
+ }
119
+ const diff = await execGit(workspaceRoot, ["show", "-U0", "--format=", commitSha]);
120
+ return diff
121
+ .split("\n")
122
+ .some((l) => l.startsWith("+") &&
123
+ !l.startsWith("+++") &&
124
+ l.includes("<item>") &&
125
+ idRe.test(l.toUpperCase()));
126
+ }
103
127
  async function commitReferencesRfc(workspaceRoot, commitSha, rfcId) {
104
128
  // Check the commit message and the diff for the RFC ID
105
129
  const commitMsg = await execGit(workspaceRoot, ["log", "-1", "--format=%B", commitSha]);
106
- if (commitMsg.includes(rfcId))
130
+ // RFC-1321: governance ids compare case-insensitively — `--id rfc-1310` must
131
+ // satisfy an `RFC-1310` subject (the RFC-IMP-03 false-fail). The (?!\d)
132
+ // boundary keeps RFC-0001 from matching RFC-00011.
133
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
134
+ if (new RegExp(`${esc(rfcId.toUpperCase())}(?!\\d)`).test(commitMsg.toUpperCase()))
107
135
  return true;
108
136
  // Also check if the commit touched a file whose name contains the RFC id
109
137
  const changedFiles = await execGit(workspaceRoot, [
@@ -113,7 +141,7 @@ async function commitReferencesRfc(workspaceRoot, commitSha, rfcId) {
113
141
  commitSha,
114
142
  ]);
115
143
  const slug = rfcId.toLowerCase();
116
- if (changedFiles.toLowerCase().includes(slug))
144
+ if (new RegExp(`${esc(slug)}(?!\\d)`).test(changedFiles.toLowerCase()))
117
145
  return true;
118
146
  return false;
119
147
  }
@@ -147,14 +175,32 @@ async function releaseRfcLock(lockPath) {
147
175
  async function checkExistingEvidence(workspaceRoot, rfcId) {
148
176
  const slug = rfcId.toLowerCase();
149
177
  const evidencePath = join(workspaceRoot, VERIFICATION_DIR, `${slug}.generated.yaml`);
178
+ let content;
179
+ try {
180
+ content = await io.readFile(evidencePath);
181
+ }
182
+ catch {
183
+ return { exists: false, overall: "missing", envelope: null, malformed: false };
184
+ }
185
+ let parsed;
150
186
  try {
151
- const content = await io.readFile(evidencePath);
152
- const evidence = yamlParse(content);
153
- return { exists: true, overall: String(evidence.overall ?? "") };
187
+ parsed = yamlParse(content);
154
188
  }
155
189
  catch {
156
- return { exists: false, overall: "missing" };
190
+ return { exists: true, overall: "malformed", envelope: null, malformed: true };
157
191
  }
192
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
193
+ // Fail closed: a committed envelope that parses to a scalar/array is
194
+ // malformed evidence, not absent evidence.
195
+ return { exists: true, overall: "malformed", envelope: null, malformed: true };
196
+ }
197
+ const evidence = parsed;
198
+ return {
199
+ exists: true,
200
+ overall: String(evidence.overall ?? ""),
201
+ envelope: evidence,
202
+ malformed: false,
203
+ };
158
204
  }
159
205
  // ─── Frontmatter mutation ────────────────────────────────────────────────────
160
206
  function mutateFrontmatter(source, status, implementedAt, updatedAt) {
@@ -173,12 +219,319 @@ function mutateFrontmatter(source, status, implementedAt, updatedAt) {
173
219
  content = content.replace(/^updatedAt: .*$/m, `updatedAt: ${updatedAt}`);
174
220
  return content;
175
221
  }
222
+ // ─── RFC-1322: --check-criteria ──────────────────────────────────────────────
223
+ /** Extract the inline `(evidence: ...)` annotation text from a criterion line. */
224
+ function extractEvidenceAnnotation(line) {
225
+ // The authoritative annotation is the LAST occurrence — criterion prose may
226
+ // reference the literal `(evidence: ...)` syntax mid-sentence (RFC-1322's own
227
+ // AC-1/AC-2 do), and taking the first match would certify `...` as evidence.
228
+ const matches = [...line.matchAll(/\(evidence:\s*(.+?)\)/g)];
229
+ return matches.at(-1)?.[1]?.trim();
230
+ }
231
+ /**
232
+ * The AC-N identifier of a checklist line, or a truncated line excerpt when it
233
+ * carries no id — STAMP-CHECK-01 diagnostics and criteriaAutoChecked key on it.
234
+ */
235
+ function criterionLabelOf(line) {
236
+ const id = line.match(/- \[[ x]\]\s*(AC-\d+):/)?.[1];
237
+ if (id)
238
+ return id;
239
+ const trimmed = line.trim();
240
+ return trimmed.length > 72 ? `${trimmed.slice(0, 69)}…` : trimmed;
241
+ }
242
+ /**
243
+ * Resolvable-annotation contract (RFC-1322 — deliberately stricter than V-37,
244
+ * which validates the `probe:` binding only and lets `file:` annotations fall
245
+ * through unvalidated): `test:<path>`, `file:<path>`, and `<path>:<line>`
246
+ * resolve when the path exists on disk as a FILE; `probe:AC-N` resolves when
247
+ * the evidence envelope carries a probe record bound to AC-N with ok === true.
248
+ * Every other form is unresolvable — the stamp certifies, so it resolves
249
+ * evidence, not just references. An empty or directory target never resolves
250
+ * (an empty `test:`/`file:` joins onto workspaceRoot, whose directory always
251
+ * exists — that would blank-check the criterion the gate exists to protect),
252
+ * and `..` segments that escape the workspace root are refused.
253
+ */
254
+ export async function resolveCriterionEvidence(annotation, envelope, workspaceRoot, io) {
255
+ const statFile = async (filePath) => {
256
+ if (filePath === "")
257
+ return false;
258
+ const resolved = resolve(workspaceRoot, filePath);
259
+ if (resolved !== workspaceRoot && !resolved.startsWith(workspaceRoot + sep)) {
260
+ return false;
261
+ }
262
+ try {
263
+ return (await io.stat(resolved)).isFile;
264
+ }
265
+ catch {
266
+ return false;
267
+ }
268
+ };
269
+ if (annotation.startsWith("probe:")) {
270
+ const refId = annotation.slice("probe:".length).trim();
271
+ return (envelope?.probes ?? []).some((r) => r.probe?.criterion === refId && r.ok === true);
272
+ }
273
+ if (annotation.startsWith("test:") || annotation.startsWith("file:")) {
274
+ // A trailing :line / :line-range rides the annotation, not the path.
275
+ const filePath = annotation
276
+ .slice(annotation.indexOf(":") + 1)
277
+ .trim()
278
+ .replace(/:\d+(?:-\d+)?$/, "");
279
+ return statFile(filePath);
280
+ }
281
+ if (/^[^:]+:\d+(?:-\d+)?$/.test(annotation)) {
282
+ const filePath = annotation.slice(0, annotation.lastIndexOf(":")).trim();
283
+ return statFile(filePath);
284
+ }
285
+ return false;
286
+ }
287
+ /**
288
+ * The committed envelope needs an in-process refresh when it is absent,
289
+ * malformed, lacks the hash fields IMP-09 binds, or its hashes diverge from
290
+ * the committed RFC bytes / acceptance list — the same comparisons IMP-09
291
+ * performs, evaluated pre-write so the auto-check pass sees probe: evidence.
292
+ */
293
+ export function envelopeNeedsRefresh(evidenceCheck, rfcMarkdown, acceptance) {
294
+ if (!evidenceCheck.exists || evidenceCheck.malformed || !evidenceCheck.envelope) {
295
+ return true;
296
+ }
297
+ const env = evidenceCheck.envelope;
298
+ if (!env.rfcFileHash || !env.acceptanceHash)
299
+ return true;
300
+ const currentFileHash = byteHashHex(rfcMarkdown);
301
+ const currentAcceptanceHash = byteHashHex(normalizeProbes(Array.isArray(acceptance) ? acceptance : []));
302
+ return env.rfcFileHash !== currentFileHash || env.acceptanceHash !== currentAcceptanceHash;
303
+ }
304
+ /** RFC-1333: committed acceptance reports for an RFC (frontmatter only). */
305
+ export async function readAcceptanceReports(workspaceRoot, rfcId) {
306
+ const dir = join(ACCEPTANCE_REPORTS_DIR, rfcId.toLowerCase());
307
+ const listed = await execGit(workspaceRoot, ["ls-files", "--", dir]);
308
+ const out = [];
309
+ for (const path of listed.split("\n").filter((p) => p.endsWith(".md"))) {
310
+ const text = await execGit(workspaceRoot, ["show", `HEAD:${path}`]);
311
+ // CRLF checkouts and BOMs must not turn a real report into "no evidence".
312
+ const m = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---/.exec(text);
313
+ if (!m)
314
+ continue;
315
+ try {
316
+ const fm = yamlParse(m[1]);
317
+ if (fm && typeof fm === "object")
318
+ out.push({ path, frontmatter: fm });
319
+ }
320
+ catch {
321
+ // Unparseable report frontmatter is not evidence.
322
+ }
323
+ }
324
+ return out;
325
+ }
326
+ /** RFC-1333: candidate..HEAD may contain only verifier-trailer or docs-only commits. */
327
+ export async function candidateBoundToHead(workspaceRoot, sha) {
328
+ const isAnc = await new Promise((done) => execFile("git", ["merge-base", "--is-ancestor", sha, "HEAD"], { cwd: workspaceRoot, env: gitEnvForCwd() }, (err) => done(!err)));
329
+ if (!isAnc)
330
+ return false;
331
+ // --first-parent -m: a merge reports its full first-parent diff, so code
332
+ // brought in by a merge cannot pass as an empty "docs-only" commit.
333
+ const log = await execGit(workspaceRoot, [
334
+ "log",
335
+ "--first-parent",
336
+ "-m",
337
+ "--format=%x1e%B%x1f",
338
+ "--name-only",
339
+ `${sha}..HEAD`,
340
+ ]);
341
+ const count = Number((await execGit(workspaceRoot, ["rev-list", "--count", `${sha}..HEAD`])) || "0");
342
+ const chunks = log.split("\x1e").filter((c) => c.includes("\x1f"));
343
+ // Fail closed: commits exist but their log could not be read.
344
+ if (count > 0 && chunks.length === 0)
345
+ return false;
346
+ for (const chunk of chunks) {
347
+ const [body = "", files = ""] = chunk.split("\x1f");
348
+ const touched = files
349
+ .split("\n")
350
+ .map((l) => l.trim())
351
+ .filter(Boolean);
352
+ const docsOnly = touched.every((f) => f.startsWith("docs/"));
353
+ if (!docsOnly && !hasVerifierTrailers(body))
354
+ return false;
355
+ }
356
+ return true;
357
+ }
358
+ /**
359
+ * RFC-IMP-06 (probe-bearing RFCs need a passing envelope) + RFC-IMP-09
360
+ * (committed envelope must hash-match the committed bytes — RFC-1271) as one
361
+ * evaluator. The default path runs it pre-lock; --check-criteria runs it
362
+ * in-lock against the envelope its emit-if-needed pass may have just
363
+ * refreshed. One ruleset, two invocation orders — the paths cannot diverge.
364
+ */
365
+ async function evaluateStampEvidenceGates(opts) {
366
+ const { evidenceCheck, requiresEvidence, hasProbes, targetId, rfcFilePath, acceptance } = opts;
367
+ const violations = [];
368
+ const warnings = [];
369
+ let evidenceRelPath;
370
+ // ── RFC-IMP-10 / RFC-IMP-11: git-derived origin gates (RFC-1330) ─────────
371
+ // Derived fresh at stamp time (head = HEAD) — the committed envelope's
372
+ // origin records are volatile context and may predate later commits.
373
+ if (hasProbes && String(opts.frontmatter["createdAt"] ?? "") >= RFC_ORIGIN_CUTOFF) {
374
+ const probes = acceptance;
375
+ const origins = await deriveProbeOrigins({
376
+ git: createOriginGit(opts.workspaceRoot),
377
+ rfcRelPath: relative(opts.workspaceRoot, rfcFilePath),
378
+ frontmatter: opts.frontmatter,
379
+ probes,
380
+ });
381
+ const gate = evaluateOriginGates({
382
+ targetId,
383
+ frontmatter: opts.frontmatter,
384
+ body: await opts.io.readFile(rfcFilePath),
385
+ probes,
386
+ origins,
387
+ });
388
+ violations.push(...gate.errors);
389
+ warnings.push(...gate.warnings);
390
+ }
391
+ // RFC-IMP-12 applies to every post-cutoff HIGH-tier RFC, probe-bearing or not.
392
+ // ── RFC-IMP-12: acceptance-verification report (RFC-1333) ─────────────
393
+ const acc = await evaluateAcceptanceVerificationGate({
394
+ targetId,
395
+ frontmatter: opts.frontmatter,
396
+ reports: await readAcceptanceReports(opts.workspaceRoot, targetId),
397
+ isCandidateBound: (sha) => candidateBoundToHead(opts.workspaceRoot, sha),
398
+ waiverReason: opts.waiverReason,
399
+ });
400
+ violations.push(...acc.errors);
401
+ warnings.push(...acc.warnings);
402
+ // ── RFC-IMP-06: probe-bearing post-cutoff RFCs need a passing envelope ────
403
+ if (requiresEvidence) {
404
+ if (!evidenceCheck.exists || evidenceCheck.overall !== "pass") {
405
+ violations.push({
406
+ rule: "RFC-IMP-06",
407
+ 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}`,
408
+ });
409
+ }
410
+ else {
411
+ evidenceRelPath = join(VERIFICATION_DIR, `${targetId.toLowerCase()}.generated.yaml`);
412
+ }
413
+ }
414
+ // ── RFC-IMP-09: stale evidence gate (RFC-1271) ────────────────────────────
415
+ // Hashes are recomputed from the working tree; combined with RFC-IMP-04
416
+ // (the RFC file must be committed-clean to stamp) the compared bytes are
417
+ // effectively the committed bytes — deliberate, keeps the gate honest
418
+ // without a second git read.
419
+ if (evidenceCheck.exists) {
420
+ if (evidenceCheck.malformed || !evidenceCheck.envelope) {
421
+ violations.push({
422
+ rule: "RFC-IMP-09",
423
+ 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.`,
424
+ });
425
+ }
426
+ else if (!hasProbes) {
427
+ violations.push({
428
+ rule: "RFC-IMP-09",
429
+ 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).`,
430
+ });
431
+ }
432
+ else {
433
+ const rfcMarkdown = await opts.io.readFile(rfcFilePath);
434
+ const currentFileHash = byteHashHex(rfcMarkdown);
435
+ const currentAcceptanceHash = byteHashHex(normalizeProbes(acceptance));
436
+ const env = evidenceCheck.envelope;
437
+ if (!env.rfcFileHash || !env.acceptanceHash) {
438
+ violations.push({
439
+ rule: "RFC-IMP-09",
440
+ 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.`,
441
+ });
442
+ }
443
+ else if (env.rfcFileHash !== currentFileHash ||
444
+ env.acceptanceHash !== currentAcceptanceHash) {
445
+ const staleFields = [
446
+ env.rfcFileHash !== currentFileHash ? "rfcFileHash" : "",
447
+ env.acceptanceHash !== currentAcceptanceHash ? "acceptanceHash" : "",
448
+ ]
449
+ .filter(Boolean)
450
+ .join(" + ");
451
+ violations.push({
452
+ rule: "RFC-IMP-09",
453
+ 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.`,
454
+ });
455
+ }
456
+ }
457
+ }
458
+ return { violations, warnings, evidenceRelPath };
459
+ }
460
+ /** In-memory auto-check pass over the unchecked criteria of the committed body. */
461
+ async function autoCheckCriteria(opts) {
462
+ const outcome = {
463
+ flippable: [],
464
+ flippedIds: [],
465
+ failures: [],
466
+ pendingRefresh: [],
467
+ };
468
+ for (const line of opts.uncheckedLines) {
469
+ const label = criterionLabelOf(line);
470
+ const annotation = extractEvidenceAnnotation(line);
471
+ if (!annotation) {
472
+ outcome.failures.push({
473
+ criterion: label,
474
+ annotation: "<no (evidence: ...) annotation>",
475
+ });
476
+ continue;
477
+ }
478
+ if (!opts.probesUsable && annotation.startsWith("probe:")) {
479
+ // Store the trimmed line so the post-flip gate can exclude pending
480
+ // criteria from the residual-unchecked check (they flip post-emit in
481
+ // the real run); labels derive via criterionLabelOf when reported.
482
+ outcome.pendingRefresh.push(line);
483
+ continue;
484
+ }
485
+ if (await resolveCriterionEvidence(annotation, opts.envelope, opts.workspaceRoot, opts.io)) {
486
+ outcome.flippable.push(line);
487
+ outcome.flippedIds.push(label);
488
+ }
489
+ else {
490
+ outcome.failures.push({ criterion: label, annotation });
491
+ }
492
+ }
493
+ return outcome;
494
+ }
495
+ /**
496
+ * Flip `- [ ]` → `- [x]` for the given unchecked criterion lines inside the
497
+ * source's `## Acceptance criteria` section only — fenced code blocks are
498
+ * skipped so a section example inside ``` fences never becomes a flip target
499
+ * (the same guard the section extractors apply), and `## Document readiness`
500
+ * DR-N items are out of scope by construction.
501
+ */
502
+ export function flipCriteriaInSource(source, uncheckedTargets) {
503
+ const lines = source.split("\n");
504
+ let inFence = false;
505
+ let inSection = false;
506
+ for (let i = 0; i < lines.length; i++) {
507
+ const line = lines[i];
508
+ if (/^```/.test(line)) {
509
+ inFence = !inFence;
510
+ continue;
511
+ }
512
+ if (inFence)
513
+ continue;
514
+ if (/^## /.test(line)) {
515
+ inSection = /^## Acceptance criteria\s*$/.test(line);
516
+ continue;
517
+ }
518
+ if (inSection && /^\s*- \[ \]/.test(line) && uncheckedTargets.has(line.trim())) {
519
+ lines[i] = line.replace(/- \[ \]/, "- [x]");
520
+ }
521
+ }
522
+ return lines.join("\n");
523
+ }
176
524
  // ─── Main handler ────────────────────────────────────────────────────────────
177
525
  export async function runRfcImplementStamp(input, context) {
178
526
  const io = resolveIo(context.io);
179
527
  const { workspaceRoot, logger, outputFormat, dryRun } = context;
180
528
  const rfcDirPath = join(workspaceRoot, RFC_DIR);
181
- const targetId = input.flags["id"];
529
+ // RFC-1321: canonicalize the governance id at parse — every stored surface
530
+ // (result rfcId, post-stamp re-emit flags, metrics ids) carries the
531
+ // canonical uppercase spelling regardless of flag casing. A non-string flag
532
+ // (repeated --id forms an array) degrades to absent rather than crashing.
533
+ const rawId = input.flags["id"];
534
+ const targetId = typeof rawId === "string" ? rawId.toUpperCase() : undefined;
182
535
  let implementationCommit = input.flags["implementation-commit"];
183
536
  // ── Flag validation ───────────────────────────────────────────────────────
184
537
  if (!targetId) {
@@ -186,6 +539,10 @@ export async function runRfcImplementStamp(input, context) {
186
539
  }
187
540
  const violations = [];
188
541
  const isDryRun = dryRun || input.flags["dry-run"] === true;
542
+ // RFC-1322: the stamp performs the checkbox flips itself — but only for
543
+ // criteria whose (evidence: ...) annotation resolves — and refreshes a
544
+ // missing/stale envelope in-process before the gates evaluate it.
545
+ const checkCriteria = input.flags["check-criteria"] === true;
189
546
  // ── Find the target RFC ───────────────────────────────────────────────────
190
547
  const files = await listRfcFiles(rfcDirPath);
191
548
  const targetFile = files.find((f) => rfcFileMatchesId(f, targetId));
@@ -222,15 +579,51 @@ export async function runRfcImplementStamp(input, context) {
222
579
  });
223
580
  return stampFailResult(violations, isDryRun, outputFormat, logger);
224
581
  }
582
+ // ── RFC-1306: --sync runs the evidence-resync chain before stamping ────────
583
+ // Positioned after the target RFC resolves (so --id is real) and before any
584
+ // criteria/commit/evidence read, so the IMP-06/09 gates see fresh artifacts.
585
+ // The chain is delegated by name through the kernel host's invoke port — the
586
+ // standalone forge CLI has no host and fails closed like rfc.evidence.sync.
587
+ if (input.flags["sync"] === true) {
588
+ if (!context.invoke) {
589
+ violations.push({
590
+ rule: "EVIDENCE-SYNC-01",
591
+ message: "--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.",
592
+ });
593
+ return stampFailResult(violations, isDryRun, outputFormat, logger);
594
+ }
595
+ let syncReport;
596
+ try {
597
+ syncReport = await context.invoke("rfc.evidence.sync", { id: targetId });
598
+ }
599
+ catch (err) {
600
+ violations.push({
601
+ rule: "EVIDENCE-SYNC-02",
602
+ message: `rfc.evidence.sync threw before stamping: ${err instanceof Error ? err.message : String(err)}. Resolve the failing step and re-run the stamp.`,
603
+ });
604
+ return stampFailResult(violations, isDryRun, outputFormat, logger);
605
+ }
606
+ if (syncReport.exitCode !== 0) {
607
+ violations.push({
608
+ rule: "EVIDENCE-SYNC-02",
609
+ message: `rfc.evidence.sync failed before stamping${syncReport.summary ? `: ${syncReport.summary}` : ""}. Resolve the failing step and re-run the stamp.`,
610
+ });
611
+ return stampFailResult(violations, isDryRun, outputFormat, logger);
612
+ }
613
+ logger.info(`[rfc.implement.stamp] --sync: ${syncReport.summary ?? "resync chain completed"}`);
614
+ }
225
615
  // ── RFC-IMP-02: criterion checks (V-26/V-27 semantics) ────────────────────
616
+ // Under --check-criteria both branches defer: unchecked lines become flip
617
+ // candidates for the auto-check pass, and checkedWithoutEvidence re-runs on
618
+ // the post-flip body — a flipped line always keeps its annotation.
226
619
  const criteriaEval = evaluateAcceptanceCriteria(body);
227
- if (criteriaEval.totalUnchecked > 0) {
620
+ if (!checkCriteria && criteriaEval.totalUnchecked > 0) {
228
621
  violations.push({
229
622
  rule: "RFC-IMP-02",
230
623
  message: `${criteriaEval.totalUnchecked} acceptance criteria are unchecked. All criteria must be checked before stamping: ${criteriaEval.uncheckedLines.join("; ")}`,
231
624
  });
232
625
  }
233
- if (criteriaEval.checkedWithoutEvidence.length > 0) {
626
+ if (!checkCriteria && criteriaEval.checkedWithoutEvidence.length > 0) {
234
627
  violations.push({
235
628
  rule: "RFC-IMP-02",
236
629
  message: `${criteriaEval.checkedWithoutEvidence.length} checked criteria lack inline (evidence: ...) annotation: ${criteriaEval.checkedWithoutEvidence.join("; ")}`,
@@ -260,10 +653,14 @@ export async function runRfcImplementStamp(input, context) {
260
653
  }
261
654
  }
262
655
  // ── RFC-0756: auto-detect implementation commit when --implementation-commit is omitted ──
656
+ // RFC-1310 STAMP-GOV-01: auto-detect candidates join the provenance scan
657
+ // set — a trailer on any implementation-shaped commit counts.
658
+ const provenanceCandidateShas = [];
263
659
  if (!implementationCommit) {
264
660
  const detected = await autoDetectImplementationCommit(workspaceRoot, targetId);
265
661
  if ("sha" in detected) {
266
662
  implementationCommit = detected.sha;
663
+ provenanceCandidateShas.push(detected.sha);
267
664
  }
268
665
  else if ("none" in detected) {
269
666
  violations.push({
@@ -275,6 +672,7 @@ export async function runRfcImplementStamp(input, context) {
275
672
  // Auto-resolve when exactly one candidate looks like an implementation
276
673
  // commit — a multi-commit RFC pipeline (audit → plan → implement → docs →
277
674
  // review) references the id at every step, but only one step implements.
675
+ provenanceCandidateShas.push(...detected.multiple.map((c) => c.sha));
278
676
  const implCandidates = detected.multiple.filter((c) => IMPLEMENTATION_SUBJECT_RE.test(c.message));
279
677
  if (implCandidates.length === 1) {
280
678
  implementationCommit = implCandidates[0].sha;
@@ -326,6 +724,28 @@ export async function runRfcImplementStamp(input, context) {
326
724
  message: `Implementation commit ${implementationCommit} does not reference ${targetId} in its message or changed files.`,
327
725
  });
328
726
  }
727
+ else {
728
+ // ── RFC-1310 STAMP-GOV-01: commit-time governance provenance ──────
729
+ // A subject mention is not provenance — the implementation commit
730
+ // (or an auto-detected sibling candidate) must carry the X-RFC
731
+ // trailer or an injected CHANGE_SUMMARY item, else the stamp would
732
+ // certify a provenance-broken implementation (DNA-59).
733
+ const scanShas = [...new Set([implementationCommit, ...provenanceCandidateShas])];
734
+ logger.info(`[rfc.implement.stamp] STAMP-GOV-01 scanning ${scanShas.length} commit(s): ${scanShas.join(", ")}`);
735
+ let provenance = false;
736
+ for (const sha of scanShas) {
737
+ if (await commitCarriesGovernanceProvenance(workspaceRoot, sha, targetId)) {
738
+ provenance = true;
739
+ break;
740
+ }
741
+ }
742
+ if (!provenance) {
743
+ violations.push({
744
+ rule: "STAMP-GOV-01",
745
+ 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.`,
746
+ });
747
+ }
748
+ }
329
749
  }
330
750
  }
331
751
  // ── RFC-IMP-06: probe-bearing RFCs require passing evidence ───────────────
@@ -333,19 +753,40 @@ export async function runRfcImplementStamp(input, context) {
333
753
  const hasProbes = Array.isArray(acceptance) && acceptance.length > 0;
334
754
  const createdAtStr = String(fm["createdAt"] ?? "");
335
755
  const requiresEvidence = createdAtStr >= RFC_METADATA_CUTOFF && hasProbes;
756
+ const rfcFilePath = join(rfcDirPath, targetFile);
336
757
  let evidenceRelPath;
337
- if (requiresEvidence) {
338
- const evidenceCheck = await checkExistingEvidence(workspaceRoot, targetId);
339
- if (!evidenceCheck.exists || evidenceCheck.overall !== "pass") {
340
- violations.push({
341
- rule: "RFC-IMP-06",
342
- 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}`,
343
- });
344
- }
345
- else {
346
- const slug = targetId.toLowerCase();
347
- evidenceRelPath = join(VERIFICATION_DIR, `${slug}.generated.yaml`);
348
- }
758
+ // RFC-1330/1333: non-blocking stamp findings (waived RFC-IMP-12: missing report or isolation).
759
+ const stampWarnings = [];
760
+ const waiverFlag = input.flags["waive-independent-verification"];
761
+ const waiverReason = typeof waiverFlag === "string" && waiverFlag.trim() ? waiverFlag.trim() : undefined;
762
+ // RFC-1271: the envelope is fetched unconditionally — a committed envelope
763
+ // must also be evaluated when hasProbes is now false, because probe
764
+ // deletion IS a criteria change and would otherwise slip past
765
+ // requiresEvidence entirely (RFC-IMP-08 exempts policy/deprecation kinds).
766
+ // let — --check-criteria re-reads the envelope after the emit-if-needed pass.
767
+ let evidenceCheck = await checkExistingEvidence(workspaceRoot, targetId);
768
+ // Default path: IMP-06 + IMP-09 fire pre-lock via the shared evaluator —
769
+ // under --check-criteria the same ruleset runs inside the lock, after the
770
+ // emit-if-needed pass may have refreshed the envelope.
771
+ if (!checkCriteria) {
772
+ const gates = await evaluateStampEvidenceGates({
773
+ evidenceCheck,
774
+ requiresEvidence,
775
+ hasProbes,
776
+ targetId,
777
+ rfcFilePath,
778
+ acceptance,
779
+ io,
780
+ frontmatter: fm,
781
+ workspaceRoot,
782
+ waiverReason,
783
+ });
784
+ violations.push(...gates.violations);
785
+ stampWarnings.push(...gates.warnings);
786
+ for (const w of gates.warnings)
787
+ logger.warn(`${w.rule}: ${w.message}`);
788
+ if (gates.evidenceRelPath)
789
+ evidenceRelPath = gates.evidenceRelPath;
349
790
  }
350
791
  // ── RFC-IMP-08: minimum-one-probe gate (RFC-0997) ─────────────────────────
351
792
  // Post-cutoff architecture/contract/command RFCs must declare at least one
@@ -363,6 +804,9 @@ export async function runRfcImplementStamp(input, context) {
363
804
  return stampFailResult(violations, isDryRun, outputFormat, logger);
364
805
  }
365
806
  // ── RFC-IMP-05: acquire RFC-specific exclusive lock ───────────────────────
807
+ // Under --check-criteria the lock must precede the FIRST write — which is
808
+ // the emit-if-needed envelope refresh, not the stamp mutation — so all
809
+ // envelope-independent gates above abort before this point.
366
810
  const { acquired, lockPath } = await acquireRfcLock(workspaceRoot, targetId);
367
811
  if (!acquired) {
368
812
  violations.push({
@@ -373,16 +817,138 @@ export async function runRfcImplementStamp(input, context) {
373
817
  }
374
818
  try {
375
819
  // ── Atomic mutation ──────────────────────────────────────────────────────
376
- const rfcFilePath = join(rfcDirPath, targetFile);
377
820
  const rfcSource = await io.readFile(rfcFilePath);
821
+ // RFC-1322: the mutation-bound source — under --check-criteria it carries
822
+ // the auto-check flips; without the flag it is the committed file text.
823
+ let stampSource = rfcSource;
824
+ let criteriaAutoChecked;
825
+ let criteriaPendingRefresh = [];
826
+ let evidenceWouldRefresh = false;
827
+ let effectiveCriteriaChecked = criteriaEval.totalChecked;
828
+ if (checkCriteria) {
829
+ // Emit-if-needed (RFC-1322 order step 4): a missing, malformed, or
830
+ // hash-stale envelope is refreshed in-process through the same direct
831
+ // runRfcVerificationEmit call the post-stamp re-emit uses — on the
832
+ // committed bytes, so IMP-09 keeps evaluating a real file state. The
833
+ // freshness precheck (RFC-1320) gates this emit exactly as a manual one.
834
+ const needsEmit = hasProbes && envelopeNeedsRefresh(evidenceCheck, rfcSource, acceptance);
835
+ evidenceWouldRefresh = needsEmit;
836
+ if (needsEmit && !isDryRun) {
837
+ let emitOk = false;
838
+ let emitSummary = "";
839
+ try {
840
+ const emitResult = await runRfcVerificationEmit({ argv: [], flags: { id: targetId } }, context);
841
+ emitOk = emitResult.exitCode === 0;
842
+ emitSummary = emitResult.summary ?? "";
843
+ }
844
+ catch (emitErr) {
845
+ violations.push({
846
+ rule: "EVIDENCE-SYNC-02",
847
+ message: `pre-stamp evidence emit for ${targetId} threw: ${emitErr instanceof Error ? emitErr.message : String(emitErr)}. Resolve the failing step and re-run the stamp.`,
848
+ });
849
+ return stampFailResult(violations, isDryRun, outputFormat, logger);
850
+ }
851
+ if (!emitOk) {
852
+ violations.push({
853
+ rule: "EVIDENCE-SYNC-02",
854
+ message: `pre-stamp evidence emit for ${targetId} failed${emitSummary ? `: ${emitSummary}` : ""}. Resolve the failing step and re-run the stamp.`,
855
+ });
856
+ return stampFailResult(violations, isDryRun, outputFormat, logger);
857
+ }
858
+ logger.info(`[rfc.implement.stamp] --check-criteria: refreshed stale/missing envelope`);
859
+ evidenceCheck = await checkExistingEvidence(workspaceRoot, targetId);
860
+ }
861
+ // Auto-check pass (RFC-1322 order step 5, in-memory): each unchecked
862
+ // criterion resolves its (evidence: ...) annotation; unresolvable ones
863
+ // abort before any RFC mutation. In dry-run with a pending refresh the
864
+ // probe: annotations are not yet resolvable — pending, not failures.
865
+ const auto = await autoCheckCriteria({
866
+ uncheckedLines: criteriaEval.uncheckedLines,
867
+ envelope: evidenceCheck.envelope,
868
+ probesUsable: !(isDryRun && needsEmit),
869
+ workspaceRoot,
870
+ io,
871
+ });
872
+ criteriaAutoChecked = auto.flippedIds;
873
+ criteriaPendingRefresh = auto.pendingRefresh.map(criterionLabelOf);
874
+ if (auto.failures.length > 0) {
875
+ violations.push({
876
+ rule: "STAMP-CHECK-01",
877
+ message: `${auto.failures.length} unchecked acceptance criteria lack resolvable (evidence: ...) annotations — ` +
878
+ `supply a resolvable reference (test:<path>, file:<path>, <path>:<line>, or probe:AC-N bound to a passing envelope probe): ` +
879
+ auto.failures.map((f) => `${f.criterion} [${f.annotation}]`).join("; "),
880
+ });
881
+ }
882
+ if (auto.flippable.length > 0) {
883
+ stampSource = flipCriteriaInSource(rfcSource, new Set(auto.flippable));
884
+ }
885
+ // Post-flip criteria gates on the mutation-bound bytes (step 6): a
886
+ // still-unchecked line means the flip failed to land — fail closed
887
+ // rather than write a partially checked document; checked lines must
888
+ // keep their annotation (a flipped line always does). Dry-run pending
889
+ // criteria (probe: awaiting the skipped emit) are excluded — the real
890
+ // run resolves them against the refreshed envelope.
891
+ const pendingSet = new Set(auto.pendingRefresh);
892
+ const postFlipEval = evaluateAcceptanceCriteria(stampSource);
893
+ const residualUnchecked = postFlipEval.uncheckedLines.filter((l) => !pendingSet.has(l));
894
+ if (residualUnchecked.length > 0) {
895
+ violations.push({
896
+ rule: "RFC-IMP-02",
897
+ message: `${residualUnchecked.length} acceptance criteria remain unchecked after the --check-criteria pass: ${residualUnchecked.join("; ")}`,
898
+ });
899
+ }
900
+ if (postFlipEval.checkedWithoutEvidence.length > 0) {
901
+ violations.push({
902
+ rule: "RFC-IMP-02",
903
+ message: `${postFlipEval.checkedWithoutEvidence.length} checked criteria lack inline (evidence: ...) annotation: ${postFlipEval.checkedWithoutEvidence.join("; ")}`,
904
+ });
905
+ }
906
+ effectiveCriteriaChecked = postFlipEval.totalChecked;
907
+ // IMP-06 + IMP-09 against the (possibly just-refreshed) envelope via
908
+ // the shared evaluator — skipped in dry-run when a refresh would run,
909
+ // since committed-bytes verdicts are not predictive of the post-emit
910
+ // state the real stamp evaluates.
911
+ if (!(isDryRun && needsEmit)) {
912
+ const gates = await evaluateStampEvidenceGates({
913
+ evidenceCheck,
914
+ requiresEvidence,
915
+ hasProbes,
916
+ targetId,
917
+ rfcFilePath,
918
+ acceptance,
919
+ io,
920
+ frontmatter: fm,
921
+ workspaceRoot,
922
+ waiverReason,
923
+ });
924
+ violations.push(...gates.violations);
925
+ stampWarnings.push(...gates.warnings);
926
+ for (const w of gates.warnings)
927
+ logger.warn(`${w.rule}: ${w.message}`);
928
+ if (gates.evidenceRelPath)
929
+ evidenceRelPath = gates.evidenceRelPath;
930
+ }
931
+ if (violations.length > 0) {
932
+ return stampFailResult(violations, isDryRun, outputFormat, logger);
933
+ }
934
+ }
378
935
  const today = toIsoDate(new Date());
379
936
  const stampedAt = new Date().toISOString();
380
- const mutatedSource = mutateFrontmatter(rfcSource, "implemented", today, today);
937
+ const mutatedSource = mutateFrontmatter(stampSource, "implemented", today, today);
381
938
  if (isDryRun) {
382
939
  if (outputFormat === "pretty") {
383
940
  logger.success(`[dry-run] ${targetId} would be stamped as implemented`);
384
941
  logger.info(` implementation commit: ${implementationCommit}`);
385
- logger.info(` criteria checked: ${criteriaEval.totalChecked}`);
942
+ logger.info(` criteria checked: ${effectiveCriteriaChecked}`);
943
+ if (criteriaAutoChecked && criteriaAutoChecked.length > 0) {
944
+ logger.info(` criteria auto-checked: ${criteriaAutoChecked.join(", ")}`);
945
+ }
946
+ if (criteriaPendingRefresh.length > 0) {
947
+ logger.info(` criteria pending envelope refresh: ${criteriaPendingRefresh.join(", ")}`);
948
+ }
949
+ if (evidenceWouldRefresh) {
950
+ logger.info(` evidence envelope would be refreshed (missing or stale)`);
951
+ }
386
952
  if (evidenceRelPath) {
387
953
  logger.info(` evidence: ${evidenceRelPath}`);
388
954
  }
@@ -391,11 +957,19 @@ export async function runRfcImplementStamp(input, context) {
391
957
  data: {
392
958
  command: "rfc.implement.stamp",
393
959
  status: "pass",
960
+ ...(stampWarnings.length > 0 ? { warnings: stampWarnings } : {}),
394
961
  data: {
395
962
  rfcId: targetId,
396
963
  implementationCommit: implementationCommit,
397
964
  stampedAt,
398
- criteriaChecked: criteriaEval.totalChecked,
965
+ criteriaChecked: effectiveCriteriaChecked,
966
+ ...(checkCriteria
967
+ ? {
968
+ criteriaAutoChecked: criteriaAutoChecked ?? [],
969
+ criteriaPendingRefresh,
970
+ evidenceWouldRefresh,
971
+ }
972
+ : {}),
399
973
  ...(evidenceRelPath ? { evidencePath: evidenceRelPath } : {}),
400
974
  },
401
975
  violations: [],
@@ -404,7 +978,8 @@ export async function runRfcImplementStamp(input, context) {
404
978
  summary: `rfc.implement.stamp: dry-run — ${targetId} would be stamped`,
405
979
  };
406
980
  }
407
- // Write the mutated RFC file atomically
981
+ // Write the mutated RFC file atomically — under --check-criteria this
982
+ // single write carries the checkbox flips AND the frontmatter mutation.
408
983
  await writeFileAtomic(rfcFilePath, mutatedSource);
409
984
  // ── RFC-1053: Generate per-RFC metrics (non-fatal, guarded by !isDryRun) ─
410
985
  let metricsPath;
@@ -416,16 +991,36 @@ export async function runRfcImplementStamp(input, context) {
416
991
  logger.warn(`[metrics] Failed to generate metrics for ${targetId}: ${metricsErr.message}`);
417
992
  }
418
993
  }
419
- // ── Re-emit evidence if probes exist (to update with new status) ─────────
420
- if (hasProbes && requiresEvidence && evidenceRelPath) {
421
- // Evidence already exists and passed — no need to re-emit on stamp
422
- // The evidence was generated before stamping; the status change is
423
- // recorded in the RFC frontmatter, not in the evidence file.
994
+ // ── RFC-1271: post-stamp evidence re-emit ────────────────────────────────
995
+ // The frontmatter mutation above changes the bytes RFC-IMP-09 binds via
996
+ // rfcFileHash — without re-emission every successful stamp manufactures a
997
+ // stale envelope. Re-emit inside the stamp for probe-bearing RFCs so the
998
+ // committed envelope describes the implemented-state file. Non-fatal:
999
+ // the mutation is already written; a failed re-emit leaves a stale
1000
+ // envelope the operator re-emits manually.
1001
+ let evidenceReEmitted = false;
1002
+ if (hasProbes) {
1003
+ try {
1004
+ const emitResult = await runRfcVerificationEmit({ argv: [], flags: { id: targetId } }, context);
1005
+ evidenceReEmitted = emitResult.exitCode === 0;
1006
+ if (evidenceReEmitted) {
1007
+ evidenceRelPath = join(VERIFICATION_DIR, `${targetId.toLowerCase()}.generated.yaml`);
1008
+ }
1009
+ else {
1010
+ logger.warn(`[evidence] post-stamp re-emit failed for ${targetId} — re-run: site-kernel run rfc.verification.emit --id ${targetId}`);
1011
+ }
1012
+ }
1013
+ catch (emitErr) {
1014
+ logger.warn(`[evidence] post-stamp re-emit failed for ${targetId}: ${emitErr.message}`);
1015
+ }
424
1016
  }
425
1017
  if (outputFormat === "pretty") {
426
1018
  logger.success(`${targetId} stamped as implemented`);
427
1019
  logger.info(` implementation commit: ${implementationCommit}`);
428
- logger.info(` criteria checked: ${criteriaEval.totalChecked}`);
1020
+ logger.info(` criteria checked: ${effectiveCriteriaChecked}`);
1021
+ if (criteriaAutoChecked && criteriaAutoChecked.length > 0) {
1022
+ logger.info(` criteria auto-checked: ${criteriaAutoChecked.join(", ")}`);
1023
+ }
429
1024
  if (evidenceRelPath) {
430
1025
  logger.info(` evidence: ${evidenceRelPath}`);
431
1026
  }
@@ -435,12 +1030,15 @@ export async function runRfcImplementStamp(input, context) {
435
1030
  data: {
436
1031
  command: "rfc.implement.stamp",
437
1032
  status: "pass",
1033
+ ...(stampWarnings.length > 0 ? { warnings: stampWarnings } : {}),
438
1034
  data: {
439
1035
  rfcId: targetId,
440
1036
  implementationCommit: implementationCommit,
441
1037
  stampedAt,
442
- criteriaChecked: criteriaEval.totalChecked,
1038
+ criteriaChecked: effectiveCriteriaChecked,
1039
+ ...(checkCriteria ? { criteriaAutoChecked: criteriaAutoChecked ?? [] } : {}),
443
1040
  ...(evidenceRelPath ? { evidencePath: evidenceRelPath } : {}),
1041
+ ...(hasProbes ? { evidenceReEmitted } : {}),
444
1042
  ...(metricsPath ? { metricsPath } : {}),
445
1043
  },
446
1044
  violations: [],