@warpgogol/forge 9.3.1 → 9.4.1

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