@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,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-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
 
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";
@@ -42,8 +38,32 @@ import {
42
38
  } from "../frontmatter-io.ts";
43
39
  import { evaluateAcceptanceCriteria } from "./validate-rules.ts";
44
40
  import { toIsoDate } from "./shared.ts";
45
- import { RFC_DIR, RFC_METADATA_CUTOFF, RFC_PROBE_BINDING_CUTOFF } from "../types.ts";
46
- import type { RfcStatus, RfcImplementStampViolation, RfcImplementStampResult } from "../types.ts";
41
+ import { byteHashHex, normalizeProbes, runRfcVerificationEmit } from "../verification-evidence.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";
59
+ import type {
60
+ RfcStatus,
61
+ RfcImplementStampViolation,
62
+ RfcImplementStampResult,
63
+ AcceptanceProbe,
64
+ VerificationEvidence,
65
+ } from "../types.ts";
66
+ import type { WorkspaceIO } from "../../../src/types.ts";
47
67
 
48
68
  // Ambient default for helper fns without a context param — handlers override
49
69
  // with `const io = resolveIo(context.io)` inside their own scope.
@@ -65,13 +85,18 @@ const IMPLEMENTATION_SUBJECT_RE = /^(implement|feat)(\([^)]*\))?!?:/i;
65
85
 
66
86
  function execGit(workspaceRoot: string, args: string[]): Promise<string> {
67
87
  return new Promise((resolve) => {
68
- execFile("git", args, { cwd: workspaceRoot, timeout: 10000 }, (err, stdout) => {
69
- if (err) {
70
- resolve("");
71
- return;
72
- }
73
- resolve(stdout.trim());
74
- });
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
+ );
75
100
  });
76
101
  }
77
102
 
@@ -89,7 +114,7 @@ async function commitReachableFromHead(workspaceRoot: string, commitSha: string)
89
114
  execFile(
90
115
  "git",
91
116
  ["merge-base", "--is-ancestor", commitSha, "HEAD"],
92
- { cwd: workspaceRoot, timeout: 10000 },
117
+ { cwd: workspaceRoot, timeout: 30000, env: gitEnvForCwd() },
93
118
  (err) => {
94
119
  resolve(!err);
95
120
  },
@@ -106,6 +131,7 @@ async function autoDetectImplementationCommit(
106
131
  const hashes = await execGit(workspaceRoot, [
107
132
  "log",
108
133
  "--fixed-strings",
134
+ "--regexp-ignore-case",
109
135
  "--no-merges",
110
136
  `--grep=${rfcId}`,
111
137
  "--format=%H",
@@ -119,6 +145,7 @@ async function autoDetectImplementationCommit(
119
145
  const details = await execGit(workspaceRoot, [
120
146
  "log",
121
147
  "--fixed-strings",
148
+ "--regexp-ignore-case",
122
149
  "--no-merges",
123
150
  `--grep=${rfcId}`,
124
151
  "--format=%h %s",
@@ -137,6 +164,39 @@ async function autoDetectImplementationCommit(
137
164
  return { multiple: candidates };
138
165
  }
139
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
+
140
200
  async function commitReferencesRfc(
141
201
  workspaceRoot: string,
142
202
  commitSha: string,
@@ -144,7 +204,11 @@ async function commitReferencesRfc(
144
204
  ): Promise<boolean> {
145
205
  // Check the commit message and the diff for the RFC ID
146
206
  const commitMsg = await execGit(workspaceRoot, ["log", "-1", "--format=%B", commitSha]);
147
- 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;
148
212
 
149
213
  // Also check if the commit touched a file whose name contains the RFC id
150
214
  const changedFiles = await execGit(workspaceRoot, [
@@ -154,7 +218,7 @@ async function commitReferencesRfc(
154
218
  commitSha,
155
219
  ]);
156
220
  const slug = rfcId.toLowerCase();
157
- if (changedFiles.toLowerCase().includes(slug)) return true;
221
+ if (new RegExp(`${esc(slug)}(?!\\d)`).test(changedFiles.toLowerCase())) return true;
158
222
 
159
223
  return false;
160
224
  }
@@ -200,16 +264,38 @@ async function releaseRfcLock(lockPath: string): Promise<void> {
200
264
  async function checkExistingEvidence(
201
265
  workspaceRoot: string,
202
266
  rfcId: string,
203
- ): Promise<{ exists: boolean; overall: string }> {
267
+ ): Promise<{
268
+ exists: boolean;
269
+ overall: string;
270
+ envelope: VerificationEvidence | null;
271
+ malformed: boolean;
272
+ }> {
204
273
  const slug = rfcId.toLowerCase();
205
274
  const evidencePath = join(workspaceRoot, VERIFICATION_DIR, `${slug}.generated.yaml`);
275
+ let content: string;
276
+ try {
277
+ content = await io.readFile(evidencePath);
278
+ } catch {
279
+ return { exists: false, overall: "missing", envelope: null, malformed: false };
280
+ }
281
+ let parsed: unknown;
206
282
  try {
207
- const content = await io.readFile(evidencePath);
208
- const evidence = yamlParse(content) as { overall?: string };
209
- return { exists: true, overall: String(evidence.overall ?? "") };
283
+ parsed = yamlParse(content);
210
284
  } catch {
211
- return { exists: false, overall: "missing" };
285
+ return { exists: true, overall: "malformed", envelope: null, malformed: true };
286
+ }
287
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
288
+ // Fail closed: a committed envelope that parses to a scalar/array is
289
+ // malformed evidence, not absent evidence.
290
+ return { exists: true, overall: "malformed", envelope: null, malformed: true };
212
291
  }
292
+ const evidence = parsed as VerificationEvidence;
293
+ return {
294
+ exists: true,
295
+ overall: String(evidence.overall ?? ""),
296
+ envelope: evidence,
297
+ malformed: false,
298
+ };
213
299
  }
214
300
 
215
301
  // ─── Frontmatter mutation ────────────────────────────────────────────────────
@@ -242,6 +328,383 @@ function mutateFrontmatter(
242
328
  return content;
243
329
  }
244
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
+
245
708
  // ─── Main handler ────────────────────────────────────────────────────────────
246
709
 
247
710
  export async function runRfcImplementStamp(
@@ -252,7 +715,12 @@ export async function runRfcImplementStamp(
252
715
  const { workspaceRoot, logger, outputFormat, dryRun } = context;
253
716
  const rfcDirPath = join(workspaceRoot, RFC_DIR);
254
717
 
255
- 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;
256
724
  let implementationCommit = input.flags["implementation-commit"] as string | undefined;
257
725
 
258
726
  // ── Flag validation ───────────────────────────────────────────────────────
@@ -262,6 +730,10 @@ export async function runRfcImplementStamp(
262
730
 
263
731
  const violations: RfcImplementStampViolation[] = [];
264
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;
265
737
 
266
738
  // ── Find the target RFC ───────────────────────────────────────────────────
267
739
  const files = await listRfcFiles(rfcDirPath);
@@ -304,15 +776,52 @@ export async function runRfcImplementStamp(
304
776
  return stampFailResult(violations, isDryRun, outputFormat, logger);
305
777
  }
306
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
+
307
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.
308
817
  const criteriaEval = evaluateAcceptanceCriteria(body);
309
- if (criteriaEval.totalUnchecked > 0) {
818
+ if (!checkCriteria && criteriaEval.totalUnchecked > 0) {
310
819
  violations.push({
311
820
  rule: "RFC-IMP-02",
312
821
  message: `${criteriaEval.totalUnchecked} acceptance criteria are unchecked. All criteria must be checked before stamping: ${criteriaEval.uncheckedLines.join("; ")}`,
313
822
  });
314
823
  }
315
- if (criteriaEval.checkedWithoutEvidence.length > 0) {
824
+ if (!checkCriteria && criteriaEval.checkedWithoutEvidence.length > 0) {
316
825
  violations.push({
317
826
  rule: "RFC-IMP-02",
318
827
  message: `${criteriaEval.checkedWithoutEvidence.length} checked criteria lack inline (evidence: ...) annotation: ${criteriaEval.checkedWithoutEvidence.join("; ")}`,
@@ -342,10 +851,14 @@ export async function runRfcImplementStamp(
342
851
  }
343
852
 
344
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[] = [];
345
857
  if (!implementationCommit) {
346
858
  const detected = await autoDetectImplementationCommit(workspaceRoot, targetId);
347
859
  if ("sha" in detected) {
348
860
  implementationCommit = detected.sha;
861
+ provenanceCandidateShas.push(detected.sha);
349
862
  } else if ("none" in detected) {
350
863
  violations.push({
351
864
  rule: "RFC-IMP-03",
@@ -355,6 +868,7 @@ export async function runRfcImplementStamp(
355
868
  // Auto-resolve when exactly one candidate looks like an implementation
356
869
  // commit — a multi-commit RFC pipeline (audit → plan → implement → docs →
357
870
  // review) references the id at every step, but only one step implements.
871
+ provenanceCandidateShas.push(...detected.multiple.map((c) => c.sha));
358
872
  const implCandidates = detected.multiple.filter((c) =>
359
873
  IMPLEMENTATION_SUBJECT_RE.test(c.message),
360
874
  );
@@ -416,6 +930,29 @@ export async function runRfcImplementStamp(
416
930
  rule: "RFC-IMP-03",
417
931
  message: `Implementation commit ${implementationCommit} does not reference ${targetId} in its message or changed files.`,
418
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
+ }
419
956
  }
420
957
  }
421
958
  }
@@ -425,20 +962,42 @@ export async function runRfcImplementStamp(
425
962
  const hasProbes = Array.isArray(acceptance) && (acceptance as unknown[]).length > 0;
426
963
  const createdAtStr = String(fm["createdAt"] ?? "");
427
964
  const requiresEvidence = createdAtStr >= RFC_METADATA_CUTOFF && hasProbes;
965
+ const rfcFilePath = join(rfcDirPath, targetFile);
428
966
 
429
967
  let evidenceRelPath: string | undefined;
430
-
431
- if (requiresEvidence) {
432
- const evidenceCheck = await checkExistingEvidence(workspaceRoot, targetId);
433
- if (!evidenceCheck.exists || evidenceCheck.overall !== "pass") {
434
- violations.push({
435
- rule: "RFC-IMP-06",
436
- 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}`,
437
- });
438
- } else {
439
- const slug = targetId.toLowerCase();
440
- evidenceRelPath = join(VERIFICATION_DIR, `${slug}.generated.yaml`);
441
- }
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;
973
+
974
+ // RFC-1271: the envelope is fetched unconditionally — a committed envelope
975
+ // must also be evaluated when hasProbes is now false, because probe
976
+ // deletion IS a criteria change and would otherwise slip past
977
+ // requiresEvidence entirely (RFC-IMP-08 exempts policy/deprecation kinds).
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;
442
1001
  }
443
1002
 
444
1003
  // ── RFC-IMP-08: minimum-one-probe gate (RFC-0997) ─────────────────────────
@@ -459,6 +1018,9 @@ export async function runRfcImplementStamp(
459
1018
  }
460
1019
 
461
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.
462
1024
  const { acquired, lockPath } = await acquireRfcLock(workspaceRoot, targetId);
463
1025
  if (!acquired) {
464
1026
  violations.push({
@@ -470,18 +1032,147 @@ export async function runRfcImplementStamp(
470
1032
 
471
1033
  try {
472
1034
  // ── Atomic mutation ──────────────────────────────────────────────────────
473
- const rfcFilePath = join(rfcDirPath, targetFile);
474
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
+ }
475
1157
 
476
1158
  const today = toIsoDate(new Date());
477
1159
  const stampedAt = new Date().toISOString();
478
- const mutatedSource = mutateFrontmatter(rfcSource, "implemented", today, today);
1160
+ const mutatedSource = mutateFrontmatter(stampSource, "implemented", today, today);
479
1161
 
480
1162
  if (isDryRun) {
481
1163
  if (outputFormat === "pretty") {
482
1164
  logger.success(`[dry-run] ${targetId} would be stamped as implemented`);
483
1165
  logger.info(` implementation commit: ${implementationCommit}`);
484
- 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
+ }
485
1176
  if (evidenceRelPath) {
486
1177
  logger.info(` evidence: ${evidenceRelPath}`);
487
1178
  }
@@ -490,11 +1181,19 @@ export async function runRfcImplementStamp(
490
1181
  data: {
491
1182
  command: "rfc.implement.stamp",
492
1183
  status: "pass",
1184
+ ...(stampWarnings.length > 0 ? { warnings: stampWarnings } : {}),
493
1185
  data: {
494
1186
  rfcId: targetId,
495
1187
  implementationCommit: implementationCommit!,
496
1188
  stampedAt,
497
- criteriaChecked: criteriaEval.totalChecked,
1189
+ criteriaChecked: effectiveCriteriaChecked,
1190
+ ...(checkCriteria
1191
+ ? {
1192
+ criteriaAutoChecked: criteriaAutoChecked ?? [],
1193
+ criteriaPendingRefresh,
1194
+ evidenceWouldRefresh,
1195
+ }
1196
+ : {}),
498
1197
  ...(evidenceRelPath ? { evidencePath: evidenceRelPath } : {}),
499
1198
  },
500
1199
  violations: [],
@@ -504,7 +1203,8 @@ export async function runRfcImplementStamp(
504
1203
  };
505
1204
  }
506
1205
 
507
- // 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.
508
1208
  await writeFileAtomic(rfcFilePath, mutatedSource);
509
1209
 
510
1210
  // ── RFC-1053: Generate per-RFC metrics (non-fatal, guarded by !isDryRun) ─
@@ -519,17 +1219,42 @@ export async function runRfcImplementStamp(
519
1219
  }
520
1220
  }
521
1221
 
522
- // ── Re-emit evidence if probes exist (to update with new status) ─────────
523
- if (hasProbes && requiresEvidence && evidenceRelPath) {
524
- // Evidence already exists and passed — no need to re-emit on stamp
525
- // The evidence was generated before stamping; the status change is
526
- // recorded in the RFC frontmatter, not in the evidence file.
1222
+ // ── RFC-1271: post-stamp evidence re-emit ────────────────────────────────
1223
+ // The frontmatter mutation above changes the bytes RFC-IMP-09 binds via
1224
+ // rfcFileHash — without re-emission every successful stamp manufactures a
1225
+ // stale envelope. Re-emit inside the stamp for probe-bearing RFCs so the
1226
+ // committed envelope describes the implemented-state file. Non-fatal:
1227
+ // the mutation is already written; a failed re-emit leaves a stale
1228
+ // envelope the operator re-emits manually.
1229
+ let evidenceReEmitted = false;
1230
+ if (hasProbes) {
1231
+ try {
1232
+ const emitResult = await runRfcVerificationEmit(
1233
+ { argv: [], flags: { id: targetId } },
1234
+ context,
1235
+ );
1236
+ evidenceReEmitted = emitResult.exitCode === 0;
1237
+ if (evidenceReEmitted) {
1238
+ evidenceRelPath = join(VERIFICATION_DIR, `${targetId.toLowerCase()}.generated.yaml`);
1239
+ } else {
1240
+ logger.warn(
1241
+ `[evidence] post-stamp re-emit failed for ${targetId} — re-run: site-kernel run rfc.verification.emit --id ${targetId}`,
1242
+ );
1243
+ }
1244
+ } catch (emitErr) {
1245
+ logger.warn(
1246
+ `[evidence] post-stamp re-emit failed for ${targetId}: ${(emitErr as Error).message}`,
1247
+ );
1248
+ }
527
1249
  }
528
1250
 
529
1251
  if (outputFormat === "pretty") {
530
1252
  logger.success(`${targetId} stamped as implemented`);
531
1253
  logger.info(` implementation commit: ${implementationCommit}`);
532
- 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
+ }
533
1258
  if (evidenceRelPath) {
534
1259
  logger.info(` evidence: ${evidenceRelPath}`);
535
1260
  }
@@ -540,12 +1265,15 @@ export async function runRfcImplementStamp(
540
1265
  data: {
541
1266
  command: "rfc.implement.stamp",
542
1267
  status: "pass",
1268
+ ...(stampWarnings.length > 0 ? { warnings: stampWarnings } : {}),
543
1269
  data: {
544
1270
  rfcId: targetId,
545
1271
  implementationCommit: implementationCommit!,
546
1272
  stampedAt,
547
- criteriaChecked: criteriaEval.totalChecked,
1273
+ criteriaChecked: effectiveCriteriaChecked,
1274
+ ...(checkCriteria ? { criteriaAutoChecked: criteriaAutoChecked ?? [] } : {}),
548
1275
  ...(evidenceRelPath ? { evidencePath: evidenceRelPath } : {}),
1276
+ ...(hasProbes ? { evidenceReEmitted } : {}),
549
1277
  ...(metricsPath ? { metricsPath } : {}),
550
1278
  },
551
1279
  violations: [],