@warpgogol/forge 7.0.0 → 8.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (455) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/bin/cli.js +6 -12
  3. package/bin/cli.ts +3 -2
  4. package/bin/resolve-entry.js +24 -0
  5. package/dist/bin/cli.js +3 -2
  6. package/dist/bin/cli.js.map +1 -1
  7. package/dist/os/authority/authority.module.d.ts +3 -0
  8. package/dist/os/authority/authority.module.d.ts.map +1 -0
  9. package/dist/os/authority/authority.module.js +169 -0
  10. package/dist/os/authority/authority.module.js.map +1 -0
  11. package/dist/os/authority/handlers/delegate-revoke.d.ts +15 -0
  12. package/dist/os/authority/handlers/delegate-revoke.d.ts.map +1 -0
  13. package/dist/os/authority/handlers/delegate-revoke.js +91 -0
  14. package/dist/os/authority/handlers/delegate-revoke.js.map +1 -0
  15. package/dist/os/authority/handlers/delegate.d.ts +14 -0
  16. package/dist/os/authority/handlers/delegate.d.ts.map +1 -0
  17. package/dist/os/authority/handlers/delegate.js +134 -0
  18. package/dist/os/authority/handlers/delegate.js.map +1 -0
  19. package/dist/os/authority/handlers/delegation-list.d.ts +12 -0
  20. package/dist/os/authority/handlers/delegation-list.d.ts.map +1 -0
  21. package/dist/os/authority/handlers/delegation-list.js +54 -0
  22. package/dist/os/authority/handlers/delegation-list.js.map +1 -0
  23. package/dist/os/authority/handlers/delegation-validate.d.ts +11 -0
  24. package/dist/os/authority/handlers/delegation-validate.d.ts.map +1 -0
  25. package/dist/os/authority/handlers/delegation-validate.js +132 -0
  26. package/dist/os/authority/handlers/delegation-validate.js.map +1 -0
  27. package/dist/os/authority/helpers.d.ts +36 -0
  28. package/dist/os/authority/helpers.d.ts.map +1 -0
  29. package/dist/os/authority/helpers.js +83 -0
  30. package/dist/os/authority/helpers.js.map +1 -0
  31. package/dist/os/authority/index.d.ts +2 -0
  32. package/dist/os/authority/index.d.ts.map +1 -0
  33. package/dist/os/authority/index.js +14 -0
  34. package/dist/os/authority/index.js.map +1 -0
  35. package/dist/os/compass/comment-safety.d.ts +83 -0
  36. package/dist/os/compass/comment-safety.d.ts.map +1 -0
  37. package/dist/os/compass/comment-safety.js +305 -0
  38. package/dist/os/compass/comment-safety.js.map +1 -0
  39. package/dist/os/compass/compass.module.d.ts.map +1 -1
  40. package/dist/os/compass/compass.module.js +47 -4
  41. package/dist/os/compass/compass.module.js.map +1 -1
  42. package/dist/os/compass/handlers/compass-change-summary-handler.d.ts +2 -1
  43. package/dist/os/compass/handlers/compass-change-summary-handler.d.ts.map +1 -1
  44. package/dist/os/compass/handlers/compass-change-summary-handler.js +34 -10
  45. package/dist/os/compass/handlers/compass-change-summary-handler.js.map +1 -1
  46. package/dist/os/compass/handlers/compass-docs-scaffold.d.ts.map +1 -1
  47. package/dist/os/compass/handlers/compass-docs-scaffold.js +54 -17
  48. package/dist/os/compass/handlers/compass-docs-scaffold.js.map +1 -1
  49. package/dist/os/compass/handlers/compass-header-scaffold-handler.d.ts +14 -0
  50. package/dist/os/compass/handlers/compass-header-scaffold-handler.d.ts.map +1 -0
  51. package/dist/os/compass/handlers/compass-header-scaffold-handler.js +261 -0
  52. package/dist/os/compass/handlers/compass-header-scaffold-handler.js.map +1 -0
  53. package/dist/os/compass/handlers/compass-header-scaffold.d.ts +31 -0
  54. package/dist/os/compass/handlers/compass-header-scaffold.d.ts.map +1 -0
  55. package/dist/os/compass/handlers/compass-header-scaffold.js +739 -0
  56. package/dist/os/compass/handlers/compass-header-scaffold.js.map +1 -0
  57. package/dist/os/compass/handlers/compass-inventory-handler.d.ts.map +1 -1
  58. package/dist/os/compass/handlers/compass-inventory-handler.js +8 -4
  59. package/dist/os/compass/handlers/compass-inventory-handler.js.map +1 -1
  60. package/dist/os/compass/handlers/compass-inventory.d.ts +6 -0
  61. package/dist/os/compass/handlers/compass-inventory.d.ts.map +1 -1
  62. package/dist/os/compass/handlers/compass-inventory.js +28 -13
  63. package/dist/os/compass/handlers/compass-inventory.js.map +1 -1
  64. package/dist/os/compass/handlers/compass-migrate-handler.d.ts.map +1 -1
  65. package/dist/os/compass/handlers/compass-migrate-handler.js +12 -26
  66. package/dist/os/compass/handlers/compass-migrate-handler.js.map +1 -1
  67. package/dist/os/compass/handlers/compass-migrate.d.ts +15 -2
  68. package/dist/os/compass/handlers/compass-migrate.d.ts.map +1 -1
  69. package/dist/os/compass/handlers/compass-migrate.js +58 -20
  70. package/dist/os/compass/handlers/compass-migrate.js.map +1 -1
  71. package/dist/os/compass/handlers/git-revision.d.ts +10 -0
  72. package/dist/os/compass/handlers/git-revision.d.ts.map +1 -1
  73. package/dist/os/compass/handlers/git-revision.js +58 -4
  74. package/dist/os/compass/handlers/git-revision.js.map +1 -1
  75. package/dist/os/compass/handlers/summary-record.d.ts +20 -5
  76. package/dist/os/compass/handlers/summary-record.d.ts.map +1 -1
  77. package/dist/os/compass/handlers/summary-record.js +175 -44
  78. package/dist/os/compass/handlers/summary-record.js.map +1 -1
  79. package/dist/os/compass/index.d.ts +1 -0
  80. package/dist/os/compass/index.d.ts.map +1 -1
  81. package/dist/os/compass/index.js +2 -0
  82. package/dist/os/compass/index.js.map +1 -1
  83. package/dist/os/compass/policy.d.ts +9 -0
  84. package/dist/os/compass/policy.d.ts.map +1 -1
  85. package/dist/os/compass/policy.js +11 -2
  86. package/dist/os/compass/policy.js.map +1 -1
  87. package/dist/os/core/core.module.js +1 -1
  88. package/dist/os/core/handlers/package-health.d.ts.map +1 -1
  89. package/dist/os/core/handlers/package-health.js +1 -6
  90. package/dist/os/core/handlers/package-health.js.map +1 -1
  91. package/dist/os/queue/types.d.ts +2 -0
  92. package/dist/os/queue/types.d.ts.map +1 -1
  93. package/dist/os/queue/types.js +3 -1
  94. package/dist/os/queue/types.js.map +1 -1
  95. package/dist/os/rfc/acceptance.d.ts.map +1 -1
  96. package/dist/os/rfc/acceptance.js +51 -1
  97. package/dist/os/rfc/acceptance.js.map +1 -1
  98. package/dist/os/rfc/decision-log.d.ts.map +1 -1
  99. package/dist/os/rfc/decision-log.js +21 -3
  100. package/dist/os/rfc/decision-log.js.map +1 -1
  101. package/dist/os/rfc/dna-trace.d.ts +2 -0
  102. package/dist/os/rfc/dna-trace.d.ts.map +1 -1
  103. package/dist/os/rfc/dna-trace.js +13 -4
  104. package/dist/os/rfc/dna-trace.js.map +1 -1
  105. package/dist/os/rfc/handlers/implement-stamp-origin.d.ts +37 -0
  106. package/dist/os/rfc/handlers/implement-stamp-origin.d.ts.map +1 -0
  107. package/dist/os/rfc/handlers/implement-stamp-origin.js +118 -0
  108. package/dist/os/rfc/handlers/implement-stamp-origin.js.map +1 -0
  109. package/dist/os/rfc/handlers/implement-stamp.d.ts +41 -1
  110. package/dist/os/rfc/handlers/implement-stamp.d.ts.map +1 -1
  111. package/dist/os/rfc/handlers/implement-stamp.js +594 -81
  112. package/dist/os/rfc/handlers/implement-stamp.js.map +1 -1
  113. package/dist/os/rfc/handlers/rfc-evidence-sync.d.ts +42 -0
  114. package/dist/os/rfc/handlers/rfc-evidence-sync.d.ts.map +1 -0
  115. package/dist/os/rfc/handlers/rfc-evidence-sync.js +147 -0
  116. package/dist/os/rfc/handlers/rfc-evidence-sync.js.map +1 -0
  117. package/dist/os/rfc/handlers/validate-rules.d.ts +9 -1
  118. package/dist/os/rfc/handlers/validate-rules.d.ts.map +1 -1
  119. package/dist/os/rfc/handlers/validate-rules.js +90 -9
  120. package/dist/os/rfc/handlers/validate-rules.js.map +1 -1
  121. package/dist/os/rfc/reachable-symbol.d.ts +17 -0
  122. package/dist/os/rfc/reachable-symbol.d.ts.map +1 -0
  123. package/dist/os/rfc/reachable-symbol.js +376 -0
  124. package/dist/os/rfc/reachable-symbol.js.map +1 -0
  125. package/dist/os/rfc/rfc.module.d.ts.map +1 -1
  126. package/dist/os/rfc/rfc.module.js +89 -5
  127. package/dist/os/rfc/rfc.module.js.map +1 -1
  128. package/dist/os/rfc/types.d.ts +89 -12
  129. package/dist/os/rfc/types.d.ts.map +1 -1
  130. package/dist/os/rfc/types.js +17 -10
  131. package/dist/os/rfc/types.js.map +1 -1
  132. package/dist/os/rfc/verification-evidence.d.ts +10 -1
  133. package/dist/os/rfc/verification-evidence.d.ts.map +1 -1
  134. package/dist/os/rfc/verification-evidence.js +175 -10
  135. package/dist/os/rfc/verification-evidence.js.map +1 -1
  136. package/dist/os/rfc/verification-origin.d.ts +58 -0
  137. package/dist/os/rfc/verification-origin.d.ts.map +1 -0
  138. package/dist/os/rfc/verification-origin.js +346 -0
  139. package/dist/os/rfc/verification-origin.js.map +1 -0
  140. package/dist/os/rfc/verification-refresh.d.ts.map +1 -1
  141. package/dist/os/rfc/verification-refresh.js +11 -1
  142. package/dist/os/rfc/verification-refresh.js.map +1 -1
  143. package/dist/os/rfc/verify-workspace.d.ts +23 -0
  144. package/dist/os/rfc/verify-workspace.d.ts.map +1 -0
  145. package/dist/os/rfc/verify-workspace.js +278 -0
  146. package/dist/os/rfc/verify-workspace.js.map +1 -0
  147. package/dist/os/session/handlers/metrics-rfc.d.ts.map +1 -1
  148. package/dist/os/session/handlers/metrics-rfc.js +3 -0
  149. package/dist/os/session/handlers/metrics-rfc.js.map +1 -1
  150. package/dist/os/session/handlers/save.d.ts.map +1 -1
  151. package/dist/os/session/handlers/save.js +41 -10
  152. package/dist/os/session/handlers/save.js.map +1 -1
  153. package/dist/os/spec/spec-status.d.ts.map +1 -1
  154. package/dist/os/spec/spec-status.js +5 -23
  155. package/dist/os/spec/spec-status.js.map +1 -1
  156. package/dist/os/spec/spec-validate.d.ts.map +1 -1
  157. package/dist/os/spec/spec-validate.js +30 -9
  158. package/dist/os/spec/spec-validate.js.map +1 -1
  159. package/dist/os/workflow/handlers.d.ts +0 -4
  160. package/dist/os/workflow/handlers.d.ts.map +1 -1
  161. package/dist/os/workflow/handlers.js +9 -36
  162. package/dist/os/workflow/handlers.js.map +1 -1
  163. package/dist/os/workflow/index.d.ts +2 -2
  164. package/dist/os/workflow/index.d.ts.map +1 -1
  165. package/dist/os/workflow/index.js +1 -1
  166. package/dist/os/workflow/index.js.map +1 -1
  167. package/dist/os/workflow/types.d.ts +0 -19
  168. package/dist/os/workflow/types.d.ts.map +1 -1
  169. package/dist/os/workflow/types.js +0 -2
  170. package/dist/os/workflow/types.js.map +1 -1
  171. package/dist/os/workflow/workflow.module.d.ts.map +1 -1
  172. package/dist/os/workflow/workflow.module.js +6 -15
  173. package/dist/os/workflow/workflow.module.js.map +1 -1
  174. package/dist/src/authority/delegations.d.ts +108 -0
  175. package/dist/src/authority/delegations.d.ts.map +1 -0
  176. package/dist/src/authority/delegations.js +217 -0
  177. package/dist/src/authority/delegations.js.map +1 -0
  178. package/dist/src/authority/index.d.ts +3 -0
  179. package/dist/src/authority/index.d.ts.map +1 -0
  180. package/dist/src/authority/index.js +17 -0
  181. package/dist/src/authority/index.js.map +1 -0
  182. package/dist/src/authority/signing.d.ts +8 -0
  183. package/dist/src/authority/signing.d.ts.map +1 -0
  184. package/dist/src/authority/signing.js +72 -0
  185. package/dist/src/authority/signing.js.map +1 -0
  186. package/dist/src/config/forge-config.d.ts +5 -0
  187. package/dist/src/config/forge-config.d.ts.map +1 -1
  188. package/dist/src/config/forge-config.js +5 -2
  189. package/dist/src/config/forge-config.js.map +1 -1
  190. package/dist/src/onboarding/agents-generate.js +1 -1
  191. package/dist/src/onboarding/doctor.js +3 -3
  192. package/dist/src/onboarding/doctor.js.map +1 -1
  193. package/dist/src/onboarding/init.js +2 -2
  194. package/dist/src/onboarding/nested-agents-templates.js +1 -1
  195. package/dist/src/onboarding/prettierignore.js +1 -1
  196. package/dist/src/onboarding/upgrade.js +2 -2
  197. package/dist/src/onboarding/workspace-discovery.js +1 -1
  198. package/dist/src/profiles/profile-schema.d.ts +2 -0
  199. package/dist/src/profiles/profile-schema.d.ts.map +1 -1
  200. package/dist/src/profiles/profile-schema.js +1 -0
  201. package/dist/src/profiles/profile-schema.js.map +1 -1
  202. package/dist/src/profiles/stack-profile.d.ts +1 -0
  203. package/dist/src/profiles/stack-profile.d.ts.map +1 -1
  204. package/dist/src/types.d.ts +23 -0
  205. package/dist/src/types.d.ts.map +1 -1
  206. package/dist/src/types.js +2 -1
  207. package/dist/src/types.js.map +1 -1
  208. package/docs/reference/cli.md +0 -1
  209. package/docs/reference/programmatic-api.md +1 -1
  210. package/os/adr/handlers/validate.test.ts +14 -0
  211. package/os/authority/authority.module.ts +183 -0
  212. package/os/authority/authority.test.ts +328 -0
  213. package/os/authority/handlers/delegate-revoke.ts +123 -0
  214. package/os/authority/handlers/delegate.ts +190 -0
  215. package/os/authority/handlers/delegation-list.ts +80 -0
  216. package/os/authority/handlers/delegation-validate.ts +231 -0
  217. package/os/authority/helpers.ts +111 -0
  218. package/os/authority/index.ts +14 -0
  219. package/os/compass/comment-safety.ts +331 -0
  220. package/os/compass/compass.module.ts +50 -4
  221. package/os/compass/handlers/compass-change-summary-handler.ts +41 -11
  222. package/os/compass/handlers/compass-docs-scaffold.ts +59 -17
  223. package/os/compass/handlers/compass-game-extensions.test.ts +3 -7
  224. package/os/compass/handlers/compass-header-scaffold-handler.ts +352 -0
  225. package/os/compass/handlers/compass-header-scaffold.ts +847 -0
  226. package/os/compass/handlers/compass-inventory-handler.ts +9 -4
  227. package/os/compass/handlers/compass-inventory.ts +29 -13
  228. package/os/compass/handlers/compass-migrate-handler.ts +13 -27
  229. package/os/compass/handlers/compass-migrate.ts +77 -21
  230. package/os/compass/handlers/git-revision.ts +59 -4
  231. package/os/compass/handlers/resolve-scan-root-package.test.ts +14 -0
  232. package/os/compass/handlers/resolve-scan-root-workpiece.test.ts +14 -0
  233. package/os/compass/handlers/summary-record.ts +194 -41
  234. package/os/compass/handlers/tests/compass-audit-plan.test.ts +6 -0
  235. package/os/compass/handlers/tests/compass-audit-record.test.ts +6 -0
  236. package/os/compass/handlers/tests/compass-audit-validate.test.ts +6 -0
  237. package/os/compass/handlers/tests/compass-change-summary-handler.test.ts +131 -0
  238. package/os/compass/handlers/tests/compass-docs-validate.test.ts +6 -0
  239. package/os/compass/handlers/tests/compass-header-scaffold.test.ts +896 -0
  240. package/os/compass/handlers/tests/compass-ledger-scope.test.ts +6 -0
  241. package/os/compass/handlers/tests/compass-migrate.test.ts +87 -9
  242. package/os/compass/handlers/tests/compass-policy.test.ts +1 -1
  243. package/os/compass/handlers/tests/compass-text-safety.test.ts +271 -0
  244. package/os/compass/handlers/tests/compass-v2-contract.test.ts +52 -3
  245. package/os/compass/handlers/tests/summary-record.test.ts +324 -3
  246. package/os/compass/index.ts +15 -0
  247. package/os/compass/policy.ts +27 -2
  248. package/os/core/core.module.ts +1 -1
  249. package/os/core/handlers/invariant-engine.test.ts +3 -1
  250. package/os/core/handlers/note-frontmatter-validate.test.ts +6 -1
  251. package/os/core/handlers/note-link-validate.test.ts +6 -1
  252. package/os/core/handlers/note-orphan-detect.test.ts +6 -1
  253. package/os/core/handlers/package-health.test.ts +6 -0
  254. package/os/core/handlers/package-health.ts +1 -6
  255. package/os/mission/handlers/archive.test.ts +14 -0
  256. package/os/naming/naming-convention.test.ts +14 -0
  257. package/os/queue/decision-ledger.test.ts +27 -4
  258. package/os/queue/queue-validate.test.ts +14 -0
  259. package/os/queue/types.ts +3 -1
  260. package/os/rfc/acceptance-reachable.test.ts +146 -0
  261. package/os/rfc/acceptance.test.ts +25 -0
  262. package/os/rfc/acceptance.ts +51 -1
  263. package/os/rfc/decision-log.ts +22 -4
  264. package/os/rfc/dna-trace.ts +17 -5
  265. package/os/rfc/frontmatter-io.test.ts +14 -0
  266. package/os/rfc/handlers/implement-stamp-acceptance-verification.test.ts +81 -0
  267. package/os/rfc/handlers/implement-stamp-binding.test.ts +79 -0
  268. package/os/rfc/handlers/implement-stamp-origin.test.ts +132 -0
  269. package/os/rfc/handlers/implement-stamp-origin.ts +154 -0
  270. package/os/rfc/handlers/implement-stamp-stale.test.ts +20 -2
  271. package/os/rfc/handlers/implement-stamp.ts +714 -87
  272. package/os/rfc/handlers/lifecycle.test.ts +14 -0
  273. package/os/rfc/handlers/rfc-evidence-sync.ts +221 -0
  274. package/os/rfc/handlers/validate-rules-rfc0997.test.ts +14 -0
  275. package/os/rfc/handlers/validate-rules-rfc1006.test.ts +14 -0
  276. package/os/rfc/handlers/validate-rules-rfc1330.test.ts +120 -0
  277. package/os/rfc/handlers/validate-rules-rfc1334.test.ts +65 -0
  278. package/os/rfc/handlers/validate-rules.test.ts +14 -0
  279. package/os/rfc/handlers/validate-rules.ts +122 -13
  280. package/os/rfc/handlers/validate.test.ts +4 -3
  281. package/os/rfc/reachable-symbol.ts +441 -0
  282. package/os/rfc/rfc-0000-template.md +3 -0
  283. package/os/rfc/rfc-create-concurrent.test.ts +6 -0
  284. package/os/rfc/rfc-create-hint.test.ts +6 -0
  285. package/os/rfc/rfc-read-only-no-side-effects.test.ts +6 -0
  286. package/os/rfc/rfc.module.ts +95 -5
  287. package/os/rfc/types.ts +116 -12
  288. package/os/rfc/verification-emit-check.test.ts +14 -0
  289. package/os/rfc/verification-emit-freshness.test.ts +415 -0
  290. package/os/rfc/verification-emit.test.ts +14 -0
  291. package/os/rfc/verification-evidence.ts +230 -10
  292. package/os/rfc/verification-normalize.test.ts +14 -0
  293. package/os/rfc/verification-origin.test.ts +236 -0
  294. package/os/rfc/verification-origin.ts +417 -0
  295. package/os/rfc/verification-refresh.test.ts +14 -0
  296. package/os/rfc/verification-refresh.ts +12 -1
  297. package/os/rfc/verifier/rfc-1333/imp12-binding.acceptance.test.ts +78 -0
  298. package/os/rfc/verifier/rfc-1333/imp12-gate.acceptance.test.ts +81 -0
  299. package/os/rfc/verifier/rfc-1333/skills-and-types.acceptance.test.ts +50 -0
  300. package/os/rfc/verifier/rfc-1333/verify-workspace.acceptance.test.ts +103 -0
  301. package/os/rfc/verify-workspace.test.ts +122 -0
  302. package/os/rfc/verify-workspace.ts +342 -0
  303. package/os/session/handlers/metrics-rfc.ts +3 -0
  304. package/os/session/handlers/save.ts +43 -9
  305. package/os/spec/spec-status.test.ts +130 -0
  306. package/os/spec/spec-status.ts +5 -18
  307. package/os/spec/spec-validate.test.ts +76 -1
  308. package/os/spec/spec-validate.ts +26 -7
  309. package/os/workflow/handlers.ts +8 -42
  310. package/os/workflow/index.ts +1 -4
  311. package/os/workflow/types.ts +0 -22
  312. package/os/workflow/workflow.module.ts +6 -16
  313. package/package.json +13 -1
  314. package/skills/_shared/agent-operating-model.md +1 -1
  315. package/skills/_shared/fo-pipeline-conventions.md +1 -0
  316. package/skills/fo/fo-add-tests/SKILL.md +14 -0
  317. package/skills/fo/fo-fix/SKILL.md +2 -1
  318. package/skills/fo/fo-handoff/SKILL.md +1 -1
  319. package/skills/fo/fo-idea-create-rfc/acceptance-criteria-standard.md +8 -0
  320. package/skills/fo/fo-idea-i-just-want-to-see-the-result/SKILL.md +4 -2
  321. package/skills/fo/fo-idea-implement/SKILL.md +68 -53
  322. package/skills/fo/fo-idea-plan/SKILL.md +3 -1
  323. package/skills/fo/fo-review/SKILL.md +12 -0
  324. package/skills/fo/fo-session-save/learned-principles.md +13 -0
  325. package/skills/fo/fo-step-commit/SKILL.md +1 -1
  326. package/src/authority/delegations.ts +267 -0
  327. package/src/authority/index.ts +38 -0
  328. package/src/authority/signing.ts +73 -0
  329. package/src/bin-entry.test.ts +37 -0
  330. package/src/compass/contract-registry.test.ts +14 -0
  331. package/src/compass/types.test.ts +14 -0
  332. package/src/config/__tests__/resolve-terminology.test.ts +14 -0
  333. package/src/config/forge-config.test.ts +14 -0
  334. package/src/config/forge-config.ts +7 -2
  335. package/src/forge-module.test.ts +14 -0
  336. package/src/knowledge/__tests__/promote.test.ts +14 -0
  337. package/src/knowledge/__tests__/serialize.test.ts +14 -0
  338. package/src/knowledge/__tests__/sync.test.ts +4 -1
  339. package/src/knowledge/budgets.test.ts +14 -0
  340. package/src/knowledge/compact.test.ts +14 -0
  341. package/src/knowledge/parse.test.ts +14 -0
  342. package/src/knowledge/schema.test.ts +14 -0
  343. package/src/migration-adapters/__tests__/ignored-files.test.ts +14 -0
  344. package/src/migration-adapters/__tests__/registry.test.ts +14 -0
  345. package/src/migration-adapters/__tests__/types.test.ts +14 -0
  346. package/src/onboarding/__tests__/workspace-discovery.test.ts +14 -0
  347. package/src/onboarding/agents-generate.ts +1 -1
  348. package/src/onboarding/compass-docs/semantic-layer-block.test.ts +6 -0
  349. package/src/onboarding/create.test.ts +14 -0
  350. package/src/onboarding/doctor-token-check.test.ts +3 -0
  351. package/src/onboarding/doctor.test.ts +14 -0
  352. package/src/onboarding/doctor.ts +3 -3
  353. package/src/onboarding/init.test.ts +14 -0
  354. package/src/onboarding/init.ts +2 -2
  355. package/src/onboarding/nested-agents-templates.ts +1 -1
  356. package/src/onboarding/prettierignore.ts +1 -1
  357. package/src/onboarding/scaffold.test.ts +14 -0
  358. package/src/onboarding/site-workshop-profile.test.ts +3 -0
  359. package/src/onboarding/upgrade.test.ts +14 -0
  360. package/src/onboarding/upgrade.ts +2 -2
  361. package/src/onboarding/workspace-discovery.ts +1 -1
  362. package/src/pipeline-status.test.ts +14 -0
  363. package/src/plugin/forge-plugin-manifest.test.ts +14 -0
  364. package/src/profiles/__tests__/profile-schema.test.ts +14 -0
  365. package/src/profiles/__tests__/stack-profile.test.ts +14 -0
  366. package/src/profiles/__tests__/terminology-utils.test.ts +14 -0
  367. package/src/profiles/profile-schema.ts +1 -0
  368. package/src/tests/acceptance-criteria.test.ts +14 -0
  369. package/src/tests/acceptance-probe-kinds.test.ts +14 -0
  370. package/src/tests/adr-implement-stamp.test.ts +14 -0
  371. package/src/tests/agents-generate-domain.test.ts +3 -0
  372. package/src/tests/agents-generate.test.ts +3 -0
  373. package/src/tests/bindings-schema.test.ts +2 -0
  374. package/src/tests/budgets.test.ts +14 -0
  375. package/src/tests/compact.test.ts +14 -0
  376. package/src/tests/compass-docs-flag.test.ts +6 -0
  377. package/src/tests/compass-docs-scaffold.test.ts +6 -0
  378. package/src/tests/compass-docs-validate-scope.test.ts +6 -0
  379. package/src/tests/contract-registry.test.ts +14 -0
  380. package/src/tests/create.test.ts +3 -0
  381. package/src/tests/discover-pack-skills.test.ts +14 -0
  382. package/src/tests/doctor-autonomy.test.ts +3 -0
  383. package/src/tests/doctor-bindings.test.ts +6 -1
  384. package/src/tests/doctor-dist-freshness.test.ts +26 -2
  385. package/src/tests/doctor-domain.test.ts +6 -1
  386. package/src/tests/doctor-fix.test.ts +3 -0
  387. package/src/tests/doctor-nested-agents.test.ts +3 -0
  388. package/src/tests/doctor-profile-id-known.test.ts +3 -0
  389. package/src/tests/doctor-skills-unmanaged.test.ts +3 -0
  390. package/src/tests/doctor-version-sync.test.ts +4 -1
  391. package/src/tests/editable-generated-region.test.ts +6 -3
  392. package/src/tests/exploration-handlers.test.ts +14 -0
  393. package/src/tests/file-size-lint.test.ts +6 -1
  394. package/src/tests/forge-autonomy-validate.test.ts +3 -1
  395. package/src/tests/forge-config.test.ts +6 -1
  396. package/src/tests/forge-validate-compass-docs.test.ts +6 -0
  397. package/src/tests/fs-atomic.test.ts +14 -0
  398. package/src/tests/fs.test.ts +14 -0
  399. package/src/tests/generated-marker.test.ts +14 -0
  400. package/src/tests/hash.test.ts +14 -0
  401. package/src/tests/implement-stamp.test.ts +476 -10
  402. package/src/tests/init-bindings.test.ts +6 -1
  403. package/src/tests/knowledge-parse.test.ts +14 -0
  404. package/src/tests/knowledge-pbt.test.ts +14 -0
  405. package/src/tests/markdown-table.test.ts +6 -3
  406. package/src/tests/memory-compact.test.ts +3 -0
  407. package/src/tests/memory-scaffold.test.ts +6 -1
  408. package/src/tests/metrics-rfc-1053.test.ts +14 -0
  409. package/src/tests/migration-adapters.test.ts +3 -0
  410. package/src/tests/package-files.test.ts +4 -1
  411. package/src/tests/package-health-lint-surface.test.ts +3 -0
  412. package/src/tests/pinned-check.test.ts +14 -0
  413. package/src/tests/pinned-init.test.ts +14 -0
  414. package/src/tests/pinned-validate.test.ts +14 -0
  415. package/src/tests/plugin-manifest.test.ts +14 -0
  416. package/src/tests/prettierignore-manage.test.ts +3 -0
  417. package/src/tests/profile-schema.test.ts +6 -1
  418. package/src/tests/profile-validate.test.ts +6 -1
  419. package/src/tests/program-lease.test.ts +3 -0
  420. package/src/tests/program-paths-extended.test.ts +3 -0
  421. package/src/tests/program-paths.test.ts +3 -0
  422. package/src/tests/program-property.test.ts +3 -0
  423. package/src/tests/program-schemas.test.ts +3 -0
  424. package/src/tests/program-spec-node.test.ts +3 -0
  425. package/src/tests/promote.test.ts +14 -0
  426. package/src/tests/public-surface.test.ts +6 -1
  427. package/src/tests/registry.test.ts +14 -0
  428. package/src/tests/rfc-evidence-sync.test.ts +347 -0
  429. package/src/tests/rfc-implement-stamp-governance.test.ts +403 -0
  430. package/src/tests/rfc-validate-delegation.test.ts +178 -0
  431. package/src/tests/scaffold-project.test.ts +3 -0
  432. package/src/tests/session-handlers.test.ts +79 -0
  433. package/src/tests/session-pbt.test.ts +14 -0
  434. package/src/tests/skill-agents-sync.test.ts +3 -4
  435. package/src/tests/skill-schema.test.ts +14 -0
  436. package/src/tests/skill-sync-marker.test.ts +3 -0
  437. package/src/tests/skill-validate-knowledge.test.ts +14 -0
  438. package/src/tests/skill-validate.test.ts +14 -0
  439. package/src/tests/stack-profile.test.ts +6 -1
  440. package/src/tests/string-utils.test.ts +14 -0
  441. package/src/tests/upgrade.test.ts +6 -1
  442. package/src/tests/werkstatt-lock.test.ts +14 -0
  443. package/src/tests/workspace-discovery-domain.test.ts +6 -1
  444. package/src/tests/workspace-discovery.test.ts +6 -1
  445. package/src/types.test.ts +14 -0
  446. package/src/types.ts +30 -1
  447. package/src/utils/__tests__/fs-idempotent.test.ts +17 -0
  448. package/src/utils/__tests__/fs-trash.test.ts +17 -0
  449. package/src/utils/fs-atomic.test.ts +17 -0
  450. package/src/utils/fs-trash-sync.test.ts +17 -0
  451. package/src/utils/fs.test.ts +17 -0
  452. package/src/utils/generated-marker.test.ts +17 -0
  453. package/src/utils/hash.test.ts +17 -0
  454. package/src/utils/string-utils.test.ts +17 -0
  455. package/src/validators/__tests__/note-orphan-detect.test.ts +14 -0
@@ -27,6 +27,7 @@ triggerPhrases: ["исправим", "примени findings", "fix all", "fix
27
27
 
28
28
  Sweep batch 1: add Compass v2 headers to 45 SKILL.md files (purpose derived from frontmatter description). Fix non-skill-markdown exclusion to check filename not workspace-relative path (packages/AGENTS.md escaped it). Add .coverage to ignoredDirs.</item>
29
29
  <item>RFC-1247: triggerPhrases vocabulary sync — mined operator phrasing applied to this skill's trigger set.</item>
30
+ <item>RFC-1332: step 4 — reason-gated tests in fo-idea-implement, fo-add-tests, fo-fix</item>
30
31
  </CHANGE_SUMMARY>
31
32
  -->
32
33
 
@@ -99,7 +100,7 @@ For each finding:
99
100
 
100
101
  **Blind-spot pass after two failures on one approach** — after two failed attempts on the same fix approach, and before the next retry or pivot, run the clean-context blind-spot pass defined in `_shared/fo-pipeline-conventions.md` §Blind-spot pass.
101
102
 
102
- After applying fixes, update any tests that should cover the change, then run the relevant package tests before the full build when that saves time.
103
+ After applying fixes, add a test only when the finding is a reproducible defect (prove it with `ref(forge.yaml bindings.commands.verifyReproduction)` against the pre-fix commit) or names a concrete regression risk; otherwise rely on the existing suite. Run the relevant package tests before the full build when that saves time.
103
104
 
104
105
  ### 3. Run scoped typecheck verification
105
106
 
@@ -20,7 +20,7 @@ triggerPhrases: ["create a handoff document", "compact conversation for next age
20
20
  <item>RFC-1097: sweep — SKILL.md headers + classification fixes
21
21
 
22
22
  Sweep batch 1: add Compass v2 headers to 45 SKILL.md files (purpose derived from frontmatter description). Fix non-skill-markdown exclusion to check filename not workspace-relative path (packages/AGENTS.md escaped it). Add .coverage to ignoredDirs.</item>
23
- <item>fix: commit references resolve by project type — ecosystem.commit where registered, plain git commit in forge workshops</item>
23
+ <item>RFC-1154: commit references resolve by project type — ecosystem.commit where registered, plain git commit in forge workshops</item>
24
24
  </CHANGE_SUMMARY>
25
25
  -->
26
26
 
@@ -35,6 +35,14 @@ A criterion is a _falsifiable claim about an observable artifact_, not a descrip
35
35
 
36
36
  **Self-test before submitting:** hand the criteria set to a hostile reviewer who has _only_ the repo and a shell. If they cannot verify every box without talking to you, the spec is prose, not a spec.
37
37
 
38
+ ## Behavioral criteria need execution probes
39
+
40
+ A criterion in WHEN or IF form describes behavior; bind it to a probe that executes something (`test`, `run`, or `page`). A criterion bound only to presence probes — `file-exists`, `command-registered`, or `file-contains`/`json-schema` over a non-document path — fails V-44. Presence probes stay correct for invariant-form `THE … SHALL` criteria (a type is exported, a rule id is declared) and for document targets. Declare `expectationSource:` honestly: the toolchain derives the origin from git history and rejects declarations it contradicts — tests written during implementation are `self`.
41
+
42
+ ## Structural wiring needs a reachable probe
43
+
44
+ Deliverables that are new exported modules or commands get a `probe: reachable` (symbol or command mode) bound to an invariant-form criterion (for example "THE command SHALL be reachable from a pipeline or declared coverage").
45
+
38
46
  ## Phase separation (RFC-1006)
39
47
 
40
48
  RFCs have two phases of criteria:
@@ -249,7 +249,9 @@ This fallback ensures review and fix are never skipped, even if `fo-idea-impleme
249
249
 
250
250
  ### 3. Report and stop
251
251
 
252
- After the pipeline is complete (or if it was interrupted and resumed), present a single summary in `aiLanguage`. **Translate all labels and headings to `aiLanguage`** — the template below is structural only. Only identifiers (RFC-XXXX, ADR-XXXX, file paths) stay untranslated.
252
+ **Terminal gate (MANDATORY, before any summary):** run `queue.validate --file <manifest>` and read the derived per-item status. The summary may only report items the validator derives as `implemented` or `skipped` — plus items the batch itself recorded as parked/blocked (ledger `parked: true` or the in-session `blocked` report language). A derived `in-progress` means the item is NOT done: return to Phase 4 instead of reporting. Never derive "done" from commits, passing tests, or a continuation summary — the validator's derivation is the single source of truth. (Retro 2026-10-17: a batch reported all four items implemented while every one of them still needed step 4.8 — `status: accepted`, unchecked criteria, stale envelopes — and only this gate caught it.)
253
+
254
+ After the gate passes, present a single summary in `aiLanguage`. **Translate all labels and headings to `aiLanguage`** — the template below is structural only. Only identifiers (RFC-XXXX, ADR-XXXX, file paths) stay untranslated.
253
255
 
254
256
  ```
255
257
  ## <Pipeline Summary in aiLanguage>
@@ -278,7 +280,7 @@ If the session was interrupted (agent stopped, context limit, crash, checkpoint
278
280
  - TODO list with steps like "Step N: ..." or "implement: RFC-XXXX step N" — these are implementation steps from the plan phase, meaning the pipeline was in step 4 (implement).
279
281
  - Git log showing `audit:`, `enhance:`, `plan:`, `implement:` commits for the same RFC/ADR — confirming pipeline progress.
280
282
  - If any of these are found, this skill IS the active pipeline — resume it, do not start a new one.
281
- 2. **Detect progress** — check which pipeline steps have already been completed by scanning for:
283
+ 2. **Detect progress** — first run `queue.validate --file <manifest>`; its derived per-item status (`implemented`/`skipped`/`in-progress` + open/parked decision counts) is the authoritative resume point. Then corroborate with artifacts:
282
284
  - Document exists in `docs/rfcs/` or `docs/adrs/` (idea creation done)
283
285
  - Audit report in `docs/audits/audit-rfc-XXXX-*.md`
284
286
  - `enhancedAt` in the RFC frontmatter
@@ -20,25 +20,12 @@ triggerPhrases: ["implement this RFC", "execute the implementation plan", "reali
20
20
  </non-goals>
21
21
  </MODULE_CONTRACT>
22
22
  <CHANGE_SUMMARY>
23
- <item>RFC-1250: ledger-bound implementation — answered entries bind at
24
- prerequisites; emergent questions auto-resolve with auto-resolved log
25
- entries; closed hard-stop enumeration parks the item (dependsOn cascade).</item>
26
- <item>RFC-1097: sweep — SKILL.md headers + classification fixes
27
-
28
- Sweep batch 1: add Compass v2 headers to 45 SKILL.md files (purpose derived from frontmatter description). Fix non-skill-markdown exclusion to check filename not workspace-relative path (packages/AGENTS.md escaped it). Add .coverage to ignoredDirs.</item>
29
- <item>RFC-1224: preserve operator forge.yaml content on upgrade, promote adrImplementStamp binding</item>
30
- <item>RFC-1250: review wave — QUEUE-07 gates un-parked opens only, ledger binding checks, fail-closed loader
31
-
32
- REVIEW-RFC-1250-01 findings: QUEUE-07 no longer fires on parked entries
33
- (the park is the containment — a parked queue stays resumable and the
34
- decision window arbitrates it); loader fails open only on ENOENT —
35
- other read errors are QUEUE-01; ledger gains queue/id-stem binding
36
- (QUEUE-02), Q-N uniqueness (QUEUE-05), and QUEUE-08 hygiene warnings
37
- (missing answers, foreign doc ids); next excludes QUEUE-07-blocked
38
- items; top-level decision totals added. Orchestrator pre-flight treats
39
- QUEUE-07 as the window agenda — structural errors still stop the batch;
40
- maturation skips parked/deferred items; uncovered imperative ask sites
41
- gain collect riders (ADR code-trace, NC markers, audit-verdict guard).</item>
23
+ <item>RFC-1317: unblock AC-7 — repair pre-existing fo-idea-implement SKILL-11/SKILL-17 violations (drop hardcoded werkstatt run literal + internal RFC ids), sync .agents copy</item>
24
+ <item>RFC-1322: step 5 — prescribe --check-criteria stamp + single-commit post-shape</item>
25
+ <item>RFC-1332: step 1 — verifyReproduction binding key; drop platform ids from pipeline skill text (SKILL-17)</item>
26
+ <item>RFC-1332: step 4 — reason-gated tests in fo-idea-implement, fo-add-tests, fo-fix</item>
27
+ <item>RFC-1333: step 4 — acceptance verification mode in fo-review, step 4.4b in fo-idea-implement, RFC-IMP-12 docs</item>
28
+ <history>RFC-1097, RFC-1224, RFC-1250, RFC-1310</history>
42
29
  </CHANGE_SUMMARY>
43
30
  -->
44
31
 
@@ -117,16 +104,19 @@ Execute the plan's step sequence in order. For each step:
117
104
 
118
105
  1. **Execute** the agent actions described in the step.
119
106
  2. **Validate** — run the step's validation command (lightweight only: `rfc.validate`, type checks, unit tests on touched files). Do **not** run heavy checks (`root build`, `build:check`, `astro:check`) during implementation — they run only after all steps are complete.
120
- 3. **Commit** after each step or phase that produces a coherent, complete unit of work:
107
+ 3. **Commit** after each step or phase that produces a coherent, complete unit of work — always through `ecosystem.commit` with the RFC id pre-baked into the `--rfc` flag (a governed id in the subject without the flag fails the commit-parity gate COMMIT-GOV-01, and the implementation commit needs the `X-RFC` trailer for the STAMP-GOV-01 provenance check):
121
108
 
122
109
  > Commands below assume RTK is installed. To check, run `rtk --version` (this is the detection command — it is not prefixed with `rtk` because it IS an `rtk` command). If `rtk --version` fails, RTK is not installed — run all commands without the `rtk` prefix.
123
110
 
124
- ```txt
125
- implement: RFC-XXXX step N — <step title>
111
+ ```sh
112
+ # invoked through the project's command runner — see fo-step-commit
113
+ ecosystem.commit --rfc RFC-XXXX --files <paths> --message "implement: RFC-XXXX step N — <step title>
126
114
 
127
- <one-line description of what was done in this step>.
115
+ <one-line description of what was done in this step>."
128
116
  ```
129
117
 
118
+ For ADR work substitute `--adr ADR-XXXX`. A conversational id mention that must NOT declare governance (e.g. "revert an earlier RFC's behavior") passes `--allow-unlinked` instead — never drop the flag silently.
119
+
130
120
  Stage only the files touched by this step. Do not stage unrelated changes — another agent may be working in a different session.
131
121
 
132
122
  **Implementation principles:**
@@ -143,9 +133,23 @@ Stage only the files touched by this step. Do not stage unrelated changes — an
143
133
  - **Compass scaffolding.** New non-trivial source files in `apps/` or `packages/` must carry `MODULE_CONTRACT` and `CHANGE_SUMMARY` scaffolding. Check the project's invariants file for the canonical Compass markup rule.
144
134
  - **Compass terminology.** Use Compass (not GRACE) in all new code, documentation, and log messages.
145
135
 
146
- #### 4.3b. Write tests
136
+ #### 4.3b. Add tests only with a reason
137
+
138
+ After implementing each plan step, add a test only when it has one of the four reasons below. Tests are written for **agents**, not humans — see `fo-add-tests` for the full process and decision tree.
139
+
140
+ **Reason gate.** Decide per change whether a new automated test is warranted. Exactly one named reason allows it:
141
+
142
+ - `requirement <AC-N>` — the test protects an acceptance criterion of the document being implemented;
143
+ - `defect <ref>` — the test reproduces a defect (review finding id, issue file, failing-log reference);
144
+ - `invariant <ref>` — the test guards a significant invariant (DNA entry, `@ai-invariant` file, or a pure function the property-based-test rule covers);
145
+ - `regression <risk>` — a named, concrete regression risk.
146
+
147
+ No reason → no new test: run the existing suite and the document's probes instead. If the adjacency check flags a new source file, add its inline exemption with the reason (`// test-adjacency: exempt — no test reason: <why>`) rather than a stub test.
148
+
149
+ For `defect`: write the test, then run `ref(forge.yaml bindings.commands.verifyReproduction)` with `{test}` = the test file and `{sha}` = the pre-fix commit. Only a `reproduced` verdict lets the test be committed under this reason; `not-reproduced` means the test does not capture the defect — rewrite it; `inconclusive` means it cannot run on the old code — restructure it against the old public surface or change the reason. Without the binding, record the observed red run in the commit body and report `Degraded: commands.verifyReproduction`.
150
+
151
+ Commits that add test files carry `Test-Reason: <reason>` (one line per file, or one shared line), plus `Repro-Verified: <pre-fix-sha>` for defect reasons.
147
152
 
148
- After implementing each plan step that produces or modifies code, write tests for the new behavior. Tests are written for **agents**, not humans — see `fo-add-tests` for the full process and decision tree.
149
153
 
150
154
  **Principles:**
151
155
 
@@ -189,6 +193,17 @@ Use the `packagesImpacted` and `appsImpacted` frontmatter lists to determine whi
189
193
 
190
194
  **Do not run a full root `root build` or `turbo run build`.** The success criterion is that all impacted workspaces pass their scoped checks, not that the entire ecosystem builds. See root AGENTS.md §Build verification discipline.
191
195
 
196
+ #### 4.4b. Independent acceptance verification
197
+
198
+ Only when the document declares `verificationTier: high`. Run after the implementation is committed and heavy checks pass:
199
+
200
+ 1. `rfc.verify.workspace --id RFC-XXXX --candidate <committed-sha>` — a git-free export with your in-range tests and the document's plan/review/session files stripped.
201
+ 2. Dispatch `fo-review` in acceptance verification mode on that export (fresh clean-context subagent, artifacts only — never your narrative).
202
+ 3. Persist the report the verifier returns; triage each counterexample `confirmed` or `disputed` with a one-line reason.
203
+ 4. For every confirmed counterexample: fix the code, then commit the verifier's minimized check **verbatim** (only location/imports may change) as a regression test together with its `probe: test` binding in the document's `acceptance:` block, in a separate commit carrying `X-Expectation-Origin: independent-verifier` and `X-Verifier-Report: <report path>`. Later edits by you to that file make it `self` again.
204
+ 5. Disputed counterexamples go to the decision ledger for the operator. Repeat with a fresh verifier at most two fix rounds; a third failure parks the item.
205
+ 6. Stamping requires a committed `verdict: pass`, `isolation: subagent` report whose candidate is followed only by verifier-trailer or docs commits.
206
+
192
207
  #### 4.5. Fix errors
193
208
 
194
209
  If any check in step 4.4 fails, fix every error:
@@ -218,56 +233,42 @@ Read the RFC's `## Acceptance criteria` section. For each checkbox:
218
233
  1. **Verify the criterion is met semantically** — check the code does what the criterion says, run the relevant command, or inspect the artifact. Mechanical existence (command registered, test passes) is NOT sufficient. The criterion must describe observable behavior that the RFC defines, not just that a command exists.
219
234
  2. **Check for stubs** — if the code contains TODO, stub, not-implemented, or placeholder logic in the path the criterion covers, the criterion is NOT met. Implement the real logic before marking it.
220
235
  3. **If a criterion is not met**, implement the missing work, commit it, and re-verify.
221
- 4. **Annotate every `[x]` with inline evidence** — add `(evidence: ...)` to each checked criterion, pointing to the _checking mechanism_, not just the artifact. Prefer `probe:AC-N` or `test: path/to/file.test.ts`, then `file:line`. This is enforced by the V-27 evidence discipline.
236
+ 4. **Annotate every criterion with inline evidence** — add `(evidence: ...)` to each `## Acceptance criteria` line, pointing to the _checking mechanism_, not just the artifact. Prefer `probe:AC-N` or `test: path/to/file.test.ts`, then `file:line`. This is enforced by the V-27 evidence discipline. **Leave the box unchecked** — `rfc.implement.stamp --check-criteria` flips evidenced `[ ]` lines itself in the same atomic write as the frontmatter mutation. The annotation grammar the stamp resolves is exactly `test:<path>`, `file:<path>`, `<path>:<line>` (path must exist) and `probe:AC-N` (a probe bound to AC-N must pass in the evidence envelope); any other form — free prose, `file:` prose combos, unbound probe refs — aborts with STAMP-CHECK-01.
222
237
  5. **If a criterion cannot be met** (e.g., requires an external dependency not yet available, requires a pilot that is not registered), do NOT mark it `[x]` and do NOT stamp `implemented`. Instead, split the deferred work into a follow-up RFC via `rfc.supersede.propose`. An RFC with unchecked `[ ]` criteria cannot transition to `implemented` — this is enforced by V-26.
223
238
  6. **Ensure `reviewers` is non-empty** — `rfc.validate` enforces V-25: implemented RFCs with an empty `reviewers` field fail validation. Add at least one reviewer (e.g. `human:<name>`) before stamping `implemented`.
224
239
  7. **Check document readiness** — if the RFC has a `## Document readiness` section, verify every `DR-N` checkbox is checked `[x]`. Unchecked `DR-N` items block `accepted`/`implemented` status via V-38. Document readiness criteria cover document quality (sections present, risks described, alternatives considered), not system behavior — they are checked by inspecting the RFC itself, not by running code.
225
240
 
226
- Do not proceed to step 4.7 until every acceptance criterion checkbox AND every document readiness checkbox is checked with evidence.
241
+ Do not proceed to step 4.7 until every criterion is verified met and carries a resolvable `(evidence: ...)` annotation, and every document readiness checkbox is checked.
227
242
 
228
- #### 4.7. Run acceptance probes and emit evidence
243
+ #### 4.7. Acceptance probes and evidence envelope
229
244
 
230
- If the RFC declares `acceptance:` probes in frontmatter:
245
+ If the RFC declares `acceptance:` probes in frontmatter, sanity-run them once before stamping:
231
246
 
232
247
  ```sh
233
248
  ref(forge.yaml bindings.commands.validateRfc) --acceptance.run --id RFC-XXXX
234
249
  ```
235
250
 
236
- If the RFC was created on or after 2026-07-07 and has acceptance probes:
237
-
238
- ```sh
239
- ref(forge.yaml bindings.commands.validateRfc) --verification.emit --id RFC-XXXX
240
- ```
251
+ The **evidence envelope is NOT emitted or committed manually** — `rfc.implement.stamp --check-criteria` refreshes a missing/malformed/stale envelope in-process on the committed bytes (emit-if-needed) and re-emits it after the mutation so the committed envelope always describes the stamped file. No `rfc.verification.emit` step, no evidence commit.
241
252
 
242
253
  **Note:** If acceptance probes are commented out (`# acceptance:`) in the RFC frontmatter, `rfc.verification.emit` silently skips creating an evidence file (`filesModified: []`, zero errors). This is expected behavior — RFCs with commented-out probes get no evidence file, and `rfc.implement.stamp` still works without it.
243
254
 
244
- Commit the evidence file:
245
-
246
- ```txt
247
- evidence: RFC-XXXX verification artifact
248
-
249
- Emit per-RFC verification evidence for RFC-XXXX implementation.
250
- ```
251
-
252
- Stage `docs/rfcs/verification/rfc-xxxx.generated.json`.
253
-
254
255
  #### 4.8. Stamp implemented
255
256
 
256
257
  Transition the RFC to `implemented` using the `rfc.implement.stamp` command. Direct edits to `status`, `implementedAt`, and `updatedAt` are prohibited for all actors.
257
258
 
258
- 1. Ensure the working tree is clean (all implementation changes committed).
259
+ 1. Ensure the working tree is clean (all implementation changes committed — including the RFC file itself carrying the verified, annotated, still-unchecked criteria).
259
260
  2. Identify the implementation commit SHA — use the **first** `implement:` commit (the commit where implementation began), not the latest fix or documentation commit. Find it via `git log --oneline` and locate the first commit with an `implement:` prefix after the `plan:` or `rfc: accept` commit.
260
- 3. Run the stamp command:
261
+ 3. Run the stamp command **with `--check-criteria`** (the default invocation; the flag auto-checks evidenced criteria, refreshes a missing/stale envelope in-process, and lands flips + frontmatter in one atomic write):
261
262
 
262
263
  ```sh
263
- ref(forge.yaml bindings.commands.implementStamp) --id RFC-XXXX --implementation-commit <sha>
264
+ ref(forge.yaml bindings.commands.implementStamp) --id RFC-XXXX --implementation-commit <sha> --check-criteria
264
265
  ```
265
266
 
266
- The command atomically validates all preconditions (accepted status, checked+evidenced criteria, clean tree, reachable RFC-referencing commit, passing probe evidence) and sets `status: implemented`, `implementedAt`, and `updatedAt` in one atomic write.
267
+ The command atomically validates all preconditions (accepted status, checked+evidenced criteria — flipped in-place when evidenced under the flag, clean tree, reachable RFC-referencing commit, passing probe evidence) and sets `status: implemented`, `implementedAt`, and `updatedAt` in one atomic write. The result reports `criteriaAutoChecked` — the criterion ids the stamp flipped.
267
268
 
268
- **Troubleshooting:** If the stamp fails with `Could not parse target RFC` (RFC-IMP-01), the RFC frontmatter has a YAML syntax error — not a missing file. Check for unquoted backtick values in `successSignals`, `nonGoals`, or other list items. YAML plain scalars starting with a backtick must be double-quoted.
269
+ **Troubleshooting:** If the stamp fails with `Could not parse target RFC` (RFC-IMP-01), the RFC frontmatter has a YAML syntax error — not a missing file. Check for unquoted backtick values in `successSignals`, `nonGoals`, or other list items. YAML plain scalars starting with a backtick must be double-quoted. If it fails STAMP-CHECK-01, the named criteria carry no resolvable `(evidence: ...)` annotation — fix the annotation (or verify the criterion is actually met), commit, and re-stamp; the flag never blank-checks.
269
270
 
270
- 4. Commit the stamped RFC file:
271
+ 4. Commit the stamped artifacts — **one commit** covering the stamped RFC file, the regenerated `docs/rfcs/verification/rfc-xxxx.generated.yaml` envelope, and `docs/metrics/rfcs/rfc-xxxx.metrics.yaml`:
271
272
 
272
273
  ```txt
273
274
  rfc: implement RFC-XXXX <short title>
@@ -276,7 +277,7 @@ Transition the RFC to `implemented` using the `rfc.implement.stamp` command. Dir
276
277
  All acceptance criteria met, verification evidence emitted, scoped build passes.
277
278
  ```
278
279
 
279
- Stage only the RFC file. The implementation commit and the stamp commit MUST be separate.
280
+ Stage the RFC file and the generated envelope + metrics together. The implementation commit and the stamp commit MUST be separate.
280
281
 
281
282
  #### 4.8b. Regenerate command manifest (MANDATORY)
282
283
 
@@ -435,9 +436,23 @@ Read the `## Decision` section and implement it in code. **For each decision poi
435
436
 
436
437
  - If a tool call fails with a recoverable error, recover autonomously: split content, use `edit`/`multi_edit`, decompose files, and retry immediately.
437
438
 
438
- #### 5.3b. Write tests
439
+ #### 5.3b. Add tests only with a reason
440
+
441
+ After implementing the decision, add a test only when it has one of the four reasons below (the same reason classes as step 4.3b). Tests are written for **agents**, not humans — see `fo-add-tests` for the full process and decision tree.
442
+
443
+ **Reason gate.** Decide per change whether a new automated test is warranted. Exactly one named reason allows it:
444
+
445
+ - `requirement <AC-N>` — the test protects an acceptance criterion of the document being implemented;
446
+ - `defect <ref>` — the test reproduces a defect (review finding id, issue file, failing-log reference);
447
+ - `invariant <ref>` — the test guards a significant invariant (DNA entry, `@ai-invariant` file, or a pure function the property-based-test rule covers);
448
+ - `regression <risk>` — a named, concrete regression risk.
449
+
450
+ No reason → no new test: run the existing suite and the document's probes instead. If the adjacency check flags a new source file, add its inline exemption with the reason (`// test-adjacency: exempt — no test reason: <why>`) rather than a stub test.
451
+
452
+ For `defect`: write the test, then run `ref(forge.yaml bindings.commands.verifyReproduction)` with `{test}` = the test file and `{sha}` = the pre-fix commit. Only a `reproduced` verdict lets the test be committed under this reason; `not-reproduced` means the test does not capture the defect — rewrite it; `inconclusive` means it cannot run on the old code — restructure it against the old public surface or change the reason. Without the binding, record the observed red run in the commit body and report `Degraded: commands.verifyReproduction`.
453
+
454
+ Commits that add test files carry `Test-Reason: <reason>` (one line per file, or one shared line), plus `Repro-Verified: <pre-fix-sha>` for defect reasons.
439
455
 
440
- After implementing the decision, write tests for the new behavior. Tests are written for **agents**, not humans — see `fo-add-tests` for the full process and decision tree.
441
456
 
442
457
  **Principles:**
443
458
 
@@ -39,6 +39,8 @@ items; top-level decision totals added. Orchestrator pre-flight treats
39
39
  QUEUE-07 as the window agenda — structural errors still stop the batch;
40
40
  maturation skips parked/deferred items; uncovered imperative ask sites
41
41
  gain collect riders (ADR code-trace, NC markers, audit-verdict guard).</item>
42
+ <item>RFC-1322: resolve fo-review findings — resolver hardening, shared gate evaluator, dry-run JSON</item>
43
+ <item>RFC-1332: step 1 — verifyReproduction binding key; drop platform ids from pipeline skill text (SKILL-17)</item>
42
44
  </CHANGE_SUMMARY>
43
45
  -->
44
46
 
@@ -179,7 +181,7 @@ Step ordering follows the contract-first pattern:
179
181
  5. **Validation** — run `rfc.validate`, `build:check`, acceptance probes.
180
182
  6. **Evidence** — run `rfc.verification.emit`, commit evidence file.
181
183
  7. **Review & Fix** — `fo-review` on all session code changes, `fo-fix` if findings (MANDATORY — do not omit from the plan).
182
- 8. **Stamp implemented** — run `rfc.implement.stamp --id RFC-XXXX --implementation-commit <sha>` to transition `accepted → implemented` (RFC). For ADRs, run `adr.implement.stamp --id ADR-XXXX --implementation-commit <sha>` per `fo-idea-implement` step 4.10.
184
+ 8. **Stamp implemented** — run `rfc.implement.stamp --id RFC-XXXX --implementation-commit <sha> --check-criteria` to transition `accepted → implemented` (the flag flips evidenced criteria and refreshes a stale envelope in-process). For ADRs, run `adr.implement.stamp --id ADR-XXXX --implementation-commit <sha>` per `fo-idea-implement` step 4.10.
183
185
 
184
186
  Mark **human review points** on steps that:
185
187
 
@@ -38,6 +38,7 @@ items; top-level decision totals added. Orchestrator pre-flight treats
38
38
  QUEUE-07 as the window agenda — structural errors still stop the batch;
39
39
  maturation skips parked/deferred items; uncovered imperative ask sites
40
40
  gain collect riders (ADR code-trace, NC markers, audit-verdict guard).</item>
41
+ <item>RFC-1333: step 4 — acceptance verification mode in fo-review, step 4.4b in fo-idea-implement, RFC-IMP-12 docs</item>
41
42
  </CHANGE_SUMMARY>
42
43
  -->
43
44
 
@@ -75,6 +76,17 @@ An executor that narrows the reviewer's inputs — passing a self-authored summa
75
76
 
76
77
  **Report persistence is the dispatcher's duty in `independent` mode.** A clean-context reviewer may be read-only and never writes files — it returns findings and verdict. The skill run that dispatched it performs steps 6–7 itself: it assembles the report, builds the YAML frontmatter (`reviewer.isolation` records the mode actually used), and writes the file to `docs/reviews/code/`. A persisted review report without the frontmatter block is a contract violation regardless of which side produced the prose.
77
78
 
79
+ ## Acceptance verification mode
80
+
81
+ Invoked as `fo-review --acceptance --rfc <RFC-id> --workspace <path>` by `fo-idea-implement` step 4.4b for documents declaring `verificationTier: high`. The oracle is the document's requirements, not conventions.
82
+
83
+ - **Inputs (artifacts only):** the export path produced by `rfc.verify.workspace --id <RFC-id> --candidate <sha>`, its `VERIFY-BUNDLE.md` (Context, Problem, Decision, Design, Acceptance criteria — and the list of hidden paths), this section as rubric, and earlier-round counterexample lists. Never the plan, the diff narrative, the implementer's tests, review reports, or session text.
84
+ - **Task:** for each acceptance criterion and each normative Design statement, write checks (test files under `.verify/` inside the export, CLI invocations, fixture inputs), run them in the export, and keep only the failing ones.
85
+ - **Minimization:** shrink every counterexample to the smallest input that still fails (property-based shrinking for generated inputs, manual delta reduction otherwise).
86
+ - **Output:** a counterexample list — `id` (CX-N), `criterion`, `input`, `expected` (quoting the document text the expectation follows from), `observed`, `reproCommand` — and a verdict `pass | counterexamples | inconclusive`. The verifier writes nothing in the main checkout; the dispatcher persists `docs/reviews/acceptance/<rfc-id-lower>/acceptance-<YYYY-MM-DD>-r<round>.md` with YAML frontmatter `rfcId, candidateSha, round, isolation, verifierModel, verdict, counterexamples`.
87
+ - **Isolation and model:** dispatch a fresh clean-context subagent per round; record `isolation` truthfully (`subagent | isolated-inline | inline`) and the model actually used. A different vendor model may be requested where the platform allows.
88
+ - **Loop cap:** at most two fix rounds (round 0 verification, then rounds 1 and 2 after fixes). A third failing verdict parks the item for operator arbitration; disputed counterexamples go to the decision ledger, never resolved by the executor.
89
+
78
90
  ## Process
79
91
 
80
92
  ### 1. Identify the diff
@@ -68,3 +68,16 @@ status: active
68
68
  ```
69
69
 
70
70
  API keys, passwords, PII must be removed from the transcript. Same redaction pattern as `fo-handoff`.
71
+
72
+ ### K-0007: Any kernel module's module-level throw kills every command — including session.save
73
+
74
+ ```knowledge-entry
75
+ id: K-0007
76
+ layer: L2
77
+ created: 2026-10-13
78
+ lastConfirmedAt: 2026-10-13
79
+ confirmations: 1
80
+ status: active
81
+ ```
82
+
83
+ The kernel registry eagerly imports all modules before dispatch (`[registry] loading module <name>` lines). A throw at module top level — e.g. a malformed regex literal in `packages/werkstatt-journal/src/kernel/studio-commands.ts` — aborts the whole CLI, so `session.save` fails before it can process `.raw/` transcripts. When session.save dies during registry load, bisect recently-edited `*/kernel/*.ts` modules; note ripgrep skips files containing raw control bytes as binary — verify suspect regexes with `sed -n '<line>p' <file> | od -c`.
@@ -28,7 +28,7 @@ triggerPhrases:
28
28
 
29
29
  Sweep batch 1: add Compass v2 headers to 45 SKILL.md files (purpose derived from frontmatter description). Fix non-skill-markdown exclusion to check filename not workspace-relative path (packages/AGENTS.md escaped it). Add .coverage to ignoredDirs.</item>
30
30
  <item>RFC-1247: triggerPhrases vocabulary sync — mined operator phrasing applied to this skill's trigger set.</item>
31
- <item>fix: step 5 resolves the commit path by project type — plain git commit in forge workshops where ecosystem.commit is not registered</item>
31
+ <item>RFC-1154: step 5 resolves the commit path by project type — plain git commit in forge workshops where ecosystem.commit is not registered</item>
32
32
  </CHANGE_SUMMARY>
33
33
  -->
34
34
 
@@ -0,0 +1,267 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>RFC-1336: forge/authority-delegations@1 — the workspace-root
4
+ delegation registry schema plus the portable loader/resolver every
5
+ human-gated consumer shares. A delegation grants one declared agent
6
+ (grantedTo) the right to run one scope on behalf of a named human
7
+ (grantedBy), site-bounded, expirable, and revocable. The registry is
8
+ policy plus audit evidence — not a cryptographic security boundary.</purpose>
9
+ <non-goals>
10
+ <item>Do not import kernel/site/engine packages — forge stays runtime-autonomous (FORGE-AUTONOMY-01).</item>
11
+ <item>Do not police which process may invoke the mutating commands — the human-only rule on authority.delegate is workspace policy (AGENTS.md), not a check inside this module.</item>
12
+ </non-goals>
13
+ </MODULE_CONTRACT>
14
+ <KEY_DECISIONS>
15
+ <item>Registry absence is tolerance-neutral — ENOENT yields an empty registry; consumers treat "no file" and "no grant" identically (RFC-1336 unchanged-behavior rule).</item>
16
+ <item>DelegationQuery carries an optional grantedBy — consumers that already know the deciding human (e.g. bordbuch.append --delegated-by) bind the query to the grantor so delegatedBy provenance cannot be fabricated against a different human's grant.</item>
17
+ <item>sites: "workspace" covers every site; an explicit id list bounds site scope. Site-scoped queries with no site never match a site-listed grant.</item>
18
+ </KEY_DECISIONS>
19
+ <CHANGE_SUMMARY>
20
+ <item>RFC-1336: initial module — schema, scope catalog, loader, resolver, serializer.</item>
21
+ <item>RFC-1336: step 1: forge authority module — delegation registry schema + resolver, four authority.* commands, optional Ed25519 signing</item>
22
+ <item>RFC-1336: delegated editorial sign-off (RFC-1336 step 3)
23
+
24
+ editorial.review.signoff admits agent:<id> reviewers under an active
25
+ editorial.signoff delegation — the record and the editorial-signoff
26
+ bordbuch event carry delegatedBy + delegationId provenance; the sign-off
27
+ schema fails closed on agent reviewers without it. leitstand.ship gains
28
+ an editorial-delegated-signoff step between sync-after-alt and
29
+ certify-main that prepares the packet (if absent) and signs as the
30
+ delegate — a journaled no-op with no delegation, so the operator path is
31
+ unchanged. certify/promote precondition remediation now names an active
32
+ delegation when one covers the site.</item>
33
+ <item>RFC-1336: delegated rfc.decision/version.major/onboarding.decision + docs (RFC-1336 steps 4-5)</item>
34
+ </CHANGE_SUMMARY>
35
+ */
36
+
37
+ import path from "node:path";
38
+ import YAML from "yaml";
39
+ import { z } from "zod";
40
+
41
+ import type { WorkspaceIO } from "../types.ts";
42
+ import { resolveIo } from "../utils/io.ts";
43
+ import { canonicalJson } from "./signing.ts";
44
+
45
+ export const AUTHORITY_DELEGATIONS_SCHEMA_ID = "forge/authority-delegations@1";
46
+ export const DELEGATIONS_FILENAME = "authority.delegations.yaml";
47
+
48
+ export const AGENT_ID_PATTERN = /^agent:[a-z0-9][a-z0-9-]*$/;
49
+ export const AGENT_OR_WILDCARD_PATTERN = /^agent:([a-z0-9][a-z0-9-]*|\*)$/;
50
+ export const HUMAN_ID_PATTERN = /^human:[a-z0-9][a-z0-9-]*$/;
51
+
52
+ /**
53
+ * The delegable scope catalogue (RFC-1336). `bordbuch.<kind>` is a
54
+ * parameterized family — any concrete Bordbuch entry kind appends its own
55
+ * scope (`bordbuch.editorial-signoff`, `bordbuch.operator-note`, …).
56
+ */
57
+ export const DELEGABLE_SCOPES = [
58
+ "editorial.signoff",
59
+ "rfc.decision",
60
+ "version.major",
61
+ "onboarding.decision",
62
+ "fleet.notify",
63
+ ] as const;
64
+
65
+ export const BORDBUCH_SCOPE_PREFIX = "bordbuch.";
66
+
67
+ /**
68
+ * Scopes that MUST NOT be delegated (RFC-1336 non-goals): security-sensitive
69
+ * or irreversible flows stay human-only. Checked at grant write time and by
70
+ * authority.delegation.validate (DELEG-04).
71
+ */
72
+ export const NON_DELEGABLE_SCOPES = [
73
+ "sternsystem.handover",
74
+ "nachweis.sign",
75
+ "nachweis.timestamp",
76
+ "cloudflare.token",
77
+ "fleet.claims.merge",
78
+ ] as const;
79
+
80
+ const isoDatetime = z.string().refine((v) => !Number.isNaN(Date.parse(v)), {
81
+ message: "must be an ISO-8601 datetime",
82
+ });
83
+
84
+ export const delegationEntrySchema = z
85
+ .object({
86
+ id: z.string().regex(/^del-[0-9]{4,}$/),
87
+ scope: z.string().min(1),
88
+ grantedTo: z.string().regex(AGENT_OR_WILDCARD_PATTERN),
89
+ grantedBy: z.string().regex(HUMAN_ID_PATTERN),
90
+ sites: z.union([z.literal("workspace"), z.array(z.string().min(1)).min(1)]),
91
+ grantedAt: isoDatetime,
92
+ expiresAt: isoDatetime.nullish(),
93
+ revokedAt: isoDatetime.nullish(),
94
+ revokedBy: z.string().regex(HUMAN_ID_PATTERN).optional(),
95
+ note: z.string().optional(),
96
+ /** Optional `--sign` provenance: "ed25519:<publicKeyHex>:<signatureHex>". */
97
+ signature: z.string().optional(),
98
+ })
99
+ .strict();
100
+
101
+ export const authorityDelegationsSchema = z
102
+ .object({
103
+ schema: z.literal(AUTHORITY_DELEGATIONS_SCHEMA_ID),
104
+ delegations: z.array(delegationEntrySchema).default([]),
105
+ })
106
+ .strict();
107
+
108
+ export type DelegationEntry = z.infer<typeof delegationEntrySchema>;
109
+ export type AuthorityDelegations = z.infer<typeof authorityDelegationsSchema>;
110
+
111
+ export class DelegationRegistryError extends Error {
112
+ constructor(message: string) {
113
+ super(message);
114
+ this.name = "DelegationRegistryError";
115
+ }
116
+ }
117
+
118
+ export function delegationsPath(workspaceRoot: string): string {
119
+ return path.join(workspaceRoot, DELEGATIONS_FILENAME);
120
+ }
121
+
122
+ /** True when the scope string names a delegable scope (catalogue or bordbuch.*). */
123
+ export function isDelegableScope(scope: string): boolean {
124
+ return (
125
+ (DELEGABLE_SCOPES as readonly string[]).includes(scope) ||
126
+ scope.startsWith(BORDBUCH_SCOPE_PREFIX)
127
+ );
128
+ }
129
+
130
+ /**
131
+ * Load the delegation registry. An absent file means zero delegations (RFC-1336:
132
+ * the file is optional); parse/schema failures are load-bearing and throw
133
+ * DelegationRegistryError — a corrupted registry must never silently resolve
134
+ * to "no delegations" or every gate disarms.
135
+ */
136
+ export async function loadDelegations(
137
+ workspaceRoot: string,
138
+ io?: WorkspaceIO,
139
+ ): Promise<AuthorityDelegations> {
140
+ const effectiveIo = resolveIo(io);
141
+ const filePath = delegationsPath(workspaceRoot);
142
+ let source: string;
143
+ try {
144
+ source = await effectiveIo.readFile(filePath);
145
+ } catch (e) {
146
+ if ((e as NodeJS.ErrnoException).code === "ENOENT") {
147
+ return { schema: AUTHORITY_DELEGATIONS_SCHEMA_ID, delegations: [] };
148
+ }
149
+ throw new DelegationRegistryError(
150
+ `cannot read ${DELEGATIONS_FILENAME}: ${e instanceof Error ? e.message : String(e)}`,
151
+ );
152
+ }
153
+ let raw: unknown;
154
+ try {
155
+ raw = YAML.parse(source);
156
+ } catch (e) {
157
+ throw new DelegationRegistryError(
158
+ `${DELEGATIONS_FILENAME} is not parseable YAML: ${e instanceof Error ? e.message : String(e)}`,
159
+ );
160
+ }
161
+ const parsed = authorityDelegationsSchema.safeParse(raw);
162
+ if (!parsed.success) {
163
+ const issues = parsed.error.issues
164
+ .map((i) => `${i.path.join(".") || "<root>"}: ${i.message}`)
165
+ .join("; ");
166
+ throw new DelegationRegistryError(`${DELEGATIONS_FILENAME} schema violation — ${issues}`);
167
+ }
168
+ return parsed.data;
169
+ }
170
+
171
+ const REGISTRY_HEADER = `# Operator authority delegations (RFC-1336) — ${AUTHORITY_DELEGATIONS_SCHEMA_ID}
172
+ # Human-granted, scoped, revocable powers for agent delegates.
173
+ # Agents MUST NOT edit this file — grants and revocations go through
174
+ # authority.delegate / authority.delegate.revoke (operator-only).
175
+ `;
176
+
177
+ /** Serialize a registry for write-back — canonical header, stable key order. */
178
+ export function serializeDelegations(registry: AuthorityDelegations): string {
179
+ return REGISTRY_HEADER + YAML.stringify(registry);
180
+ }
181
+
182
+ /**
183
+ * The bytes a `--sign` signature covers: canonical JSON of the entry without
184
+ * its signature field (imported here so signers and verifiers share one
185
+ * canonicalization — signing.ts owns the crypto).
186
+ */
187
+ export function canonicalDelegationPayload(entry: DelegationEntry): string {
188
+ const { signature: _signature, ...rest } = entry;
189
+ return canonicalJson(rest);
190
+ }
191
+
192
+ /**
193
+ * Query a loaded registry for an active grant. A delegation is active when it
194
+ * is not revoked and not expired (expiresAt strictly in the future, or null).
195
+ * `grantedBy` binds the query to the grantor when the caller already knows
196
+ * which human must have authorized the act; `site` limits the match to grants
197
+ * covering that site (`sites: "workspace"` covers all). Multiple matches
198
+ * resolve to the most recently granted entry.
199
+ */
200
+ export interface DelegationQuery {
201
+ scope: string;
202
+ /**
203
+ * Acting agent identity — "agent:<id>". When omitted the query is an
204
+ * existence check: any active grant covering scope+site matches regardless
205
+ * of grantee (used by precondition helpers that only need to know a
206
+ * delegation exists).
207
+ */
208
+ agent?: string;
209
+ /** Site the operation targets; absent means a workspace-scope operation. */
210
+ site?: string;
211
+ /** When set, only grants recorded by this human match (grantor binding). */
212
+ grantedBy?: string;
213
+ }
214
+
215
+ export function resolveDelegation(
216
+ registry: AuthorityDelegations,
217
+ query: DelegationQuery,
218
+ now: Date = new Date(),
219
+ ): DelegationEntry | null {
220
+ const matches = registry.delegations.filter((d) => {
221
+ if (d.scope !== query.scope) return false;
222
+ if (d.revokedAt) return false;
223
+ if (d.expiresAt && new Date(d.expiresAt).getTime() <= now.getTime()) return false;
224
+ if (query.agent !== undefined && d.grantedTo !== query.agent && d.grantedTo !== "agent:*") {
225
+ return false;
226
+ }
227
+ if (query.grantedBy !== undefined && d.grantedBy !== query.grantedBy) return false;
228
+ if (d.sites === "workspace") return true;
229
+ return query.site !== undefined && d.sites.includes(query.site);
230
+ });
231
+ if (matches.length === 0) return null;
232
+ // Most specific grantee first (an explicit agent:<id> beats the wildcard),
233
+ // then most recently granted.
234
+ const specificity = (d: DelegationEntry) => (d.grantedTo === "agent:*" ? 0 : 1);
235
+ return matches.reduce((a, b) =>
236
+ specificity(a) !== specificity(b)
237
+ ? specificity(a) > specificity(b)
238
+ ? a
239
+ : b
240
+ : a.grantedAt >= b.grantedAt
241
+ ? a
242
+ : b,
243
+ );
244
+ }
245
+
246
+ /**
247
+ * The actor identity a delegated operation records. A grant to an explicit
248
+ * `agent:<id>` names its actor; a wildcard `agent:*` grant requires the caller
249
+ * to supply the session's agent id so provenance stays specific.
250
+ */
251
+ export function delegationActor(grant: DelegationEntry, sessionAgentId?: string): string | null {
252
+ if (grant.grantedTo !== "agent:*") return grant.grantedTo;
253
+ if (sessionAgentId && AGENT_ID_PATTERN.test(sessionAgentId)) return sessionAgentId;
254
+ return null;
255
+ }
256
+
257
+ /**
258
+ * Normalize a session-declared agent id — callers read WERKSTATT_AGENT_ID,
259
+ * which accepts both "devin" and "agent:devin". Anything else is not a
260
+ * usable actor id and returns undefined (callers fail closed).
261
+ */
262
+ export function normalizeAgentId(raw: string | undefined): string | undefined {
263
+ const trimmed = raw?.trim();
264
+ if (!trimmed) return undefined;
265
+ const id = trimmed.startsWith("agent:") ? trimmed : `agent:${trimmed}`;
266
+ return AGENT_ID_PATTERN.test(id) ? id : undefined;
267
+ }