@warpgogol/forge 9.3.1 → 9.4.0

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 (467) hide show
  1. package/AGENTS.md +32 -0
  2. package/CHANGELOG.md +25 -0
  3. package/README.md +2 -2
  4. package/bin/cli.ts +4 -4
  5. package/dist/bin/cli.js +4 -4
  6. package/dist/bin/cli.js.map +1 -1
  7. package/dist/os/adr/handlers/list-create.d.ts.map +1 -1
  8. package/dist/os/adr/handlers/list-create.js +23 -2
  9. package/dist/os/adr/handlers/list-create.js.map +1 -1
  10. package/dist/os/adr/types.d.ts +2 -0
  11. package/dist/os/adr/types.d.ts.map +1 -1
  12. package/dist/os/adr/types.js +2 -2
  13. package/dist/os/adr/types.js.map +1 -1
  14. package/dist/os/compass/handlers/compass-audit-handler.d.ts.map +1 -1
  15. package/dist/os/compass/handlers/compass-audit-handler.js +3 -1
  16. package/dist/os/compass/handlers/compass-audit-handler.js.map +1 -1
  17. package/dist/os/compass/handlers/compass-header-scaffold-handler.d.ts.map +1 -1
  18. package/dist/os/compass/handlers/compass-header-scaffold-handler.js +6 -12
  19. package/dist/os/compass/handlers/compass-header-scaffold-handler.js.map +1 -1
  20. package/dist/os/compass/handlers/git-revision.d.ts +2 -0
  21. package/dist/os/compass/handlers/git-revision.d.ts.map +1 -1
  22. package/dist/os/compass/handlers/git-revision.js +7 -2
  23. package/dist/os/compass/handlers/git-revision.js.map +1 -1
  24. package/dist/os/compass/handlers/summary-record.d.ts.map +1 -1
  25. package/dist/os/compass/handlers/summary-record.js +24 -14
  26. package/dist/os/compass/handlers/summary-record.js.map +1 -1
  27. package/dist/os/conformance/conformance.module.d.ts.map +1 -1
  28. package/dist/os/conformance/conformance.module.js +21 -4
  29. package/dist/os/conformance/conformance.module.js.map +1 -1
  30. package/dist/os/conformance/handlers/conformance-validate.d.ts.map +1 -1
  31. package/dist/os/conformance/handlers/conformance-validate.js +64 -8
  32. package/dist/os/conformance/handlers/conformance-validate.js.map +1 -1
  33. package/dist/os/core/archive-regen.d.ts +99 -0
  34. package/dist/os/core/archive-regen.d.ts.map +1 -0
  35. package/dist/os/core/archive-regen.js +220 -0
  36. package/dist/os/core/archive-regen.js.map +1 -0
  37. package/dist/os/core/core.module.d.ts.map +1 -1
  38. package/dist/os/core/core.module.js +159 -18
  39. package/dist/os/core/core.module.js.map +1 -1
  40. package/dist/os/core/handlers/assets-helpers.d.ts.map +1 -1
  41. package/dist/os/core/handlers/assets-helpers.js +8 -3
  42. package/dist/os/core/handlers/assets-helpers.js.map +1 -1
  43. package/dist/os/core/handlers/forge-autonomy-validate.d.ts.map +1 -1
  44. package/dist/os/core/handlers/forge-autonomy-validate.js +3 -1
  45. package/dist/os/core/handlers/forge-autonomy-validate.js.map +1 -1
  46. package/dist/os/core/handlers/package-health.d.ts +130 -0
  47. package/dist/os/core/handlers/package-health.d.ts.map +1 -1
  48. package/dist/os/core/handlers/package-health.js +548 -7
  49. package/dist/os/core/handlers/package-health.js.map +1 -1
  50. package/dist/os/core/handlers/release-prepare.d.ts.map +1 -1
  51. package/dist/os/core/handlers/release-prepare.js +5 -2
  52. package/dist/os/core/handlers/release-prepare.js.map +1 -1
  53. package/dist/os/flow/digest.d.ts.map +1 -1
  54. package/dist/os/flow/digest.js +3 -1
  55. package/dist/os/flow/digest.js.map +1 -1
  56. package/dist/os/flow/dirty-classify.d.ts +48 -0
  57. package/dist/os/flow/dirty-classify.d.ts.map +1 -0
  58. package/dist/os/flow/dirty-classify.js +81 -0
  59. package/dist/os/flow/dirty-classify.js.map +1 -0
  60. package/dist/os/flow/flow.module.d.ts.map +1 -1
  61. package/dist/os/flow/flow.module.js +85 -19
  62. package/dist/os/flow/flow.module.js.map +1 -1
  63. package/dist/os/flow/gate-engine.d.ts +13 -0
  64. package/dist/os/flow/gate-engine.d.ts.map +1 -0
  65. package/dist/os/flow/gate-engine.js +32 -0
  66. package/dist/os/flow/gate-engine.js.map +1 -0
  67. package/dist/os/flow/git.d.ts +45 -4
  68. package/dist/os/flow/git.d.ts.map +1 -1
  69. package/dist/os/flow/git.js +95 -27
  70. package/dist/os/flow/git.js.map +1 -1
  71. package/dist/os/flow/handlers/flow-backmerge.d.ts.map +1 -1
  72. package/dist/os/flow/handlers/flow-backmerge.js +12 -5
  73. package/dist/os/flow/handlers/flow-backmerge.js.map +1 -1
  74. package/dist/os/flow/handlers/flow-check.d.ts.map +1 -1
  75. package/dist/os/flow/handlers/flow-check.js +25 -3
  76. package/dist/os/flow/handlers/flow-check.js.map +1 -1
  77. package/dist/os/flow/handlers/flow-cut.d.ts +4 -1
  78. package/dist/os/flow/handlers/flow-cut.d.ts.map +1 -1
  79. package/dist/os/flow/handlers/flow-cut.js +54 -31
  80. package/dist/os/flow/handlers/flow-cut.js.map +1 -1
  81. package/dist/os/flow/handlers/flow-discard.d.ts.map +1 -1
  82. package/dist/os/flow/handlers/flow-discard.js +33 -5
  83. package/dist/os/flow/handlers/flow-discard.js.map +1 -1
  84. package/dist/os/flow/handlers/flow-fix.d.ts.map +1 -1
  85. package/dist/os/flow/handlers/flow-fix.js +13 -10
  86. package/dist/os/flow/handlers/flow-fix.js.map +1 -1
  87. package/dist/os/flow/handlers/flow-hold.d.ts.map +1 -1
  88. package/dist/os/flow/handlers/flow-hold.js +13 -7
  89. package/dist/os/flow/handlers/flow-hold.js.map +1 -1
  90. package/dist/os/flow/handlers/flow-install.d.ts +2 -1
  91. package/dist/os/flow/handlers/flow-install.d.ts.map +1 -1
  92. package/dist/os/flow/handlers/flow-install.js +56 -13
  93. package/dist/os/flow/handlers/flow-install.js.map +1 -1
  94. package/dist/os/flow/handlers/flow-integrate.d.ts +48 -2
  95. package/dist/os/flow/handlers/flow-integrate.d.ts.map +1 -1
  96. package/dist/os/flow/handlers/flow-integrate.js +536 -65
  97. package/dist/os/flow/handlers/flow-integrate.js.map +1 -1
  98. package/dist/os/flow/handlers/flow-open.d.ts +14 -0
  99. package/dist/os/flow/handlers/flow-open.d.ts.map +1 -1
  100. package/dist/os/flow/handlers/flow-open.js +117 -12
  101. package/dist/os/flow/handlers/flow-open.js.map +1 -1
  102. package/dist/os/flow/handlers/flow-status.d.ts +13 -0
  103. package/dist/os/flow/handlers/flow-status.d.ts.map +1 -1
  104. package/dist/os/flow/handlers/flow-status.js +35 -14
  105. package/dist/os/flow/handlers/flow-status.js.map +1 -1
  106. package/dist/os/flow/index.d.ts +1 -0
  107. package/dist/os/flow/index.d.ts.map +1 -1
  108. package/dist/os/flow/index.js +3 -1
  109. package/dist/os/flow/index.js.map +1 -1
  110. package/dist/os/flow/line-version.d.ts.map +1 -1
  111. package/dist/os/flow/line-version.js +2 -1
  112. package/dist/os/flow/line-version.js.map +1 -1
  113. package/dist/os/flow/locks.d.ts +37 -1
  114. package/dist/os/flow/locks.d.ts.map +1 -1
  115. package/dist/os/flow/locks.js +34 -14
  116. package/dist/os/flow/locks.js.map +1 -1
  117. package/dist/os/flow/preflight.d.ts +114 -0
  118. package/dist/os/flow/preflight.d.ts.map +1 -0
  119. package/dist/os/flow/preflight.js +620 -0
  120. package/dist/os/flow/preflight.js.map +1 -0
  121. package/dist/os/flow/publish.d.ts +7 -0
  122. package/dist/os/flow/publish.d.ts.map +1 -1
  123. package/dist/os/flow/publish.js +165 -3
  124. package/dist/os/flow/publish.js.map +1 -1
  125. package/dist/os/flow/registry.d.ts +26 -1
  126. package/dist/os/flow/registry.d.ts.map +1 -1
  127. package/dist/os/flow/registry.js +27 -6
  128. package/dist/os/flow/registry.js.map +1 -1
  129. package/dist/os/flow/scripts.d.ts +4 -0
  130. package/dist/os/flow/scripts.d.ts.map +1 -1
  131. package/dist/os/flow/scripts.js +8 -2
  132. package/dist/os/flow/scripts.js.map +1 -1
  133. package/dist/os/flow/session-checkout.d.ts +33 -0
  134. package/dist/os/flow/session-checkout.d.ts.map +1 -0
  135. package/dist/os/flow/session-checkout.js +151 -0
  136. package/dist/os/flow/session-checkout.js.map +1 -0
  137. package/dist/os/flow/worktree-path.d.ts.map +1 -1
  138. package/dist/os/flow/worktree-path.js +9 -3
  139. package/dist/os/flow/worktree-path.js.map +1 -1
  140. package/dist/os/instructions/handlers/budget-validate.d.ts +1 -0
  141. package/dist/os/instructions/handlers/budget-validate.d.ts.map +1 -1
  142. package/dist/os/instructions/handlers/budget-validate.js +12 -4
  143. package/dist/os/instructions/handlers/budget-validate.js.map +1 -1
  144. package/dist/os/instructions/instructions.module.d.ts.map +1 -1
  145. package/dist/os/instructions/instructions.module.js +4 -1
  146. package/dist/os/instructions/instructions.module.js.map +1 -1
  147. package/dist/os/mission/open-missions.d.ts +8 -0
  148. package/dist/os/mission/open-missions.d.ts.map +1 -0
  149. package/dist/os/mission/open-missions.js +42 -0
  150. package/dist/os/mission/open-missions.js.map +1 -0
  151. package/dist/os/queue/manifest.d.ts.map +1 -1
  152. package/dist/os/queue/manifest.js +11 -1
  153. package/dist/os/queue/manifest.js.map +1 -1
  154. package/dist/os/rfc/acceptance.d.ts +14 -0
  155. package/dist/os/rfc/acceptance.d.ts.map +1 -1
  156. package/dist/os/rfc/acceptance.js +18 -10
  157. package/dist/os/rfc/acceptance.js.map +1 -1
  158. package/dist/os/rfc/decision-log.d.ts.map +1 -1
  159. package/dist/os/rfc/decision-log.js +11 -2
  160. package/dist/os/rfc/decision-log.js.map +1 -1
  161. package/dist/os/rfc/frontmatter-io.d.ts +23 -0
  162. package/dist/os/rfc/frontmatter-io.d.ts.map +1 -1
  163. package/dist/os/rfc/frontmatter-io.js +82 -1
  164. package/dist/os/rfc/frontmatter-io.js.map +1 -1
  165. package/dist/os/rfc/handlers/implement-stamp-deviations.d.ts.map +1 -1
  166. package/dist/os/rfc/handlers/implement-stamp-deviations.js +24 -2
  167. package/dist/os/rfc/handlers/implement-stamp-deviations.js.map +1 -1
  168. package/dist/os/rfc/handlers/implement-stamp.d.ts.map +1 -1
  169. package/dist/os/rfc/handlers/implement-stamp.js +16 -3
  170. package/dist/os/rfc/handlers/implement-stamp.js.map +1 -1
  171. package/dist/os/rfc/handlers/index-graph.d.ts.map +1 -1
  172. package/dist/os/rfc/handlers/index-graph.js +5 -4
  173. package/dist/os/rfc/handlers/index-graph.js.map +1 -1
  174. package/dist/os/rfc/handlers/list-create.d.ts.map +1 -1
  175. package/dist/os/rfc/handlers/list-create.js +83 -8
  176. package/dist/os/rfc/handlers/list-create.js.map +1 -1
  177. package/dist/os/rfc/handlers/rfc-evidence-sync.d.ts +48 -0
  178. package/dist/os/rfc/handlers/rfc-evidence-sync.d.ts.map +1 -1
  179. package/dist/os/rfc/handlers/rfc-evidence-sync.js +131 -2
  180. package/dist/os/rfc/handlers/rfc-evidence-sync.js.map +1 -1
  181. package/dist/os/rfc/handlers/validate-rules.d.ts +21 -1
  182. package/dist/os/rfc/handlers/validate-rules.d.ts.map +1 -1
  183. package/dist/os/rfc/handlers/validate-rules.js +77 -5
  184. package/dist/os/rfc/handlers/validate-rules.js.map +1 -1
  185. package/dist/os/rfc/handlers/validate.d.ts.map +1 -1
  186. package/dist/os/rfc/handlers/validate.js +64 -6
  187. package/dist/os/rfc/handlers/validate.js.map +1 -1
  188. package/dist/os/rfc/next-id.d.ts +38 -0
  189. package/dist/os/rfc/next-id.d.ts.map +1 -0
  190. package/dist/os/rfc/next-id.js +165 -0
  191. package/dist/os/rfc/next-id.js.map +1 -0
  192. package/dist/os/rfc/probe-batch.d.ts.map +1 -1
  193. package/dist/os/rfc/probe-batch.js +6 -1
  194. package/dist/os/rfc/probe-batch.js.map +1 -1
  195. package/dist/os/rfc/rfc.module.d.ts.map +1 -1
  196. package/dist/os/rfc/rfc.module.js +36 -8
  197. package/dist/os/rfc/rfc.module.js.map +1 -1
  198. package/dist/os/rfc/types.d.ts +35 -6
  199. package/dist/os/rfc/types.d.ts.map +1 -1
  200. package/dist/os/rfc/types.js +6 -6
  201. package/dist/os/rfc/types.js.map +1 -1
  202. package/dist/os/rfc/verification-evidence.d.ts +1 -1
  203. package/dist/os/rfc/verification-evidence.d.ts.map +1 -1
  204. package/dist/os/rfc/verification-evidence.js +81 -28
  205. package/dist/os/rfc/verification-evidence.js.map +1 -1
  206. package/dist/os/rfc/verification-origin.d.ts +8 -0
  207. package/dist/os/rfc/verification-origin.d.ts.map +1 -1
  208. package/dist/os/rfc/verification-origin.js +47 -0
  209. package/dist/os/rfc/verification-origin.js.map +1 -1
  210. package/dist/os/session/handlers/save.d.ts.map +1 -1
  211. package/dist/os/session/handlers/save.js +31 -7
  212. package/dist/os/session/handlers/save.js.map +1 -1
  213. package/dist/os/spec/spec-schema.d.ts +8 -0
  214. package/dist/os/spec/spec-schema.d.ts.map +1 -1
  215. package/dist/os/spec/spec-schema.js +1 -0
  216. package/dist/os/spec/spec-schema.js.map +1 -1
  217. package/dist/os/spec/spec-status.d.ts +8 -0
  218. package/dist/os/spec/spec-status.d.ts.map +1 -1
  219. package/dist/os/spec/spec-status.js +18 -6
  220. package/dist/os/spec/spec-status.js.map +1 -1
  221. package/dist/os/spec/spec-validate.d.ts.map +1 -1
  222. package/dist/os/spec/spec-validate.js +62 -15
  223. package/dist/os/spec/spec-validate.js.map +1 -1
  224. package/dist/os/spec/spec.module.d.ts.map +1 -1
  225. package/dist/os/spec/spec.module.js +13 -5
  226. package/dist/os/spec/spec.module.js.map +1 -1
  227. package/dist/os/system/handlers/system-map-validate.d.ts.map +1 -1
  228. package/dist/os/system/handlers/system-map-validate.js +2 -1
  229. package/dist/os/system/handlers/system-map-validate.js.map +1 -1
  230. package/dist/os/system/handlers/system-outbox-scan.d.ts +11 -0
  231. package/dist/os/system/handlers/system-outbox-scan.d.ts.map +1 -1
  232. package/dist/os/system/handlers/system-outbox-scan.js +54 -6
  233. package/dist/os/system/handlers/system-outbox-scan.js.map +1 -1
  234. package/dist/os/system/handlers/system-task-create.d.ts.map +1 -1
  235. package/dist/os/system/handlers/system-task-create.js +6 -1
  236. package/dist/os/system/handlers/system-task-create.js.map +1 -1
  237. package/dist/os/system/handlers/system-versionset-record.d.ts +14 -0
  238. package/dist/os/system/handlers/system-versionset-record.d.ts.map +1 -1
  239. package/dist/os/system/handlers/system-versionset-record.js +246 -6
  240. package/dist/os/system/handlers/system-versionset-record.js.map +1 -1
  241. package/dist/os/system/repo.d.ts +1 -1
  242. package/dist/os/system/repo.d.ts.map +1 -1
  243. package/dist/os/system/repo.js +53 -3
  244. package/dist/os/system/repo.js.map +1 -1
  245. package/dist/os/system/scenario-schemas.d.ts +109 -3
  246. package/dist/os/system/scenario-schemas.d.ts.map +1 -1
  247. package/dist/os/system/scenario-schemas.js +66 -10
  248. package/dist/os/system/scenario-schemas.js.map +1 -1
  249. package/dist/os/system/system.module.d.ts.map +1 -1
  250. package/dist/os/system/system.module.js +69 -17
  251. package/dist/os/system/system.module.js.map +1 -1
  252. package/dist/os/system/tests/contract-fixtures.d.ts +17 -0
  253. package/dist/os/system/tests/contract-fixtures.d.ts.map +1 -0
  254. package/dist/os/system/tests/contract-fixtures.js +109 -0
  255. package/dist/os/system/tests/contract-fixtures.js.map +1 -0
  256. package/dist/src/config/forge-config.d.ts +54 -18
  257. package/dist/src/config/forge-config.d.ts.map +1 -1
  258. package/dist/src/config/forge-config.js +41 -9
  259. package/dist/src/config/forge-config.js.map +1 -1
  260. package/dist/src/conformance/index.d.ts +6 -0
  261. package/dist/src/conformance/index.d.ts.map +1 -1
  262. package/dist/src/conformance/index.js +36 -1
  263. package/dist/src/conformance/index.js.map +1 -1
  264. package/dist/src/formal/proof-runner.d.ts.map +1 -1
  265. package/dist/src/formal/proof-runner.js +10 -2
  266. package/dist/src/formal/proof-runner.js.map +1 -1
  267. package/dist/src/migration-adapters/node-typescript-pnpm/index.js +3 -1
  268. package/dist/src/migration-adapters/node-typescript-pnpm/index.js.map +1 -1
  269. package/dist/src/migration-adapters/phaser-pnpm/index.js +3 -1
  270. package/dist/src/migration-adapters/phaser-pnpm/index.js.map +1 -1
  271. package/dist/src/onboarding/agents-generate.js +4 -4
  272. package/dist/src/onboarding/agents-generate.js.map +1 -1
  273. package/dist/src/onboarding/nested-agents-generate.d.ts.map +1 -1
  274. package/dist/src/onboarding/nested-agents-generate.js +3 -1
  275. package/dist/src/onboarding/nested-agents-generate.js.map +1 -1
  276. package/dist/src/onboarding/scaffold-project.js +2 -2
  277. package/dist/src/onboarding/scaffold-project.js.map +1 -1
  278. package/dist/src/onboarding/upgrade.d.ts.map +1 -1
  279. package/dist/src/onboarding/upgrade.js +14 -2
  280. package/dist/src/onboarding/upgrade.js.map +1 -1
  281. package/dist/src/onboarding/workspace-discovery.d.ts.map +1 -1
  282. package/dist/src/onboarding/workspace-discovery.js +3 -1
  283. package/dist/src/onboarding/workspace-discovery.js.map +1 -1
  284. package/dist/src/skill-schema.d.ts +3 -0
  285. package/dist/src/skill-schema.d.ts.map +1 -1
  286. package/dist/src/skill-schema.js +9 -2
  287. package/dist/src/skill-schema.js.map +1 -1
  288. package/dist/src/spec/resolve-spec-source.d.ts +45 -0
  289. package/dist/src/spec/resolve-spec-source.d.ts.map +1 -0
  290. package/dist/src/spec/resolve-spec-source.js +153 -0
  291. package/dist/src/spec/resolve-spec-source.js.map +1 -0
  292. package/dist/src/utils/command-inventory.d.ts +28 -0
  293. package/dist/src/utils/command-inventory.d.ts.map +1 -0
  294. package/dist/src/utils/command-inventory.js +84 -0
  295. package/dist/src/utils/command-inventory.js.map +1 -0
  296. package/dist/src/utils/io.d.ts.map +1 -1
  297. package/dist/src/utils/io.js +6 -1
  298. package/dist/src/utils/io.js.map +1 -1
  299. package/dist/src/utils/repo-path.d.ts +10 -0
  300. package/dist/src/utils/repo-path.d.ts.map +1 -0
  301. package/dist/src/utils/repo-path.js +52 -0
  302. package/dist/src/utils/repo-path.js.map +1 -0
  303. package/dist/src/utils/spawn.d.ts +23 -0
  304. package/dist/src/utils/spawn.d.ts.map +1 -0
  305. package/dist/src/utils/spawn.js +83 -0
  306. package/dist/src/utils/spawn.js.map +1 -0
  307. package/docs/branch-model.md +1 -1
  308. package/docs/guides/existing-project.md +1 -1
  309. package/docs/maintainers/publishing.md +1 -1
  310. package/docs/reference/cli.md +8 -2
  311. package/docs/reference/profiles.md +1 -1
  312. package/os/adr/handlers/list-create.ts +26 -2
  313. package/os/adr/types.ts +4 -2
  314. package/os/compass/handlers/compass-audit-handler.ts +6 -1
  315. package/os/compass/handlers/compass-header-scaffold-handler.ts +12 -11
  316. package/os/compass/handlers/git-revision.ts +8 -2
  317. package/os/compass/handlers/summary-record.ts +25 -14
  318. package/os/compass/handlers/tests/compass-invariant-binding.test.ts +3 -2
  319. package/os/conformance/conformance.module.ts +21 -4
  320. package/os/conformance/handlers/conformance-validate.ts +108 -16
  321. package/os/conformance/handlers/tests/conformance-package-consumer.test.ts +200 -0
  322. package/os/core/archive-regen.ts +279 -0
  323. package/os/core/core.module.ts +176 -29
  324. package/os/core/docs-archive.test.ts +413 -3
  325. package/os/core/handlers/assets-helpers.ts +8 -3
  326. package/os/core/handlers/forge-autonomy-validate.ts +3 -1
  327. package/os/core/handlers/package-health.test.ts +418 -4
  328. package/os/core/handlers/package-health.ts +629 -7
  329. package/os/core/handlers/release-prepare.ts +5 -2
  330. package/os/flow/digest.ts +3 -1
  331. package/os/flow/dirty-classify.ts +112 -0
  332. package/os/flow/flow.module.ts +92 -24
  333. package/os/flow/gate-engine.ts +45 -0
  334. package/os/flow/git.ts +117 -29
  335. package/os/flow/handlers/flow-backmerge.ts +14 -4
  336. package/os/flow/handlers/flow-check.ts +27 -2
  337. package/os/flow/handlers/flow-cut.ts +97 -46
  338. package/os/flow/handlers/flow-discard.ts +33 -5
  339. package/os/flow/handlers/flow-fix.ts +22 -10
  340. package/os/flow/handlers/flow-hold.ts +20 -7
  341. package/os/flow/handlers/flow-install.ts +59 -12
  342. package/os/flow/handlers/flow-integrate.ts +808 -182
  343. package/os/flow/handlers/flow-open.ts +135 -11
  344. package/os/flow/handlers/flow-status.ts +45 -13
  345. package/os/flow/index.ts +3 -1
  346. package/os/flow/line-version.ts +2 -1
  347. package/os/flow/locks.ts +56 -14
  348. package/os/flow/preflight.ts +763 -0
  349. package/os/flow/publish.ts +200 -5
  350. package/os/flow/registry.ts +43 -7
  351. package/os/flow/scripts.ts +13 -2
  352. package/os/flow/session-checkout.ts +186 -0
  353. package/os/flow/tests/dirty-classify.test.ts +116 -0
  354. package/os/flow/tests/fixtures/branch-names.yaml +40 -40
  355. package/os/flow/tests/flow-discard.test.ts +32 -0
  356. package/os/flow/tests/flow-guard-parity.test.ts +10 -2
  357. package/os/flow/tests/flow-install.test.ts +7 -3
  358. package/os/flow/tests/flow-integrate.gate-report.test.ts +144 -0
  359. package/os/flow/tests/flow-integrate.preflight.test.ts +561 -0
  360. package/os/flow/tests/flow-integrate.reattach.test.ts +197 -0
  361. package/os/flow/tests/flow-integrate.remediation.test.ts +254 -0
  362. package/os/flow/tests/flow-integrate.test.ts +348 -17
  363. package/os/flow/tests/flow-open.pending.test.ts +277 -0
  364. package/os/flow/tests/flow-open.test.ts +52 -9
  365. package/os/flow/tests/flow-push-publish.test.ts +124 -0
  366. package/os/flow/tests/flow-status.test.ts +31 -1
  367. package/os/flow/tests/locks.test.ts +39 -3
  368. package/os/flow/tests/scripts.test.ts +5 -2
  369. package/os/flow/tests/state-roots.test.ts +8 -5
  370. package/os/flow/worktree-path.ts +9 -3
  371. package/os/formal/handlers/proof-check.test.ts +6 -3
  372. package/os/instructions/budget.test.ts +31 -0
  373. package/os/instructions/handlers/budget-validate.ts +13 -4
  374. package/os/instructions/instructions.module.ts +4 -1
  375. package/os/mission/open-missions.ts +50 -0
  376. package/os/queue/decision-ledger.test.ts +18 -0
  377. package/os/queue/manifest.ts +17 -1
  378. package/os/rfc/acceptance.ts +30 -10
  379. package/os/rfc/decision-log.ts +13 -2
  380. package/os/rfc/frontmatter-io.ts +89 -1
  381. package/os/rfc/handlers/implement-stamp-deviations.test.ts +83 -0
  382. package/os/rfc/handlers/implement-stamp-deviations.ts +22 -2
  383. package/os/rfc/handlers/implement-stamp-stale.test.ts +5 -1
  384. package/os/rfc/handlers/implement-stamp.ts +16 -3
  385. package/os/rfc/handlers/index-graph.ts +5 -4
  386. package/os/rfc/handlers/lifecycle.test.ts +136 -0
  387. package/os/rfc/handlers/list-create.test.ts +82 -0
  388. package/os/rfc/handlers/list-create.ts +101 -8
  389. package/os/rfc/handlers/rfc-evidence-sync.test.ts +504 -0
  390. package/os/rfc/handlers/rfc-evidence-sync.ts +192 -2
  391. package/os/rfc/handlers/tests/index-graph.test.ts +2 -1
  392. package/os/rfc/handlers/validate-rules-rfc1454.test.ts +73 -0
  393. package/os/rfc/handlers/validate-rules.ts +103 -7
  394. package/os/rfc/handlers/validate.ts +68 -4
  395. package/os/rfc/next-id.ts +232 -0
  396. package/os/rfc/probe-batch.ts +6 -1
  397. package/os/rfc/rfc.module.ts +41 -8
  398. package/os/rfc/types.ts +28 -6
  399. package/os/rfc/verification-emit-freshness.test.ts +5 -1
  400. package/os/rfc/verification-emit.test.ts +5 -1
  401. package/os/rfc/verification-evidence.ts +99 -33
  402. package/os/rfc/verification-origin.ts +59 -0
  403. package/os/rfc/verification-refresh.test.ts +5 -1
  404. package/os/rfc/verifier/rfc-1333/imp12-binding.acceptance.test.ts +5 -1
  405. package/os/session/handlers/save.ts +35 -7
  406. package/os/session/tests/session-save.test.ts +154 -0
  407. package/os/spec/spec-schema.ts +3 -0
  408. package/os/spec/spec-status.ts +22 -6
  409. package/os/spec/spec-validate.package-source.test.ts +187 -0
  410. package/os/spec/spec-validate.ts +65 -14
  411. package/os/spec/spec.module.ts +13 -5
  412. package/os/system/handlers/system-map-validate.ts +4 -2
  413. package/os/system/handlers/system-outbox-scan.ts +65 -21
  414. package/os/system/handlers/system-task-create.ts +6 -1
  415. package/os/system/handlers/system-versionset-record.ts +301 -16
  416. package/os/system/repo.ts +59 -18
  417. package/os/system/scenario-schemas.ts +91 -12
  418. package/os/system/system.module.ts +70 -17
  419. package/os/system/tests/contract-fixtures.ts +139 -0
  420. package/os/system/tests/scenario-pin-drift-check.test.ts +114 -0
  421. package/os/system/tests/scenario-validator-check.test.ts +96 -0
  422. package/os/system/tests/system-task-dispatch.test.ts +4 -1
  423. package/os/system/tests/system-versionset.test.ts +7 -3
  424. package/os/system/tests/version-set-v2.test.ts +78 -0
  425. package/package.json +9 -1
  426. package/skills/fo/fo-doctor/SKILL.md +151 -0
  427. package/skills/fo/fo-handoff/SKILL.md +22 -0
  428. package/skills/fo/fo-idea-create-rfc/acceptance-criteria-standard.md +2 -1
  429. package/skills/fo/fo-idea-implement/SKILL.md +5 -2
  430. package/skills/fo/fo-idea-plan/SKILL.md +5 -5
  431. package/skills/fo/fo-session-retro/SKILL.md +37 -11
  432. package/skills/fo/fo-spec-ingest/SKILL.md +8 -0
  433. package/skills/fo/fo-system-dispatch/SKILL.md +1 -0
  434. package/skills/meta/skill-create/SKILL.md +2 -1
  435. package/src/bin-entry.test.ts +3 -1
  436. package/src/config/forge-config.ts +57 -13
  437. package/src/conformance/index.ts +46 -1
  438. package/src/formal/proof-runner.ts +10 -2
  439. package/src/migration-adapters/node-typescript-pnpm/index.ts +3 -1
  440. package/src/migration-adapters/phaser-pnpm/index.ts +3 -1
  441. package/src/onboarding/agents-generate.ts +4 -4
  442. package/src/onboarding/nested-agents-generate.ts +3 -1
  443. package/src/onboarding/scaffold-project.ts +2 -2
  444. package/src/onboarding/upgrade.ts +13 -2
  445. package/src/onboarding/workspace-discovery.ts +3 -1
  446. package/src/pipeline-status.test.ts +1 -1
  447. package/src/skill-schema.ts +9 -2
  448. package/src/spec/resolve-spec-source.ts +184 -0
  449. package/src/tests/acceptance-probe-kinds.test.ts +3 -1
  450. package/src/tests/agents-generate-domain.test.ts +3 -2
  451. package/src/tests/agents-generate.test.ts +2 -1
  452. package/src/tests/create-flow.test.ts +3 -1
  453. package/src/tests/create.test.ts +12 -2
  454. package/src/tests/editable-generated-region.test.ts +2 -2
  455. package/src/tests/fixtures/agents-generate-business-before.txt +2 -0
  456. package/src/tests/implement-stamp.test.ts +5 -2
  457. package/src/tests/rfc-implement-stamp-governance.test.ts +6 -2
  458. package/src/tests/rfc-verification-verdict-ingest.test.ts +5 -1
  459. package/src/tests/scaffold-project.test.ts +3 -1
  460. package/src/tests/upgrade.test.ts +79 -3
  461. package/src/tests/workspace-discovery.test.ts +4 -3
  462. package/src/utils/command-inventory.ts +105 -0
  463. package/src/utils/io.ts +6 -1
  464. package/src/utils/repo-path.ts +49 -0
  465. package/src/utils/spawn.ts +88 -0
  466. package/src/tests/rfc-evidence-sync.test.ts +0 -369
  467. package/src/tests/skill-agents-sync.test.ts +0 -192
@@ -20,37 +20,54 @@ at cleanup without moving develop again.</purpose>
20
20
  <item>Task-file preservation runs inside the cleanup branch BEFORE the worktree-teardown hook and only for owner.kind task — a `git clean -fdx` teardown would destroy `.forge/task/` first, and a copy failure refuses cleanup (FLOW-INT-04) so the report is never lost with the worktree (RFC-1509 Q-16).</item>
21
21
  </KEY_DECISIONS>
22
22
  <CHANGE_SUMMARY>
23
- <item>RFC-1504: steps 2-3 — holderIsDead, boot-id payload, dead-holder break in withFlowLock</item>
24
- <item>RFC-1509: implement RFC-1509 — system task queue, dispatch briefs and task reports</item>
25
- <item>RFC-1509: record task-file preservation decisions in flow handlers</item>
26
- <item>RFC-1509: close RFC-1509 review r1 findings — mark-failed escape, open-error refusal, dry-run coverage</item>
27
- <item>RFC-1509: record RFC-1509 preserve-before-teardown ordering in key decisions</item>
28
- <history>RFC-1487, RFC-1490, RFC-1491</history>
23
+ <item>RFC-1528: close review findings — manifest-union command inventory for regen/preflight</item>
24
+ <item>RFC-1536: owning-checkout routing, FLOW-OPEN-01 dirty-primary warning, shared governance-id allocation (RFC+ADR)</item>
25
+ <item>RFC-1538: revalidate integration preconditions post-lock and reuse the session engine</item>
26
+ <item>RFC-1531: remediation flags --reattach/--auto-clean/--autocommit on the classified dirty set, FLOW-INT-17 remediation-failure refusals, classified FLOW-INT-01 data</item>
27
+ <item>RFC-1532: persist integration-gate reports per attempt and link them from the flow journal</item>
28
+ <history>RFC-1487, RFC-1490, RFC-1491, RFC-1504, RFC-1509, RFC-1515, RFC-1528, RFC-1537</history>
29
29
  </CHANGE_SUMMARY>
30
30
  */
31
31
 
32
32
  import type {
33
+ CommandRegistry,
33
34
  Diagnostic,
34
35
  ForgeCommandInput,
35
36
  ForgeCommandResult,
37
+ ForgeInvokeCommand,
36
38
  ForgeRuntimeContext,
37
39
  WorkspaceIO,
38
40
  } from "../../../src/types.ts";
39
41
  import { resolveIo } from "../../../src/utils/io.ts";
42
+ import {
43
+ AUTO_CLEAN_PASS_CLASSES,
44
+ SWEEP_COMMIT_SUBJECT,
45
+ classifyDirtyPath,
46
+ classifyDirtyTree,
47
+ summarizeClasses,
48
+ } from "../dirty-classify.ts";
40
49
  import {
41
50
  branchExists,
42
51
  currentBranch,
43
52
  git,
53
+ gitCommit,
44
54
  isAncestor,
45
55
  requireGit,
46
56
  statusDirty,
47
57
  statusTracked,
48
58
  topLevel,
59
+ worktreeAdd,
49
60
  worktreeList,
50
61
  } from "../git.ts";
51
- import { LockTimeoutError, withFlowLock } from "../locks.ts";
62
+ import {
63
+ describeHeldLock,
64
+ LockTimeoutError,
65
+ withFlowLock,
66
+ type HeldLockDiagnostic,
67
+ } from "../locks.ts";
52
68
  import {
53
69
  appendJournal,
70
+ readJournal,
54
71
  commonGitDir,
55
72
  FlowRegistrySchemaError,
56
73
  INTEGRATE_LOCK_RELATIVE_PATH,
@@ -61,12 +78,17 @@ import {
61
78
  } from "../registry.ts";
62
79
  import { runFlowScript, type FlowScriptResult } from "../scripts.ts";
63
80
  import { preserveTaskFiles } from "../task-files.ts";
64
- import { primaryWorktree } from "../worktree-path.ts";
65
- import { join } from "node:path";
81
+ import { flowWorktreePath, primaryWorktree } from "../worktree-path.ts";
82
+ import { pruneReservationsForSession } from "../../rfc/next-id.ts";
83
+ import { rm } from "node:fs/promises";
84
+ import { dirname, join } from "node:path";
66
85
 
67
86
  export const INTEGRATE_LOCK_WAIT_MS = 30 * 60_000;
68
87
  export const INTEGRATE_LOCK_STALE_MS = 2 * 3_600_000;
69
88
 
89
+ /** RFC-1515 AC-4: the refused lock attempt reports who holds it. */
90
+ export type LockDiagnostic = HeldLockDiagnostic;
91
+
70
92
  export interface FlowIntegrateData {
71
93
  branch: string | null;
72
94
  integrated: boolean;
@@ -80,6 +102,30 @@ export interface FlowIntegrateData {
80
102
  /** worktree-teardown script result when cleanup ran — never an integration-gate result. */
81
103
  teardown?: FlowScriptResult | null;
82
104
  cleanedUp: boolean;
105
+ /** RFC-1515: forge-local state paths the cleanliness check tolerated this
106
+ * run — journaled so "tolerated" is auditable, never a suppressed blocker. */
107
+ toleratedState?: string[];
108
+ /** RFC-1537: declared regenerable dirt tolerated this run — {path, class}
109
+ * per classified path; journaled, never committed or silently absorbed. */
110
+ toleratedDirt?: Array<{ path: string; class: string }>;
111
+ /** RFC-1538: "already-integrated" when the branch's work is already in
112
+ * develop and nothing remains to do — idempotent exit, no cleanup run. */
113
+ disposition?: "already-integrated";
114
+ /** RFC-1538: generated-file rebase conflicts auto-resolved via their owner
115
+ * commands — journaled, never silently merged. */
116
+ autoResolved?: string[];
117
+ /** RFC-1538: which checkout's build ran the integration gate. */
118
+ gateEngine?: "session" | "primary";
119
+ /** RFC-1531: worktree path --reattach created this run. */
120
+ reattachedTo?: string;
121
+ /** RFC-1531: reattach target a --dry-run reports without mutating. */
122
+ wouldReattach?: string;
123
+ /** RFC-1531: disposable-class paths --auto-clean deleted this run. */
124
+ autoCleaned?: string[];
125
+ /** RFC-1531: sha of the --autocommit sweep commit (SWEEP_COMMIT_SUBJECT). */
126
+ autocommitSha?: string;
127
+ /** RFC-1515: holder payload when FLOW-INT-08 refused on a held lock. */
128
+ lock?: LockDiagnostic;
83
129
  diagnostics: Diagnostic[];
84
130
  }
85
131
 
@@ -88,6 +134,7 @@ function refuse(
88
134
  message: string,
89
135
  fixHint: string,
90
136
  partial?: Partial<FlowIntegrateData>,
137
+ diagData?: Record<string, unknown>,
91
138
  ): FlowIntegrateData {
92
139
  return {
93
140
  branch: partial?.branch ?? null,
@@ -97,7 +144,15 @@ function refuse(
97
144
  rebased: partial?.rebased ?? false,
98
145
  gate: partial?.gate ?? null,
99
146
  cleanedUp: partial?.cleanedUp ?? false,
100
- diagnostics: [{ ruleId, severity: "error", message, fixHint }],
147
+ ...(partial?.toleratedState !== undefined ? { toleratedState: partial.toleratedState } : {}),
148
+ ...(partial?.toleratedDirt !== undefined ? { toleratedDirt: partial.toleratedDirt } : {}),
149
+ ...(partial?.reattachedTo !== undefined ? { reattachedTo: partial.reattachedTo } : {}),
150
+ ...(partial?.autoCleaned !== undefined ? { autoCleaned: partial.autoCleaned } : {}),
151
+ ...(partial?.autocommitSha !== undefined ? { autocommitSha: partial.autocommitSha } : {}),
152
+ ...(partial?.lock !== undefined ? { lock: partial.lock } : {}),
153
+ diagnostics: [
154
+ { ruleId, severity: "error", message, fixHint, ...(diagData ? { data: diagData } : {}) },
155
+ ],
101
156
  };
102
157
  }
103
158
 
@@ -122,9 +177,14 @@ async function cleanupIntegrated(
122
177
  nowIso: string,
123
178
  journalEvent: "integrate" | "backmerge" = "integrate",
124
179
  journalBase?: string,
180
+ journalToleratedDirt?: Array<{ path: string; class: string }>,
181
+ journalAutoResolved?: string[],
182
+ journalRemediation?: { reattachedTo?: string; autoCleaned?: string[]; autocommitSha?: string },
183
+ journalGateReport?: string,
125
184
  ): Promise<{ cleanedUp: boolean; diagnostics: Diagnostic[]; gate: FlowScriptResult | null }> {
126
185
  const branchExistsNow = await branchExists(primary, io, entry.name);
127
186
  let teardownRan: FlowScriptResult | null = null;
187
+ let toleratedPaths: string[] = [];
128
188
  if (worktree !== null && (await io.exists(worktree))) {
129
189
  // RFC-1509 Q-16: preserve BEFORE the teardown hook — a `git clean -fdx`
130
190
  // teardown would destroy .forge/task/ with the rest of the worktree.
@@ -166,6 +226,18 @@ async function cleanupIntegrated(
166
226
  ],
167
227
  };
168
228
  }
229
+ // RFC-1515: `statusDirty` predicts `git worktree remove` — allowlisted
230
+ // forge-local state is untracked-not-ignored, so a tolerated-only tree
231
+ // still refuses removal. Delete the tolerated paths first (declared-
232
+ // disposable state; task payloads are already preserved above); a
233
+ // fresh check showing real entries leaves remove to report them.
234
+ const residual = await statusDirty(worktree, io);
235
+ if (residual.entries.length === 0 && residual.toleratedState.length > 0) {
236
+ toleratedPaths = residual.toleratedState;
237
+ for (const rel of residual.toleratedState) {
238
+ await rm(join(worktree, rel), { force: true, recursive: true });
239
+ }
240
+ }
169
241
  const remove = await git(primary, io, ["worktree", "remove", worktree]);
170
242
  if (remove.exitCode !== 0) {
171
243
  return {
@@ -183,7 +255,15 @@ async function cleanupIntegrated(
183
255
  }
184
256
  }
185
257
  if (branchExistsNow) {
186
- const del = await git(primary, io, ["branch", "-d", entry.name]);
258
+ // RFC-1515: a vanished worktree leaves a stale `git worktree`
259
+ // registration that pins the branch — prune it before deletion. Merged
260
+ // state is already proven by isAncestor, so `-D` is the verified delete
261
+ // (`-d` re-derives containment in the current worktree context, which
262
+ // the F-0093 *.stale race corrupted).
263
+ if (worktree !== null && !(await io.exists(worktree))) {
264
+ await git(primary, io, ["worktree", "prune"]);
265
+ }
266
+ const del = await git(primary, io, ["branch", "-D", entry.name]);
187
267
  if (del.exitCode !== 0) {
188
268
  return {
189
269
  cleanedUp: false,
@@ -211,6 +291,24 @@ async function cleanupIntegrated(
211
291
  sha,
212
292
  detail: journalEvent === "backmerge" ? `back-merged into develop` : `integrated into develop`,
213
293
  base: journalBase,
294
+ ...(toleratedPaths.length > 0 ? { toleratedState: toleratedPaths } : {}),
295
+ ...(journalToleratedDirt !== undefined && journalToleratedDirt.length > 0
296
+ ? { toleratedDirt: journalToleratedDirt }
297
+ : {}),
298
+ ...(journalAutoResolved !== undefined && journalAutoResolved.length > 0
299
+ ? { autoResolved: journalAutoResolved }
300
+ : {}),
301
+ ...(journalRemediation?.reattachedTo !== undefined
302
+ ? { reattachedTo: journalRemediation.reattachedTo }
303
+ : {}),
304
+ ...(journalRemediation?.autoCleaned !== undefined &&
305
+ journalRemediation.autoCleaned.length > 0
306
+ ? { autoCleaned: journalRemediation.autoCleaned }
307
+ : {}),
308
+ ...(journalRemediation?.autocommitSha !== undefined
309
+ ? { autocommitSha: journalRemediation.autocommitSha }
310
+ : {}),
311
+ ...(journalGateReport !== undefined ? { gateReport: journalGateReport } : {}),
214
312
  });
215
313
  } catch (error) {
216
314
  if (error instanceof LockTimeoutError || error instanceof FlowRegistrySchemaError) {
@@ -235,8 +333,43 @@ async function cleanupIntegrated(
235
333
  /**
236
334
  * Core of flow.integrate — callable with an injected clock. Refusal paths
237
335
  * return diagnostics; `integrated`/`cleanedUp` report what really happened.
336
+ * The exported wrapper journals every refusal (RFC-1537); this attempt body
337
+ * stays pure.
238
338
  */
239
339
  export async function integrateFlowBranch(
340
+ repoRoot: string,
341
+ io: WorkspaceIO,
342
+ opts: Parameters<typeof integrateFlowBranchAttempt>[2],
343
+ ): Promise<FlowIntegrateData> {
344
+ const data = await integrateFlowBranchAttempt(repoRoot, io, opts);
345
+ const error = data.diagnostics.find((d) => d.severity === "error");
346
+ if (error !== undefined && data.branch !== null) {
347
+ // Best-effort bookkeeping — a journal write failure never adds a refusal.
348
+ try {
349
+ const common = await commonGitDir(io, repoRoot);
350
+ const sha =
351
+ (await git(repoRoot, io, ["rev-parse", "--verify", "-q", `refs/heads/${data.branch}`]))
352
+ .stdout.trim() || "unknown";
353
+ await appendJournal(io, common, {
354
+ event: "integrate-refusal",
355
+ branch: data.branch,
356
+ sha,
357
+ detail: error.message,
358
+ rule: error.ruleId,
359
+ ...(data.toleratedState !== undefined ? { toleratedState: data.toleratedState } : {}),
360
+ ...(data.toleratedDirt !== undefined ? { toleratedDirt: data.toleratedDirt } : {}),
361
+ // RFC-1532: the refused attempt's report links here too — the journal
362
+ // answers "which gate report belongs to this refusal" in one field.
363
+ ...(data.gate?.reportPath ? { gateReport: data.gate.reportPath } : {}),
364
+ });
365
+ } catch {
366
+ /* journal is audit, not gate */
367
+ }
368
+ }
369
+ return data;
370
+ }
371
+
372
+ async function integrateFlowBranchAttempt(
240
373
  repoRoot: string,
241
374
  io: WorkspaceIO,
242
375
  opts: {
@@ -246,14 +379,25 @@ export async function integrateFlowBranch(
246
379
  onProgress?: (m: string) => void;
247
380
  /** Caller already holds the integration lock (flow.cut/fix releases). */
248
381
  lockHeld?: boolean;
382
+ /** Test seam — shrink the lock-wait budget so a held lock refuses fast. */
383
+ lockWaitMs?: number;
249
384
  /** Gate target — passed to the integration gate as FORGE_FLOW_TARGET. */
250
385
  target?: "develop" | "main";
386
+ /** RFC-1528: kernel invoke port for the bounded preflight validators. */
387
+ invoke?: ForgeInvokeCommand;
388
+ /** RFC-1528: command registry for preflight resolvability. */
389
+ commandRegistry?: CommandRegistry;
390
+ /** RFC-1531: recreate a vanished registered worktree inside the lock. */
391
+ reattach?: boolean;
392
+ /** RFC-1531: delete disposable-classified dirty paths, then re-evaluate. */
393
+ autoClean?: boolean;
394
+ /** RFC-1531: sweep remaining dirty entries into a fixed-subject commit. */
395
+ autocommit?: boolean;
251
396
  },
252
397
  ): Promise<FlowIntegrateData> {
253
398
  const now = opts.now ?? new Date();
254
399
 
255
- const branch =
256
- opts.branch ?? (await currentBranch(repoRoot, io));
400
+ const branch = opts.branch ?? (await currentBranch(repoRoot, io));
257
401
  if (branch === null) {
258
402
  return refuse(
259
403
  "FLOW-INT-06",
@@ -267,12 +411,45 @@ export async function integrateFlowBranch(
267
411
  resolved = await resolveEntry(repoRoot, io, branch);
268
412
  } catch (error) {
269
413
  if (error instanceof FlowRegistrySchemaError) {
270
- return refuse("FLOW-07", error.message, `repair or remove ${registryPath(await commonGitDir(io, repoRoot))}`);
414
+ return refuse(
415
+ "FLOW-07",
416
+ error.message,
417
+ `repair or remove ${registryPath(await commonGitDir(io, repoRoot))}`,
418
+ );
271
419
  }
272
420
  throw error;
273
421
  }
274
422
  const { common, entry } = resolved;
275
423
  if (entry === null) {
424
+ // RFC-1538: a second integrate after a successful one finds no entry —
425
+ // report "already-integrated" (exit 0) instead of FLOW-INT-06 when the
426
+ // journal proves the branch landed or develop already contains its tip.
427
+ let contained = false;
428
+ try {
429
+ const journal = await readJournal(io, common);
430
+ contained = journal.some(
431
+ (e) => e.branch === branch && (e.event === "integrate" || e.event === "backmerge"),
432
+ );
433
+ } catch {
434
+ contained = false;
435
+ }
436
+ if (!contained && (await branchExists(repoRoot, io, branch))) {
437
+ const tip = (await git(repoRoot, io, ["rev-parse", branch])).stdout.trim();
438
+ contained = await isAncestor(repoRoot, io, tip, "develop");
439
+ }
440
+ if (contained) {
441
+ return {
442
+ branch,
443
+ integrated: true,
444
+ developBefore: null,
445
+ developAfter: null,
446
+ rebased: false,
447
+ gate: null,
448
+ cleanedUp: true,
449
+ disposition: "already-integrated",
450
+ diagnostics: [],
451
+ };
452
+ }
276
453
  return refuse(
277
454
  "FLOW-INT-06",
278
455
  `${branch} is not a registered session/task branch`,
@@ -304,6 +481,14 @@ export async function integrateFlowBranch(
304
481
  const live = await worktreeList(primary, io);
305
482
  const wtPath = live.find((w) => w.branch === branch)?.path ?? entry.worktree;
306
483
  if (wtPath === null || !(await io.exists(wtPath))) {
484
+ // RFC-1531: report the reattach target --reattach would use — nothing
485
+ // is created under --dry-run (AC-7).
486
+ const wouldReattach =
487
+ opts.reattach === true
488
+ ? entry.worktree !== null && (await io.exists(dirname(entry.worktree)))
489
+ ? entry.worktree
490
+ : flowWorktreePath(primary, branch)
491
+ : undefined;
307
492
  return {
308
493
  branch,
309
494
  integrated: false,
@@ -312,17 +497,25 @@ export async function integrateFlowBranch(
312
497
  rebased: false,
313
498
  gate: null,
314
499
  cleanedUp: false,
500
+ ...(wouldReattach !== undefined ? { wouldReattach } : {}),
315
501
  diagnostics: [
316
502
  {
317
503
  ruleId: "FLOW-07",
318
504
  severity: "error",
319
- message: `registry entry for ${branch} names worktree ${wtPath}, which does not exist`,
320
- fixHint: "inspect with flow.status — a stale entry may need flow.discard",
505
+ message: `registry entry for ${branch} names worktree ${wtPath}, which does not exist (vanished)` +
506
+ (wouldReattach !== undefined ? ` — --reattach would recreate it at ${wouldReattach}` : ""),
507
+ fixHint:
508
+ "re-run with --reattach to recreate the worktree at its recorded path, or run flow.discard to drop the registry entry and force-delete the branch",
509
+ data: { vanished: true, ...(wouldReattach !== undefined ? { wouldReattach } : {}) },
321
510
  },
322
511
  ],
323
512
  };
324
513
  }
325
514
  const dirty = await statusDirty(wtPath, io);
515
+ // RFC-1531: the dry-run diagnostic carries the classified dirty set so
516
+ // the operator reads the remedy (--auto-clean scope) without mutating.
517
+ const classified = classifyDirtyTree(dirty.entries);
518
+ const disposable = classified.filter((c) => c.class === "disposable").map((c) => c.path);
326
519
  return {
327
520
  branch,
328
521
  integrated: false,
@@ -331,14 +524,27 @@ export async function integrateFlowBranch(
331
524
  rebased: false,
332
525
  gate: null,
333
526
  cleanedUp: false,
527
+ ...(dirty.toleratedState.length > 0 ? { toleratedState: dirty.toleratedState } : {}),
334
528
  diagnostics:
335
- dirty.length > 0
529
+ dirty.entries.length > 0
336
530
  ? [
337
531
  {
338
532
  ruleId: "FLOW-INT-01",
339
533
  severity: "error",
340
- message: `worktree ${wtPath} has ${dirty.length} uncommitted change(s)`,
341
- fixHint: "commit or revert the uncommitted changes inside the session worktree",
534
+ message:
535
+ `worktree ${wtPath} has ${dirty.entries.length} uncommitted change(s)` +
536
+ (dirty.toleratedState.length > 0
537
+ ? ` — tolerated forge-local state: ${dirty.toleratedState.join(", ")}`
538
+ : ""),
539
+ fixHint:
540
+ "commit or revert the uncommitted changes inside the session worktree, or remediate with --auto-clean / --autocommit, then re-run",
541
+ data: {
542
+ entries: classified,
543
+ classes: summarizeClasses(classified),
544
+ toleratedState: dirty.toleratedState,
545
+ ...(opts.autoClean === true ? { wouldAutoClean: disposable } : {}),
546
+ ...(opts.autocommit === true ? { wouldAutocommit: true } : {}),
547
+ },
342
548
  },
343
549
  ]
344
550
  : [],
@@ -350,206 +556,594 @@ export async function integrateFlowBranch(
350
556
  // Steps 0–5 under the integration lock (or inside the caller's lock when
351
557
  // lockHeld — flow.cut holds it across the whole release).
352
558
  const integrateInner = async (): Promise<FlowIntegrateData> => {
353
- const developBefore = (await git(primary, io, ["rev-parse", "develop"])).stdout.trim();
354
- const hasBranch = await branchExists(primary, io, branch);
355
-
356
- // Rerun/resume: develop already contains the branch tip (or the
357
- // branch ref is gone) — nothing to move; clean up outside the lock.
358
- let resume = !hasBranch;
359
- let branchTip: string | null = null;
360
- if (hasBranch) {
361
- branchTip = (await git(primary, io, ["rev-parse", branch])).stdout.trim();
362
- resume = await isAncestor(primary, io, branchTip, "develop");
363
- }
364
- if (resume) {
365
- return {
366
- branch,
367
- integrated: true,
368
- developBefore,
369
- developAfter: developBefore,
370
- rebased: false,
371
- gate: null,
372
- cleanedUp: false,
373
- diagnostics: [],
374
- };
375
- }
559
+ const developBefore = (await git(primary, io, ["rev-parse", "develop"])).stdout.trim();
560
+ const hasBranch = await branchExists(primary, io, branch);
376
561
 
377
- // (2) the branch worktree must exist and be clean.
378
- const worktrees = await worktreeList(primary, io);
379
- const branchWorktree =
380
- worktrees.find((w) => w.branch === branch)?.path ?? entry.worktree;
381
- if (branchWorktree === null || !(await io.exists(branchWorktree))) {
382
- return refuse(
383
- "FLOW-07",
384
- `registry entry for ${branch} names worktree ${branchWorktree}, which does not exist`,
385
- "inspect with flow.status — a stale entry may need flow.discard",
386
- { branch, developBefore },
387
- );
388
- }
389
- const dirty = await statusDirty(branchWorktree, io);
390
- if (dirty.length > 0) {
562
+ // Rerun/resume: develop already contains the branch tip (or the
563
+ // branch ref is gone) — nothing to move; clean up outside the lock.
564
+ let resume = !hasBranch;
565
+ let branchTip: string | null = null;
566
+ if (hasBranch) {
567
+ branchTip = (await git(primary, io, ["rev-parse", branch])).stdout.trim();
568
+ resume = await isAncestor(primary, io, branchTip, "develop");
569
+ }
570
+ if (resume) {
571
+ return {
572
+ branch,
573
+ integrated: true,
574
+ developBefore,
575
+ developAfter: developBefore,
576
+ rebased: false,
577
+ gate: null,
578
+ cleanedUp: false,
579
+ diagnostics: [],
580
+ };
581
+ }
582
+
583
+ // RFC-1538: post-lock revalidation — the registry observed pre-lock can
584
+ // have changed while this run waited on the integration lock (F-0138:
585
+ // a racing integrate's teardown deleted entry+worktree under us).
586
+ const liveRegistry = await readRegistry(io, common);
587
+ const liveEntry = liveRegistry.branches.find((b) => b.name === branch);
588
+ if (liveEntry === undefined) {
589
+ // Registration vanished mid-wait. Contained work already landed → the
590
+ // winner completed; report idempotently. Otherwise mid-teardown.
591
+ const liveBranch = await branchExists(primary, io, branch);
592
+ const liveContained =
593
+ liveBranch &&
594
+ (await isAncestor(
595
+ primary,
596
+ io,
597
+ (await git(primary, io, ["rev-parse", branch])).stdout.trim(),
598
+ "develop",
599
+ ));
600
+ if (liveContained || !liveBranch) {
601
+ return {
602
+ branch,
603
+ integrated: true,
604
+ developBefore,
605
+ developAfter: developBefore,
606
+ rebased: false,
607
+ gate: null,
608
+ cleanedUp: true,
609
+ disposition: "already-integrated",
610
+ diagnostics: [],
611
+ };
612
+ }
613
+ return refuse(
614
+ "FLOW-INT-15",
615
+ `registry entry for ${branch} vanished while waiting on the integration lock, but the branch is not contained in develop (mid-teardown state)`,
616
+ "run flow.status for the live view; recover the orphaned entry with flow.discard",
617
+ { branch, developBefore },
618
+ );
619
+ }
620
+
621
+ // (2) the branch worktree must exist and be clean.
622
+ const worktrees = await worktreeList(primary, io);
623
+ // `live` is the worktree git currently associates with the branch — a
624
+ // STALE registration keeps naming the dead recorded path until pruned,
625
+ // so `live !== null` does not prove the directory exists.
626
+ const live = worktrees.find((w) => w.branch === branch)?.path ?? null;
627
+ let branchWorktree = live ?? liveEntry.worktree;
628
+ let reattachedTo: string | undefined;
629
+ // Occupied: the recorded path exists on disk but git associates no live
630
+ // worktree with the branch — a foreign tree squats there.
631
+ const occupied =
632
+ live === null && liveEntry.worktree !== null && (await io.exists(liveEntry.worktree));
633
+ const vanished =
634
+ !occupied && (branchWorktree === null || !(await io.exists(branchWorktree)));
635
+ if (opts.reattach === true && occupied) {
636
+ return refuse(
637
+ "FLOW-INT-17",
638
+ `registry worktree path ${liveEntry.worktree} exists on disk but is not a worktree of ${branch} (occupied)`,
639
+ "remove or rename the occupant, then re-run flow.integrate --reattach",
640
+ { branch, developBefore },
641
+ { occupied: true },
642
+ );
643
+ }
644
+ if (opts.reattach === true && vanished) {
645
+ // RFC-1531 --reattach: recreate the vanished worktree inside the lock,
646
+ // before the dirty/preflight checks. The recorded registry path is
647
+ // preferred when its parent exists (operators learned that location);
648
+ // the canonical <repo>@<branch> sibling is the fallback.
649
+ const recorded = liveEntry.worktree;
650
+ const target =
651
+ recorded !== null && (await io.exists(dirname(recorded)))
652
+ ? recorded
653
+ : flowWorktreePath(primary, branch);
654
+ // F-0093: a vanished worktree can leave a stale `git worktree`
655
+ // registration that pins the branch — prune before adding (mirrors
656
+ // cleanupIntegrated's ordering).
657
+ await git(primary, io, ["worktree", "prune"]);
658
+ const add = await worktreeAdd(primary, io, target, branch);
659
+ if (add.exitCode !== 0) {
660
+ return refuse(
661
+ "FLOW-INT-17",
662
+ `git worktree add ${target} ${branch} failed: ${add.stderr.trim()}`,
663
+ "resolve the git error (stale registration? occupied path?) and re-run flow.integrate --reattach",
664
+ { branch, developBefore },
665
+ );
666
+ }
667
+ reattachedTo = target;
668
+ branchWorktree = target;
669
+ opts.onProgress?.(`reattached ${branch} at ${target}`);
670
+ }
671
+ if (branchWorktree === null || !(await io.exists(branchWorktree))) {
672
+ return refuse(
673
+ "FLOW-INT-15",
674
+ `registry entry for ${branch} names worktree ${branchWorktree}, which does not exist (vanished mid-teardown state — the branch is not contained in develop)`,
675
+ "re-run with --reattach to recreate the worktree, or run flow.status for the live view and flow.discard to drop the entry",
676
+ { branch, developBefore },
677
+ { vanished: true },
678
+ );
679
+ }
680
+ let dirty = await statusDirty(branchWorktree, io);
681
+ if (dirty.toleratedState.length > 0) {
682
+ opts.onProgress?.(`tolerated forge-local state: ${dirty.toleratedState.join(", ")}`);
683
+ }
684
+
685
+ // RFC-1531 remediation flags — before the dirty checks: --auto-clean
686
+ // deletes ONLY disposable-class paths (closed allowlist — a work-class
687
+ // member in the set deletes nothing and still refuses FLOW-INT-01, and
688
+ // an importer-prune lockfile refuses too: restoring/committing it is a
689
+ // content decision, AC-4), then --autocommit sweeps the remainder into
690
+ // the fixed-subject commit. Remediation failures refuse FLOW-INT-17.
691
+ let autoCleaned: string[] | undefined;
692
+ let autocommitSha: string | undefined;
693
+ if (dirty.entries.length > 0 && (opts.autoClean === true || opts.autocommit === true)) {
694
+ const { classifyDirtyEntries } = await import("../preflight.ts");
695
+ const classified = await classifyDirtyEntries(branchWorktree, io, dirty.entries);
696
+ // Pass = AUTO_CLEAN_PASS_CLASSES (tolerated family incl. the RFC-1537
697
+ // regenerable classes) or disposable. Blocker = work or importer-prune
698
+ // — AC-4 names importer-prune a refusal class: restoring/committing a
699
+ // lockfile is a content decision, never a cleanup step.
700
+ const blocker = classified.filter(
701
+ (c) =>
702
+ c.class !== "disposable" && !AUTO_CLEAN_PASS_CLASSES.includes(c.class),
703
+ );
704
+ if (opts.autoClean === true) {
705
+ // A blocker refuses only when nothing downstream will commit it:
706
+ // with --autocommit also set, work members sweep into the commit —
707
+ // the RFC's composed order is clean → commit → integrate.
708
+ if (blocker.length > 0 && opts.autocommit !== true) {
391
709
  return refuse(
392
710
  "FLOW-INT-01",
393
- `worktree ${branchWorktree} has ${dirty.length} uncommitted change(s): ${dirty.slice(0, 10).join(", ")}`,
394
- "commit or revert the uncommitted changes inside the session worktree, then re-run",
395
- { branch, developBefore },
711
+ `worktree ${branchWorktree} has ${blocker.length} uncommitted change(s) outside the disposable set: ${blocker
712
+ .slice(0, 10)
713
+ .map((b) => `${b.path} (${b.class})`)
714
+ .join(", ")} — --auto-clean deletes nothing on a mixed set`,
715
+ "commit or revert the work-class entries inside the session worktree, or re-run with --autocommit to sweep them into a commit",
716
+ { branch, developBefore, toleratedState: dirty.toleratedState },
717
+ {
718
+ entries: classified,
719
+ classes: summarizeClasses(classified),
720
+ toleratedState: dirty.toleratedState,
721
+ },
396
722
  );
397
723
  }
398
-
399
- // Port entries (RFC-1490): develop must not have moved since the port
400
- // opened, and the tip must be the fixed-message merge whose second
401
- // parent is port.mainSha. No rebase — that would linearize the merge.
402
- if (entry.port !== null) {
403
- if (developBefore !== entry.baseSha) {
404
- return refuse(
405
- "FLOW-INT-10",
406
- `develop moved to ${developBefore.slice(0, 9)} since the port branch opened (base ${entry.baseSha.slice(0, 9)})`,
407
- "run flow.backmerge --redo to reopen the port on the new develop tip",
408
- { branch, developBefore },
409
- );
410
- }
411
- const expectedSubject = `release ${entry.port.tags.join(", ")} → develop`;
412
- const parents = await git(branchWorktree, io, ["rev-list", "--parents", "-1", "HEAD"]);
413
- const parts = parents.stdout.trim().split(/\s+/);
414
- const subject = (await git(branchWorktree, io, ["log", "-1", "--format=%s"])).stdout.trim();
415
- if (parts.length !== 3 || parts[2] !== entry.port.mainSha || subject !== expectedSubject) {
724
+ const toDelete = classified.filter((c) => c.class === "disposable");
725
+ autoCleaned = [];
726
+ for (const entry of toDelete) {
727
+ try {
728
+ await rm(join(branchWorktree, entry.path), { force: true, recursive: true });
729
+ autoCleaned.push(entry.path);
730
+ opts.onProgress?.(`auto-clean: deleted ${entry.path}`);
731
+ } catch (error) {
416
732
  return refuse(
417
- "FLOW-INT-09",
418
- `port tip is not the back-merge commit — expected merge '${expectedSubject}' with second parent ${entry.port.mainSha.slice(0, 9)}`,
419
- "commit the resolved merge inside the port worktree with git commit --no-edit, or run flow.backmerge --redo",
420
- { branch, developBefore },
733
+ "FLOW-INT-17",
734
+ `--auto-clean could not delete ${entry.path}: ${error instanceof Error ? error.message : String(error)}`,
735
+ "delete the path manually inside the session worktree, then re-run flow.integrate",
736
+ { branch, developBefore, autoCleaned },
421
737
  );
422
738
  }
423
739
  }
424
-
425
- // (3) rebase onto the current develop — never for port entries.
426
- const rebaseBase = (await git(primary, io, ["rev-parse", "develop"])).stdout.trim();
427
- const rebase =
428
- entry.port !== null
429
- ? { exitCode: 0, stdout: "", stderr: "" }
430
- : await git(branchWorktree, io, ["rebase", "develop"]);
431
- if (rebase.exitCode !== 0) {
432
- const conflicts = await git(branchWorktree, io, [
433
- "diff",
434
- "--name-only",
435
- "--diff-filter=U",
436
- ]);
437
- const paths = conflicts.stdout
438
- .split("\n")
439
- .map((l) => l.trim())
440
- .filter((l) => l.length > 0);
441
- await git(branchWorktree, io, ["rebase", "--abort"]);
740
+ dirty = await statusDirty(branchWorktree, io);
741
+ }
742
+ if (opts.autocommit === true && dirty.entries.length > 0) {
743
+ // Stage exactly the remaining entry paths — never `git add -A`:
744
+ // tolerated FORGE_STATE paths are journaled, never committed.
745
+ const paths = dirty.entries.map((line) => line.slice(3).trim());
746
+ const add = await git(branchWorktree, io, ["add", "-A", "--", ...paths]);
747
+ if (add.exitCode !== 0) {
442
748
  return refuse(
443
- "FLOW-INT-02",
444
- `rebase onto develop conflicts in: ${paths.join(", ") || "(unknown paths)"}`,
445
- "resolve the rebase inside the session worktree, commit, and re-run flow.integrate",
446
- { branch, developBefore },
749
+ "FLOW-INT-17",
750
+ `--autocommit staging failed: ${add.stderr.trim()}`,
751
+ "inspect the session worktree state, then re-run flow.integrate",
752
+ { branch, developBefore, autoCleaned },
447
753
  );
448
754
  }
449
-
450
- // (4) integration gate — the primary's copy gates the branch.
451
- const gate = await runFlowScript(io, "integration-gate", {
452
- primary,
453
- cwd: branchWorktree,
454
- env: {
455
- FLOW_PRIMARY: primary,
456
- FLOW_BRANCH: branch,
457
- FLOW_BASE_SHA: rebaseBase,
458
- FORGE_FLOW_TARGET: opts.target ?? "develop",
459
- },
460
- });
461
- if (gate.status === "failed") {
755
+ const commit = await gitCommit(branchWorktree, io, [
756
+ "commit",
757
+ "-m",
758
+ SWEEP_COMMIT_SUBJECT,
759
+ ], "integrate");
760
+ if (commit.exitCode !== 0) {
462
761
  return refuse(
463
- "FLOW-INT-05",
464
- `hooks/integration-gate.sh refused the integration (exit ${gate.exitCode}): ${gate.stderrTail}`,
465
- `fix what ${primary}/hooks/integration-gate.sh demands, then re-run`,
466
- { branch, developBefore, rebased: entry.port === null, gate },
762
+ "FLOW-INT-17",
763
+ `--autocommit commit failed: ${commit.stderr.trim()}`,
764
+ "the staging stays for the operator to inspect — resolve and commit or reset inside the session worktree, then re-run",
765
+ { branch, developBefore, autoCleaned },
467
766
  );
468
767
  }
768
+ autocommitSha = (
769
+ await git(branchWorktree, io, ["rev-parse", "HEAD"])
770
+ ).stdout.trim();
771
+ opts.onProgress?.(
772
+ `autocommit: swept ${paths.length} path(s) into ${autocommitSha.slice(0, 9)} (${SWEEP_COMMIT_SUBJECT})`,
773
+ );
774
+ dirty = await statusDirty(branchWorktree, io);
775
+ }
776
+ }
777
+ // RFC-1537: declared regenerable dirt tolerated on this attempt —
778
+ // surfaced in data + journaled on integrate/refusal, never committed.
779
+ let toleratedDirt: Array<{ path: string; class: string }> = [];
780
+ // RFC-1528: bounded preflight — dirty-tree checks with lockfile
781
+ // classification, then the four validators that used to fire only inside
782
+ // the expensive integration gate. Non-port path only (port entries keep
783
+ // their own FLOW-INT-09/10 semantics); first failure refuses before the
784
+ // rebase and before the gate spawns.
785
+ if (entry.port === null) {
786
+ const { runIntegratePreflight } = await import("../preflight.ts");
787
+ const preflight = await runIntegratePreflight({
788
+ primary,
789
+ branchWorktree,
790
+ branch,
791
+ io,
792
+ worktreeDirty: dirty,
793
+ invoke: opts.invoke,
794
+ commandRegistry: opts.commandRegistry,
795
+ });
796
+ toleratedDirt = preflight.tolerated;
797
+ for (const skipped of preflight.skipped) {
798
+ opts.onProgress?.(
799
+ skipped.reason === "no-invoke"
800
+ ? `preflight: ${skipped.check} skipped — no invoke port (standalone CLI)`
801
+ : `preflight: ${skipped.check} skipped — command not in the live inventory`,
802
+ );
803
+ }
804
+ for (const t of preflight.tolerated) {
805
+ opts.onProgress?.(`tolerated regenerable state: ${t.path} (${t.class})`);
806
+ }
807
+ if (!preflight.ok && preflight.refuse) {
808
+ return refuse(
809
+ preflight.refuse.ruleId,
810
+ preflight.refuse.message,
811
+ preflight.refuse.fixHint,
812
+ {
813
+ branch,
814
+ developBefore,
815
+ toleratedState: dirty.toleratedState,
816
+ toleratedDirt: preflight.tolerated,
817
+ reattachedTo,
818
+ autoCleaned,
819
+ autocommitSha,
820
+ },
821
+ preflight.refuse.data,
822
+ );
823
+ }
824
+ } else if (dirty.entries.length > 0) {
825
+ // Port path keeps its own refusal surface but the same regenerable
826
+ // classes still tolerate (RFC-1537) — an importer-materializing port
827
+ // worktree is no harder to integrate than a session one.
828
+ const { classifyDirt } = await import("../preflight.ts");
829
+ const verdict = await classifyDirt(branchWorktree, io, dirty.entries);
830
+ toleratedDirt = verdict.tolerated;
831
+ for (const t of verdict.tolerated) {
832
+ opts.onProgress?.(`tolerated regenerable state: ${t.path} (${t.class})`);
833
+ }
834
+ if (verdict.unattributed.length > 0) {
835
+ const entries = verdict.unattributed.map((line) => {
836
+ const path = line.slice(3).trim();
837
+ return { path, class: classifyDirtyPath(path) };
838
+ });
839
+ return refuse(
840
+ "FLOW-INT-01",
841
+ `worktree ${branchWorktree} has ${verdict.unattributed.length} uncommitted change(s): ${verdict.unattributed.slice(0, 10).join(", ")}` +
842
+ (verdict.tolerated.length > 0
843
+ ? ` — tolerated regenerable state: ${verdict.tolerated.map((t) => `${t.path} (${t.class})`).join(", ")}`
844
+ : "") +
845
+ (dirty.toleratedState.length > 0
846
+ ? ` — tolerated forge-local state: ${dirty.toleratedState.join(", ")}`
847
+ : ""),
848
+ "commit or revert the uncommitted changes inside the session worktree, or remediate with --auto-clean / --autocommit, then re-run",
849
+ {
850
+ branch,
851
+ developBefore,
852
+ toleratedState: dirty.toleratedState,
853
+ toleratedDirt: verdict.tolerated,
854
+ reattachedTo,
855
+ autoCleaned,
856
+ autocommitSha,
857
+ },
858
+ {
859
+ entries,
860
+ classes: summarizeClasses(entries),
861
+ toleratedState: dirty.toleratedState,
862
+ },
863
+ );
864
+ }
865
+ }
866
+
867
+ // Port entries (RFC-1490): develop must not have moved since the port
868
+ // opened, and the tip must be the fixed-message merge whose second
869
+ // parent is port.mainSha. No rebase — that would linearize the merge.
870
+ if (entry.port !== null) {
871
+ if (developBefore !== entry.baseSha) {
872
+ return refuse(
873
+ "FLOW-INT-10",
874
+ `develop moved to ${developBefore.slice(0, 9)} since the port branch opened (base ${entry.baseSha.slice(0, 9)})`,
875
+ "run flow.backmerge --redo to reopen the port on the new develop tip",
876
+ { branch, developBefore },
877
+ );
878
+ }
879
+ const expectedSubject = `release ${entry.port.tags.join(", ")} → develop`;
880
+ const parents = await git(branchWorktree, io, ["rev-list", "--parents", "-1", "HEAD"]);
881
+ const parts = parents.stdout.trim().split(/\s+/);
882
+ const subject = (await git(branchWorktree, io, ["log", "-1", "--format=%s"])).stdout.trim();
883
+ if (parts.length !== 3 || parts[2] !== entry.port.mainSha || subject !== expectedSubject) {
884
+ return refuse(
885
+ "FLOW-INT-09",
886
+ `port tip is not the back-merge commit — expected merge '${expectedSubject}' with second parent ${entry.port.mainSha.slice(0, 9)}`,
887
+ "commit the resolved merge inside the port worktree with git commit --no-edit, or run flow.backmerge --redo",
888
+ { branch, developBefore },
889
+ );
890
+ }
891
+ }
469
892
 
470
- // (5) primary must sit clean on develop, then fast-forward.
471
- const primaryBranch = await currentBranch(primary, io);
472
- const primaryDirty = await statusTracked(primary, io);
473
- if (primaryBranch !== "develop" || primaryDirty.length > 0) {
893
+ // (3) rebase onto the current develop — never for port entries.
894
+ // RFC-1538: a conflict confined to generated artifacts resolves via its
895
+ // owner command (checkout --theirs + regenerate + continue) — the
896
+ // generated-file doctrine applied inside the rebase path; anything else
897
+ // still refuses FLOW-INT-02 for a human.
898
+ const rebaseBase = (await git(primary, io, ["rev-parse", "develop"])).stdout.trim();
899
+ const autoResolved: string[] = [];
900
+ if (entry.port === null) {
901
+ let rebase = await git(branchWorktree, io, ["rebase", "develop"]);
902
+ let guard = 0;
903
+ while (rebase.exitCode !== 0 && guard++ < 8) {
904
+ const conflicts = await git(branchWorktree, io, [
905
+ "diff",
906
+ "--name-only",
907
+ "--diff-filter=U",
908
+ ]);
909
+ const paths = conflicts.stdout
910
+ .split("\n")
911
+ .map((l) => l.trim())
912
+ .filter((l) => l.length > 0);
913
+ const { classifyRebaseConflicts } = await import("../preflight.ts");
914
+ const verdict = await classifyRebaseConflicts(branchWorktree, io, paths);
915
+ const resolvable =
916
+ paths.length > 0 &&
917
+ verdict.nonGenerated.length === 0 &&
918
+ verdict.owners.length === paths.length &&
919
+ opts.invoke !== undefined;
920
+ if (!resolvable) {
921
+ await git(branchWorktree, io, ["rebase", "--abort"]);
474
922
  return refuse(
475
- "FLOW-INT-03",
476
- primaryBranch !== "develop"
477
- ? `primary worktree is on ${primaryBranch ?? "detached HEAD"}, not develop`
478
- : `primary worktree has ${primaryDirty.length} uncommitted change(s)`,
479
- "switch the primary to develop and commit or revert its tracked changes, then re-run — the branch stays rebased",
480
- { branch, developBefore, rebased: entry.port === null, gate },
923
+ "FLOW-INT-02",
924
+ `rebase onto develop conflicts in: ${paths.join(", ") || "(unknown paths)"}` +
925
+ (verdict.owners.length > 0
926
+ ? opts.invoke === undefined
927
+ ? " — generated conflicts present but no invoke port is available to regenerate them"
928
+ : " — mixed generated/non-generated conflict set"
929
+ : ""),
930
+ "resolve the rebase inside the session worktree, commit, and re-run flow.integrate",
931
+ { branch, developBefore },
481
932
  );
482
933
  }
483
- const developNow = (await git(primary, io, ["rev-parse", "develop"])).stdout.trim();
484
- if (!(await isAncestor(primary, io, developNow, branch))) {
485
- return refuse(
486
- "FLOW-INT-07",
487
- `develop moved to ${developNow.slice(0, 9)} after the rebase despite the integration lock`,
488
- "re-run flow.integrate — it rebases onto the new develop tip",
489
- { branch, developBefore, rebased: entry.port === null, gate },
490
- );
934
+ let failed = false;
935
+ for (const o of verdict.owners) {
936
+ await git(branchWorktree, io, ["checkout", "--theirs", "--", o.path]);
937
+ const regen = await opts.invoke!(o.command, o.flags);
938
+ if (regen.ok === false || (regen.exitCode !== undefined && regen.exitCode !== 0)) {
939
+ await git(branchWorktree, io, ["rebase", "--abort"]);
940
+ failed = true;
941
+ return refuse(
942
+ "FLOW-INT-02",
943
+ `auto-resolve of generated conflict ${o.path} failed: ${o.command} — ${regen.summary ?? `exit ${regen.exitCode}`}`,
944
+ "resolve the rebase inside the session worktree manually, commit, and re-run flow.integrate",
945
+ { branch, developBefore },
946
+ );
947
+ }
948
+ await git(branchWorktree, io, ["add", "--", o.path]);
949
+ opts.onProgress?.(`conflict: ${o.path} — regenerated via ${o.command}`);
950
+ autoResolved.push(o.path);
491
951
  }
492
- const merge = await git(primary, io, ["merge", "--ff-only", branch]);
493
- if (merge.exitCode !== 0) {
494
- return refuse(
495
- "FLOW-INT-07",
496
- `git merge --ff-only ${branch} failed: ${merge.stderr.trim()}`,
497
- "develop diverged from the rebased base — re-run flow.integrate to rebase again",
498
- { branch, developBefore, rebased: entry.port === null, gate },
499
- );
952
+ if (failed) break;
953
+ rebase = await git(branchWorktree, io, [
954
+ "-c",
955
+ "core.editor=true",
956
+ "rebase",
957
+ "--continue",
958
+ ]);
959
+ }
960
+ if (rebase.exitCode !== 0) {
961
+ const conflicts = await git(branchWorktree, io, [
962
+ "diff",
963
+ "--name-only",
964
+ "--diff-filter=U",
965
+ ]);
966
+ const paths = conflicts.stdout
967
+ .split("\n")
968
+ .map((l) => l.trim())
969
+ .filter((l) => l.length > 0);
970
+ await git(branchWorktree, io, ["rebase", "--abort"]);
971
+ return refuse(
972
+ "FLOW-INT-02",
973
+ `rebase onto develop conflicts in: ${paths.join(", ") || "(unknown paths)"}`,
974
+ "resolve the rebase inside the session worktree, commit, and re-run flow.integrate",
975
+ { branch, developBefore },
976
+ );
977
+ }
978
+ }
979
+
980
+ // (4) integration gate — the primary's script, executed by the session
981
+ // engine's build when the worktree carries one (RFC-1538): the code
982
+ // under review judges itself; the checks it faces stay primary-owned.
983
+ const { resolveGateEngine } = await import("../gate-engine.ts");
984
+ const engine = await resolveGateEngine(branchWorktree, primary, io);
985
+ const warnings: Diagnostic[] = [];
986
+ if (engine.source === "primary" && (await io.exists(join(primary, "hooks", "integration-gate.sh")))) {
987
+ warnings.push({
988
+ ruleId: "FLOW-INT-16",
989
+ severity: "warning",
990
+ message: `no session engine build under ${branchWorktree} — the integration gate runs the primary engine`,
991
+ fixHint:
992
+ "run pnpm install inside the session worktree to have its own build judged; the F-0137 self-referential escape is a backport worktree",
993
+ });
994
+ }
995
+ opts.onProgress?.(`gate engine: ${engine.source} (${engine.root})`);
996
+ const gate = await runFlowScript(io, "integration-gate", {
997
+ primary,
998
+ cwd: engine.root,
999
+ env: {
1000
+ FLOW_PRIMARY: primary,
1001
+ FLOW_BRANCH: branch,
1002
+ FLOW_BASE_SHA: rebaseBase,
1003
+ FORGE_FLOW_TARGET: opts.target ?? "develop",
1004
+ },
1005
+ });
1006
+ if (gate.status === "failed") {
1007
+ return refuse(
1008
+ "FLOW-INT-05",
1009
+ `hooks/integration-gate.sh refused the integration (exit ${gate.exitCode}): ${gate.stderrTail}`,
1010
+ `fix what ${primary}/hooks/integration-gate.sh demands, then re-run`,
1011
+ { branch, developBefore, rebased: entry.port === null, gate },
1012
+ // RFC-1532 AC-4: name the persisted report so the fixing agent reads
1013
+ // full check rows instead of re-running the gate.
1014
+ gate.reportPath ? { reportPath: gate.reportPath } : undefined,
1015
+ );
1016
+ }
1017
+
1018
+ // (5) primary must sit clean on develop, then fast-forward. Mid-gate
1019
+ // importer churn from another session's open mission tolerates here too
1020
+ // (RFC-1537) — the same classifier the preflight ran.
1021
+ const primaryBranch = await currentBranch(primary, io);
1022
+ const primaryDirty = await statusTracked(primary, io);
1023
+ if (primaryBranch !== "develop" || primaryDirty.entries.length > 0) {
1024
+ let unattributed = primaryDirty.entries;
1025
+ if (primaryDirty.entries.length > 0) {
1026
+ const { classifyDirt } = await import("../preflight.ts");
1027
+ const verdict = await classifyDirt(primary, io, primaryDirty.entries);
1028
+ unattributed = verdict.unattributed;
1029
+ if (verdict.tolerated.length > 0) {
1030
+ toleratedDirt = [...toleratedDirt, ...verdict.tolerated];
1031
+ for (const t of verdict.tolerated) {
1032
+ opts.onProgress?.(`tolerated regenerable state on primary: ${t.path} (${t.class})`);
1033
+ }
500
1034
  }
501
- const developAfter = (await git(primary, io, ["rev-parse", "develop"])).stdout.trim();
502
- return {
503
- branch,
504
- integrated: true,
505
- developBefore,
506
- developAfter,
507
- rebased: entry.port === null,
508
- gate,
509
- cleanedUp: false,
510
- diagnostics: [],
511
- };
1035
+ }
1036
+ if (primaryBranch !== "develop" || unattributed.length > 0) {
1037
+ return refuse(
1038
+ "FLOW-INT-03",
1039
+ primaryBranch !== "develop"
1040
+ ? `primary worktree is on ${primaryBranch ?? "detached HEAD"}, not develop`
1041
+ : `primary worktree has ${unattributed.length} uncommitted change(s)`,
1042
+ "switch the primary to develop and commit or revert its tracked changes, then re-run — the branch stays rebased",
1043
+ {
1044
+ branch,
1045
+ developBefore,
1046
+ rebased: entry.port === null,
1047
+ gate,
1048
+ ...(toleratedDirt.length > 0 ? { toleratedDirt } : {}),
1049
+ },
1050
+ );
1051
+ }
1052
+ }
1053
+ const developNow = (await git(primary, io, ["rev-parse", "develop"])).stdout.trim();
1054
+ if (!(await isAncestor(primary, io, developNow, branch))) {
1055
+ return refuse(
1056
+ "FLOW-INT-07",
1057
+ `develop moved to ${developNow.slice(0, 9)} after the rebase despite the integration lock`,
1058
+ "re-run flow.integrate — it rebases onto the new develop tip",
1059
+ { branch, developBefore, rebased: entry.port === null, gate },
1060
+ );
1061
+ }
1062
+ const merge = await git(primary, io, ["merge", "--ff-only", branch]);
1063
+ if (merge.exitCode !== 0) {
1064
+ return refuse(
1065
+ "FLOW-INT-07",
1066
+ `git merge --ff-only ${branch} failed: ${merge.stderr.trim()}`,
1067
+ "develop diverged from the rebased base — re-run flow.integrate to rebase again",
1068
+ { branch, developBefore, rebased: entry.port === null, gate },
1069
+ );
1070
+ }
1071
+ const developAfter = (await git(primary, io, ["rev-parse", "develop"])).stdout.trim();
1072
+ return {
1073
+ branch,
1074
+ integrated: true,
1075
+ developBefore,
1076
+ developAfter,
1077
+ rebased: entry.port === null,
1078
+ gate,
1079
+ cleanedUp: false,
1080
+ ...(dirty.toleratedState.length > 0 ? { toleratedState: dirty.toleratedState } : {}),
1081
+ ...(toleratedDirt.length > 0 ? { toleratedDirt } : {}),
1082
+ ...(autoResolved.length > 0 ? { autoResolved } : {}),
1083
+ ...(reattachedTo !== undefined ? { reattachedTo } : {}),
1084
+ ...(autoCleaned !== undefined && autoCleaned.length > 0 ? { autoCleaned } : {}),
1085
+ ...(autocommitSha !== undefined ? { autocommitSha } : {}),
1086
+ gateEngine: engine.source,
1087
+ diagnostics: warnings,
1088
+ };
512
1089
  };
513
1090
 
514
1091
  let inner: FlowIntegrateData;
515
1092
  try {
516
- inner = opts.lockHeld === true
517
- ? await integrateInner()
518
- : await withFlowLock(
519
- lockPath,
520
- {
521
- waitMs: INTEGRATE_LOCK_WAIT_MS,
522
- staleMs: INTEGRATE_LOCK_STALE_MS,
523
- progressEveryMs: 60_000,
524
- onProgress: opts.onProgress,
525
- onStale: (l) =>
526
- opts.onProgress?.(
527
- l.reason === "dead-holder"
528
- ? `broke dead-holder integration lock (pid ${l.pid ?? "?"} on ${l.host ?? "?"}, held since ${l.at})`
529
- : `broke stale integration lock (held since ${l.at}, ${Math.round(l.ageMs / 60000)} min old)`,
530
- ),
531
- },
532
- integrateInner,
533
- io,
534
- );
1093
+ inner =
1094
+ opts.lockHeld === true
1095
+ ? await integrateInner()
1096
+ : await withFlowLock(
1097
+ lockPath,
1098
+ {
1099
+ waitMs: opts.lockWaitMs ?? INTEGRATE_LOCK_WAIT_MS,
1100
+ staleMs: INTEGRATE_LOCK_STALE_MS,
1101
+ progressEveryMs: 60_000,
1102
+ onProgress: opts.onProgress,
1103
+ onStale: (l) =>
1104
+ opts.onProgress?.(
1105
+ l.reason === "dead-holder"
1106
+ ? `broke dead-holder integration lock (pid ${l.pid ?? "?"} on ${l.host ?? "?"}, held since ${l.at})`
1107
+ : `broke stale integration lock (held since ${l.at}, ${Math.round(l.ageMs / 60000)} min old)`,
1108
+ ),
1109
+ },
1110
+ integrateInner,
1111
+ io,
1112
+ );
535
1113
  } catch (error) {
536
1114
  if (error instanceof LockTimeoutError) {
1115
+ // RFC-1515 AC-4: a refused attempt reports the holder on the first
1116
+ // try — the lock payload names pid/host/at/heldMs plus a disposition
1117
+ // computed by the same dead-holder classifier withFlowLock uses.
1118
+ const holder = error.holder;
1119
+ const lock: LockDiagnostic | undefined =
1120
+ holder === undefined ? undefined : describeHeldLock(holder, INTEGRATE_LOCK_STALE_MS);
537
1121
  return refuse(
538
1122
  "FLOW-INT-08",
539
- `integration lock ${error.lockPath} is held by another integration`,
540
- "wait for the running integration to finish, or break the stale lock after 2 h automatically",
541
- { branch },
1123
+ lock === undefined
1124
+ ? `integration lock ${error.lockPath} is held by another integration (holder unknown)`
1125
+ : `integration lock ${error.lockPath} is held by pid ${lock.pid} on ${lock.host ?? "unknown host"} since ${lock.at} (${lock.disposition})`,
1126
+ "run forge werkstatt.lock.status for the live view, or forge werkstatt.lock.recover to break a dead holder's lock",
1127
+ { branch, lock },
542
1128
  );
543
1129
  }
544
1130
  if (error instanceof FlowRegistrySchemaError) {
545
- return refuse("FLOW-07", error.message, `repair or remove ${registryPath(common)}`, { branch });
1131
+ return refuse("FLOW-07", error.message, `repair or remove ${registryPath(common)}`, {
1132
+ branch,
1133
+ });
546
1134
  }
547
1135
  throw error;
548
1136
  }
549
1137
 
550
- if (!inner.integrated || inner.diagnostics.length > 0) return inner;
1138
+ // Only error-severity diagnostics are refusals — warnings (e.g. the
1139
+ // FLOW-INT-16 primary-engine notice) must not skip cleanup and journaling.
1140
+ if (!inner.integrated || inner.diagnostics.some((d) => d.severity === "error")) return inner;
551
1141
 
552
1142
  // (6) cleanup — outside the lock; every git call runs with -C primary.
1143
+ // RFC-1536: prune this session's own id reservations once the branch
1144
+ // landed — other sessions' entries stay untouched.
1145
+ await pruneReservationsForSession(io, primary, branch);
1146
+
553
1147
  const worktrees = await worktreeList(primary, io);
554
1148
  const branchWorktree = worktrees.find((w) => w.branch === branch)?.path ?? entry.worktree;
555
1149
  const cleanup = await cleanupIntegrated(
@@ -562,6 +1156,14 @@ export async function integrateFlowBranch(
562
1156
  now.toISOString(),
563
1157
  entry.port !== null ? "backmerge" : "integrate",
564
1158
  inner.developBefore ?? undefined,
1159
+ inner.toleratedDirt,
1160
+ inner.autoResolved,
1161
+ {
1162
+ reattachedTo: inner.reattachedTo,
1163
+ autoCleaned: inner.autoCleaned,
1164
+ autocommitSha: inner.autocommitSha,
1165
+ },
1166
+ inner.gate?.reportPath ?? undefined,
565
1167
  );
566
1168
  return {
567
1169
  ...inner,
@@ -590,6 +1192,11 @@ export async function runFlowIntegrate(
590
1192
  branch: typeof branchFlag === "string" ? branchFlag : null,
591
1193
  dryRun: context.dryRun || input.flags["dry-run"] === true,
592
1194
  onProgress: (m) => logger.info(` ${m}`),
1195
+ invoke: context.invoke,
1196
+ commandRegistry: context.commandRegistry,
1197
+ reattach: input.flags["reattach"] === true,
1198
+ autoClean: input.flags["auto-clean"] === true,
1199
+ autocommit: input.flags["autocommit"] === true,
593
1200
  });
594
1201
 
595
1202
  const refused = data.diagnostics.find((d) => d.severity === "error");
@@ -600,8 +1207,27 @@ export async function runFlowIntegrate(
600
1207
  logger.section("flow.integrate");
601
1208
  logger.info(` branch: ${data.branch}`);
602
1209
  logger.info(` integrated: ${data.integrated}${data.rebased ? " (rebased)" : ""}`);
603
- logger.info(` develop: ${data.developBefore?.slice(0, 9)} → ${data.developAfter?.slice(0, 9)}`);
1210
+ logger.info(
1211
+ ` develop: ${data.developBefore?.slice(0, 9)} → ${data.developAfter?.slice(0, 9)}`,
1212
+ );
604
1213
  logger.info(` cleanedUp: ${data.cleanedUp}`);
1214
+ if (data.toleratedDirt !== undefined && data.toleratedDirt.length > 0) {
1215
+ logger.info(
1216
+ ` tolerated: ${data.toleratedDirt.map((t) => `${t.path} (${t.class})`).join(", ")}`,
1217
+ );
1218
+ }
1219
+ if (data.toleratedState !== undefined && data.toleratedState.length > 0) {
1220
+ logger.info(` tolerated forge state: ${data.toleratedState.join(", ")}`);
1221
+ }
1222
+ if (data.reattachedTo !== undefined) {
1223
+ logger.info(` reattached: ${data.reattachedTo}`);
1224
+ }
1225
+ if (data.autoCleaned !== undefined && data.autoCleaned.length > 0) {
1226
+ logger.info(` auto-cleaned: ${data.autoCleaned.join(", ")}`);
1227
+ }
1228
+ if (data.autocommitSha !== undefined) {
1229
+ logger.info(` autocommit: ${data.autocommitSha.slice(0, 9)} (${SWEEP_COMMIT_SUBJECT})`);
1230
+ }
605
1231
  }
606
1232
  }
607
1233