@osovv/vv-opencode 2.0.1 → 2.1.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 (296) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +87 -86
  3. package/dist/commands/completion.js +0 -1
  4. package/dist/commands/completion.js.map +1 -1
  5. package/dist/commands/doctor.js +6 -9
  6. package/dist/commands/doctor.js.map +1 -1
  7. package/dist/commands/init.d.ts +2 -1
  8. package/dist/commands/init.js +7 -12
  9. package/dist/commands/init.js.map +1 -1
  10. package/dist/commands/install.d.ts +4 -0
  11. package/dist/commands/install.js +40 -37
  12. package/dist/commands/install.js.map +1 -1
  13. package/dist/commands/launch.d.ts +2 -1
  14. package/dist/commands/launch.js +18 -14
  15. package/dist/commands/launch.js.map +1 -1
  16. package/dist/commands/patch-provider.d.ts +225 -307
  17. package/dist/commands/patch-provider.js +92 -296
  18. package/dist/commands/patch-provider.js.map +1 -1
  19. package/dist/commands/status.js +7 -10
  20. package/dist/commands/status.js.map +1 -1
  21. package/dist/commands/sync.d.ts +4 -0
  22. package/dist/commands/sync.js +38 -35
  23. package/dist/commands/sync.js.map +1 -1
  24. package/dist/index.d.ts +25 -5
  25. package/dist/index.js +73 -34
  26. package/dist/index.js.map +1 -1
  27. package/dist/lib/agent-tool-catalog.d.ts +1 -1
  28. package/dist/lib/agent-tool-catalog.js +3 -6
  29. package/dist/lib/agent-tool-catalog.js.map +1 -1
  30. package/dist/lib/agent-tool-contract.d.ts +22 -13
  31. package/dist/lib/agent-tool-contract.js +20 -20
  32. package/dist/lib/agent-tool-contract.js.map +1 -1
  33. package/dist/lib/analytics/types.d.ts +7 -1
  34. package/dist/lib/analytics/types.js +2 -2
  35. package/dist/lib/analytics/types.js.map +1 -1
  36. package/dist/lib/config-layers.d.ts +28 -6
  37. package/dist/lib/config-layers.js +268 -73
  38. package/dist/lib/config-layers.js.map +1 -1
  39. package/dist/lib/managed-agents.d.ts +24 -2
  40. package/dist/lib/managed-agents.js +45 -15
  41. package/dist/lib/managed-agents.js.map +1 -1
  42. package/dist/lib/model-roles.d.ts +5 -0
  43. package/dist/lib/model-roles.js +22 -1
  44. package/dist/lib/model-roles.js.map +1 -1
  45. package/dist/lib/opencode/agent-registrations.d.ts +4 -4
  46. package/dist/lib/opencode/agent-registrations.js +386 -197
  47. package/dist/lib/opencode/agent-registrations.js.map +1 -1
  48. package/dist/lib/opencode/inspection.d.ts +13 -13
  49. package/dist/lib/opencode/inspection.js +69 -106
  50. package/dist/lib/opencode/inspection.js.map +1 -1
  51. package/dist/lib/opencode/model-overrides.d.ts +2 -2
  52. package/dist/lib/opencode/model-overrides.js +192 -47
  53. package/dist/lib/opencode/model-overrides.js.map +1 -1
  54. package/dist/lib/opencode/paths.d.ts +6 -2
  55. package/dist/lib/opencode/paths.js +12 -11
  56. package/dist/lib/opencode/paths.js.map +1 -1
  57. package/dist/lib/opencode/plugin-registration.d.ts +10 -11
  58. package/dist/lib/opencode/plugin-registration.js +76 -138
  59. package/dist/lib/opencode/plugin-registration.js.map +1 -1
  60. package/dist/lib/opencode/shared-utils.d.ts +47 -3
  61. package/dist/lib/opencode/shared-utils.js +346 -15
  62. package/dist/lib/opencode/shared-utils.js.map +1 -1
  63. package/dist/lib/opencode.d.ts +5 -6
  64. package/dist/lib/opencode.js +10 -10
  65. package/dist/lib/opencode.js.map +1 -1
  66. package/dist/lib/vvoc-config.js +4 -4
  67. package/dist/lib/vvoc-config.js.map +1 -1
  68. package/dist/lib/vvoc-paths.d.ts +7 -0
  69. package/dist/lib/vvoc-paths.js +15 -1
  70. package/dist/lib/vvoc-paths.js.map +1 -1
  71. package/dist/lib/vvoc-preset-registry.d.ts +38 -50
  72. package/dist/lib/vvoc-preset-registry.js +38 -48
  73. package/dist/lib/vvoc-preset-registry.js.map +1 -1
  74. package/dist/plugins/analytics/index.d.ts +20 -14
  75. package/dist/plugins/analytics/index.js +281 -133
  76. package/dist/plugins/analytics/index.js.map +1 -1
  77. package/dist/plugins/guardian/index.d.ts +63 -42
  78. package/dist/plugins/guardian/index.js +217 -759
  79. package/dist/plugins/guardian/index.js.map +1 -1
  80. package/dist/plugins/hashline-edit/index.d.ts +145 -31
  81. package/dist/plugins/hashline-edit/index.js +679 -244
  82. package/dist/plugins/hashline-edit/index.js.map +1 -1
  83. package/dist/plugins/hashline-edit/schemas.d.ts +1 -1
  84. package/dist/plugins/hashline-edit/schemas.js +3 -3
  85. package/dist/plugins/hashline-edit/schemas.js.map +1 -1
  86. package/dist/plugins/model-roles/index.d.ts +18 -4
  87. package/dist/plugins/model-roles/index.js +44 -181
  88. package/dist/plugins/model-roles/index.js.map +1 -1
  89. package/dist/plugins/peak-hours/index.d.ts +23 -23
  90. package/dist/plugins/peak-hours/index.js +211 -180
  91. package/dist/plugins/peak-hours/index.js.map +1 -1
  92. package/dist/plugins/secrets-redaction/deep.js +35 -51
  93. package/dist/plugins/secrets-redaction/deep.js.map +1 -1
  94. package/dist/plugins/secrets-redaction/index.d.ts +96 -8
  95. package/dist/plugins/secrets-redaction/index.js +290 -102
  96. package/dist/plugins/secrets-redaction/index.js.map +1 -1
  97. package/dist/plugins/secrets-redaction/session.d.ts +9 -0
  98. package/dist/plugins/secrets-redaction/session.js +21 -4
  99. package/dist/plugins/secrets-redaction/session.js.map +1 -1
  100. package/dist/plugins/secrets-redaction/stream.d.ts +92 -0
  101. package/dist/plugins/secrets-redaction/stream.js +772 -0
  102. package/dist/plugins/secrets-redaction/stream.js.map +1 -0
  103. package/dist/plugins/spec-guard/index.d.ts +49 -18
  104. package/dist/plugins/spec-guard/index.js +231 -129
  105. package/dist/plugins/spec-guard/index.js.map +1 -1
  106. package/dist/plugins/system-context-injection/index.d.ts +10 -4
  107. package/dist/plugins/system-context-injection/index.js +271 -78
  108. package/dist/plugins/system-context-injection/index.js.map +1 -1
  109. package/dist/plugins/tool-history-compaction/index.d.ts +26 -4
  110. package/dist/plugins/tool-history-compaction/index.js +170 -32
  111. package/dist/plugins/tool-history-compaction/index.js.map +1 -1
  112. package/dist/plugins/tool-history-compaction/transform.d.ts +47 -16
  113. package/dist/plugins/tool-history-compaction/transform.js +173 -55
  114. package/dist/plugins/tool-history-compaction/transform.js.map +1 -1
  115. package/dist/plugins/web-tools/fetch-service.d.ts +51 -13
  116. package/dist/plugins/web-tools/fetch-service.js +106 -75
  117. package/dist/plugins/web-tools/fetch-service.js.map +1 -1
  118. package/dist/plugins/web-tools/index.d.ts +58 -16
  119. package/dist/plugins/web-tools/index.js +202 -91
  120. package/dist/plugins/web-tools/index.js.map +1 -1
  121. package/dist/plugins/web-tools/media-loader.d.ts +3 -3
  122. package/dist/plugins/web-tools/media-loader.js +3 -3
  123. package/dist/plugins/web-tools/media-loader.js.map +1 -1
  124. package/dist/plugins/web-tools/providers/native-fetch.d.ts +2 -2
  125. package/dist/plugins/web-tools/providers/native-fetch.js +1 -1
  126. package/dist/plugins/web-tools/providers/native-fetch.js.map +1 -1
  127. package/dist/plugins/web-tools/providers/spider.d.ts +2 -2
  128. package/dist/plugins/web-tools/providers/spider.js +1 -1
  129. package/dist/plugins/web-tools/providers/spider.js.map +1 -1
  130. package/dist/plugins/web-tools/providers/zai.d.ts +2 -2
  131. package/dist/plugins/web-tools/providers/zai.js +1 -1
  132. package/dist/plugins/web-tools/providers/zai.js.map +1 -1
  133. package/dist/plugins/web-tools/schemas.d.ts +1 -1
  134. package/dist/plugins/web-tools/schemas.js +3 -3
  135. package/dist/plugins/web-tools/schemas.js.map +1 -1
  136. package/dist/plugins/web-tools/search-service.d.ts +81 -12
  137. package/dist/plugins/web-tools/search-service.js +104 -57
  138. package/dist/plugins/web-tools/search-service.js.map +1 -1
  139. package/dist/plugins/workflow/authorization.d.ts +44 -10
  140. package/dist/plugins/workflow/authorization.js +113 -73
  141. package/dist/plugins/workflow/authorization.js.map +1 -1
  142. package/dist/plugins/workflow/cancellation.d.ts +86 -0
  143. package/dist/plugins/workflow/cancellation.js +202 -0
  144. package/dist/plugins/workflow/cancellation.js.map +1 -0
  145. package/dist/plugins/workflow/checkpoints.d.ts +7 -1
  146. package/dist/plugins/workflow/checkpoints.js +141 -21
  147. package/dist/plugins/workflow/checkpoints.js.map +1 -1
  148. package/dist/plugins/workflow/delegated.d.ts +14 -0
  149. package/dist/plugins/workflow/delegated.js +6 -5
  150. package/dist/plugins/workflow/delegated.js.map +1 -1
  151. package/dist/plugins/workflow/host.d.ts +81 -0
  152. package/dist/plugins/workflow/host.js +189 -0
  153. package/dist/plugins/workflow/host.js.map +1 -0
  154. package/dist/plugins/workflow/index.d.ts +69 -4
  155. package/dist/plugins/workflow/index.js +1391 -1026
  156. package/dist/plugins/workflow/index.js.map +1 -1
  157. package/dist/plugins/workflow/recovery.d.ts +3 -5
  158. package/dist/plugins/workflow/recovery.js +18 -33
  159. package/dist/plugins/workflow/recovery.js.map +1 -1
  160. package/dist/plugins/workflow/repair.d.ts +31 -5
  161. package/dist/plugins/workflow/repair.js +116 -48
  162. package/dist/plugins/workflow/repair.js.map +1 -1
  163. package/dist/plugins/workflow/results.d.ts +31 -31
  164. package/dist/plugins/workflow/results.js +4 -4
  165. package/dist/plugins/workflow/results.js.map +1 -1
  166. package/dist/plugins/workflow/schemas.d.ts +3 -3
  167. package/dist/plugins/workflow/schemas.js +5 -5
  168. package/dist/plugins/workflow/schemas.js.map +1 -1
  169. package/dist/plugins/workflow/system-instruction.md +4 -0
  170. package/dist/plugins/workflow/tooling.d.ts +6 -0
  171. package/dist/plugins/workflow/tooling.js +3 -1
  172. package/dist/plugins/workflow/tooling.js.map +1 -1
  173. package/dist/runtime/auxiliary.d.ts +13 -0
  174. package/dist/runtime/auxiliary.js +108 -0
  175. package/dist/runtime/auxiliary.js.map +1 -0
  176. package/dist/runtime/client.d.ts +88 -0
  177. package/dist/runtime/client.js +174 -0
  178. package/dist/runtime/client.js.map +1 -0
  179. package/dist/runtime/context-inspection-contract.d.ts +397 -0
  180. package/dist/runtime/context-inspection-contract.js +622 -0
  181. package/dist/runtime/context-inspection-contract.js.map +1 -0
  182. package/dist/runtime/context-inspection.d.ts +52 -0
  183. package/dist/runtime/context-inspection.js +324 -0
  184. package/dist/runtime/context-inspection.js.map +1 -0
  185. package/dist/runtime/context.d.ts +192 -0
  186. package/dist/runtime/context.js +1246 -0
  187. package/dist/runtime/context.js.map +1 -0
  188. package/dist/runtime/coordination.d.ts +40 -0
  189. package/dist/runtime/coordination.js +87 -0
  190. package/dist/runtime/coordination.js.map +1 -0
  191. package/dist/runtime/model-registry.d.ts +34 -0
  192. package/dist/runtime/model-registry.js +227 -0
  193. package/dist/runtime/model-registry.js.map +1 -0
  194. package/dist/runtime/permissions.d.ts +20 -0
  195. package/dist/runtime/permissions.js +250 -0
  196. package/dist/runtime/permissions.js.map +1 -0
  197. package/dist/runtime/snapshot-config.d.ts +80 -0
  198. package/dist/runtime/snapshot-config.js +268 -0
  199. package/dist/runtime/snapshot-config.js.map +1 -0
  200. package/dist/runtime/snapshot-store.d.ts +25 -0
  201. package/dist/runtime/snapshot-store.js +519 -0
  202. package/dist/runtime/snapshot-store.js.map +1 -0
  203. package/dist/runtime/snapshots.d.ts +59 -0
  204. package/dist/runtime/snapshots.js +721 -0
  205. package/dist/runtime/snapshots.js.map +1 -0
  206. package/dist/runtime/types.d.ts +713 -0
  207. package/dist/runtime/types.js +190 -0
  208. package/dist/runtime/types.js.map +1 -0
  209. package/dist/tui/analytics/indicator.d.ts +25 -26
  210. package/dist/tui/analytics/indicator.js +66 -74
  211. package/dist/tui/analytics/indicator.js.map +1 -1
  212. package/dist/tui/branding/footer.d.ts +7 -12
  213. package/dist/tui/branding/footer.js +16 -24
  214. package/dist/tui/branding/footer.js.map +1 -1
  215. package/dist/tui/context/analyze.d.ts +20 -9
  216. package/dist/tui/context/analyze.js +295 -257
  217. package/dist/tui/context/analyze.js.map +1 -1
  218. package/dist/tui/context/collect.d.ts +29 -3
  219. package/dist/tui/context/collect.js +450 -66
  220. package/dist/tui/context/collect.js.map +1 -1
  221. package/dist/tui/context/plugin.d.ts +21 -7
  222. package/dist/tui/context/plugin.js +65 -70
  223. package/dist/tui/context/plugin.js.map +1 -1
  224. package/dist/tui/context/types.d.ts +174 -43
  225. package/dist/tui/context/types.js +25 -19
  226. package/dist/tui/context/types.js.map +1 -1
  227. package/dist/tui/context/view.d.ts +33 -7
  228. package/dist/tui/context/view.js +136 -81
  229. package/dist/tui/context/view.js.map +1 -1
  230. package/dist/tui/peak-hours/banner.d.ts +13 -11
  231. package/dist/tui/peak-hours/banner.js +48 -80
  232. package/dist/tui/peak-hours/banner.js.map +1 -1
  233. package/dist/tui/policy.d.ts +69 -0
  234. package/dist/tui/policy.js +169 -0
  235. package/dist/tui/policy.js.map +1 -0
  236. package/dist/tui.d.ts +3 -8
  237. package/dist/tui.js +72 -68
  238. package/dist/tui.js.map +1 -1
  239. package/package.json +19 -15
  240. package/schemas/vvoc/v3.json +1 -1
  241. package/server.js +3 -5
  242. package/templates/agents/enhancer.md +10 -5
  243. package/templates/agents/guardian.md +10 -4
  244. package/templates/agents/investigator.md +4 -2
  245. package/templates/agents/vv-code-reviewer.md +4 -2
  246. package/templates/agents/vv-spec-reviewer.md +4 -2
  247. package/templates/skills/vv-execute/references/tool-contracts.md +1 -1
  248. package/tui.js +3 -5
  249. package/dist/plugins/analytics/v2.d.ts +0 -21
  250. package/dist/plugins/analytics/v2.js +0 -133
  251. package/dist/plugins/analytics/v2.js.map +0 -1
  252. package/dist/plugins/guardian/v2.d.ts +0 -13
  253. package/dist/plugins/guardian/v2.js +0 -204
  254. package/dist/plugins/guardian/v2.js.map +0 -1
  255. package/dist/plugins/hashline-edit/v2.d.ts +0 -12
  256. package/dist/plugins/hashline-edit/v2.js +0 -145
  257. package/dist/plugins/hashline-edit/v2.js.map +0 -1
  258. package/dist/plugins/model-roles/v2.d.ts +0 -24
  259. package/dist/plugins/model-roles/v2.js +0 -274
  260. package/dist/plugins/model-roles/v2.js.map +0 -1
  261. package/dist/plugins/peak-hours/v2.d.ts +0 -12
  262. package/dist/plugins/peak-hours/v2.js +0 -99
  263. package/dist/plugins/peak-hours/v2.js.map +0 -1
  264. package/dist/plugins/secrets-redaction/v2.d.ts +0 -19
  265. package/dist/plugins/secrets-redaction/v2.js +0 -138
  266. package/dist/plugins/secrets-redaction/v2.js.map +0 -1
  267. package/dist/plugins/spec-guard/v2.d.ts +0 -12
  268. package/dist/plugins/spec-guard/v2.js +0 -139
  269. package/dist/plugins/spec-guard/v2.js.map +0 -1
  270. package/dist/plugins/system-context-injection/agent-contexts.d.ts +0 -5
  271. package/dist/plugins/system-context-injection/agent-contexts.js +0 -164
  272. package/dist/plugins/system-context-injection/agent-contexts.js.map +0 -1
  273. package/dist/plugins/system-context-injection/v2.d.ts +0 -13
  274. package/dist/plugins/system-context-injection/v2.js +0 -60
  275. package/dist/plugins/system-context-injection/v2.js.map +0 -1
  276. package/dist/plugins/tool-history-compaction/v2.d.ts +0 -11
  277. package/dist/plugins/tool-history-compaction/v2.js +0 -56
  278. package/dist/plugins/tool-history-compaction/v2.js.map +0 -1
  279. package/dist/plugins/v2-runtime/config-watcher.d.ts +0 -26
  280. package/dist/plugins/v2-runtime/config-watcher.js +0 -111
  281. package/dist/plugins/v2-runtime/config-watcher.js.map +0 -1
  282. package/dist/plugins/v2-runtime/index.d.ts +0 -50
  283. package/dist/plugins/v2-runtime/index.js +0 -114
  284. package/dist/plugins/v2-runtime/index.js.map +0 -1
  285. package/dist/plugins/v2-runtime/location-config.d.ts +0 -51
  286. package/dist/plugins/v2-runtime/location-config.js +0 -91
  287. package/dist/plugins/v2-runtime/location-config.js.map +0 -1
  288. package/dist/plugins/v2-runtime/setup.d.ts +0 -48
  289. package/dist/plugins/v2-runtime/setup.js +0 -174
  290. package/dist/plugins/v2-runtime/setup.js.map +0 -1
  291. package/dist/plugins/web-tools/v2.d.ts +0 -11
  292. package/dist/plugins/web-tools/v2.js +0 -99
  293. package/dist/plugins/web-tools/v2.js.map +0 -1
  294. package/dist/plugins/workflow/v2.d.ts +0 -76
  295. package/dist/plugins/workflow/v2.js +0 -283
  296. package/dist/plugins/workflow/v2.js.map +0 -1
@@ -1,39 +1,46 @@
1
1
  // FILE: src/plugins/workflow/index.ts
2
- // VERSION: 0.9.1
2
+ // VERSION: 2.0.0
3
3
  // START_MODULE_CONTRACT
4
- // PURPOSE: Register workflow tools and enforcement while injecting only startup-profile-compatible vv-controller guidance, including profile-independent control tools with bounded recovery, host-call-bound attempts, terminal report-rejection settlement, checkpoint reviewer linkage, and strict owned-tool contract publication/validation.
5
- // SCOPE: work_item_open/list/close registration, profile-independent work_item_decide and work_checkpoint registration with root-session authorization and an SDK-backed read-only authorization-message lookup for user-authorized recovery, owned tool.definition publication of strict input JSON Schemas plus early validateWorkflowToolInput guards in tool.execute.before (without touching task-launch hooks), pre-dispatch structural validation of mutation tools, tracked launch validation with delegated barriers, overlapping-write gates, and authoritative native sealed-run rejection, live host-call bindings that convert supported foreground vv-implementer task launches into failed delegated attempts on confirmed host-terminal errors, result normalization and bounded same-session continuation with explicit hard-stop suppression, callID-bound delegated attempt results, terminal settlement of protocol-invalid reports as report_rejected attempts through staged persistence, checkpoint reviewer bookkeeping, round aggregation with bounded excerpts, implementation round limits, checked persistence, and profile-selected chat.message guidance. Tool argument schemas come from schemas.ts; branch-aware validation from input-validation.ts; the authorization guard and message lookups from authorization.ts; staged transactions and committed recovery from recovery.ts.
6
- // DEPENDS: [@opencode-ai/plugin, src/lib/agent-tool-contract.ts, src/lib/config-layers.ts, src/lib/orchestration.ts, src/lib/plugin-toggle-config.ts, src/plugins/workflow/authorization.ts, src/plugins/workflow/checkpoint-io.ts, src/plugins/workflow/checkpoints.ts, src/plugins/workflow/delegated.ts, src/plugins/workflow/input-validation.ts, src/plugins/workflow/persistence.ts, src/plugins/workflow/protocol.ts, src/plugins/workflow/recovery.ts, src/plugins/workflow/repair.ts, src/plugins/workflow/results.ts, src/plugins/workflow/schemas.ts, src/plugins/workflow/state.ts, src/plugins/workflow/tooling.ts, src/plugins/workflow/transitions.ts, src/plugins/v2-runtime/index.ts]
7
- // LINKS: M-PLUGIN-WORKFLOW, M-ORCHESTRATION-PROFILES, M-WORKFLOW-PROTOCOL, M-WORKFLOW-REPAIR, M-WORKFLOW-STATE, M-WORKFLOW-TRANSITIONS, M-WORKFLOW-TOOLING, M-WORKFLOW-PERSISTENCE, M-WORKFLOW-DELEGATED, M-AGENT-TOOL-CONTRACT, V-M-PLUGIN-WORKFLOW
4
+ // PURPOSE: Register the five workflow tools as native OpenCode 2.0.18 tools and enforce tracked launch/result/continuation/cancellation semantics through native tool and session hooks while injecting only startup-profile-compatible vv-controller guidance.
5
+ // SCOPE: Native Plugin.define entry, work_item_open/list/close registration, profile-independent work_item_decide and work_checkpoint registration with root-session authorization and native session-backed authorization-message lookup, native tool input-schema publication plus early execute.before structural guards, tracked native subagent launch validation with delegated barriers and overlapping-write gates, authoritative native sealed-run rejection, live host-call bindings that convert supported foreground subagent launches into failed delegated attempts on confirmed host-terminal errors, native structured subagent result normalization with bounded same-child continuation, background terminal settlement from the native subagent synthetic delivery, callID-bound delegated attempt results, terminal settlement of protocol-invalid reports as report_rejected attempts through staged persistence, checkpoint reviewer bookkeeping, round aggregation, implementation round limits, checked persistence, and profile-selected session-context guidance. Tool argument schemas come from schemas.ts; branch-aware validation from input-validation.ts; the authorization guard and message lookups from authorization.ts; staged transactions and committed recovery from recovery.ts; native host shape decoding from host.ts; native cancellation evidence from cancellation.ts.
6
+ // DEPENDS: [@opencode/plugin, zod (schemas), src/lib/agent-tool-contract.ts, src/lib/config-layers.ts, src/lib/orchestration.ts, src/lib/plugin-toggle-config.ts, src/plugins/workflow/authorization.ts, src/plugins/workflow/cancellation.ts, src/plugins/workflow/checkpoint-io.ts, src/plugins/workflow/checkpoints.ts, src/plugins/workflow/delegated.ts, src/plugins/workflow/host.ts, src/plugins/workflow/input-validation.ts, src/plugins/workflow/persistence.ts, src/plugins/workflow/protocol.ts, src/plugins/workflow/recovery.ts, src/plugins/workflow/repair.ts, src/plugins/workflow/results.ts, src/plugins/workflow/schemas.ts, src/plugins/workflow/state.ts, src/plugins/workflow/tooling.ts, src/plugins/workflow/transitions.ts]
7
+ // LINKS: M-PLUGIN-WORKFLOW, M-ORCHESTRATION-PROFILES, M-WORKFLOW-PROTOCOL, M-WORKFLOW-REPAIR, M-WORKFLOW-STATE, M-WORKFLOW-TRANSITIONS, M-WORKFLOW-TOOLING, M-WORKFLOW-PERSISTENCE, M-WORKFLOW-DELEGATED, M-WORKFLOW-AUTHORITY, M-AGENT-TOOL-CONTRACT, V-M-PLUGIN-WORKFLOW
8
8
  // ROLE: RUNTIME
9
9
  // MAP_MODE: EXPORTS
10
10
  // END_MODULE_CONTRACT
11
11
  //
12
12
  // START_MODULE_MAP
13
- // WorkflowPlugin - Registers workflow work-item tools, profile-independent control tools whose execution remains root-session gated, owned tool.definition/execute.before contract hooks, tracked task protocol enforcement with callID-bound delegated attempts, bounded recovery with durable persist-and-rollback commits, terminal report-rejection settlement, checkpoint linkage, live host-call failure bindings, and primary-session workflow guidance injection.
14
- // default - Dual subpath entrypoint: v2 setup() seam plus v1 server() delegating to the named factory.
13
+ // WorkflowClient - Narrow authenticated full-client surface consumed by the plugin.
14
+ // WorkflowRuntime - Narrow shared native runtime surface (snapshots/config/client/release).
15
+ // WorkflowPluginOptions - Optional injectable runtime acquisition for tests.
16
+ // createWorkflowPlugin - Plugin factory; the default export acquires the real native runtime.
17
+ // WorkflowPlugin - Native Plugin.define object registering workflow work-item tools, profile-independent root-gated control tools, owned input-schema publication and execute.before guards, tracked native subagent protocol enforcement with callID-bound delegated attempts, bounded recovery with durable persist-and-rollback commits, terminal report-rejection settlement, checkpoint linkage, background completion settlement, evidence-gated explicit cancellation recovery, and primary-session workflow guidance injection.
18
+ // default - Default export: the native WorkflowPlugin object.
15
19
  // END_MODULE_MAP
16
20
  //
17
21
  // START_CHANGE_SUMMARY
18
- // LAST_CHANGE: [C-OPENCODE-V2-MIGRATION T-001 - Added the dual subpath entrypoint so the plugin loads under OpenCode v1 via server() and v2 via setup(). Prior: C-AGENT-TOOL-CONTRACTS T-007 - Appended one shared tracked result-protocol instruction, generated from protocol.ts status vocabularies, to the review-only/selective/delegated guidance so common launch/result rules and the on-demand reference path are available without the native execution skill; the profile-specific ownership text and the tracked system instruction are otherwise unchanged. Prior T-004: removed the redundant registration spread and made the native launch hook reject an authoritatively sealed plan run.]
22
+ // LAST_CHANGE: [C-OPENCODE-V2-NATIVE wi-7 attempt 2 - Tracked/delegated/reviewer launches are staged, persisted, then published so a failed write refuses before native execution and leaves attempt/budget/reviewer state intact; the event pump contains per-event handler failures with bounded diagnostics; a rejected lazy client acquisition is retried instead of cached forever; foreground bounded-continuation acquisition/repair failures are contained locally so the original-output report_rejected path settles instead of leaving the attempt in_flight.]
19
23
  // END_CHANGE_SUMMARY
20
- import { tool } from "@opencode-ai/plugin";
24
+ import { Plugin } from "@opencode/plugin";
25
+ import { z } from "zod";
21
26
  import { attemptTrackedResultRepair, detectExplicitHardStopStatus, isTrackedResultRepairEligible, unwrapResumableTaskResult, } from "./repair.js";
22
27
  import { describeStatusVocabulary, parseResultBlock, parseWorkItemHeader, TRACKED_SUBAGENT_NAMES, } from "./protocol.js";
23
- import { applyTrackedResult, createRecordLookupKey, createWorkflowResultExcerpt, beginTrackedLaunch, createWorkItemStore, getReviewRound, getWorkItem, revertReviewerLaunch, } from "./state.js";
24
- import { applyDelegatedLaunchFailure, applyDelegatedReportRejection, applyDelegatedResult, beginDelegatedLaunch, revertInFlightDelegatedLaunches, summarizeDelegatedProgress, } from "./delegated.js";
28
+ import { applyTrackedResult, createRecordLookupKey, createWorkflowResultExcerpt, beginTrackedLaunch, createWorkItemStore, createWorkItemStoreView, getReviewRound, getWorkItem, revertReviewerLaunch, } from "./state.js";
29
+ import { runWorkflowTransaction, WorkflowTransactionQueue, } from "./transactions.js";
30
+ import { applyDelegatedLaunchFailure, applyDelegatedReportRejection, applyDelegatedResult, beginDelegatedLaunch, summarizeDelegatedProgress, } from "./delegated.js";
25
31
  import { checkpointBarrierUnsatisfied, findOverlappingInFlightReview, recordCheckpointReviewerLaunch, recordCheckpointReviewerResult, } from "./checkpoints.js";
26
32
  import { getAllowedNextAgents, getAttemptedImplementationRound, getReviewerRoleForAgent, shouldBlockRound, } from "./transitions.js";
27
33
  import { createWorkItemCloseTool, createWorkItemDecideTool, createWorkItemListTool, createWorkItemOpenTool, createWorkCheckpointTool, } from "./tooling.js";
28
- import { workCheckpointArgs, workItemCloseArgs, workItemDecideArgs, workItemListArgs, workItemOpenArgs, } from "./schemas.js";
29
34
  import { isWorkflowToolId, validateWorkflowToolInput, workflowToolContracts, } from "./input-validation.js";
30
- import { ContractInputError, createToolDefinitionAdapter } from "../../lib/agent-tool-contract.js";
31
- import { serializeWorkflowResult, workflowInputFailure } from "./results.js";
35
+ import { ContractInputError } from "../../lib/agent-tool-contract.js";
36
+ import { normalizeWorkflowFailure, serializeWorkflowResult, workflowInputFailure, WorkflowDiagnosticError, } from "./results.js";
32
37
  import { deriveDelegatedGuidance } from "./inspection.js";
33
38
  import { assertWorkflowToolAccess, createWorkflowAuthorization, shouldInjectForAgent, } from "./authorization.js";
34
39
  import { createRecoverySupport } from "./recovery.js";
40
+ import { acquireNativeSnapshotRuntime, } from "../../runtime/context.js";
41
+ import { createConsoleDiagnosticSink, decodeNativeSubagentResult, evaluateFreshExclusiveLaunch, parseSubagentCompletionElement, readNativeSubagentInput, readSubagentAgent, readSubagentPrompt, } from "./host.js";
42
+ import { evaluateCancellationEvidence, isAbortedStructuredError, parseSubagentToolFailure, } from "./cancellation.js";
35
43
  import workflowSystemInstructionTemplate from "./system-instruction.md?raw";
36
- import { loadVvocConfig } from "../../lib/config-layers.js";
37
44
  import { resolveOrchestrationPolicy, } from "../../lib/orchestration.js";
38
45
  import { isVvocPluginEnabled } from "../../lib/plugin-toggle-config.js";
39
46
  import { deleteWorkflowSessionDir, hydrateWorkflowStateChecked, snapshotWorkflowStateChecked, } from "./persistence.js";
@@ -89,6 +96,9 @@ timing, never wording — or a recorded advance authority referenced by runId an
89
96
  finite shared reserve still has a unit. Recovery never accepts a result, replaces a reviewer, or
90
97
  changes declared scope. A rejected report (a worker execution that finished with a protocol-invalid
91
98
  result) is recorded with bounded diagnostics and has the same recovery path; it never becomes DONE.
99
+ A worker cancelled by the host stays in-flight across a restart; recovery requires authoritative
100
+ native cancellation evidence (parent tool-call cancellation, the child's terminal abort, and child
101
+ quiescence) and settles the attempt and the recovery together.
92
102
 
93
103
  Requirements may come from the supported approved native spec/plan package under .vvoc/specs/, a
94
104
  provided plan reference, or the current conversation. Register a native package once with
@@ -136,67 +146,10 @@ function getWorkflowSystemInstruction(policy) {
136
146
  function isTrackedSubagent(value) {
137
147
  return typeof value === "string" && TRACKED_SUBAGENT_SET.has(value);
138
148
  }
139
- function readTaskSubagentType(args) {
140
- if (!args || typeof args !== "object") {
141
- return undefined;
142
- }
143
- const value = args.subagent_type;
144
- if (typeof value !== "string") {
145
- return undefined;
146
- }
147
- const normalized = value.trim();
148
- return normalized || undefined;
149
- }
150
- function readTaskPrompt(args) {
151
- if (!args || typeof args !== "object") {
152
- return "";
153
- }
154
- const value = args.prompt;
155
- if (typeof value !== "string") {
156
- return "";
157
- }
158
- return value;
159
- }
160
149
  function delegatedLaunchBindingKey(sessionId, callId) {
161
150
  return `${sessionId}::${callId}`;
162
151
  }
163
- /**
164
- * Read the launch-critical task arguments that decide fresh-exclusive
165
- * eligibility. Background, resume, and command/subtask launches are excluded;
166
- * contradictory non-boolean or non-string values also fail closed.
167
- */
168
- function readDelegatedLaunchEligibility(args) {
169
- if (!args || typeof args !== "object") {
170
- return { eligible: false, reason: "missing_launch_args" };
171
- }
172
- const record = args;
173
- if ("background" in record && record.background !== false) {
174
- return { eligible: false, reason: "requested_background" };
175
- }
176
- if ("task_id" in record && record.task_id !== undefined) {
177
- const taskId = record.task_id;
178
- if (typeof taskId !== "string" || taskId.trim() === "") {
179
- return { eligible: false, reason: "invalid_task_id" };
180
- }
181
- return { eligible: false, reason: "resume_task_id", resumedTaskId: taskId.trim() };
182
- }
183
- // The host subtask path always supplies a `command` key (even when its value
184
- // is undefined), and a slash-command launch always supplies a value, so key
185
- // presence alone is the reliable command/subtask exclusion.
186
- if ("command" in record) {
187
- const command = record.command;
188
- if (command !== undefined && command !== null && typeof command !== "string") {
189
- return { eligible: false, reason: "invalid_command" };
190
- }
191
- return { eligible: false, reason: "command_or_subtask_launch" };
192
- }
193
- return { eligible: true };
194
- }
195
- /** Exact current-host wrapper that precedes a returned child task error. */
196
- function delegatedHostFailurePrefix(childSessionId) {
197
- return `Subagent failed (task_id: ${childSessionId}): `;
198
- }
199
- // END_BLOCK_DELEGATED_FAILURE_BINDING_TYPES
152
+ // END_BLOCK_LAUNCH_MUTATION_TYPES
200
153
  function appendSystemInstruction(existingSystem, instruction) {
201
154
  if (!existingSystem?.trim()) {
202
155
  return instruction;
@@ -274,19 +227,109 @@ function createHardStopMessage(options) {
274
227
  "Inspect work_item_list before retrying.",
275
228
  ].join("\n");
276
229
  }
277
- export const WorkflowPlugin = async ({ client, directory, worktree }) => {
278
- const vvoc = await loadVvocConfig({ cwd: directory });
279
- if (!isVvocPluginEnabled(vvoc.config, "workflow"))
280
- return {};
281
- const resolvedPolicy = resolveOrchestrationPolicy(vvoc.config);
282
- const workflowSystemInstruction = getWorkflowSystemInstruction(resolvedPolicy);
283
- const trustedWorkspaceRoot = worktree || directory;
230
+ function isRecord(value) {
231
+ return typeof value === "object" && value !== null && !Array.isArray(value);
232
+ }
233
+ function schemaFor(toolId) {
234
+ const contract = workflowToolContracts.find((candidate) => candidate.toolId === toolId);
235
+ if (!contract)
236
+ throw new Error(`missing workflow tool contract ${toolId}`);
237
+ return contract.runtimeSchema;
238
+ }
239
+ // START_BLOCK_NATIVE_TOOL_RESULT
240
+ /** Convert a serialized workflow string into a native Tool.Result. */
241
+ function nativeToolResult(output) {
242
+ return { output, content: output };
243
+ }
244
+ /** Native workflow plugin factory; the default export uses the real runtime. */
245
+ export function createWorkflowPlugin(options = {}) {
246
+ return Plugin.define({
247
+ id: "vvoc.workflow",
248
+ setup: (ctx) => setupWorkflow(ctx, options),
249
+ });
250
+ }
251
+ async function setupWorkflow(ctx, options) {
252
+ const acquire = options.acquireRuntime ??
253
+ (async (c) => (await acquireNativeSnapshotRuntime(c)));
254
+ const runtime = await acquire(ctx);
255
+ // The authenticated full client is acquired LAZILY: authenticating it during
256
+ // plugin setup can deadlock host activation, so only a real lookup triggers it.
257
+ // A rejected acquisition is NOT cached forever: the share is reset so a later
258
+ // lookup can authenticate again instead of permanently poisoning all callers.
259
+ let clientPromise;
260
+ const getClient = () => {
261
+ if (clientPromise === undefined) {
262
+ const pending = runtime.client();
263
+ clientPromise = pending;
264
+ void pending.catch(() => {
265
+ if (clientPromise === pending)
266
+ clientPromise = undefined;
267
+ });
268
+ }
269
+ return clientPromise;
270
+ };
271
+ const directory = ctx.location.directory;
272
+ const trustedWorkspaceRoot = ctx.location.project?.directory ?? directory;
273
+ // Registration is STABLE and independent of startup config. Execution,
274
+ // visibility and guidance are gated per bound family below. Setup never
275
+ // grants execution authority from the startup/current config.
276
+ const WORKFLOW_TOOL_NAMES = workflowToolContracts.map((contract) => contract.toolId);
277
+ async function resolveFamilyPolicy(sessionId) {
278
+ let capture;
279
+ try {
280
+ capture = await runtime.snapshots.configFor(sessionId);
281
+ }
282
+ catch {
283
+ return undefined;
284
+ }
285
+ if (capture === undefined) {
286
+ // A first accepted workload may be persisted but not yet published;
287
+ // reconcile through the native acceptance service, then read again.
288
+ try {
289
+ await runtime.snapshots.accept({ sessionID: sessionId });
290
+ }
291
+ catch {
292
+ // fall through to the second read; absence fails closed below
293
+ }
294
+ try {
295
+ capture = await runtime.snapshots.configFor(sessionId);
296
+ }
297
+ catch {
298
+ return undefined;
299
+ }
300
+ }
301
+ if (capture === undefined)
302
+ return undefined;
303
+ return {
304
+ policy: resolveOrchestrationPolicy(capture.vvoc),
305
+ enabled: isVvocPluginEnabled(capture.vvoc, "workflow"),
306
+ };
307
+ }
308
+ async function requireFamilyEnabled(sessionId) {
309
+ const family = await resolveFamilyPolicy(sessionId);
310
+ if (family === undefined) {
311
+ throw new WorkflowDiagnosticError("FAMILY_UNBOUND", "authorization", `FAMILY_UNBOUND: no immutable policy capture is bound to session ${sessionId}; workflow tools fail closed until a family is bound.`);
312
+ }
313
+ if (!family.enabled) {
314
+ throw new WorkflowDiagnosticError("FAMILY_DISABLED", "authorization", `FAMILY_DISABLED: the workflow plugin is disabled for the policy bound to session ${sessionId}.`);
315
+ }
316
+ return family.policy;
317
+ }
318
+ const diagnostics = createConsoleDiagnosticSink({
319
+ namespace: "workflow",
320
+ });
321
+ // Serializes launch-state mutations with the same staged persist-then-publish
322
+ // boundary used by recovery: a launch never advances live attempt/budget/
323
+ // reviewer state without a durable snapshot of that transition.
324
+ const workflowTransactions = new WorkflowTransactionQueue();
284
325
  // START_BLOCK_PERSISTENCE_SETUP
285
326
  // Each session (main or subagent) gets its own isolated store.
286
327
  // This prevents subagent tool calls from interfering with the main session's work items.
287
328
  // Hydration uses the checked loader: invalid persisted state is tracked so new
288
329
  // control transactions and snapshot writes fail closed instead of silently
289
- // resetting a malformed run.
330
+ // resetting a malformed run. A restart boundary does NOT refund in-flight
331
+ // attempts or consumed budget: a cancelled worker's attempt stays in-flight
332
+ // until explicit, evidence-backed recovery settles it.
290
333
  const stores = new Map();
291
334
  const invalidHydrationSessions = new Set();
292
335
  function getOrCreateStore(sessionId) {
@@ -295,22 +338,6 @@ export const WorkflowPlugin = async ({ client, directory, worktree }) => {
295
338
  const hydrated = hydrateWorkflowStateChecked(sessionId);
296
339
  if (hydrated.status === "valid") {
297
340
  store = createWorkItemStore(hydrated.data);
298
- // A freshly hydrated session crossed a process-restart boundary: any
299
- // persisted in-flight delegated attempt can never receive its host
300
- // callback again, so reclaim it without consuming the attempt budget.
301
- const reclaimed = revertInFlightDelegatedLaunches(store.getStoreData(), sessionId);
302
- if (reclaimed.reverted > 0) {
303
- void client.app
304
- .log({
305
- body: {
306
- service: "workflow",
307
- level: "info",
308
- message: "[workflow][hydration][BLOCK_RECLAIM_ATTEMPTS] orphaned in-flight delegated attempts reverted",
309
- extra: { sessionID: sessionId, workItemIds: reclaimed.workItemIds },
310
- },
311
- })
312
- .catch(() => undefined);
313
- }
314
341
  }
315
342
  else {
316
343
  if (hydrated.status === "invalid") {
@@ -338,9 +365,9 @@ export const WorkflowPlugin = async ({ client, directory, worktree }) => {
338
365
  // END_BLOCK_PERSISTENCE_SETUP
339
366
  // START_BLOCK_DELEGATED_FAILURE_BINDING
340
367
  // Live host-call bindings let the plugin consume confirmed host-terminal
341
- // failures of foreground vv-implementer tasks without hydrating a store from
342
- // an event. Every exclusion is sticky: once a binding is tainted it can never
343
- // authorize a failure transition.
368
+ // failures of foreground subagent launches without hydrating a store from
369
+ // an event. Every exclusion is sticky: once a binding is tainted it can
370
+ // never authorize a failure transition.
344
371
  const delegatedLaunchBindings = new Map();
345
372
  const resumedChildSessions = new Set();
346
373
  const childPromptMessageIds = new Map();
@@ -356,6 +383,13 @@ export const WorkflowPlugin = async ({ client, directory, worktree }) => {
356
383
  taintDelegatedLaunchBinding(binding, reason);
357
384
  }
358
385
  }
386
+ function findBindingByChild(childSessionId) {
387
+ for (const binding of delegatedLaunchBindings.values()) {
388
+ if (binding.childSessionId === childSessionId)
389
+ return binding;
390
+ }
391
+ return undefined;
392
+ }
359
393
  /**
360
394
  * Track distinct user-prompt message ids per session: a child session
361
395
  * prompted with more than one distinct message is shared or resumed, so it
@@ -377,25 +411,19 @@ export const WorkflowPlugin = async ({ client, directory, worktree }) => {
377
411
  taintBindingsForChild(sessionId, "child_reprompted");
378
412
  }
379
413
  }
380
- function observeTaskLaunchArgs(args) {
381
- const launch = readDelegatedLaunchEligibility(args);
382
- if (!launch.resumedTaskId)
414
+ function observeSubagentLaunchInput(input) {
415
+ const parsed = readNativeSubagentInput(input);
416
+ if (!parsed?.sessionID)
383
417
  return;
384
- resumedChildSessions.add(launch.resumedTaskId);
385
- taintBindingsForChild(launch.resumedTaskId, "child_resumed");
386
- }
387
- function observeAfterHookEntry(sessionId, callId) {
388
- const binding = delegatedLaunchBindings.get(delegatedLaunchBindingKey(sessionId, callId));
389
- if (binding) {
390
- binding.afterHookEntered = true;
391
- }
418
+ resumedChildSessions.add(parsed.sessionID);
419
+ taintBindingsForChild(parsed.sessionID, "child_resumed");
392
420
  }
393
- function observeAfterHookMetadata(sessionId, callId, metadata) {
421
+ /** Observe native result metadata for the bound child/background identity. */
422
+ function observeAfterMetadata(sessionId, callId, metadata) {
394
423
  const binding = delegatedLaunchBindings.get(delegatedLaunchBindingKey(sessionId, callId));
395
- if (!binding || !metadata || typeof metadata !== "object")
424
+ if (!binding || !isRecord(metadata))
396
425
  return;
397
- const record = metadata;
398
- const child = record.sessionId;
426
+ const child = metadata.sessionID;
399
427
  if (typeof child === "string" && child.trim() !== "") {
400
428
  if (binding.childSessionId === undefined) {
401
429
  binding.childSessionId = child;
@@ -404,13 +432,6 @@ export const WorkflowPlugin = async ({ client, directory, worktree }) => {
404
432
  taintDelegatedLaunchBinding(binding, "metadata_child_replaced");
405
433
  }
406
434
  }
407
- if (record.background === true)
408
- taintDelegatedLaunchBinding(binding, "metadata_background");
409
- if (typeof record.jobId === "string" && record.jobId !== "") {
410
- taintDelegatedLaunchBinding(binding, "metadata_job");
411
- }
412
- if (record.interrupted === true)
413
- taintDelegatedLaunchBinding(binding, "metadata_interrupted");
414
435
  }
415
436
  /**
416
437
  * Stage the failed-attempt transition, persist a checked snapshot of the
@@ -418,7 +439,7 @@ export const WorkflowPlugin = async ({ client, directory, worktree }) => {
418
439
  * between the final identity/exclusion check and the commit; a checked write
419
440
  * failure leaves the live in-flight attempt (and retry block) intact.
420
441
  */
421
- function commitDelegatedLaunchFailure(sessionId, binding, failureExcerpt) {
442
+ function commitDelegatedLaunchFailure(sessionId, binding, failureExcerpt, completedAt) {
422
443
  const liveStore = stores.get(sessionId);
423
444
  if (!liveStore || invalidHydrationSessions.has(sessionId))
424
445
  return;
@@ -429,32 +450,25 @@ export const WorkflowPlugin = async ({ client, directory, worktree }) => {
429
450
  workItemId: binding.workItemId,
430
451
  callId: binding.callId,
431
452
  failureExcerpt,
453
+ ...(completedAt === undefined ? {} : { completedAt }),
432
454
  });
433
455
  if (!applied.ok) {
434
- // Stale, duplicate, or already-transitioned: settle without mutation.
435
456
  binding.settled = true;
436
457
  return;
437
458
  }
438
459
  const stagedData = stagedStore.getStoreData();
439
460
  const persisted = snapshotWorkflowStateChecked(sessionId, stagedData);
440
461
  if (!persisted.ok) {
441
- // Keep the live in-flight attempt and evidence so an unpersisted retry
442
- // is never authorized; a later authoritative event can retry safely.
443
- void client.app
444
- .log({
445
- body: {
446
- service: "workflow",
447
- level: "error",
448
- message: "[workflow][delegatedFailure][BLOCK_DELEGATED_FAILURE] persistence failed",
449
- extra: {
450
- sessionID: sessionId,
451
- workItemId: binding.workItemId,
452
- attempt: binding.attempt,
453
- error: persisted.error.slice(0, 300),
454
- },
462
+ diagnostics.log({
463
+ level: "error",
464
+ message: "[workflow][delegatedFailure][BLOCK_DELEGATED_FAILURE] persistence failed",
465
+ extra: {
466
+ sessionID: sessionId,
467
+ workItemId: binding.workItemId,
468
+ attempt: binding.attempt,
469
+ error: persisted.error.slice(0, 300),
455
470
  },
456
- })
457
- .catch(() => undefined);
471
+ });
458
472
  return;
459
473
  }
460
474
  const lookupKey = createRecordLookupKey(sessionId, binding.workItemId);
@@ -463,23 +477,18 @@ export const WorkflowPlugin = async ({ client, directory, worktree }) => {
463
477
  return;
464
478
  liveData.records.set(lookupKey, committed);
465
479
  binding.settled = true;
466
- void client.app
467
- .log({
468
- body: {
469
- service: "workflow",
470
- level: "warn",
471
- message: "[workflow][delegatedFailure][BLOCK_DELEGATED_FAILURE] host-terminal launch failure recorded",
472
- extra: {
473
- sessionID: sessionId,
474
- workItemId: binding.workItemId,
475
- attempt: applied.attempt,
476
- consumedAttempts: applied.consumedAttempts,
477
- attemptBudget: applied.attemptBudget,
478
- retryAllowed: applied.retryAllowed,
479
- },
480
+ diagnostics.log({
481
+ level: "warn",
482
+ message: "[workflow][delegatedFailure][BLOCK_DELEGATED_FAILURE] host-terminal launch failure recorded",
483
+ extra: {
484
+ sessionID: sessionId,
485
+ workItemId: binding.workItemId,
486
+ attempt: applied.attempt,
487
+ consumedAttempts: applied.consumedAttempts,
488
+ attemptBudget: applied.attemptBudget,
489
+ retryAllowed: applied.retryAllowed,
480
490
  },
481
- })
482
- .catch(() => undefined);
491
+ });
483
492
  }
484
493
  /**
485
494
  * Settle a confirmed terminal protocol-invalid delegated report: the domain
@@ -503,27 +512,21 @@ export const WorkflowPlugin = async ({ client, directory, worktree }) => {
503
512
  ...(explicitHardStop ? { explicitHardStop } : {}),
504
513
  });
505
514
  if (!applied.ok) {
506
- // Stale, duplicate, or already-transitioned: nothing to settle.
507
515
  return undefined;
508
516
  }
509
517
  const stagedData = stagedStore.getStoreData();
510
518
  const persisted = snapshotWorkflowStateChecked(sessionId, stagedData);
511
519
  if (!persisted.ok) {
512
- void client.app
513
- .log({
514
- body: {
515
- service: "workflow",
516
- level: "error",
517
- message: "[workflow][reportRejection][BLOCK_REPORT_REJECTION] persistence failed",
518
- extra: {
519
- sessionID: sessionId,
520
- workItemId,
521
- attempt: applied.attempt,
522
- error: persisted.error.slice(0, 300),
523
- },
520
+ diagnostics.log({
521
+ level: "error",
522
+ message: "[workflow][reportRejection][BLOCK_REPORT_REJECTION] persistence failed",
523
+ extra: {
524
+ sessionID: sessionId,
525
+ workItemId,
526
+ attempt: applied.attempt,
527
+ error: persisted.error.slice(0, 300),
524
528
  },
525
- })
526
- .catch(() => undefined);
529
+ });
527
530
  return undefined;
528
531
  }
529
532
  const lookupKey = createRecordLookupKey(sessionId, workItemId);
@@ -531,122 +534,70 @@ export const WorkflowPlugin = async ({ client, directory, worktree }) => {
531
534
  if (!committed)
532
535
  return undefined;
533
536
  liveData.records.set(lookupKey, committed);
534
- void client.app
535
- .log({
536
- body: {
537
- service: "workflow",
538
- level: "warn",
539
- message: "[workflow][reportRejection][BLOCK_REPORT_REJECTION] terminal report rejected and settled",
540
- extra: {
541
- sessionID: sessionId,
542
- workItemId,
543
- attempt: applied.attempt,
544
- protocolErrorCode,
545
- observedHardStop: explicitHardStop,
546
- consumedAttempts: applied.consumedAttempts,
547
- attemptBudget: applied.attemptBudget,
548
- },
537
+ diagnostics.log({
538
+ level: "warn",
539
+ message: "[workflow][reportRejection][BLOCK_REPORT_REJECTION] terminal report rejected and settled",
540
+ extra: {
541
+ sessionID: sessionId,
542
+ workItemId,
543
+ attempt: applied.attempt,
544
+ protocolErrorCode,
545
+ observedHardStop: explicitHardStop,
546
+ consumedAttempts: applied.consumedAttempts,
547
+ attemptBudget: applied.attemptBudget,
549
548
  },
550
- })
551
- .catch(() => undefined);
549
+ });
552
550
  return applied.attempt;
553
551
  }
554
- function handleDelegatedPartUpdated(properties) {
555
- const part = properties.part;
556
- if (!part || typeof part !== "object")
557
- return;
558
- if (part.type !== "tool" || part.tool !== "task")
559
- return;
560
- const parentSessionId = typeof part.sessionID === "string" ? part.sessionID : undefined;
561
- const callId = typeof part.callID === "string" ? part.callID : undefined;
562
- if (!parentSessionId || !callId)
563
- return;
564
- const binding = delegatedLaunchBindings.get(delegatedLaunchBindingKey(parentSessionId, callId));
552
+ /** Settle one confirmed host-terminal failure from a native tool error. */
553
+ function handleSubagentToolTermination(sessionId, callId, failure, detail) {
554
+ const binding = delegatedLaunchBindings.get(delegatedLaunchBindingKey(sessionId, callId));
565
555
  if (!binding)
566
556
  return;
567
- const state = part.state;
568
- if (!state || typeof state !== "object")
557
+ // Only a confirmed host-terminal 'failed' termination consumes the attempt
558
+ // immediately. A cancelled/interrupted tool call stays in-flight and is
559
+ // settled only by explicit, evidence-backed cancellation recovery.
560
+ if (failure.kind !== "failed")
569
561
  return;
570
- const isError = state.status === "error";
571
- const metadata = state.metadata && typeof state.metadata === "object"
572
- ? state.metadata
573
- : undefined;
574
- if (!metadata) {
575
- // A non-error part may simply not carry metadata yet; an error without
576
- // metadata can never be bound and is latched blocked to stay fail-closed.
577
- if (isError)
578
- taintDelegatedLaunchBinding(binding, "metadata_missing_on_error");
579
- return;
580
- }
581
- const metaParent = metadata.parentSessionId;
582
- const metaChild = metadata.sessionId;
583
- if (metaParent !== parentSessionId) {
584
- taintDelegatedLaunchBinding(binding, "metadata_parent_mismatch");
562
+ if (binding.background)
585
563
  return;
586
- }
587
- if (typeof metaChild !== "string" || metaChild.trim() === "") {
588
- taintDelegatedLaunchBinding(binding, "metadata_child_missing");
564
+ if (binding.afterHookEntered || !binding.eligible || binding.settled)
589
565
  return;
590
- }
591
566
  if (binding.childSessionId === undefined) {
592
- binding.childSessionId = metaChild;
567
+ binding.childSessionId = failure.childSessionId;
593
568
  }
594
- else if (binding.childSessionId !== metaChild) {
569
+ else if (binding.childSessionId !== failure.childSessionId) {
595
570
  taintDelegatedLaunchBinding(binding, "metadata_child_replaced");
596
571
  return;
597
572
  }
598
- if (metadata.background === true) {
599
- taintDelegatedLaunchBinding(binding, "metadata_background");
600
- return;
601
- }
602
- if (typeof metadata.jobId === "string" && metadata.jobId !== "") {
603
- taintDelegatedLaunchBinding(binding, "metadata_job");
604
- return;
605
- }
606
- if (metadata.interrupted === true) {
607
- taintDelegatedLaunchBinding(binding, "metadata_interrupted");
608
- return;
609
- }
610
- if (resumedChildSessions.has(metaChild)) {
573
+ if (resumedChildSessions.has(failure.childSessionId)) {
611
574
  taintDelegatedLaunchBinding(binding, "child_resumed");
612
575
  return;
613
576
  }
614
- if (binding.afterHookEntered || !binding.eligible || binding.settled)
615
- return;
616
- if (!isError)
617
- return;
618
- const error = state.error;
619
- if (typeof error !== "string")
620
- return;
621
- if (!error.startsWith(delegatedHostFailurePrefix(metaChild)))
622
- return;
623
577
  const failureExcerpt = createWorkflowResultExcerpt({
624
- text: error,
578
+ text: detail,
625
579
  source: "normalized_output",
626
580
  });
627
581
  if (!failureExcerpt)
628
582
  return;
629
- if (!stores.has(parentSessionId) || invalidHydrationSessions.has(parentSessionId))
583
+ if (!stores.has(sessionId) || invalidHydrationSessions.has(sessionId))
630
584
  return;
631
- commitDelegatedLaunchFailure(parentSessionId, binding, failureExcerpt);
585
+ commitDelegatedLaunchFailure(sessionId, binding, failureExcerpt);
632
586
  }
633
587
  // END_BLOCK_DELEGATED_FAILURE_BINDING
634
588
  // START_BLOCK_DELEGATED_AUTHORIZATION
635
589
  // New control mutations require the primary vv-controller session; the
636
- // guard, its root-session identity check, and the SDK-backed message
637
- // lookups live in authorization.js over this explicit plugin context.
590
+ // guard, its root/fork identity check, and the native session-backed
591
+ // message lookups live in authorization.js over this explicit plugin context.
638
592
  const { assertPrimaryControllerMutation, lookupRecoveryUserMessage, lookupAuthorityMessage } = createWorkflowAuthorization({
639
- client,
593
+ getClient,
640
594
  directory,
641
- worktree,
642
595
  trustedWorkspaceRoot,
643
596
  invalidHydrationSessions,
644
597
  });
645
598
  // END_BLOCK_DELEGATED_AUTHORIZATION
646
599
  // START_BLOCK_RECOVERY_SUPPORT
647
- // Staged generic transactions and durably committed recovery with rollback
648
- // live in recovery.js over this explicit persistence seam.
649
- const { commitGenericToolResult, executeCommittedRecovery, captureRecordRestore, captureCheckpointRestore, } = createRecoverySupport({ client, stores, invalidHydrationSessions });
600
+ const { commitGenericToolResult, executeCommittedRecovery, captureRecordRestore, captureCheckpointRestore, } = createRecoverySupport({ diagnostics, stores, invalidHydrationSessions });
650
601
  // END_BLOCK_RECOVERY_SUPPORT
651
602
  // START_BLOCK_CHECKPOINT_LINKAGE
652
603
  /** Find the in-flight checkpoint generation whose linked review item matches. */
@@ -663,870 +614,1284 @@ export const WorkflowPlugin = async ({ client, directory, worktree }) => {
663
614
  return undefined;
664
615
  }
665
616
  // END_BLOCK_CHECKPOINT_LINKAGE
666
- // START_BLOCK_PLUGIN_ENTRY
617
+ // START_BLOCK_CANCELLATION_EVIDENCE
618
+ /**
619
+ * Retrieve authoritative native cancellation evidence for an in-flight
620
+ * delegated attempt: the parent subagent tool-call termination, the actual
621
+ * child's LATEST terminal abort attributable to this launch, and full child
622
+ * quiescence (not active, empty inbox). Historical timestamps come from the
623
+ * parent assistant tool part's own `time.completed` and the child terminal
624
+ * assistant message's `time.completed`; recovery never repairs them.
625
+ */
626
+ async function gatherCancellationEvidence(sessionId, callId, knownChildSessionId) {
627
+ const finite = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
628
+ let client;
629
+ try {
630
+ client = await getClient();
631
+ }
632
+ catch {
633
+ return { ok: false, reason: "CLIENT_UNAVAILABLE" };
634
+ }
635
+ let parentMessages;
636
+ try {
637
+ const list = await client.message.list({
638
+ sessionID: sessionId,
639
+ order: "desc",
640
+ limit: 50,
641
+ type: "assistant",
642
+ });
643
+ parentMessages = isRecord(list) && Array.isArray(list.data) ? list.data : [];
644
+ }
645
+ catch {
646
+ return { ok: false, reason: "PARENT_LOOKUP_FAILED" };
647
+ }
648
+ let parentFailure;
649
+ let parentCompletedMs;
650
+ let parentCreatedMs;
651
+ let childSessionId = knownChildSessionId;
652
+ for (const message of parentMessages) {
653
+ if (!isRecord(message) || message.type !== "assistant" || !Array.isArray(message.content))
654
+ continue;
655
+ for (const part of message.content) {
656
+ if (!isRecord(part) || part.type !== "tool" || part.id !== callId)
657
+ continue;
658
+ // The tool-call name must be the native subagent tool.
659
+ if (part.name !== "subagent")
660
+ continue;
661
+ const state = part.state;
662
+ if (!isRecord(state))
663
+ continue;
664
+ const metadata = isRecord(state.metadata) ? state.metadata : undefined;
665
+ const metaChild = metadata?.sessionID;
666
+ if (typeof metaChild === "string" && metaChild !== "") {
667
+ if (childSessionId === undefined)
668
+ childSessionId = metaChild;
669
+ else if (childSessionId !== metaChild) {
670
+ return { ok: false, reason: "PARENT_CHILD_SESSION_MISMATCH" };
671
+ }
672
+ }
673
+ if (state.status !== "error")
674
+ continue;
675
+ const error = state.error;
676
+ if (!isRecord(error) || typeof error.message !== "string")
677
+ continue;
678
+ const parsed = parseSubagentToolFailure(error.message);
679
+ if (!parsed)
680
+ continue;
681
+ // Native timing lives beside `state`, on the assistant tool part.
682
+ const partTime = isRecord(part.time) ? part.time : undefined;
683
+ const completed = partTime ? finite(partTime.completed) : undefined;
684
+ if (completed === undefined || completed <= 0) {
685
+ return { ok: false, reason: "PARENT_TERMINAL_TIME_MISSING" };
686
+ }
687
+ parentFailure = parsed;
688
+ parentCompletedMs = completed;
689
+ parentCreatedMs = partTime ? finite(partTime.created) : undefined;
690
+ }
691
+ }
692
+ if (childSessionId === undefined) {
693
+ return { ok: false, reason: "MISSING_CHILD_IDENTITY" };
694
+ }
695
+ if (!parentFailure || parentCompletedMs === undefined) {
696
+ return { ok: false, reason: "NO_PARENT_CANCELLATION_EVIDENCE" };
697
+ }
698
+ if (parentFailure.childSessionId !== childSessionId) {
699
+ return { ok: false, reason: "PARENT_CHILD_SESSION_MISMATCH" };
700
+ }
701
+ // Child identity must be a real child of the parent session.
702
+ let childParentID;
703
+ try {
704
+ const childInfo = (await client.session.get({ sessionID: childSessionId }));
705
+ childParentID = childInfo.parentID;
706
+ }
707
+ catch {
708
+ return { ok: false, reason: "CHILD_LOOKUP_FAILED" };
709
+ }
710
+ if (childParentID !== sessionId) {
711
+ return { ok: false, reason: "CHILD_NOT_OF_PARENT" };
712
+ }
713
+ // Full quiescence: the child is not active and its inbox has no pending
714
+ // work. A missing/invalid native record is UNAVAILABLE evidence, not
715
+ // quiescence, so it refuses.
716
+ try {
717
+ const active = await client.session.active();
718
+ if (!isRecord(active)) {
719
+ return { ok: false, reason: "CHILD_ACTIVE_STATE_UNAVAILABLE" };
720
+ }
721
+ if (active[childSessionId] !== undefined) {
722
+ return { ok: false, reason: "CHILD_STILL_ACTIVE" };
723
+ }
724
+ const inbox = await client.session.inbox.list({ sessionID: childSessionId });
725
+ if (!Array.isArray(inbox)) {
726
+ return { ok: false, reason: "CHILD_INBOX_UNAVAILABLE" };
727
+ }
728
+ if (inbox.length > 0) {
729
+ return { ok: false, reason: "CHILD_INBOX_NOT_EMPTY" };
730
+ }
731
+ }
732
+ catch {
733
+ return { ok: false, reason: "CHILD_QUIESCENCE_LOOKUP_FAILED" };
734
+ }
735
+ let childMessages;
736
+ try {
737
+ const list = await client.message.list({
738
+ sessionID: childSessionId,
739
+ order: "desc",
740
+ limit: 10,
741
+ type: "assistant",
742
+ });
743
+ childMessages = isRecord(list) && Array.isArray(list.data) ? list.data : [];
744
+ }
745
+ catch {
746
+ return { ok: false, reason: "CHILD_LOOKUP_FAILED" };
747
+ }
748
+ // The LATEST terminal assistant must be aborted; a later success or a new
749
+ // active run is never evidence.
750
+ const latest = childMessages.find((message) => isRecord(message) && message.type === "assistant");
751
+ if (!isRecord(latest)) {
752
+ return { ok: false, reason: "NO_CHILD_TERMINAL_ABORT" };
753
+ }
754
+ const childError = isRecord(latest.error) ? latest.error : undefined;
755
+ if (childError === undefined ||
756
+ typeof childError.type !== "string" ||
757
+ typeof childError.message !== "string" ||
758
+ !isAbortedStructuredError({ type: childError.type, message: childError.message })) {
759
+ return { ok: false, reason: "CHILD_TERMINAL_NOT_ABORTED" };
760
+ }
761
+ const childTime = isRecord(latest.time) ? latest.time : undefined;
762
+ const childCompletedMs = childTime ? finite(childTime.completed) : undefined;
763
+ if (childCompletedMs === undefined || childCompletedMs <= 0) {
764
+ return { ok: false, reason: "CHILD_TERMINAL_TIME_MISSING" };
765
+ }
766
+ const childCreatedMs = childTime ? finite(childTime.created) : undefined;
767
+ if (childCreatedMs === undefined || childCreatedMs <= 0) {
768
+ return { ok: false, reason: "CHILD_TERMINAL_TIME_MISSING" };
769
+ }
770
+ if (parentCreatedMs === undefined || parentCreatedMs <= 0) {
771
+ return { ok: false, reason: "PARENT_TERMINAL_TIME_MISSING" };
772
+ }
773
+ if (childCreatedMs < parentCreatedMs) {
774
+ return { ok: false, reason: "CHILD_TERMINAL_BEFORE_LAUNCH" };
775
+ }
776
+ const decision = evaluateCancellationEvidence({
777
+ parentSessionId: sessionId,
778
+ callID: callId,
779
+ childSessionId,
780
+ parentToolFailure: parentFailure,
781
+ childTerminalError: { type: childError.type, message: childError.message },
782
+ childActive: false,
783
+ });
784
+ if (!decision.ok) {
785
+ return { ok: false, reason: decision.reason };
786
+ }
787
+ // Both exact historical timestamps are required; max of the exact values.
788
+ return {
789
+ ok: true,
790
+ childSessionId,
791
+ completedAtMs: Math.max(parentCompletedMs, childCompletedMs),
792
+ };
793
+ }
794
+ // END_BLOCK_CANCELLATION_EVIDENCE
795
+ // START_BLOCK_PLUGIN_TOOLS
667
796
  // Tool wrappers still need a store reference for description/args shape
668
- // but execute handlers resolve the right store per-call
797
+ // but execute handlers resolve the right store per-call.
669
798
  const dummyStore = createWorkItemStore();
670
799
  const workItemOpenTool = createWorkItemOpenTool(dummyStore);
671
800
  const workItemListTool = createWorkItemListTool(dummyStore);
672
801
  const workItemCloseTool = createWorkItemCloseTool(dummyStore);
673
- const workItemDecideTool = createWorkItemDecideTool(dummyStore, {
674
- lookupUserMessage: lookupRecoveryUserMessage,
675
- });
676
- const workCheckpointTool = createWorkCheckpointTool(dummyStore, {
802
+ const delegatedControlOptions = {
677
803
  lookupUserMessage: lookupRecoveryUserMessage,
678
804
  lookupAuthorityMessage,
679
- });
680
- // START_BLOCK_TOOL_CONTRACT_HOOKS
681
- // Owned-only contract publication and early structural/branch validation.
682
- // The tool.definition adapter publishes the strict input JSON Schema through
683
- // the host's observable jsonSchema member (T-001-proven seam) without
684
- // replacing the host decoder; the execute.before guard rejects invalid
685
- // raw arguments with bounded tokenized paths before any handler runs and
686
- // never touches the task-launch hooks below.
687
- const toolDefinitionAdapter = createToolDefinitionAdapter([...workflowToolContracts]);
688
- // END_BLOCK_TOOL_CONTRACT_HOOKS
689
- return {
690
- tool: {
691
- work_item_open: tool({
692
- description: workItemOpenTool.description,
693
- args: workItemOpenArgs,
694
- async execute(args, context) {
695
- assertWorkflowToolAccess(context.agent, "work_item_open");
696
- const validation = validateWorkflowToolInput("work_item_open", args);
697
- if (!validation.ok) {
698
- return stringifyToolOutput(workflowInputFailure("work_item_open", context.sessionID, validation.issues));
699
- }
700
- const isGeneric = validation.data.execution !== undefined || validation.data.runId !== undefined;
701
- if (isGeneric) {
702
- // Hydrate/validate the session store before the transaction boundary
703
- // reads it, matching every other tool entry point.
704
- getOrCreateStore(context.sessionID);
705
- const result = await commitGenericToolResult(context.sessionID, "work_item_open", (view) => workItemOpenTool.execute(args, {
706
- sessionId: context.sessionID,
707
- workspaceRoot: trustedWorkspaceRoot,
708
- }, view));
709
- return stringifyToolOutput(result, result.ok === true ? "committed" : "not_applied");
710
- }
711
- const sessionStore = getOrCreateStore(context.sessionID);
712
- const opened = workItemOpenTool.execute(args, { sessionId: context.sessionID }, sessionStore);
713
- const openedPersisted = snapshotSession(context.sessionID);
714
- return stringifyToolOutput(opened, opened.ok === false ? "not_applied" : openedPersisted.ok ? "committed" : "unknown");
715
- },
716
- }),
717
- work_item_list: tool({
718
- description: workItemListTool.description,
719
- args: workItemListArgs,
720
- async execute(args, context) {
721
- assertWorkflowToolAccess(context.agent, "work_item_list");
722
- const sessionStore = getOrCreateStore(context.sessionID);
723
- return stringifyToolOutput(workItemListTool.execute(args, { sessionId: context.sessionID }, sessionStore));
724
- },
725
- }),
726
- work_item_close: tool({
727
- description: workItemCloseTool.description,
728
- args: workItemCloseArgs,
729
- async execute(args, context) {
730
- assertWorkflowToolAccess(context.agent, "work_item_close");
731
- const sessionStore = getOrCreateStore(context.sessionID);
732
- const closed = workItemCloseTool.execute(args, { sessionId: context.sessionID }, sessionStore);
733
- const closedPersisted = snapshotSession(context.sessionID);
734
- return stringifyToolOutput(closed, closed.ok === false ? "not_applied" : closedPersisted.ok ? "committed" : "unknown");
735
- },
736
- }),
737
- // Control tools are registered independent of the startup profile; they
738
- // remain root-session, agent, workspace, and invalid-hydration gated at
739
- // execution time.
740
- work_item_decide: tool({
741
- description: workItemDecideTool.description,
742
- args: workItemDecideArgs,
743
- async execute(args, context) {
744
- // Resolve the store first so invalid persisted state is detected
745
- // before the authorization check reports it as a control denial.
746
- const sessionStore = getOrCreateStore(context.sessionID);
747
- await assertPrimaryControllerMutation(context.agent, context.sessionID, { directory: context.directory, worktree: context.worktree }, "work_item_decide");
748
- const validation = validateWorkflowToolInput("work_item_decide", args);
749
- if (!validation.ok) {
750
- return stringifyToolOutput(workflowInputFailure("work_item_decide", context.sessionID, validation.issues));
751
- }
752
- // Recovery is the only decision family that must persist
753
- // before it exposes new launch permissions. Authority-bearing
754
- // recovery stages the work-item recovery and the reserve debit in
755
- // one serialized transaction so they commit or fail together.
756
- // Routing uses the same validated/normalized values the handler consumes.
757
- const parsedDecide = validation.data;
758
- if (parsedDecide.decision === "recover") {
759
- if (parsedDecide.authorityId !== undefined) {
760
- const staged = await commitGenericToolResult(context.sessionID, "work_item_decide", (view) => workItemDecideTool.execute(args, { sessionId: context.sessionID }, view));
761
- return stringifyToolOutput(staged, staged.ok === true ? "committed" : "not_applied");
805
+ };
806
+ const workItemDecideTool = createWorkItemDecideTool(dummyStore, delegatedControlOptions);
807
+ const workCheckpointTool = createWorkCheckpointTool(dummyStore, delegatedControlOptions);
808
+ await ctx.tool.transform((editor) => {
809
+ // START_BLOCK_TOOL_CONTRACT_PUBLICATION
810
+ // The strict closed input schema is published directly to the native tool
811
+ // registry; execute.before independently re-validates raw arguments with
812
+ // bounded tokenized paths before any handler runs.
813
+ editor.add({
814
+ name: "work_item_open",
815
+ input: schemaFor("work_item_open"),
816
+ output: z.string(),
817
+ description: workItemOpenTool.description,
818
+ options: { codemode: false },
819
+ execute: async (args, context) => {
820
+ assertWorkflowToolAccess(String(context.agent), "work_item_open");
821
+ await requireFamilyEnabled(context.sessionID);
822
+ const validation = validateWorkflowToolInput("work_item_open", args);
823
+ if (!validation.ok) {
824
+ return nativeToolResult(stringifyToolOutput(workflowInputFailure("work_item_open", context.sessionID, validation.issues)));
825
+ }
826
+ const isGeneric = validation.data.execution !== undefined || validation.data.runId !== undefined;
827
+ if (isGeneric) {
828
+ getOrCreateStore(context.sessionID);
829
+ const result = await commitGenericToolResult(context.sessionID, "work_item_open", (view) => workItemOpenTool.execute(args, { sessionId: context.sessionID, workspaceRoot: trustedWorkspaceRoot }, view));
830
+ return nativeToolResult(stringifyToolOutput(result, result.ok === true ? "committed" : "not_applied"));
831
+ }
832
+ const sessionStore = getOrCreateStore(context.sessionID);
833
+ const opened = workItemOpenTool.execute(args, { sessionId: context.sessionID }, sessionStore);
834
+ const openedPersisted = snapshotSession(context.sessionID);
835
+ return nativeToolResult(stringifyToolOutput(opened, opened.ok === false ? "not_applied" : openedPersisted.ok ? "committed" : "unknown"));
836
+ },
837
+ });
838
+ editor.add({
839
+ name: "work_item_list",
840
+ input: schemaFor("work_item_list"),
841
+ output: z.string(),
842
+ description: workItemListTool.description,
843
+ options: { codemode: false },
844
+ execute: async (args, context) => {
845
+ assertWorkflowToolAccess(String(context.agent), "work_item_list");
846
+ await requireFamilyEnabled(context.sessionID);
847
+ const sessionStore = getOrCreateStore(context.sessionID);
848
+ return nativeToolResult(stringifyToolOutput(workItemListTool.execute(args, { sessionId: context.sessionID }, sessionStore)));
849
+ },
850
+ });
851
+ editor.add({
852
+ name: "work_item_close",
853
+ input: schemaFor("work_item_close"),
854
+ output: z.string(),
855
+ description: workItemCloseTool.description,
856
+ options: { codemode: false },
857
+ execute: async (args, context) => {
858
+ assertWorkflowToolAccess(String(context.agent), "work_item_close");
859
+ await requireFamilyEnabled(context.sessionID);
860
+ const sessionStore = getOrCreateStore(context.sessionID);
861
+ const closed = workItemCloseTool.execute(args, { sessionId: context.sessionID }, sessionStore);
862
+ const closedPersisted = snapshotSession(context.sessionID);
863
+ return nativeToolResult(stringifyToolOutput(closed, closed.ok === false ? "not_applied" : closedPersisted.ok ? "committed" : "unknown"));
864
+ },
865
+ });
866
+ editor.add({
867
+ name: "work_item_decide",
868
+ input: schemaFor("work_item_decide"),
869
+ output: z.string(),
870
+ description: workItemDecideTool.description,
871
+ options: { codemode: false },
872
+ execute: async (args, context) => {
873
+ const sessionStore = getOrCreateStore(context.sessionID);
874
+ await assertPrimaryControllerMutation(String(context.agent), context.sessionID, "work_item_decide");
875
+ await requireFamilyEnabled(context.sessionID);
876
+ const validation = validateWorkflowToolInput("work_item_decide", args);
877
+ if (!validation.ok) {
878
+ return nativeToolResult(stringifyToolOutput(workflowInputFailure("work_item_decide", context.sessionID, validation.issues)));
879
+ }
880
+ const parsedDecide = validation.data;
881
+ if (parsedDecide.decision === "recover") {
882
+ // START_BLOCK_EXPLICIT_CANCELLATION_RECOVERY
883
+ // A recover whose delegated attempt is still in-flight (a worker
884
+ // cancelled by the host) is the cancellation path for EVERY recover
885
+ // authorization family — ordinary, root-user, or recorded advance
886
+ // authority. It requires authoritative native cancellation evidence
887
+ // and settles the attempt and the recovery in ONE staged transaction
888
+ // with the historical completion timestamp. No evidence, an active
889
+ // child, a changed attempt identity, or a failed write leaves both
890
+ // the settlement and the budget unchanged.
891
+ const workItemId = parsedDecide.workItemId.trim();
892
+ const inFlight = getWorkItem(sessionStore, context.sessionID, workItemId)?.delegated?.attempts.find((attempt) => attempt.status === "in_flight");
893
+ if (inFlight?.callId !== undefined) {
894
+ const evidence = await gatherCancellationEvidence(context.sessionID, inFlight.callId, undefined);
895
+ if (!evidence.ok) {
896
+ return nativeToolResult(stringifyToolOutput(normalizeWorkflowFailure({
897
+ tool: "work_item_decide",
898
+ sessionId: context.sessionID,
899
+ ok: false,
900
+ errorCode: "CANCELLATION_EVIDENCE_REQUIRED",
901
+ category: "state",
902
+ message: `CANCELLATION_EVIDENCE_REQUIRED: recovery of cancelled attempt ${inFlight.attempt} of ${workItemId} needs authoritative parent cancellation, child terminal abort and quiescence evidence (${evidence.reason}); settlement and budget are unchanged.`,
903
+ })));
762
904
  }
763
- const workItemId = parsedDecide.workItemId.trim();
764
- const recovered = await executeCommittedRecovery(context.sessionID, (liveStore) => workItemDecideTool.execute(args, { sessionId: context.sessionID }, liveStore), () => captureRecordRestore(context.sessionID, workItemId), (result) => result.ok === true);
765
- // executeCommittedRecovery returns a success only after a durable
766
- // write, and throws (rollback) if the write fails.
767
- return stringifyToolOutput(recovered, recovered.ok === true ? "committed" : "not_applied");
768
- }
769
- const decided = await workItemDecideTool.execute(args, { sessionId: context.sessionID }, sessionStore);
770
- if (decided.ok) {
771
- const persisted = snapshotSession(context.sessionID);
772
- if (!persisted.ok) {
773
- throw new Error(`PERSISTENCE_FAILED: decision applied in memory but could not be persisted: ${persisted.error}`);
905
+ // Re-check the exact in-flight attempt after the async lookups so a
906
+ // changed/duplicate call binding can never be settled.
907
+ const liveAttempt = getWorkItem(sessionStore, context.sessionID, workItemId)?.delegated?.attempts.find((attempt) => attempt.status === "in_flight");
908
+ if (liveAttempt === undefined ||
909
+ liveAttempt.callId !== inFlight.callId ||
910
+ liveAttempt.attempt !== inFlight.attempt) {
911
+ return nativeToolResult(stringifyToolOutput(normalizeWorkflowFailure({
912
+ tool: "work_item_decide",
913
+ sessionId: context.sessionID,
914
+ ok: false,
915
+ errorCode: "CANCELLATION_EVIDENCE_REQUIRED",
916
+ category: "state",
917
+ message: "CANCELLATION_EVIDENCE_REQUIRED: the in-flight attempt changed during evidence lookup; settlement and budget are unchanged.",
918
+ })));
774
919
  }
920
+ const completedAt = new Date(evidence.completedAtMs).toISOString();
921
+ const completed = await commitGenericToolResult(context.sessionID, "work_item_decide", (view) => {
922
+ const failureExcerpt = createWorkflowResultExcerpt({
923
+ text: "Subagent cancelled: recovered from native parent cancellation, child terminal abort and quiescence evidence.",
924
+ source: "normalized_output",
925
+ });
926
+ if (!failureExcerpt) {
927
+ return normalizeWorkflowFailure({
928
+ tool: "work_item_decide",
929
+ sessionId: context.sessionID,
930
+ ok: false,
931
+ errorCode: "CANCELLATION_SETTLEMENT_FAILED",
932
+ category: "state",
933
+ message: "CANCELLATION_SETTLEMENT_FAILED: could not build a bounded cancellation excerpt.",
934
+ });
935
+ }
936
+ const settled = applyDelegatedLaunchFailure(view, {
937
+ sessionId: context.sessionID,
938
+ workItemId,
939
+ callId: inFlight.callId,
940
+ failureExcerpt,
941
+ completedAt,
942
+ });
943
+ if (!settled.ok) {
944
+ return normalizeWorkflowFailure({
945
+ tool: "work_item_decide",
946
+ sessionId: context.sessionID,
947
+ ok: false,
948
+ errorCode: settled.errorCode,
949
+ category: "state",
950
+ message: settled.message,
951
+ });
952
+ }
953
+ return workItemDecideTool.execute(args, { sessionId: context.sessionID, cancellationSettled: true }, view);
954
+ });
955
+ return nativeToolResult(stringifyToolOutput(completed, completed.ok === true ? "committed" : "not_applied"));
775
956
  }
776
- return stringifyToolOutput(decided, decided.ok === true ? "committed" : "not_applied");
777
- },
778
- }),
779
- work_checkpoint: tool({
780
- description: workCheckpointTool.description,
781
- args: workCheckpointArgs,
782
- async execute(args, context) {
783
- // Resolve the store first so invalid persisted state is detected
784
- // before the authorization check reports it as a control denial.
785
- const sessionStore = getOrCreateStore(context.sessionID);
786
- await assertPrimaryControllerMutation(context.agent, context.sessionID, { directory: context.directory, worktree: context.worktree }, "work_checkpoint");
787
- const validation = validateWorkflowToolInput("work_checkpoint", args);
788
- if (!validation.ok) {
789
- return stringifyToolOutput(workflowInputFailure("work_checkpoint", context.sessionID, validation.issues));
790
- }
791
- const parsedArgs = validation.data;
792
- const toolContext = {
793
- sessionId: context.sessionID,
794
- workspaceRoot: trustedWorkspaceRoot,
795
- loadPlan: async (planPath, workspaceRoot) => {
796
- const loaded = await loadApprovedDelegatedPlan({ workspaceRoot, planPath });
797
- return loaded.ok ? loaded.plan : { loadError: `${loaded.code}: ${loaded.message}` };
798
- },
799
- };
800
- // Generic (non-native) executions route through the atomic
801
- // transaction boundary: staged persist, then publish. Routing uses
802
- // the same trimmed runId the handler looks up, not a raw caller
803
- // field that could select a different persistence path.
804
- const runIdArg = parsedArgs.runId?.trim() ?? "";
805
- const liveExecution = runIdArg
806
- ? sessionStore.getStoreData().executions.get(runIdArg)
807
- : undefined;
808
- const authorityAction = parsedArgs.action === "authorize" ||
809
- parsedArgs.action === "record_approval" ||
810
- parsedArgs.action === "revoke_authority";
811
- const genericAction = parsedArgs.action !== "register" &&
812
- liveExecution !== undefined &&
813
- (liveExecution.source.kind !== "native-package" || authorityAction);
814
- const nativeAuthorityRecover = parsedArgs.action === "recover" &&
815
- parsedArgs.authorityId !== undefined &&
816
- liveExecution !== undefined;
817
- const genericRegister = parsedArgs.action === "register" && parsedArgs.planPath === undefined;
818
- if (genericAction || genericRegister || nativeAuthorityRecover) {
819
- const result = await commitGenericToolResult(context.sessionID, "work_checkpoint", (view) => workCheckpointTool.execute(args, toolContext, view));
820
- return stringifyToolOutput(result, result.ok === true ? "committed" : "not_applied");
821
- }
822
- // Checkpoint recovery commits durably on the live store and
823
- // rolls the checkpoint entry back on write failure, so a
824
- // granted generation is never exposed before its state is
825
- // durably recorded.
826
- if (parsedArgs.action === "recover") {
827
- const runId = parsedArgs.runId ?? "";
828
- const checkpointId = parsedArgs.checkpointId ?? "";
829
- const recovered = await executeCommittedRecovery(context.sessionID, (liveStore) => workCheckpointTool.execute(args, toolContext, liveStore), () => captureCheckpointRestore(context.sessionID, runId, checkpointId), (result) => result.ok === true);
830
- return stringifyToolOutput(recovered, recovered.ok === true ? "committed" : "not_applied");
957
+ // END_BLOCK_EXPLICIT_CANCELLATION_RECOVERY
958
+ if (parsedDecide.authorityId !== undefined) {
959
+ const staged = await commitGenericToolResult(context.sessionID, "work_item_decide", (view) => workItemDecideTool.execute(args, { sessionId: context.sessionID }, view));
960
+ return nativeToolResult(stringifyToolOutput(staged, staged.ok === true ? "committed" : "not_applied"));
831
961
  }
832
- const result = await workCheckpointTool.execute({ ...args }, toolContext, sessionStore);
833
- if (result.ok) {
834
- const persisted = snapshotSession(context.sessionID);
835
- if (!persisted.ok) {
836
- throw new Error(`PERSISTENCE_FAILED: checkpoint change applied in memory but could not be persisted: ${persisted.error}`);
837
- }
962
+ const recovered = await executeCommittedRecovery(context.sessionID, (liveStore) => workItemDecideTool.execute(args, { sessionId: context.sessionID }, liveStore), () => captureRecordRestore(context.sessionID, workItemId), (result) => result.ok === true);
963
+ return nativeToolResult(stringifyToolOutput(recovered, recovered.ok === true ? "committed" : "not_applied"));
964
+ }
965
+ const decided = await workItemDecideTool.execute(args, { sessionId: context.sessionID }, sessionStore);
966
+ if (decided.ok) {
967
+ const persisted = snapshotSession(context.sessionID);
968
+ if (!persisted.ok) {
969
+ throw new Error(`PERSISTENCE_FAILED: decision applied in memory but could not be persisted: ${persisted.error}`);
838
970
  }
839
- return stringifyToolOutput(result, result.ok === true ? "committed" : "not_applied");
840
- },
841
- }),
842
- },
843
- "tool.definition": toolDefinitionAdapter,
844
- "tool.execute.before": async (input, output) => {
845
- // Owned workflow tools get strict structural plus branch validation on
846
- // the raw forwarded arguments before their handlers run. This runs before
847
- // the non-task early return and never mutates output.args.
848
- if (isWorkflowToolId(input.tool)) {
849
- const validation = validateWorkflowToolInput(input.tool, output.args);
971
+ }
972
+ return nativeToolResult(stringifyToolOutput(decided, decided.ok === true ? "committed" : "not_applied"));
973
+ },
974
+ });
975
+ editor.add({
976
+ name: "work_checkpoint",
977
+ input: schemaFor("work_checkpoint"),
978
+ output: z.string(),
979
+ description: workCheckpointTool.description,
980
+ options: { codemode: false },
981
+ execute: async (args, context) => {
982
+ const sessionStore = getOrCreateStore(context.sessionID);
983
+ await assertPrimaryControllerMutation(String(context.agent), context.sessionID, "work_checkpoint");
984
+ await requireFamilyEnabled(context.sessionID);
985
+ const validation = validateWorkflowToolInput("work_checkpoint", args);
850
986
  if (!validation.ok) {
851
- throw new ContractInputError(input.tool, validation.issues);
987
+ return nativeToolResult(stringifyToolOutput(workflowInputFailure("work_checkpoint", context.sessionID, validation.issues)));
852
988
  }
853
- return;
854
- }
855
- if (input.tool !== "task") {
856
- return;
857
- }
858
- // Observe resume identities from every task launch, including untracked
859
- // ones, before any early return so a resumed child cannot stay eligible.
860
- observeTaskLaunchArgs(output.args);
861
- const subagentType = readTaskSubagentType(output.args);
862
- if (!isTrackedSubagent(subagentType)) {
863
- return;
864
- }
865
- const sessionStore = getOrCreateStore(input.sessionID);
866
- const header = parseWorkItemHeader(readTaskPrompt(output.args));
867
- if (!header.ok) {
868
- await client.app.log({
869
- body: {
870
- service: "workflow",
871
- level: "warn",
872
- message: "[workflow][launchValidation][BLOCK_VALIDATE_LAUNCH] launch rejected",
873
- extra: {
874
- sessionID: input.sessionID,
875
- agent: subagentType,
876
- reason: header.error.code,
877
- },
989
+ const parsedArgs = validation.data;
990
+ const toolContext = {
991
+ sessionId: context.sessionID,
992
+ workspaceRoot: trustedWorkspaceRoot,
993
+ loadPlan: async (planPath, workspaceRoot) => {
994
+ const loaded = await loadApprovedDelegatedPlan({ workspaceRoot, planPath });
995
+ return loaded.ok ? loaded.plan : { loadError: `${loaded.code}: ${loaded.message}` };
878
996
  },
879
- });
880
- throw new Error(`LAUNCH_REJECTED_MISSING_HEADER: ${header.error.message}`);
881
- }
882
- const workItem = getWorkItem(sessionStore, input.sessionID, header.value);
883
- if (!workItem || workItem.state === "closed") {
884
- await client.app.log({
885
- body: {
886
- service: "workflow",
887
- level: "warn",
888
- message: "[workflow][launchValidation][BLOCK_VALIDATE_LAUNCH] launch rejected",
889
- extra: {
890
- sessionID: input.sessionID,
891
- agent: subagentType,
892
- workItemId: header.value,
893
- reason: "WORK_ITEM_NOT_OPEN",
894
- },
895
- },
896
- });
897
- throw new Error(`${WORK_ITEM_MISSING_MARKER} LAUNCH_REJECTED_UNKNOWN_WORK_ITEM: no open work item ${header.value} exists in this session. Use work_item_open first or check state with work_item_list.`);
898
- }
899
- // Generic executions enforce declared task dependencies and checkpoint
900
- // barriers at launch, not only at completion.
901
- if (subagentType === "vv-implementer") {
902
- const data = sessionStore.getStoreData();
903
- for (const execution of data.executions.values()) {
904
- if (execution.sessionId !== input.sessionID)
905
- continue;
906
- const boundTask = [...execution.tasks.values()].find((binding) => binding.workItemId === workItem.workItemId);
907
- if (!boundTask)
908
- continue;
909
- const launchable = isTaskLaunchableInStore(data, {
910
- sessionId: input.sessionID,
911
- runId: execution.runId,
912
- taskId: boundTask.taskId,
913
- });
914
- if (!launchable.ok) {
915
- await client.app.log({
916
- body: {
917
- service: "workflow",
918
- level: "warn",
919
- message: "[workflow][launchValidation][BLOCK_VALIDATE_LAUNCH] dependency gate",
920
- extra: {
921
- sessionID: input.sessionID,
922
- workItemId: workItem.workItemId,
923
- runId: execution.runId,
924
- taskId: boundTask.taskId,
925
- reason: launchable.reason,
926
- },
927
- },
928
- });
929
- throw new Error(`${INVALID_NEXT_AGENT_MARKER} LAUNCH_REJECTED_DEPENDENCY: task ${boundTask.taskId} cannot start yet: ${launchable.message}`);
997
+ };
998
+ const runIdArg = parsedArgs.runId?.trim() ?? "";
999
+ const liveExecution = runIdArg
1000
+ ? sessionStore.getStoreData().executions.get(runIdArg)
1001
+ : undefined;
1002
+ const authorityAction = parsedArgs.action === "authorize" ||
1003
+ parsedArgs.action === "record_approval" ||
1004
+ parsedArgs.action === "revoke_authority";
1005
+ const genericAction = parsedArgs.action !== "register" &&
1006
+ liveExecution !== undefined &&
1007
+ (liveExecution.source.kind !== "native-package" || authorityAction);
1008
+ const nativeAuthorityRecover = parsedArgs.action === "recover" &&
1009
+ parsedArgs.authorityId !== undefined &&
1010
+ liveExecution !== undefined;
1011
+ const genericRegister = parsedArgs.action === "register" && parsedArgs.planPath === undefined;
1012
+ if (genericAction || genericRegister || nativeAuthorityRecover) {
1013
+ const result = await commitGenericToolResult(context.sessionID, "work_checkpoint", (view) => workCheckpointTool.execute(args, toolContext, view));
1014
+ return nativeToolResult(stringifyToolOutput(result, result.ok === true ? "committed" : "not_applied"));
1015
+ }
1016
+ if (parsedArgs.action === "recover") {
1017
+ const runId = parsedArgs.runId ?? "";
1018
+ const checkpointId = parsedArgs.checkpointId ?? "";
1019
+ const recovered = await executeCommittedRecovery(context.sessionID, (liveStore) => workCheckpointTool.execute(args, toolContext, liveStore), () => captureCheckpointRestore(context.sessionID, runId, checkpointId), (result) => result.ok === true);
1020
+ return nativeToolResult(stringifyToolOutput(recovered, recovered.ok === true ? "committed" : "not_applied"));
1021
+ }
1022
+ const result = await workCheckpointTool.execute({ ...args }, toolContext, sessionStore);
1023
+ if (result.ok) {
1024
+ const persisted = snapshotSession(context.sessionID);
1025
+ if (!persisted.ok) {
1026
+ throw new Error(`PERSISTENCE_FAILED: checkpoint change applied in memory but could not be persisted: ${persisted.error}`);
930
1027
  }
931
- break;
932
1028
  }
1029
+ return nativeToolResult(stringifyToolOutput(result, result.ok === true ? "committed" : "not_applied"));
1030
+ },
1031
+ });
1032
+ });
1033
+ // END_BLOCK_TOOL_CONTRACT_PUBLICATION
1034
+ // END_BLOCK_PLUGIN_TOOLS
1035
+ // START_BLOCK_TOOL_EXECUTE_BEFORE
1036
+ const beforeRegistration = await ctx.tool.hook("execute.before", async (event) => {
1037
+ // Owned workflow tools get strict structural plus branch validation on
1038
+ // the raw forwarded arguments before their handlers run. This runs before
1039
+ // the subagent early return and never mutates event.input.
1040
+ if (isWorkflowToolId(event.tool)) {
1041
+ const validation = validateWorkflowToolInput(event.tool, event.input);
1042
+ if (!validation.ok) {
1043
+ throw new ContractInputError(event.tool, validation.issues);
933
1044
  }
934
- const allowedNextAgents = getAllowedNextAgents(workItem);
935
- const reviewRound = getReviewRound(workItem);
936
- const attemptedRound = subagentType === "vv-implementer" ? getAttemptedImplementationRound(workItem) : reviewRound;
937
- const roundBlocked = workItem.mode === "implementation" &&
938
- subagentType === "vv-implementer" &&
939
- shouldBlockRound(attemptedRound);
940
- await client.app.log({
941
- body: {
942
- service: "workflow",
943
- level: "info",
944
- message: "[workflow][loopGate][BLOCK_CHECK_ROUND_LIMIT] round limit check",
945
- extra: {
946
- sessionID: input.sessionID,
947
- workItemId: workItem.workItemId,
948
- state: workItem.state,
949
- agent: subagentType,
950
- reviewRound,
951
- attemptedRound,
952
- blocked: roundBlocked,
953
- },
1045
+ return;
1046
+ }
1047
+ if (event.tool !== "subagent") {
1048
+ return;
1049
+ }
1050
+ // Observe resume identities from every launch, including untracked ones,
1051
+ // before any early return so a resumed child cannot stay eligible.
1052
+ observeSubagentLaunchInput(event.input);
1053
+ const subagentType = readSubagentAgent(event.input);
1054
+ if (!isTrackedSubagent(subagentType)) {
1055
+ return;
1056
+ }
1057
+ const sessionStore = getOrCreateStore(event.sessionID);
1058
+ const header = parseWorkItemHeader(readSubagentPrompt(event.input));
1059
+ if (!header.ok) {
1060
+ diagnostics.log({
1061
+ level: "warn",
1062
+ message: "[workflow][launchValidation][BLOCK_VALIDATE_LAUNCH] launch rejected",
1063
+ extra: { sessionID: event.sessionID, agent: subagentType, reason: header.error.code },
1064
+ });
1065
+ throw new Error(`LAUNCH_REJECTED_MISSING_HEADER: ${header.error.message}`);
1066
+ }
1067
+ const workItem = getWorkItem(sessionStore, event.sessionID, header.value);
1068
+ if (!workItem || workItem.state === "closed") {
1069
+ diagnostics.log({
1070
+ level: "warn",
1071
+ message: "[workflow][launchValidation][BLOCK_VALIDATE_LAUNCH] launch rejected",
1072
+ extra: {
1073
+ sessionID: event.sessionID,
1074
+ agent: subagentType,
1075
+ workItemId: header.value,
1076
+ reason: "WORK_ITEM_NOT_OPEN",
954
1077
  },
955
1078
  });
956
- if (roundBlocked) {
957
- await client.app.log({
958
- body: {
959
- service: "workflow",
1079
+ throw new Error(`${WORK_ITEM_MISSING_MARKER} LAUNCH_REJECTED_UNKNOWN_WORK_ITEM: no open work item ${header.value} exists in this session. Use work_item_open first or check state with work_item_list.`);
1080
+ }
1081
+ if (subagentType === "vv-implementer") {
1082
+ const data = sessionStore.getStoreData();
1083
+ for (const execution of data.executions.values()) {
1084
+ if (execution.sessionId !== event.sessionID)
1085
+ continue;
1086
+ const boundTask = [...execution.tasks.values()].find((binding) => binding.workItemId === workItem.workItemId);
1087
+ if (!boundTask)
1088
+ continue;
1089
+ const launchable = isTaskLaunchableInStore(data, {
1090
+ sessionId: event.sessionID,
1091
+ runId: execution.runId,
1092
+ taskId: boundTask.taskId,
1093
+ });
1094
+ if (!launchable.ok) {
1095
+ diagnostics.log({
960
1096
  level: "warn",
961
- message: "[workflow][launchValidation][BLOCK_VALIDATE_LAUNCH] launch rejected",
1097
+ message: "[workflow][launchValidation][BLOCK_VALIDATE_LAUNCH] dependency gate",
962
1098
  extra: {
963
- sessionID: input.sessionID,
1099
+ sessionID: event.sessionID,
964
1100
  workItemId: workItem.workItemId,
965
- agent: subagentType,
966
- reviewRound,
1101
+ runId: execution.runId,
1102
+ taskId: boundTask.taskId,
1103
+ reason: launchable.reason,
967
1104
  },
968
- },
969
- });
970
- throw new Error(createRoundLimitMessage(workItem, attemptedRound));
1105
+ });
1106
+ throw new Error(`${INVALID_NEXT_AGENT_MARKER} LAUNCH_REJECTED_DEPENDENCY: task ${boundTask.taskId} cannot start yet: ${launchable.message}`);
1107
+ }
1108
+ break;
971
1109
  }
972
- const launched = beginTrackedLaunch(sessionStore, {
973
- sessionId: input.sessionID,
1110
+ }
1111
+ const allowedNextAgents = getAllowedNextAgents(workItem);
1112
+ const reviewRound = getReviewRound(workItem);
1113
+ const attemptedRound = subagentType === "vv-implementer" ? getAttemptedImplementationRound(workItem) : reviewRound;
1114
+ const roundBlocked = workItem.mode === "implementation" &&
1115
+ subagentType === "vv-implementer" &&
1116
+ shouldBlockRound(attemptedRound);
1117
+ diagnostics.log({
1118
+ level: "info",
1119
+ message: "[workflow][loopGate][BLOCK_CHECK_ROUND_LIMIT] round limit check",
1120
+ extra: {
1121
+ sessionID: event.sessionID,
974
1122
  workItemId: workItem.workItemId,
1123
+ state: workItem.state,
975
1124
  agent: subagentType,
1125
+ reviewRound,
1126
+ attemptedRound,
1127
+ blocked: roundBlocked,
1128
+ },
1129
+ });
1130
+ if (roundBlocked) {
1131
+ diagnostics.log({
1132
+ level: "warn",
1133
+ message: "[workflow][launchValidation][BLOCK_VALIDATE_LAUNCH] launch rejected",
1134
+ extra: {
1135
+ sessionID: event.sessionID,
1136
+ workItemId: workItem.workItemId,
1137
+ agent: subagentType,
1138
+ reviewRound,
1139
+ },
976
1140
  });
977
- if (!launched.ok) {
978
- await client.app.log({
979
- body: {
980
- service: "workflow",
981
- level: "warn",
982
- message: "[workflow][launchValidation][BLOCK_VALIDATE_LAUNCH] launch rejected",
983
- extra: {
984
- sessionID: input.sessionID,
985
- agent: subagentType,
986
- workItemId: workItem.workItemId,
987
- state: workItem.state,
988
- allowedNextAgents,
989
- reason: launched.errorCode,
990
- },
991
- },
992
- });
993
- throw new Error(`${INVALID_NEXT_AGENT_MARKER} LAUNCH_REJECTED_INVALID_TRANSITION: ${workItem.workItemId} in state ${workItem.state} only allows ${launched.allowedAgents.join(", ") || "no tracked agent"}. ${launched.message}`);
994
- }
995
- // START_BLOCK_DELEGATED_LAUNCH_BINDING
996
- // Delegated implementer launches consume a callID-bound attempt after the
997
- // checkpoint barrier and overlapping-write gates pass. Reviewer launches
998
- // on a checkpoint-linked review item bind their call identity to the
999
- // current generation.
1000
- if (workItem.mode === "delegated" && subagentType === "vv-implementer") {
1001
- const data = sessionStore.getStoreData();
1002
- const planRunId = workItem.delegated?.planRunId;
1003
- if (planRunId) {
1004
- const run = data.planRuns.get(planRunId);
1005
- if (run?.status === "sealed") {
1006
- throw new Error(`LAUNCH_REJECTED_SEALED: run ${planRunId} is sealed and cannot launch ${workItem.workItemId}.`);
1007
- }
1008
- const binding = run
1009
- ? [...run.tasks.values()].find((task) => task.workItemId === workItem.workItemId)
1010
- : undefined;
1011
- const taskDefinition = run?.definition.tasks.find((task) => task.taskId === binding?.taskId);
1012
- if (run && taskDefinition) {
1013
- const barrier = checkpointBarrierUnsatisfied(data, planRunId, taskDefinition.wave);
1014
- if (barrier.ok && barrier.blockers.length > 0) {
1015
- throw new Error(`LAUNCH_REJECTED_CHECKPOINT_BARRIER: ${workItem.workItemId} is in wave ${taskDefinition.wave} blocked by unpassed checkpoint(s) ${barrier.blockers.join(", ")}.`);
1016
- }
1017
- }
1018
- const overlapping = findOverlappingInFlightReview(data, planRunId, workItem.delegated?.writeScope ?? []);
1019
- if (overlapping) {
1020
- throw new Error(`LAUNCH_REJECTED_OVERLAPPING_REVIEW: declared write scope overlaps checkpoint ${overlapping} currently in review.`);
1141
+ throw new Error(createRoundLimitMessage(workItem, attemptedRound));
1142
+ }
1143
+ // Read-only pre-launch gates: they never mutate state, so they stay on the
1144
+ // live snapshot and refuse before any staged transaction begins.
1145
+ if (workItem.mode === "delegated" && subagentType === "vv-implementer") {
1146
+ const data = sessionStore.getStoreData();
1147
+ const planRunId = workItem.delegated?.planRunId;
1148
+ if (planRunId) {
1149
+ const run = data.planRuns.get(planRunId);
1150
+ if (run?.status === "sealed") {
1151
+ throw new Error(`LAUNCH_REJECTED_SEALED: run ${planRunId} is sealed and cannot launch ${workItem.workItemId}.`);
1152
+ }
1153
+ const binding = run
1154
+ ? [...run.tasks.values()].find((task) => task.workItemId === workItem.workItemId)
1155
+ : undefined;
1156
+ const taskDefinition = run?.definition.tasks.find((task) => task.taskId === binding?.taskId);
1157
+ if (run && taskDefinition) {
1158
+ const barrier = checkpointBarrierUnsatisfied(data, planRunId, taskDefinition.wave);
1159
+ if (barrier.ok && barrier.blockers.length > 0) {
1160
+ throw new Error(`LAUNCH_REJECTED_CHECKPOINT_BARRIER: ${workItem.workItemId} is in wave ${taskDefinition.wave} blocked by unpassed checkpoint(s) ${barrier.blockers.join(", ")}.`);
1021
1161
  }
1022
1162
  }
1023
- const delegatedLaunch = beginDelegatedLaunch(sessionStore, {
1024
- sessionId: input.sessionID,
1163
+ const overlapping = findOverlappingInFlightReview(data, planRunId, workItem.delegated?.writeScope ?? []);
1164
+ if (overlapping) {
1165
+ throw new Error(`LAUNCH_REJECTED_OVERLAPPING_REVIEW: declared write scope overlaps checkpoint ${overlapping} currently in review.`);
1166
+ }
1167
+ }
1168
+ }
1169
+ // The launch transition is STAGED: begin the tracked/delegated/reviewer
1170
+ // domain change on a cloned store, persist that snapshot atomically, and
1171
+ // only then publish it plus the in-memory host-call binding. A failed write
1172
+ // refuses the launch BEFORE the native subagent executes and leaves the
1173
+ // original attempt/budget/reviewer state untouched.
1174
+ const parsedLaunchInput = workItem.mode === "delegated" && subagentType === "vv-implementer"
1175
+ ? readNativeSubagentInput(event.input)
1176
+ : undefined;
1177
+ const launchEligibility = parsedLaunchInput
1178
+ ? evaluateFreshExclusiveLaunch(parsedLaunchInput)
1179
+ : { eligible: false, reason: "resume_session" };
1180
+ const launchTransaction = await runWorkflowTransaction({
1181
+ queue: workflowTransactions,
1182
+ sessionId: event.sessionID,
1183
+ getData: () => sessionStore.getStoreData(),
1184
+ persist: async (sessionId, data) => {
1185
+ if (invalidHydrationSessions.has(sessionId)) {
1186
+ return {
1187
+ ok: false,
1188
+ error: `persisted workflow state for session ${sessionId} is invalid; refusing to overwrite it`,
1189
+ };
1190
+ }
1191
+ return snapshotWorkflowStateChecked(sessionId, data);
1192
+ },
1193
+ operation: (stagedData) => {
1194
+ const stagedStore = createWorkItemStoreView(stagedData);
1195
+ const launched = beginTrackedLaunch(stagedStore, {
1196
+ sessionId: event.sessionID,
1025
1197
  workItemId: workItem.workItemId,
1026
- callId: input.callID,
1198
+ agent: subagentType,
1027
1199
  });
1028
- if (!delegatedLaunch.ok) {
1029
- await client.app.log({
1030
- body: {
1031
- service: "workflow",
1032
- level: "warn",
1033
- message: "[workflow][launchValidation][BLOCK_VALIDATE_LAUNCH] launch rejected",
1034
- extra: {
1035
- sessionID: input.sessionID,
1036
- agent: subagentType,
1037
- workItemId: workItem.workItemId,
1038
- reason: delegatedLaunch.errorCode,
1039
- },
1200
+ if (!launched.ok) {
1201
+ return {
1202
+ result: {
1203
+ kind: "tracked-rejected",
1204
+ errorCode: launched.errorCode,
1205
+ message: launched.message,
1206
+ allowedAgents: launched.allowedAgents,
1040
1207
  },
1208
+ skipPersist: true,
1209
+ };
1210
+ }
1211
+ // START_BLOCK_DELEGATED_LAUNCH_BINDING
1212
+ if (workItem.mode === "delegated" && subagentType === "vv-implementer") {
1213
+ const delegatedLaunch = beginDelegatedLaunch(stagedStore, {
1214
+ sessionId: event.sessionID,
1215
+ workItemId: workItem.workItemId,
1216
+ callId: String(event.id),
1041
1217
  });
1042
- throw new Error(`LAUNCH_REJECTED_DELEGATED_${delegatedLaunch.errorCode}: ${delegatedLaunch.message}`);
1218
+ if (!delegatedLaunch.ok) {
1219
+ return {
1220
+ result: {
1221
+ kind: "delegated-rejected",
1222
+ errorCode: delegatedLaunch.errorCode,
1223
+ message: delegatedLaunch.message,
1224
+ },
1225
+ skipPersist: true,
1226
+ };
1227
+ }
1228
+ return { result: { kind: "applied", delegatedAttempt: delegatedLaunch.attempt } };
1229
+ }
1230
+ if (subagentType === "vv-implementer") {
1231
+ return { result: { kind: "applied" } };
1043
1232
  }
1044
- // Bind the successful launch so a later confirmed host-terminal error
1045
- // for this exact call can be consumed as a failed attempt. Eligibility
1046
- // captures background/resume/command exclusions up front.
1047
- const eligibility = readDelegatedLaunchEligibility(output.args);
1048
- delegatedLaunchBindings.set(delegatedLaunchBindingKey(input.sessionID, input.callID), {
1049
- sessionId: input.sessionID,
1050
- callId: input.callID,
1051
- workItemId: workItem.workItemId,
1052
- attempt: delegatedLaunch.attempt,
1053
- eligible: eligibility.eligible,
1054
- ineligibleReason: eligibility.reason,
1055
- afterHookEntered: false,
1056
- settled: false,
1057
- });
1058
- }
1059
- else {
1060
1233
  const reviewerRole = getReviewerRoleForAgent(subagentType);
1061
1234
  if (reviewerRole) {
1062
- const linked = findCheckpointByReviewItem(input.sessionID, workItem.workItemId);
1235
+ const linked = findCheckpointByReviewItem(event.sessionID, workItem.workItemId);
1063
1236
  if (linked) {
1064
- const bound = recordCheckpointReviewerLaunch(sessionStore, {
1237
+ const bound = recordCheckpointReviewerLaunch(stagedStore, {
1065
1238
  runId: linked.run.runId,
1066
1239
  checkpointId: linked.checkpointId,
1067
1240
  reviewer: reviewerRole,
1068
- callId: input.callID,
1241
+ callId: String(event.id),
1069
1242
  });
1070
1243
  if (!bound.ok) {
1071
- revertReviewerLaunch(sessionStore, {
1072
- sessionId: input.sessionID,
1073
- workItemId: workItem.workItemId,
1074
- agent: subagentType,
1075
- });
1076
- throw new Error(`LAUNCH_REJECTED_CHECKPOINT_REVIEW: ${bound.errorCode}: ${bound.message}`);
1244
+ return {
1245
+ result: {
1246
+ kind: "reviewer-rejected",
1247
+ errorCode: bound.errorCode,
1248
+ message: bound.message,
1249
+ },
1250
+ skipPersist: true,
1251
+ };
1077
1252
  }
1078
1253
  }
1079
1254
  }
1080
- }
1081
- // END_BLOCK_DELEGATED_LAUNCH_BINDING
1082
- snapshotSession(input.sessionID);
1083
- await client.app.log({
1084
- body: {
1085
- service: "workflow",
1086
- level: "info",
1087
- message: "[workflow][launchValidation][BLOCK_VALIDATE_LAUNCH] launch validated",
1088
- extra: {
1089
- sessionID: input.sessionID,
1090
- workItemId: workItem.workItemId,
1091
- state: workItem.state,
1092
- agent: subagentType,
1093
- reviewRound,
1094
- attemptedRound,
1095
- mode: workItem.mode,
1096
- },
1255
+ return { result: { kind: "applied" } };
1256
+ // END_BLOCK_DELEGATED_LAUNCH_BINDING
1257
+ },
1258
+ });
1259
+ if (!launchTransaction.ok) {
1260
+ diagnostics.log({
1261
+ level: "error",
1262
+ message: "[workflow][launchValidation][BLOCK_VALIDATE_LAUNCH] launch persistence failed",
1263
+ extra: {
1264
+ sessionID: event.sessionID,
1265
+ workItemId: workItem.workItemId,
1266
+ agent: subagentType,
1267
+ error: launchTransaction.error.slice(0, 300),
1097
1268
  },
1098
1269
  });
1099
- },
1100
- "tool.execute.after": async (input, output) => {
1101
- // Latch the ambiguous after-hook path synchronously before any logging,
1102
- // parsing, or repair so a later error event for this call cannot be
1103
- // classified as a terminal launch failure.
1104
- if (input.tool === "task") {
1105
- observeAfterHookEntry(input.sessionID, input.callID);
1106
- observeAfterHookMetadata(input.sessionID, input.callID, output?.metadata);
1107
- }
1108
- if (input.tool !== "task") {
1109
- return;
1110
- }
1111
- const subagentType = readTaskSubagentType(input.args);
1112
- if (!isTrackedSubagent(subagentType)) {
1113
- return;
1270
+ throw new Error(`LAUNCH_PERSISTENCE_FAILED: ${workItem.workItemId} launch was refused because its transition could not be persisted: ${launchTransaction.error}`);
1271
+ }
1272
+ const launch = launchTransaction.result;
1273
+ if (launch.kind === "tracked-rejected") {
1274
+ diagnostics.log({
1275
+ level: "warn",
1276
+ message: "[workflow][launchValidation][BLOCK_VALIDATE_LAUNCH] launch rejected",
1277
+ extra: {
1278
+ sessionID: event.sessionID,
1279
+ agent: subagentType,
1280
+ workItemId: workItem.workItemId,
1281
+ state: workItem.state,
1282
+ allowedNextAgents,
1283
+ reason: launch.errorCode,
1284
+ },
1285
+ });
1286
+ throw new Error(`${INVALID_NEXT_AGENT_MARKER} LAUNCH_REJECTED_INVALID_TRANSITION: ${workItem.workItemId} in state ${workItem.state} only allows ${launch.allowedAgents.join(", ") || "no tracked agent"}. ${launch.message}`);
1287
+ }
1288
+ if (launch.kind === "delegated-rejected") {
1289
+ diagnostics.log({
1290
+ level: "warn",
1291
+ message: "[workflow][launchValidation][BLOCK_VALIDATE_LAUNCH] launch rejected",
1292
+ extra: {
1293
+ sessionID: event.sessionID,
1294
+ agent: subagentType,
1295
+ workItemId: workItem.workItemId,
1296
+ reason: launch.errorCode,
1297
+ },
1298
+ });
1299
+ throw new Error(`LAUNCH_REJECTED_DELEGATED_${launch.errorCode}: ${launch.message}`);
1300
+ }
1301
+ if (launch.kind === "reviewer-rejected") {
1302
+ throw new Error(`LAUNCH_REJECTED_CHECKPOINT_REVIEW: ${launch.errorCode}: ${launch.message}`);
1303
+ }
1304
+ // Publish the live host-call binding only after the durable commit.
1305
+ if (workItem.mode === "delegated" && subagentType === "vv-implementer") {
1306
+ delegatedLaunchBindings.set(delegatedLaunchBindingKey(event.sessionID, String(event.id)), {
1307
+ sessionId: event.sessionID,
1308
+ callId: String(event.id),
1309
+ workItemId: workItem.workItemId,
1310
+ attempt: launch.delegatedAttempt ?? 0,
1311
+ eligible: launchEligibility.eligible,
1312
+ ...(launchEligibility.eligible ? {} : { ineligibleReason: launchEligibility.reason }),
1313
+ afterHookEntered: false,
1314
+ ...("resumedChildSessionId" in launchEligibility &&
1315
+ launchEligibility.resumedChildSessionId !== undefined
1316
+ ? { childSessionId: launchEligibility.resumedChildSessionId }
1317
+ : {}),
1318
+ background: parsedLaunchInput?.background === true,
1319
+ settled: false,
1320
+ });
1321
+ }
1322
+ else if (subagentType === "vv-implementer") {
1323
+ delegatedLaunchBindings.set(delegatedLaunchBindingKey(event.sessionID, String(event.id)), {
1324
+ sessionId: event.sessionID,
1325
+ callId: String(event.id),
1326
+ workItemId: workItem.workItemId,
1327
+ attempt: 0,
1328
+ eligible: false,
1329
+ ineligibleReason: "non_delegated_mode",
1330
+ afterHookEntered: false,
1331
+ background: false,
1332
+ settled: false,
1333
+ });
1334
+ }
1335
+ diagnostics.log({
1336
+ level: "info",
1337
+ message: "[workflow][launchValidation][BLOCK_VALIDATE_LAUNCH] launch validated",
1338
+ extra: {
1339
+ sessionID: event.sessionID,
1340
+ workItemId: workItem.workItemId,
1341
+ state: workItem.state,
1342
+ agent: subagentType,
1343
+ reviewRound,
1344
+ attemptedRound,
1345
+ mode: workItem.mode,
1346
+ },
1347
+ });
1348
+ });
1349
+ // END_BLOCK_TOOL_EXECUTE_BEFORE
1350
+ // START_BLOCK_TOOL_EXECUTE_AFTER
1351
+ const afterRegistration = await ctx.tool.hook("execute.after", async (event) => {
1352
+ // Latch the ambiguous after-hook path synchronously before any logging,
1353
+ // parsing, or repair so a later error event for this call cannot be
1354
+ // classified as a terminal launch failure.
1355
+ if (event.tool === "subagent" && event.status === "completed") {
1356
+ const binding = delegatedLaunchBindings.get(delegatedLaunchBindingKey(event.sessionID, String(event.id)));
1357
+ if (binding)
1358
+ binding.afterHookEntered = true;
1359
+ observeAfterMetadata(event.sessionID, String(event.id), event.result.metadata);
1360
+ }
1361
+ if (event.tool !== "subagent") {
1362
+ return;
1363
+ }
1364
+ const subagentType = readSubagentAgent(event.input);
1365
+ if (!isTrackedSubagent(subagentType)) {
1366
+ return;
1367
+ }
1368
+ const header = parseWorkItemHeader(readSubagentPrompt(event.input));
1369
+ if (!header.ok) {
1370
+ diagnostics.log({
1371
+ level: "warn",
1372
+ message: "[workflow][resultParsing][BLOCK_PARSE_RESULT] protocol error",
1373
+ extra: { sessionID: event.sessionID, agent: subagentType, reason: header.error.code },
1374
+ });
1375
+ throw new Error(`RESULT_PROTOCOL_ERROR: ${header.error.message}`);
1376
+ }
1377
+ const revertLaunch = () => {
1378
+ const store = getOrCreateStore(event.sessionID);
1379
+ revertReviewerLaunch(store, {
1380
+ sessionId: event.sessionID,
1381
+ workItemId: header.value,
1382
+ agent: subagentType,
1383
+ });
1384
+ snapshotSession(event.sessionID);
1385
+ };
1386
+ if (event.status === "error") {
1387
+ // A host-terminal failure surfaced by the native tool. The binding
1388
+ // consults the exact pinned subagent failure/cancel message; unrelated
1389
+ // provider errors never settle a delegated attempt.
1390
+ const failure = parseSubagentToolFailure(event.error.message);
1391
+ if (failure) {
1392
+ handleSubagentToolTermination(event.sessionID, String(event.id), failure, event.error.message);
1114
1393
  }
1115
- const header = parseWorkItemHeader(readTaskPrompt(input.args));
1116
- if (!header.ok) {
1117
- await client.app.log({
1118
- body: {
1119
- service: "workflow",
1120
- level: "warn",
1121
- message: "[workflow][resultParsing][BLOCK_PARSE_RESULT] protocol error",
1122
- extra: {
1123
- sessionID: input.sessionID,
1124
- agent: subagentType,
1125
- reason: header.error.code,
1126
- },
1127
- },
1128
- });
1129
- throw new Error(`RESULT_PROTOCOL_ERROR: ${header.error.message}`);
1394
+ revertLaunch();
1395
+ return;
1396
+ }
1397
+ const decoded = decodeNativeSubagentResult(event.result.output);
1398
+ if (decoded?.status === "running") {
1399
+ // Background launch: the attempt stays in-flight; the terminal result
1400
+ // arrives later as a native session.synthetic delivery.
1401
+ const binding = delegatedLaunchBindings.get(delegatedLaunchBindingKey(event.sessionID, String(event.id)));
1402
+ if (binding) {
1403
+ binding.background = true;
1404
+ if (binding.childSessionId === undefined)
1405
+ binding.childSessionId = decoded.sessionID;
1130
1406
  }
1131
- // Revert an in-flight reviewer launch on any failure below so the work
1132
- // item is not permanently stranded in REVIEWER_ALREADY_IN_FLIGHT. No-op
1133
- // for implementer launches (they carry no in-flight reviewer slot).
1134
- const revertLaunch = () => {
1135
- const store = getOrCreateStore(input.sessionID);
1136
- revertReviewerLaunch(store, {
1137
- sessionId: input.sessionID,
1138
- workItemId: header.value,
1139
- agent: subagentType,
1140
- });
1141
- snapshotSession(input.sessionID);
1407
+ return;
1408
+ }
1409
+ const outputText = decoded?.status === "completed"
1410
+ ? decoded.output
1411
+ : typeof event.result.output === "string"
1412
+ ? event.result.output
1413
+ : typeof event.result.content === "string"
1414
+ ? event.result.content
1415
+ : undefined;
1416
+ if (outputText === undefined) {
1417
+ diagnostics.log({
1418
+ level: "warn",
1419
+ message: "[workflow][resultParsing][BLOCK_PARSE_RESULT] protocol error",
1420
+ extra: { sessionID: event.sessionID, agent: subagentType, reason: "INVALID_TASK_OUTPUT" },
1421
+ });
1422
+ revertLaunch();
1423
+ event.result = {
1424
+ output: "RESULT_PROTOCOL_ERROR: tracked agent output must be text",
1425
+ content: "RESULT_PROTOCOL_ERROR: tracked agent output must be text",
1142
1426
  };
1143
- if (typeof output.output !== "string") {
1144
- await client.app.log({
1145
- body: {
1146
- service: "workflow",
1147
- level: "warn",
1148
- message: "[workflow][resultParsing][BLOCK_PARSE_RESULT] protocol error",
1149
- extra: {
1150
- sessionID: input.sessionID,
1151
- agent: subagentType,
1152
- reason: "INVALID_TASK_OUTPUT",
1153
- },
1427
+ return;
1428
+ }
1429
+ const finalText = await applyTrackedOutputResult({
1430
+ sessionId: event.sessionID,
1431
+ callId: String(event.id),
1432
+ subagentType,
1433
+ workItemId: header.value,
1434
+ outputText,
1435
+ childSessionId: decoded?.sessionID,
1436
+ revertLaunch,
1437
+ });
1438
+ if (finalText !== undefined) {
1439
+ event.result = { output: finalText, content: finalText, metadata: event.result.metadata };
1440
+ }
1441
+ });
1442
+ // END_BLOCK_TOOL_EXECUTE_AFTER
1443
+ // START_BLOCK_RESULT_APPLICATION
1444
+ /** Parse, optionally continue, and settle one tracked completed subagent result. */
1445
+ async function applyTrackedOutputResult(options) {
1446
+ const { sessionId, callId, subagentType, workItemId, outputText } = options;
1447
+ const unwrapped = unwrapResumableTaskResult(outputText);
1448
+ let effectiveNormalizedOutput = unwrapped.normalizedOutput;
1449
+ let parsed = parseResultBlock({
1450
+ agent: subagentType,
1451
+ output: effectiveNormalizedOutput,
1452
+ expectedWorkItemId: workItemId,
1453
+ });
1454
+ if (!parsed.ok) {
1455
+ const explicitHardStop = detectExplicitHardStopStatus(unwrapped.normalizedOutput);
1456
+ const repairChildId = options.childSessionId ?? unwrapped.envelope?.taskId;
1457
+ // A real native child identity is enough for one bounded continuation;
1458
+ // the legacy envelope is no longer required.
1459
+ if (repairChildId !== undefined &&
1460
+ isTrackedResultRepairEligible(parsed.error.code) &&
1461
+ !explicitHardStop) {
1462
+ diagnostics.log({
1463
+ level: "info",
1464
+ message: "[workflow][resultParsing][BLOCK_PARSE_RESULT] bounded continuation attempted",
1465
+ extra: {
1466
+ sessionID: sessionId,
1467
+ agent: subagentType,
1468
+ workItemId,
1469
+ taskId: repairChildId,
1470
+ reason: parsed.error.code,
1471
+ attempt: 1,
1154
1472
  },
1155
1473
  });
1156
- revertLaunch();
1157
- throw new Error("RESULT_PROTOCOL_ERROR: tracked task output must be a string");
1158
- }
1159
- const unwrapped = unwrapResumableTaskResult(output.output);
1160
- let effectiveNormalizedOutput = unwrapped.normalizedOutput;
1161
- let parsed = parseResultBlock({
1162
- agent: subagentType,
1163
- output: effectiveNormalizedOutput,
1164
- expectedWorkItemId: header.value,
1165
- });
1166
- if (!parsed.ok) {
1167
- const explicitHardStop = detectExplicitHardStopStatus(unwrapped.normalizedOutput);
1168
- if (unwrapped.envelope &&
1169
- isTrackedResultRepairEligible(parsed.error.code) &&
1170
- !explicitHardStop) {
1171
- await client.app.log({
1172
- body: {
1173
- service: "workflow",
1174
- level: "info",
1175
- message: "[workflow][resultParsing][BLOCK_PARSE_RESULT] bounded continuation attempted",
1176
- extra: {
1177
- sessionID: input.sessionID,
1178
- agent: subagentType,
1179
- workItemId: header.value,
1180
- taskId: unwrapped.envelope.taskId,
1181
- reason: parsed.error.code,
1182
- attempt: 1,
1183
- },
1184
- },
1185
- });
1186
- const repairedOutput = await attemptTrackedResultRepair({
1187
- client,
1188
- directory,
1189
- taskId: unwrapped.envelope.taskId,
1474
+ // Client acquisition and the bounded continuation are contained LOCALLY:
1475
+ // a rejected lazy client or a continuation failure must not escape the
1476
+ // after hook, which would leave the attempt in_flight. Falling through
1477
+ // lets the existing original-output protocol path settle a truthful
1478
+ // report_rejected with the original excerpt and hard-stop rules.
1479
+ let repairedOutput;
1480
+ try {
1481
+ repairedOutput = await attemptTrackedResultRepair({
1482
+ client: await getClient(),
1483
+ sessionId: repairChildId,
1190
1484
  agent: subagentType,
1191
- workItemId: header.value,
1485
+ workItemId,
1192
1486
  malformedOutput: unwrapped.normalizedOutput,
1193
1487
  parseErrorCode: parsed.error.code,
1194
1488
  parseErrorMessage: parsed.error.message,
1195
1489
  });
1196
- if (repairedOutput) {
1197
- effectiveNormalizedOutput = repairedOutput;
1198
- parsed = parseResultBlock({
1199
- agent: subagentType,
1200
- output: effectiveNormalizedOutput,
1201
- expectedWorkItemId: header.value,
1202
- });
1203
- }
1204
1490
  }
1205
- }
1206
- if (!parsed.ok) {
1207
- const protocolFailureExcerpt = createWorkflowResultExcerpt({
1208
- text: unwrapped.normalizedOutput,
1209
- source: "normalized_output",
1210
- });
1211
- await client.app.log({
1212
- body: {
1213
- service: "workflow",
1491
+ catch (error) {
1492
+ diagnostics.log({
1214
1493
  level: "warn",
1215
- message: "[workflow][resultParsing][BLOCK_PARSE_RESULT] protocol error",
1494
+ message: "[workflow][resultParsing][BLOCK_PARSE_RESULT] bounded continuation unavailable",
1216
1495
  extra: {
1217
- sessionID: input.sessionID,
1496
+ sessionID: sessionId,
1218
1497
  agent: subagentType,
1219
- workItemId: header.value,
1498
+ workItemId,
1499
+ taskId: repairChildId,
1220
1500
  reason: parsed.error.code,
1501
+ error: error instanceof Error ? error.message : String(error),
1221
1502
  },
1222
- },
1223
- });
1224
- revertLaunch();
1225
- // A confirmed terminal delegated execution whose report stays
1226
- // protocol-invalid settles as a completed execution with a rejected
1227
- // report: never in flight, never DONE, with the observed substantive
1228
- // hard stop preserved and a supported recovery path remaining.
1229
- // Unknown (non-string) or mismatched outputs never reach here.
1230
- const currentForSettlement = getWorkItem(getOrCreateStore(input.sessionID), input.sessionID, header.value);
1231
- const settledAttempt = (() => {
1232
- if (!protocolFailureExcerpt || !currentForSettlement)
1233
- return undefined;
1234
- if (currentForSettlement.state === "closed" ||
1235
- currentForSettlement.mode !== "delegated" ||
1236
- subagentType !== "vv-implementer") {
1237
- return undefined;
1238
- }
1239
- if (!currentForSettlement.delegated?.attempts.some((attempt) => attempt.status === "in_flight" && attempt.callId === input.callID)) {
1240
- return undefined;
1241
- }
1242
- const observedHardStop = detectExplicitHardStopStatus(unwrapped.normalizedOutput);
1243
- return commitDelegatedReportRejection(input.sessionID, header.value, input.callID, parsed.error.code, protocolFailureExcerpt, observedHardStop);
1244
- })();
1245
- const settlementLines = settledAttempt
1246
- ? [
1247
- `Report rejected: attempt ${settledAttempt} of ${header.value} settled as report_rejected with bounded diagnostics retained.`,
1248
- (() => {
1249
- const store = getOrCreateStore(input.sessionID);
1250
- const settledRecord = getWorkItem(store, input.sessionID, header.value);
1251
- const guidance = settledRecord
1252
- ? deriveDelegatedGuidance({
1253
- record: settledRecord,
1254
- progress: summarizeDelegatedProgress(settledRecord),
1255
- latest: latestAttemptView(settledRecord),
1256
- context: { data: store.getStoreData(), sessionId: input.sessionID },
1257
- })
1258
- : undefined;
1259
- return `Next action: ${guidance?.nextAction ?? "inspect work_item_list"}${guidance?.nextAction === "recover" ||
1260
- guidance?.nextAction === "recover_with_user_authorization"
1261
- ? ' through work_item_decide decision "recover"'
1262
- : ""}.`;
1263
- })(),
1264
- ]
1265
- : [];
1266
- throw new Error([
1267
- `RESULT_PROTOCOL_ERROR: ${parsed.error.message}`,
1268
- ...settlementLines,
1269
- formatResultExcerptForError(protocolFailureExcerpt),
1270
- ].join("\n"));
1503
+ });
1504
+ }
1505
+ if (repairedOutput) {
1506
+ effectiveNormalizedOutput = repairedOutput;
1507
+ parsed = parseResultBlock({
1508
+ agent: subagentType,
1509
+ output: effectiveNormalizedOutput,
1510
+ expectedWorkItemId: workItemId,
1511
+ });
1512
+ }
1271
1513
  }
1272
- const resultExcerpt = createResultExcerptForParsedOutput({
1273
- body: parsed.value.body,
1274
- normalizedOutput: effectiveNormalizedOutput,
1514
+ }
1515
+ if (!parsed.ok) {
1516
+ const protocolFailureExcerpt = createWorkflowResultExcerpt({
1517
+ text: unwrapped.normalizedOutput,
1518
+ source: "normalized_output",
1275
1519
  });
1276
- await client.app.log({
1277
- body: {
1278
- service: "workflow",
1279
- level: "info",
1280
- message: "[workflow][resultParsing][BLOCK_PARSE_RESULT] result parsed",
1281
- extra: {
1282
- sessionID: input.sessionID,
1283
- agent: subagentType,
1284
- workItemId: parsed.value.workItemId,
1285
- status: parsed.value.status,
1286
- route: parsed.value.route,
1287
- },
1520
+ diagnostics.log({
1521
+ level: "warn",
1522
+ message: "[workflow][resultParsing][BLOCK_PARSE_RESULT] protocol error",
1523
+ extra: {
1524
+ sessionID: sessionId,
1525
+ agent: subagentType,
1526
+ workItemId,
1527
+ reason: parsed.error.code,
1288
1528
  },
1289
1529
  });
1290
- const sessionStore = getOrCreateStore(input.sessionID);
1291
- const current = getWorkItem(sessionStore, input.sessionID, parsed.value.workItemId);
1292
- if (!current || current.state === "closed") {
1293
- await client.app.log({
1294
- body: {
1295
- service: "workflow",
1296
- level: "warn",
1297
- message: "[workflow][resultParsing][BLOCK_PARSE_RESULT] protocol error",
1298
- extra: {
1299
- sessionID: input.sessionID,
1300
- agent: subagentType,
1301
- workItemId: parsed.value.workItemId,
1302
- reason: "WORK_ITEM_NOT_OPEN",
1303
- },
1304
- },
1305
- });
1306
- revertLaunch();
1307
- throw new Error([
1308
- `RESULT_PROTOCOL_ERROR: no open work item ${parsed.value.workItemId} exists in this session`,
1309
- formatResultExcerptForError(resultExcerpt),
1310
- ].join("\n"));
1311
- }
1312
- // START_BLOCK_DELEGATED_RESULT_BINDING
1313
- // Delegated implementer results apply to their matching callID-bound
1314
- // attempt; reviewer results on checkpoint-linked review items are
1315
- // recorded into the current generation before the legacy round applies.
1316
- if (current.mode === "delegated" && subagentType === "vv-implementer") {
1317
- const appliedDelegated = applyDelegatedResult(sessionStore, {
1318
- sessionId: input.sessionID,
1319
- workItemId: parsed.value.workItemId,
1320
- callId: input.callID,
1321
- resultStatus: parsed.value.status,
1322
- resultExcerpt,
1323
- });
1324
- if (!appliedDelegated.ok) {
1325
- await client.app.log({
1326
- body: {
1327
- service: "workflow",
1328
- level: "warn",
1329
- message: "[workflow][resultParsing][BLOCK_PARSE_RESULT] protocol error",
1330
- extra: {
1331
- sessionID: input.sessionID,
1332
- agent: subagentType,
1333
- workItemId: parsed.value.workItemId,
1334
- reason: appliedDelegated.errorCode,
1335
- },
1336
- },
1337
- });
1338
- throw new Error([
1339
- `RESULT_PROTOCOL_ERROR: ${appliedDelegated.message}`,
1340
- formatResultExcerptForError(resultExcerpt),
1341
- ].join("\n"));
1530
+ options.revertLaunch();
1531
+ const currentForSettlement = getWorkItem(getOrCreateStore(sessionId), sessionId, workItemId);
1532
+ const settledAttempt = (() => {
1533
+ if (!protocolFailureExcerpt || !currentForSettlement)
1534
+ return undefined;
1535
+ if (currentForSettlement.state === "closed" ||
1536
+ currentForSettlement.mode !== "delegated" ||
1537
+ subagentType !== "vv-implementer") {
1538
+ return undefined;
1342
1539
  }
1343
- await client.app.log({
1344
- body: {
1345
- service: "workflow",
1346
- level: "info",
1347
- message: "[workflow][stateTransition][BLOCK_TRANSITION_STATE] state transitioned",
1348
- extra: {
1349
- sessionID: input.sessionID,
1350
- agent: subagentType,
1351
- workItemId: parsed.value.workItemId,
1352
- fromState: appliedDelegated.fromState,
1353
- toState: appliedDelegated.toState,
1354
- mode: "delegated",
1355
- attempt: appliedDelegated.attempt,
1356
- },
1357
- },
1358
- });
1359
- snapshotSession(input.sessionID);
1360
- if (appliedDelegated.record.state === "needs_context" ||
1361
- appliedDelegated.record.state === "blocked") {
1362
- throw new Error(createHardStopMessage({
1363
- record: appliedDelegated.record,
1364
- triggeringAgent: subagentType,
1365
- triggeringStatus: parsed.value.status,
1366
- triggeringExcerpt: resultExcerpt,
1367
- }));
1540
+ if (!currentForSettlement.delegated?.attempts.some((attempt) => attempt.status === "in_flight" && attempt.callId === callId)) {
1541
+ return undefined;
1368
1542
  }
1369
- return;
1370
- }
1371
- const reviewerRoleForCheckpoint = getReviewerRoleForAgent(subagentType);
1372
- if (reviewerRoleForCheckpoint) {
1373
- const linked = findCheckpointByReviewItem(input.sessionID, parsed.value.workItemId);
1374
- if (linked) {
1375
- const recorded = recordCheckpointReviewerResult(sessionStore, {
1376
- runId: linked.run.runId,
1377
- checkpointId: linked.checkpointId,
1378
- reviewer: reviewerRoleForCheckpoint,
1379
- callId: input.callID,
1380
- status: parsed.value.status,
1381
- });
1382
- if (!recorded.ok) {
1383
- await client.app.log({
1384
- body: {
1385
- service: "workflow",
1386
- level: "warn",
1387
- message: "[workflow][resultParsing][BLOCK_PARSE_RESULT] protocol error",
1388
- extra: {
1389
- sessionID: input.sessionID,
1390
- agent: subagentType,
1391
- workItemId: parsed.value.workItemId,
1392
- reason: recorded.errorCode,
1393
- },
1394
- },
1395
- });
1396
- revertLaunch();
1397
- throw new Error([
1398
- `RESULT_PROTOCOL_ERROR: checkpoint ${linked.checkpointId} rejected the reviewer result: ${recorded.message}`,
1399
- formatResultExcerptForError(resultExcerpt),
1400
- ].join("\n"));
1401
- }
1402
- }
1403
- }
1404
- // END_BLOCK_DELEGATED_RESULT_BINDING
1405
- const applied = applyTrackedResult(sessionStore, {
1406
- sessionId: input.sessionID,
1543
+ const observedHardStop = detectExplicitHardStopStatus(unwrapped.normalizedOutput);
1544
+ return commitDelegatedReportRejection(sessionId, workItemId, callId, parsed.error.code, protocolFailureExcerpt, observedHardStop);
1545
+ })();
1546
+ const settlementLines = settledAttempt
1547
+ ? [
1548
+ `Report rejected: attempt ${settledAttempt} of ${workItemId} settled as report_rejected with bounded diagnostics retained.`,
1549
+ (() => {
1550
+ const store = getOrCreateStore(sessionId);
1551
+ const settledRecord = getWorkItem(store, sessionId, workItemId);
1552
+ const guidance = settledRecord
1553
+ ? deriveDelegatedGuidance({
1554
+ record: settledRecord,
1555
+ progress: summarizeDelegatedProgress(settledRecord),
1556
+ latest: latestAttemptView(settledRecord),
1557
+ context: { data: store.getStoreData(), sessionId },
1558
+ })
1559
+ : undefined;
1560
+ return `Next action: ${guidance?.nextAction ?? "inspect work_item_list"}${guidance?.nextAction === "recover" ||
1561
+ guidance?.nextAction === "recover_with_user_authorization"
1562
+ ? ' through work_item_decide decision "recover"'
1563
+ : ""}.`;
1564
+ })(),
1565
+ ]
1566
+ : [];
1567
+ return [
1568
+ `RESULT_PROTOCOL_ERROR: ${parsed.error.message}`,
1569
+ ...settlementLines,
1570
+ formatResultExcerptForError(protocolFailureExcerpt),
1571
+ ].join("\n");
1572
+ }
1573
+ const resultExcerpt = createResultExcerptForParsedOutput({
1574
+ body: parsed.value.body,
1575
+ normalizedOutput: effectiveNormalizedOutput,
1576
+ });
1577
+ diagnostics.log({
1578
+ level: "info",
1579
+ message: "[workflow][resultParsing][BLOCK_PARSE_RESULT] result parsed",
1580
+ extra: {
1581
+ sessionID: sessionId,
1582
+ agent: subagentType,
1583
+ workItemId: parsed.value.workItemId,
1584
+ status: parsed.value.status,
1585
+ route: parsed.value.route,
1586
+ },
1587
+ });
1588
+ const sessionStore = getOrCreateStore(sessionId);
1589
+ const current = getWorkItem(sessionStore, sessionId, parsed.value.workItemId);
1590
+ if (!current || current.state === "closed") {
1591
+ options.revertLaunch();
1592
+ return [
1593
+ `RESULT_PROTOCOL_ERROR: no open work item ${parsed.value.workItemId} exists in this session`,
1594
+ formatResultExcerptForError(resultExcerpt),
1595
+ ].join("\n");
1596
+ }
1597
+ if (current.mode === "delegated" && subagentType === "vv-implementer") {
1598
+ const appliedDelegated = applyDelegatedResult(sessionStore, {
1599
+ sessionId,
1407
1600
  workItemId: parsed.value.workItemId,
1408
- result: parsed.value,
1601
+ callId,
1602
+ resultStatus: parsed.value.status,
1409
1603
  resultExcerpt,
1410
1604
  });
1411
- if (!applied.ok) {
1412
- await client.app.log({
1413
- body: {
1414
- service: "workflow",
1415
- level: "warn",
1416
- message: "[workflow][resultParsing][BLOCK_PARSE_RESULT] protocol error",
1417
- extra: {
1418
- sessionID: input.sessionID,
1419
- agent: subagentType,
1420
- workItemId: parsed.value.workItemId,
1421
- reason: applied.errorCode,
1422
- },
1423
- },
1424
- });
1425
- revertLaunch();
1426
- throw new Error([
1427
- `RESULT_PROTOCOL_ERROR: ${applied.message}`,
1605
+ if (!appliedDelegated.ok) {
1606
+ return [
1607
+ `RESULT_PROTOCOL_ERROR: ${appliedDelegated.message}`,
1428
1608
  formatResultExcerptForError(resultExcerpt),
1429
- ].join("\n"));
1609
+ ].join("\n");
1430
1610
  }
1431
- await client.app.log({
1432
- body: {
1433
- service: "workflow",
1434
- level: "info",
1435
- message: "[workflow][stateTransition][BLOCK_TRANSITION_STATE] state transitioned",
1436
- extra: {
1437
- sessionID: input.sessionID,
1438
- agent: subagentType,
1439
- workItemId: parsed.value.workItemId,
1440
- fromState: applied.fromState,
1441
- toState: applied.record.state,
1442
- specReviewCount: applied.record.specReviewCount,
1443
- codeReviewCount: applied.record.codeReviewCount,
1444
- reviewRound: getReviewRound(applied.record),
1445
- aggregateComplete: applied.aggregateComplete,
1446
- },
1611
+ diagnostics.log({
1612
+ level: "info",
1613
+ message: "[workflow][stateTransition][BLOCK_TRANSITION_STATE] state transitioned",
1614
+ extra: {
1615
+ sessionID: sessionId,
1616
+ agent: subagentType,
1617
+ workItemId: parsed.value.workItemId,
1618
+ fromState: appliedDelegated.fromState,
1619
+ toState: appliedDelegated.toState,
1620
+ mode: "delegated",
1621
+ attempt: appliedDelegated.attempt,
1447
1622
  },
1448
1623
  });
1449
- snapshotSession(input.sessionID);
1450
- if (applied.record.state === "needs_context" || applied.record.state === "blocked") {
1451
- throw new Error(createHardStopMessage({
1452
- record: applied.record,
1624
+ snapshotSession(sessionId);
1625
+ if (appliedDelegated.record.state === "needs_context" ||
1626
+ appliedDelegated.record.state === "blocked") {
1627
+ return createHardStopMessage({
1628
+ record: appliedDelegated.record,
1453
1629
  triggeringAgent: subagentType,
1454
1630
  triggeringStatus: parsed.value.status,
1455
1631
  triggeringExcerpt: resultExcerpt,
1456
- }));
1632
+ });
1457
1633
  }
1458
- },
1459
- "chat.message": async (_input, output) => {
1460
- if (!shouldInjectForAgent(output.message.agent)) {
1461
- return;
1634
+ return undefined;
1635
+ }
1636
+ const reviewerRoleForCheckpoint = getReviewerRoleForAgent(subagentType);
1637
+ if (reviewerRoleForCheckpoint) {
1638
+ const linked = findCheckpointByReviewItem(sessionId, parsed.value.workItemId);
1639
+ if (linked) {
1640
+ const recorded = recordCheckpointReviewerResult(sessionStore, {
1641
+ runId: linked.run.runId,
1642
+ checkpointId: linked.checkpointId,
1643
+ reviewer: reviewerRoleForCheckpoint,
1644
+ callId,
1645
+ status: parsed.value.status,
1646
+ });
1647
+ if (!recorded.ok) {
1648
+ options.revertLaunch();
1649
+ return [
1650
+ `RESULT_PROTOCOL_ERROR: checkpoint ${linked.checkpointId} rejected the reviewer result: ${recorded.message}`,
1651
+ formatResultExcerptForError(resultExcerpt),
1652
+ ].join("\n");
1653
+ }
1462
1654
  }
1463
- output.message.system = appendSystemInstruction(output.message.system, workflowSystemInstruction);
1464
- },
1465
- event: async (input) => {
1466
- const event = input.event;
1467
- const eventType = event.type;
1468
- const properties = event.properties ?? {};
1469
- // message.part.updated identifies its session through properties.part,
1470
- // not properties.sessionID, and must never hydrate a store.
1471
- if (eventType === "message.part.updated") {
1472
- handleDelegatedPartUpdated(properties);
1655
+ }
1656
+ const applied = applyTrackedResult(sessionStore, {
1657
+ sessionId,
1658
+ workItemId: parsed.value.workItemId,
1659
+ result: parsed.value,
1660
+ resultExcerpt,
1661
+ });
1662
+ if (!applied.ok) {
1663
+ options.revertLaunch();
1664
+ return [
1665
+ `RESULT_PROTOCOL_ERROR: ${applied.message}`,
1666
+ formatResultExcerptForError(resultExcerpt),
1667
+ ].join("\n");
1668
+ }
1669
+ diagnostics.log({
1670
+ level: "info",
1671
+ message: "[workflow][stateTransition][BLOCK_TRANSITION_STATE] state transitioned",
1672
+ extra: {
1673
+ sessionID: sessionId,
1674
+ agent: subagentType,
1675
+ workItemId: parsed.value.workItemId,
1676
+ fromState: applied.fromState,
1677
+ toState: applied.record.state,
1678
+ specReviewCount: applied.record.specReviewCount,
1679
+ codeReviewCount: applied.record.codeReviewCount,
1680
+ reviewRound: getReviewRound(applied.record),
1681
+ aggregateComplete: applied.aggregateComplete,
1682
+ },
1683
+ });
1684
+ snapshotSession(sessionId);
1685
+ if (applied.record.state === "needs_context" || applied.record.state === "blocked") {
1686
+ return createHardStopMessage({
1687
+ record: applied.record,
1688
+ triggeringAgent: subagentType,
1689
+ triggeringStatus: parsed.value.status,
1690
+ triggeringExcerpt: resultExcerpt,
1691
+ });
1692
+ }
1693
+ return undefined;
1694
+ }
1695
+ /**
1696
+ * Settle one background subagent completion delivered as a native
1697
+ * `session.synthetic` element. Only a binding whose child matches is settled;
1698
+ * a running status is never treated as a completed result.
1699
+ */
1700
+ async function handleBackgroundDelivery(parentSessionId, text, metadata) {
1701
+ // The synthetic delivery must be a genuine native subagent completion for
1702
+ // the same parent session and bound child. A forged literal wrapper or an
1703
+ // unrelated session is never accepted.
1704
+ if (!isRecord(metadata))
1705
+ return;
1706
+ if (metadata.source !== "subagent")
1707
+ return;
1708
+ const parsed = parseSubagentCompletionElement(text);
1709
+ if (!parsed)
1710
+ return;
1711
+ const metaChild = metadata.childID;
1712
+ const metaState = metadata.state;
1713
+ if (typeof metaChild !== "string" || metaChild !== parsed.sessionID)
1714
+ return;
1715
+ if (typeof metaState !== "string" || metaState !== parsed.state)
1716
+ return;
1717
+ const binding = findBindingByChild(parsed.sessionID);
1718
+ if (!binding || !binding.background || binding.settled)
1719
+ return;
1720
+ if (binding.sessionId !== parentSessionId)
1721
+ return;
1722
+ const sessionId = binding.sessionId;
1723
+ const callId = binding.callId;
1724
+ if (parsed.state === "cancelled" || parsed.state === "error") {
1725
+ // A background `cancelled` delivery stays in-flight for explicit
1726
+ // evidence-backed cancellation recovery. A background `error` is a
1727
+ // confirmed terminal failure and settles the bound attempt directly
1728
+ // (bypassing the foreground-only guard).
1729
+ if (parsed.state === "cancelled")
1473
1730
  return;
1474
- }
1475
- // A child session that receives more than one user prompt has been
1476
- // resumed or re-prompted and is no longer a fresh-exclusive child.
1477
- if (eventType === "message.updated") {
1478
- const messageInfo = properties.info;
1479
- if (messageInfo &&
1480
- messageInfo.role === "user" &&
1481
- typeof messageInfo.sessionID === "string") {
1482
- observeChildPrompt(messageInfo.sessionID, typeof messageInfo.id === "string" ? messageInfo.id : undefined);
1483
- }
1731
+ const failureExcerpt = createWorkflowResultExcerpt({
1732
+ text: parsed.output,
1733
+ source: "normalized_output",
1734
+ });
1735
+ if (!failureExcerpt)
1484
1736
  return;
1485
- }
1486
- const info = properties.info;
1487
- const eventSessionId = properties.sessionID ?? info?.id;
1488
- if (!eventSessionId)
1737
+ commitDelegatedLaunchFailure(sessionId, binding, failureExcerpt);
1738
+ return;
1739
+ }
1740
+ // A completed background delivery must correspond to a terminal,
1741
+ // non-aborted child run; verify through the full client before settling.
1742
+ try {
1743
+ const client = await getClient();
1744
+ const childInfo = (await client.session.get({ sessionID: parsed.sessionID }));
1745
+ if (childInfo.parentID !== parentSessionId)
1489
1746
  return;
1490
- // Hydration happens in tool.execute.before — not here,
1491
- // because session.status fires for subagent child sessions too,
1492
- // which would erroneously change persistedSessionId mid-flow.
1493
- if (eventType === "session.status") {
1747
+ const active = (await client.session.active());
1748
+ if (active !== undefined && active !== null && active[parsed.sessionID] !== undefined)
1494
1749
  return;
1750
+ }
1751
+ catch {
1752
+ return;
1753
+ }
1754
+ const workItem = getWorkItem(getOrCreateStore(sessionId), sessionId, binding.workItemId);
1755
+ if (!workItem || workItem.state === "closed")
1756
+ return;
1757
+ const subagentType = workItem.mode === "delegated" ? "vv-implementer" : undefined;
1758
+ if (!subagentType)
1759
+ return;
1760
+ binding.afterHookEntered = true;
1761
+ await applyTrackedOutputResult({
1762
+ sessionId,
1763
+ callId,
1764
+ subagentType,
1765
+ workItemId: binding.workItemId,
1766
+ outputText: parsed.output,
1767
+ childSessionId: parsed.sessionID,
1768
+ revertLaunch: () => undefined,
1769
+ });
1770
+ }
1771
+ // END_BLOCK_RESULT_APPLICATION
1772
+ // START_BLOCK_SESSION_CONTEXT_GUIDANCE
1773
+ const guidanceRegistration = await ctx.session.hook("context", async (event) => {
1774
+ const family = await resolveFamilyPolicy(event.sessionID);
1775
+ // A disabled/unbound family neither sees the workflow tools nor receives
1776
+ // workflow guidance; the tools stay registered but are hidden per session.
1777
+ if (family === undefined || !family.enabled) {
1778
+ const tools = event.tools;
1779
+ if (tools !== undefined) {
1780
+ for (const name of WORKFLOW_TOOL_NAMES)
1781
+ delete tools[name];
1495
1782
  }
1496
- if (eventType === "session.deleted") {
1497
- for (const [key, binding] of delegatedLaunchBindings) {
1498
- if (binding.sessionId === eventSessionId) {
1499
- delegatedLaunchBindings.delete(key);
1783
+ return;
1784
+ }
1785
+ if (!shouldInjectForAgent(event.agent))
1786
+ return;
1787
+ const instruction = getWorkflowSystemInstruction(family.policy);
1788
+ event.system.push({ type: "text", text: appendSystemInstruction(undefined, instruction) });
1789
+ });
1790
+ // END_BLOCK_SESSION_CONTEXT_GUIDANCE
1791
+ // START_BLOCK_EVENT_PUMP
1792
+ const lifecycle = new AbortController();
1793
+ const pump = (async () => {
1794
+ try {
1795
+ for await (const event of ctx.event.subscribe({ signal: lifecycle.signal })) {
1796
+ // Contain every handler failure PER EVENT: a rejected client acquisition,
1797
+ // malformed background result, or cleanup error must not end the only
1798
+ // subscription and silently stop later completion/failure/deletion work.
1799
+ try {
1800
+ const type = typeof event.type === "string" ? event.type : "";
1801
+ const data = isRecord(event.data) ? event.data : undefined;
1802
+ if (type === "session.synthetic" && data) {
1803
+ const text = data.text;
1804
+ const parentSessionId = data.sessionID;
1805
+ if (typeof text === "string" && typeof parentSessionId === "string") {
1806
+ await handleBackgroundDelivery(parentSessionId, text, data.metadata);
1807
+ }
1808
+ continue;
1809
+ }
1810
+ if (type === "session.tool.failed" && data) {
1811
+ const sessionID = data.sessionID;
1812
+ const callID = data.id;
1813
+ const error = isRecord(data.error) ? data.error : undefined;
1814
+ const message = typeof error?.message === "string" ? error.message : undefined;
1815
+ if (typeof sessionID === "string" &&
1816
+ typeof callID === "string" &&
1817
+ message !== undefined) {
1818
+ observeAfterMetadata(sessionID, callID, data.metadata);
1819
+ const failure = parseSubagentToolFailure(message);
1820
+ if (failure)
1821
+ handleSubagentToolTermination(sessionID, callID, failure, message);
1822
+ }
1823
+ continue;
1824
+ }
1825
+ if ((type === "session.tool.called" ||
1826
+ type === "session.tool.progress" ||
1827
+ type === "session.tool.success") &&
1828
+ data) {
1829
+ const sessionID = data.sessionID;
1830
+ const callID = data.id;
1831
+ if (typeof sessionID === "string" && typeof callID === "string") {
1832
+ observeAfterMetadata(sessionID, callID, data.metadata);
1833
+ }
1834
+ continue;
1835
+ }
1836
+ if (type === "session.inbox.enqueued" && data) {
1837
+ const sessionID = data.sessionID;
1838
+ const inboxID = data.inboxID;
1839
+ if (typeof sessionID === "string" && typeof inboxID === "string") {
1840
+ observeChildPrompt(sessionID, inboxID);
1841
+ }
1842
+ continue;
1843
+ }
1844
+ if (type === "session.deleted" && data) {
1845
+ const sessionID = data.sessionID;
1846
+ if (typeof sessionID === "string") {
1847
+ for (const [key, binding] of delegatedLaunchBindings) {
1848
+ if (binding.sessionId === sessionID)
1849
+ delegatedLaunchBindings.delete(key);
1850
+ }
1851
+ childPromptMessageIds.delete(sessionID);
1852
+ resumedChildSessions.delete(sessionID);
1853
+ stores.delete(sessionID);
1854
+ invalidHydrationSessions.delete(sessionID);
1855
+ await deleteWorkflowSessionDir(sessionID);
1856
+ diagnostics.log({
1857
+ level: "info",
1858
+ message: "[workflow][sessionCleanup][BLOCK_SESSION_CLEANUP] deleted",
1859
+ extra: { sessionID },
1860
+ });
1861
+ }
1500
1862
  }
1501
1863
  }
1502
- childPromptMessageIds.delete(eventSessionId);
1503
- resumedChildSessions.delete(eventSessionId);
1504
- stores.delete(eventSessionId);
1505
- await deleteWorkflowSessionDir(eventSessionId);
1506
- await client.app.log({
1507
- body: {
1508
- service: "workflow",
1509
- level: "info",
1510
- message: "[workflow][sessionCleanup][BLOCK_SESSION_CLEANUP] deleted",
1864
+ catch (error) {
1865
+ const data = isRecord(event.data) ? event.data : undefined;
1866
+ diagnostics.log({
1867
+ level: "error",
1868
+ message: "[workflow][eventPump][BLOCK_EVENT_PUMP] contained handler failure",
1511
1869
  extra: {
1512
- sessionID: eventSessionId,
1870
+ eventType: typeof event.type === "string" ? event.type : "unknown",
1871
+ ...(typeof data?.sessionID === "string" ? { sessionID: data.sessionID } : {}),
1872
+ error: error instanceof Error ? error.message : String(error),
1513
1873
  },
1514
- },
1515
- });
1516
- return;
1874
+ });
1875
+ }
1517
1876
  }
1518
- },
1877
+ }
1878
+ catch {
1879
+ // A closed native event stream ends the pump; plugin cleanup aborts it.
1880
+ }
1881
+ })();
1882
+ void pump;
1883
+ // END_BLOCK_EVENT_PUMP
1884
+ return async () => {
1885
+ lifecycle.abort();
1886
+ await pump.catch(() => undefined);
1887
+ await afterRegistration.dispose();
1888
+ await beforeRegistration.dispose();
1889
+ await guidanceRegistration.dispose();
1890
+ await runtime.release();
1519
1891
  };
1520
- };
1892
+ }
1893
+ /** Native workflow plugin: registers workflow tools, native hooks and the event pump. */
1894
+ export const WorkflowPlugin = createWorkflowPlugin();
1895
+ export default WorkflowPlugin;
1521
1896
  // END_BLOCK_PLUGIN_ENTRY
1522
- // START_BLOCK_DUAL_SUBPATH_ENTRY
1523
- import { defineDualPlugin } from "../v2-runtime/index.js";
1524
- import { createV2Adapter } from "../v2-runtime/setup.js";
1525
- import { setupWorkflowV2 } from "./v2.js";
1526
- export default defineDualPlugin({
1527
- id: "vvoc.workflow",
1528
- v1: WorkflowPlugin,
1529
- v2: (ctx) => setupWorkflowV2(createV2Adapter(ctx)),
1530
- });
1531
- // END_BLOCK_DUAL_SUBPATH_ENTRY
1532
1897
  //# sourceMappingURL=index.js.map