@fantasticit/sumi 0.12.0 → 0.14.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 (468) hide show
  1. package/README.md +22 -22
  2. package/dist/adapters.d.ts +3 -27
  3. package/dist/adapters.js +75 -127
  4. package/dist/adapters.js.map +1 -1
  5. package/dist/agent-hooks.d.ts +34 -8
  6. package/dist/agent-hooks.js +561 -179
  7. package/dist/agent-hooks.js.map +1 -1
  8. package/dist/agents.d.ts +1 -1
  9. package/dist/agents.js +15 -16
  10. package/dist/agents.js.map +1 -1
  11. package/dist/bin.js +14 -10
  12. package/dist/bin.js.map +1 -1
  13. package/dist/cli.d.ts +1 -1
  14. package/dist/cli.js +144 -15
  15. package/dist/cli.js.map +1 -1
  16. package/dist/compaction-marker.d.ts +4 -0
  17. package/dist/compaction-marker.js +37 -0
  18. package/dist/compaction-marker.js.map +1 -0
  19. package/dist/config-text.d.ts +1 -1
  20. package/dist/config-text.js +21 -13
  21. package/dist/config-text.js.map +1 -1
  22. package/dist/constraint-list.js +1 -1
  23. package/dist/constraint-list.js.map +1 -1
  24. package/dist/context-providers.js +12 -0
  25. package/dist/context-providers.js.map +1 -0
  26. package/dist/context.js +51 -51
  27. package/dist/context.js.map +1 -1
  28. package/dist/declared-hooks.d.ts +29 -0
  29. package/dist/declared-hooks.js +99 -0
  30. package/dist/declared-hooks.js.map +1 -0
  31. package/dist/hook-output.d.ts +3 -0
  32. package/dist/hook-output.js +5 -0
  33. package/dist/hook-output.js.map +1 -0
  34. package/dist/hook-routing.d.ts +33 -1
  35. package/dist/hook-routing.js +137 -24
  36. package/dist/hook-routing.js.map +1 -1
  37. package/dist/host-adapters.d.ts +32 -0
  38. package/dist/host-adapters.js +97 -0
  39. package/dist/host-adapters.js.map +1 -0
  40. package/dist/instructions.js +7 -5
  41. package/dist/instructions.js.map +1 -1
  42. package/dist/run-stats.d.ts +6 -0
  43. package/dist/run-stats.js +44 -3
  44. package/dist/run-stats.js.map +1 -1
  45. package/dist/scaffold-commands.js +82 -9
  46. package/dist/scaffold-commands.js.map +1 -1
  47. package/dist/stop-hint.d.ts +4 -0
  48. package/dist/stop-hint.js +29 -0
  49. package/dist/stop-hint.js.map +1 -0
  50. package/dist/subagent-history.d.ts +2 -0
  51. package/dist/subagent-history.js +35 -0
  52. package/dist/subagent-history.js.map +1 -0
  53. package/dist/task.d.ts +16 -0
  54. package/dist/task.js +55 -36
  55. package/dist/task.js.map +1 -1
  56. package/dist/vendor.d.ts +1 -1
  57. package/dist/vendor.js +10 -24
  58. package/dist/vendor.js.map +1 -1
  59. package/dist/visualize-page.d.ts +1 -1
  60. package/dist/visualize-page.js +40 -39
  61. package/dist/visualize-page.js.map +1 -1
  62. package/dist/visualize-sessions.d.ts +34 -0
  63. package/dist/visualize-sessions.js +181 -0
  64. package/dist/visualize-sessions.js.map +1 -0
  65. package/dist/visualize.js +22 -3
  66. package/dist/visualize.js.map +1 -1
  67. package/node_modules/@sumi/create/dist/scaffold.js +5 -4
  68. package/node_modules/@sumi/create/dist/scaffold.js.map +1 -1
  69. package/node_modules/@sumi/create/package.json +2 -2
  70. package/node_modules/@sumi/create/template/AGENTS.md +1 -1
  71. package/node_modules/@sumi/create/template/control/config.yaml +3 -0
  72. package/node_modules/@sumi/create/template/control/flows/change.flow.yaml +8 -5
  73. package/node_modules/@sumi/create/template/control/flows/check.flow.yaml +7 -21
  74. package/node_modules/@sumi/create/template/control/rubrics/behavior.yaml +14 -1
  75. package/node_modules/@sumi/create/template/control/rubrics/omission.yaml +1 -1
  76. package/node_modules/@sumi/create/template/control/rubrics/{clean-code.yaml → quality.yaml} +12 -4
  77. package/node_modules/@sumi/create/template/control/rules/boundaries.md +25 -0
  78. package/node_modules/@sumi/create/template/control/rules/codecheck.md +1 -1
  79. package/node_modules/@sumi/create/template/control/rules/development.md +7 -2
  80. package/node_modules/@sumi/create/template/init/AGENTS.md +1 -1
  81. package/node_modules/@sumi/create/template/init/control/flows/change.flow.yaml +7 -4
  82. package/node_modules/@sumi/create/template/init/control/flows/check.flow.yaml +3 -0
  83. package/node_modules/@sumi/create/template/init/control/rubrics/behavior.yaml +30 -0
  84. package/node_modules/@sumi/create/template/init/control/rubrics/omission.yaml +13 -0
  85. package/node_modules/@sumi/create/template/init/control/rubrics/quality.yaml +22 -0
  86. package/node_modules/@sumi/create/template/init/control/rubrics/security.yaml +20 -0
  87. package/node_modules/@sumi/create/template/init/openspec/config.yaml +6 -0
  88. package/node_modules/@sumi/create/template/openspec/config.yaml +6 -0
  89. package/node_modules/@sumi/kernel/dist/brief.js +1 -1
  90. package/node_modules/@sumi/kernel/dist/brief.js.map +1 -1
  91. package/node_modules/@sumi/kernel/dist/config.d.ts +13 -0
  92. package/node_modules/@sumi/kernel/dist/config.js +23 -2
  93. package/node_modules/@sumi/kernel/dist/config.js.map +1 -1
  94. package/node_modules/@sumi/kernel/dist/context-providers.d.ts +17 -0
  95. package/node_modules/@sumi/kernel/dist/context-providers.js +74 -0
  96. package/node_modules/@sumi/kernel/dist/context-providers.js.map +1 -0
  97. package/node_modules/@sumi/kernel/dist/engine.d.ts +2 -0
  98. package/node_modules/@sumi/kernel/dist/engine.js +124 -72
  99. package/node_modules/@sumi/kernel/dist/engine.js.map +1 -1
  100. package/node_modules/@sumi/kernel/dist/flow.d.ts +16 -0
  101. package/node_modules/@sumi/kernel/dist/flow.js +27 -0
  102. package/node_modules/@sumi/kernel/dist/flow.js.map +1 -1
  103. package/node_modules/@sumi/kernel/dist/index.d.ts +3 -0
  104. package/node_modules/@sumi/kernel/dist/index.js +3 -0
  105. package/node_modules/@sumi/kernel/dist/index.js.map +1 -1
  106. package/node_modules/@sumi/kernel/dist/plan.d.ts +12 -0
  107. package/node_modules/@sumi/kernel/dist/plan.js.map +1 -1
  108. package/node_modules/@sumi/kernel/dist/record.d.ts +14 -3
  109. package/node_modules/@sumi/kernel/dist/record.js +138 -6
  110. package/node_modules/@sumi/kernel/dist/record.js.map +1 -1
  111. package/node_modules/@sumi/kernel/dist/resume.d.ts +3 -1
  112. package/node_modules/@sumi/kernel/dist/resume.js +35 -27
  113. package/node_modules/@sumi/kernel/dist/resume.js.map +1 -1
  114. package/node_modules/@sumi/kernel/dist/runtime.d.ts +2 -0
  115. package/node_modules/@sumi/kernel/dist/runtime.js +30 -0
  116. package/node_modules/@sumi/kernel/dist/runtime.js.map +1 -0
  117. package/node_modules/@sumi/kernel/dist/scope.d.ts +2 -1
  118. package/node_modules/@sumi/kernel/dist/scope.js +2 -2
  119. package/node_modules/@sumi/kernel/dist/scope.js.map +1 -1
  120. package/node_modules/@sumi/kernel/dist/source-monitor.d.ts +20 -0
  121. package/node_modules/@sumi/kernel/dist/source-monitor.js +105 -0
  122. package/node_modules/@sumi/kernel/dist/source-monitor.js.map +1 -0
  123. package/node_modules/@sumi/kernel/dist/step-cache.d.ts +1 -1
  124. package/node_modules/@sumi/kernel/dist/step-cache.js +62 -51
  125. package/node_modules/@sumi/kernel/dist/step-cache.js.map +1 -1
  126. package/node_modules/@sumi/kernel/dist/step.d.ts +61 -0
  127. package/node_modules/@sumi/kernel/dist/step.js +55 -0
  128. package/node_modules/@sumi/kernel/dist/step.js.map +1 -0
  129. package/node_modules/@sumi/kernel/package.json +2 -2
  130. package/node_modules/@sumi/plugin-sdk/README.md +3 -3
  131. package/node_modules/@sumi/plugin-sdk/dist/context-delivery.d.ts +15 -0
  132. package/node_modules/@sumi/plugin-sdk/dist/context-delivery.js +28 -0
  133. package/node_modules/@sumi/plugin-sdk/dist/context-delivery.js.map +1 -0
  134. package/node_modules/@sumi/plugin-sdk/dist/context-scope.d.ts +2 -0
  135. package/node_modules/@sumi/plugin-sdk/dist/context-scope.js +49 -0
  136. package/node_modules/@sumi/plugin-sdk/dist/context-scope.js.map +1 -0
  137. package/node_modules/@sumi/plugin-sdk/dist/edit-paths.d.ts +2 -0
  138. package/node_modules/@sumi/plugin-sdk/dist/edit-paths.js +54 -0
  139. package/node_modules/@sumi/plugin-sdk/dist/edit-paths.js.map +1 -0
  140. package/node_modules/@sumi/plugin-sdk/dist/files.d.ts +7 -0
  141. package/node_modules/@sumi/plugin-sdk/dist/files.js +107 -1
  142. package/node_modules/@sumi/plugin-sdk/dist/files.js.map +1 -1
  143. package/node_modules/@sumi/plugin-sdk/dist/git.d.ts +2 -0
  144. package/node_modules/@sumi/plugin-sdk/dist/git.js +11 -0
  145. package/node_modules/@sumi/plugin-sdk/dist/git.js.map +1 -1
  146. package/node_modules/@sumi/plugin-sdk/dist/hook-input.d.ts +5 -0
  147. package/node_modules/@sumi/plugin-sdk/dist/hook-input.js +41 -0
  148. package/node_modules/@sumi/plugin-sdk/dist/hook-input.js.map +1 -0
  149. package/node_modules/@sumi/plugin-sdk/dist/host-event.d.ts +20 -0
  150. package/node_modules/@sumi/plugin-sdk/dist/host-event.js +56 -0
  151. package/node_modules/@sumi/plugin-sdk/dist/host-event.js.map +1 -0
  152. package/node_modules/@sumi/plugin-sdk/dist/html-page.d.ts +5 -0
  153. package/node_modules/@sumi/plugin-sdk/dist/html-page.js +93 -0
  154. package/node_modules/@sumi/plugin-sdk/dist/html-page.js.map +1 -0
  155. package/node_modules/@sumi/plugin-sdk/dist/html-style.d.ts +1 -0
  156. package/node_modules/@sumi/plugin-sdk/dist/html-style.js +27 -0
  157. package/node_modules/@sumi/plugin-sdk/dist/html-style.js.map +1 -0
  158. package/node_modules/@sumi/plugin-sdk/dist/index.d.ts +9 -0
  159. package/node_modules/@sumi/plugin-sdk/dist/index.js +9 -0
  160. package/node_modules/@sumi/plugin-sdk/dist/index.js.map +1 -1
  161. package/node_modules/@sumi/plugin-sdk/dist/permissions.d.ts +7 -0
  162. package/node_modules/@sumi/plugin-sdk/dist/permissions.js +41 -0
  163. package/node_modules/@sumi/plugin-sdk/dist/permissions.js.map +1 -0
  164. package/node_modules/@sumi/plugin-sdk/dist/project.d.ts +2 -0
  165. package/node_modules/@sumi/plugin-sdk/dist/project.js +2 -0
  166. package/node_modules/@sumi/plugin-sdk/dist/project.js.map +1 -1
  167. package/node_modules/@sumi/plugin-sdk/dist/protocol.d.ts +53 -4
  168. package/node_modules/@sumi/plugin-sdk/dist/protocol.js +30 -1
  169. package/node_modules/@sumi/plugin-sdk/dist/protocol.js.map +1 -1
  170. package/node_modules/@sumi/plugin-sdk/dist/sdk.js +3 -1
  171. package/node_modules/@sumi/plugin-sdk/dist/sdk.js.map +1 -1
  172. package/node_modules/@sumi/plugin-sdk/dist/session-context.d.ts +26 -1
  173. package/node_modules/@sumi/plugin-sdk/dist/session-context.js +159 -56
  174. package/node_modules/@sumi/plugin-sdk/dist/session-context.js.map +1 -1
  175. package/node_modules/@sumi/plugin-sdk/dist/shell.js +22 -9
  176. package/node_modules/@sumi/plugin-sdk/dist/shell.js.map +1 -1
  177. package/node_modules/@sumi/plugin-sdk/dist/snapshot.d.ts +12 -0
  178. package/node_modules/@sumi/plugin-sdk/dist/snapshot.js +29 -5
  179. package/node_modules/@sumi/plugin-sdk/dist/snapshot.js.map +1 -1
  180. package/node_modules/@sumi/plugin-sdk/dist/trace.d.ts +40 -2
  181. package/node_modules/@sumi/plugin-sdk/dist/trace.js +115 -25
  182. package/node_modules/@sumi/plugin-sdk/dist/trace.js.map +1 -1
  183. package/node_modules/@sumi/plugin-sdk/dist/validate.js +27 -3
  184. package/node_modules/@sumi/plugin-sdk/dist/validate.js.map +1 -1
  185. package/node_modules/@sumi/plugin-sdk/dist/yaml-text.d.ts +7 -0
  186. package/node_modules/@sumi/plugin-sdk/dist/yaml-text.js +116 -0
  187. package/node_modules/@sumi/plugin-sdk/dist/yaml-text.js.map +1 -0
  188. package/node_modules/@sumi/plugin-sdk/package.json +3 -2
  189. package/node_modules/@sumi/plugins-core/dist/agent-rules.d.ts +2 -4
  190. package/node_modules/@sumi/plugins-core/dist/agent-rules.js +12 -4
  191. package/node_modules/@sumi/plugins-core/dist/agent-rules.js.map +1 -1
  192. package/node_modules/@sumi/plugins-core/dist/baseline.d.ts +2 -1
  193. package/node_modules/@sumi/plugins-core/dist/baseline.js +12 -2
  194. package/node_modules/@sumi/plugins-core/dist/baseline.js.map +1 -1
  195. package/node_modules/@sumi/plugins-core/dist/change-impact.d.ts +11 -0
  196. package/node_modules/@sumi/plugins-core/dist/change-impact.js +116 -0
  197. package/node_modules/@sumi/plugins-core/dist/change-impact.js.map +1 -0
  198. package/node_modules/@sumi/plugins-core/dist/commands/adopt.js +7 -5
  199. package/node_modules/@sumi/plugins-core/dist/commands/adopt.js.map +1 -1
  200. package/node_modules/@sumi/plugins-core/dist/commands/agent-rules-before-edit.js +2 -3
  201. package/node_modules/@sumi/plugins-core/dist/commands/agent-rules-before-edit.js.map +1 -1
  202. package/node_modules/@sumi/plugins-core/dist/commands/agent-rules-prompt.js +2 -3
  203. package/node_modules/@sumi/plugins-core/dist/commands/agent-rules-prompt.js.map +1 -1
  204. package/node_modules/@sumi/plugins-core/dist/commands/context-impact.d.ts +1 -0
  205. package/node_modules/@sumi/plugins-core/dist/commands/context-impact.js +11 -0
  206. package/node_modules/@sumi/plugins-core/dist/commands/context-impact.js.map +1 -0
  207. package/node_modules/@sumi/plugins-core/dist/context-provider.d.ts +3 -0
  208. package/node_modules/@sumi/plugins-core/dist/context-provider.js +45 -0
  209. package/node_modules/@sumi/plugins-core/dist/context-provider.js.map +1 -0
  210. package/node_modules/@sumi/plugins-core/dist/plugins/coverage.js +112 -15
  211. package/node_modules/@sumi/plugins-core/dist/plugins/coverage.js.map +1 -1
  212. package/node_modules/@sumi/plugins-core/dist/plugins/test-affected.js +32 -5
  213. package/node_modules/@sumi/plugins-core/dist/plugins/test-affected.js.map +1 -1
  214. package/node_modules/@sumi/plugins-core/dist/vitest-runner.js +1 -0
  215. package/node_modules/@sumi/plugins-core/dist/vitest-runner.js.map +1 -1
  216. package/node_modules/@sumi/plugins-core/instructions/bugfix.md +4 -0
  217. package/node_modules/@sumi/plugins-core/instructions/feature.md +2 -0
  218. package/node_modules/@sumi/plugins-core/package.json +2 -2
  219. package/node_modules/@sumi/plugins-core/sumi-plugins.yaml +9 -0
  220. package/node_modules/@sumi/plugins-governance/assets/hook-bootstrap.cjs +167 -0
  221. package/node_modules/@sumi/plugins-governance/dist/boundary-hooks.d.ts +12 -0
  222. package/node_modules/@sumi/plugins-governance/dist/boundary-hooks.js +76 -0
  223. package/node_modules/@sumi/plugins-governance/dist/boundary-hooks.js.map +1 -0
  224. package/node_modules/@sumi/plugins-governance/dist/boundary.d.ts +42 -0
  225. package/node_modules/@sumi/plugins-governance/dist/boundary.js +206 -0
  226. package/node_modules/@sumi/plugins-governance/dist/boundary.js.map +1 -0
  227. package/node_modules/@sumi/plugins-governance/dist/checkout.d.ts +1 -0
  228. package/node_modules/@sumi/plugins-governance/dist/checkout.js +16 -6
  229. package/node_modules/@sumi/plugins-governance/dist/checkout.js.map +1 -1
  230. package/node_modules/@sumi/plugins-governance/dist/commands/boundary-after-edit.d.ts +1 -0
  231. package/node_modules/@sumi/plugins-governance/dist/commands/boundary-after-edit.js +14 -0
  232. package/node_modules/@sumi/plugins-governance/dist/commands/boundary-after-edit.js.map +1 -0
  233. package/node_modules/@sumi/plugins-governance/dist/commands/boundary-before-edit.d.ts +1 -0
  234. package/node_modules/@sumi/plugins-governance/dist/commands/boundary-before-edit.js +22 -0
  235. package/node_modules/@sumi/plugins-governance/dist/commands/boundary-before-edit.js.map +1 -0
  236. package/node_modules/@sumi/plugins-governance/dist/commands/boundary-prompt.d.ts +1 -0
  237. package/node_modules/@sumi/plugins-governance/dist/commands/boundary-prompt.js +12 -0
  238. package/node_modules/@sumi/plugins-governance/dist/commands/boundary-prompt.js.map +1 -0
  239. package/node_modules/@sumi/plugins-governance/dist/commands/boundary.d.ts +1 -0
  240. package/node_modules/@sumi/plugins-governance/dist/commands/boundary.js +48 -0
  241. package/node_modules/@sumi/plugins-governance/dist/commands/boundary.js.map +1 -0
  242. package/node_modules/@sumi/plugins-governance/dist/commands/context-state.d.ts +1 -0
  243. package/node_modules/@sumi/plugins-governance/dist/commands/context-state.js +4 -0
  244. package/node_modules/@sumi/plugins-governance/dist/commands/context-state.js.map +1 -0
  245. package/node_modules/@sumi/plugins-governance/dist/commands/gate.js +162 -24
  246. package/node_modules/@sumi/plugins-governance/dist/commands/gate.js.map +1 -1
  247. package/node_modules/@sumi/plugins-governance/dist/commands/guard.js +2 -2
  248. package/node_modules/@sumi/plugins-governance/dist/commands/guard.js.map +1 -1
  249. package/node_modules/@sumi/plugins-governance/dist/commands/pr-report-check.js +5 -2
  250. package/node_modules/@sumi/plugins-governance/dist/commands/pr-report-check.js.map +1 -1
  251. package/node_modules/@sumi/plugins-governance/dist/commands/pr-report.js +11 -2
  252. package/node_modules/@sumi/plugins-governance/dist/commands/pr-report.js.map +1 -1
  253. package/node_modules/@sumi/plugins-governance/dist/commands/resume-work.d.ts +1 -0
  254. package/node_modules/@sumi/plugins-governance/dist/commands/resume-work.js +6 -0
  255. package/node_modules/@sumi/plugins-governance/dist/commands/resume-work.js.map +1 -0
  256. package/node_modules/@sumi/plugins-governance/dist/commands/run-policy.d.ts +1 -0
  257. package/node_modules/@sumi/plugins-governance/dist/commands/run-policy.js +19 -0
  258. package/node_modules/@sumi/plugins-governance/dist/commands/run-policy.js.map +1 -0
  259. package/node_modules/@sumi/plugins-governance/dist/commands/stop-work.d.ts +1 -0
  260. package/node_modules/@sumi/plugins-governance/dist/commands/stop-work.js +12 -0
  261. package/node_modules/@sumi/plugins-governance/dist/commands/stop-work.js.map +1 -0
  262. package/node_modules/@sumi/plugins-governance/dist/commands/view.d.ts +1 -0
  263. package/node_modules/@sumi/plugins-governance/dist/commands/view.js +45 -0
  264. package/node_modules/@sumi/plugins-governance/dist/commands/view.js.map +1 -0
  265. package/node_modules/@sumi/plugins-governance/dist/context-provider.d.ts +2 -0
  266. package/node_modules/@sumi/plugins-governance/dist/context-provider.js +22 -0
  267. package/node_modules/@sumi/plugins-governance/dist/context-provider.js.map +1 -0
  268. package/node_modules/@sumi/plugins-governance/dist/gate-cache.js +11 -3
  269. package/node_modules/@sumi/plugins-governance/dist/gate-cache.js.map +1 -1
  270. package/node_modules/@sumi/plugins-governance/dist/guard.js +47 -26
  271. package/node_modules/@sumi/plugins-governance/dist/guard.js.map +1 -1
  272. package/node_modules/@sumi/plugins-governance/dist/human-stop.d.ts +4 -0
  273. package/node_modules/@sumi/plugins-governance/dist/human-stop.js +39 -0
  274. package/node_modules/@sumi/plugins-governance/dist/human-stop.js.map +1 -0
  275. package/node_modules/@sumi/plugins-governance/dist/index.d.ts +4 -1
  276. package/node_modules/@sumi/plugins-governance/dist/index.js +4 -1
  277. package/node_modules/@sumi/plugins-governance/dist/index.js.map +1 -1
  278. package/node_modules/@sumi/plugins-governance/dist/plugins/state-writable.d.ts +1 -0
  279. package/node_modules/@sumi/plugins-governance/dist/plugins/state-writable.js +4 -0
  280. package/node_modules/@sumi/plugins-governance/dist/plugins/state-writable.js.map +1 -0
  281. package/node_modules/@sumi/plugins-governance/dist/pr-report-compose.d.ts +1 -1
  282. package/node_modules/@sumi/plugins-governance/dist/pr-report-compose.js +6 -2
  283. package/node_modules/@sumi/plugins-governance/dist/pr-report-compose.js.map +1 -1
  284. package/node_modules/@sumi/plugins-governance/dist/pr-report-markers.d.ts +1 -0
  285. package/node_modules/@sumi/plugins-governance/dist/pr-report-markers.js +1 -0
  286. package/node_modules/@sumi/plugins-governance/dist/pr-report-markers.js.map +1 -1
  287. package/node_modules/@sumi/plugins-governance/dist/pr-report-sections.js +4 -1
  288. package/node_modules/@sumi/plugins-governance/dist/pr-report-sections.js.map +1 -1
  289. package/node_modules/@sumi/plugins-governance/dist/pr-report-status.d.ts +1 -1
  290. package/node_modules/@sumi/plugins-governance/dist/pr-report-status.js +22 -3
  291. package/node_modules/@sumi/plugins-governance/dist/pr-report-status.js.map +1 -1
  292. package/node_modules/@sumi/plugins-governance/dist/preflight.d.ts +14 -0
  293. package/node_modules/@sumi/plugins-governance/dist/preflight.js +110 -0
  294. package/node_modules/@sumi/plugins-governance/dist/preflight.js.map +1 -0
  295. package/node_modules/@sumi/plugins-governance/dist/protected.d.ts +1 -0
  296. package/node_modules/@sumi/plugins-governance/dist/protected.js +1 -0
  297. package/node_modules/@sumi/plugins-governance/dist/protected.js.map +1 -1
  298. package/node_modules/@sumi/plugins-governance/dist/report-view.d.ts +12 -0
  299. package/node_modules/@sumi/plugins-governance/dist/report-view.js +59 -0
  300. package/node_modules/@sumi/plugins-governance/dist/report-view.js.map +1 -0
  301. package/node_modules/@sumi/plugins-governance/dist/semantic.js +11 -2
  302. package/node_modules/@sumi/plugins-governance/dist/semantic.js.map +1 -1
  303. package/node_modules/@sumi/plugins-governance/dist/state-access.d.ts +3 -0
  304. package/node_modules/@sumi/plugins-governance/dist/state-access.js +35 -0
  305. package/node_modules/@sumi/plugins-governance/dist/state-access.js.map +1 -0
  306. package/node_modules/@sumi/plugins-governance/dist/state.js +1 -4
  307. package/node_modules/@sumi/plugins-governance/dist/state.js.map +1 -1
  308. package/node_modules/@sumi/plugins-governance/dist/upgrade-command.d.ts +1 -0
  309. package/node_modules/@sumi/plugins-governance/dist/upgrade-command.js +30 -0
  310. package/node_modules/@sumi/plugins-governance/dist/upgrade-command.js.map +1 -0
  311. package/node_modules/@sumi/plugins-governance/dist/view-page.d.ts +4 -0
  312. package/node_modules/@sumi/plugins-governance/dist/view-page.js +51 -0
  313. package/node_modules/@sumi/plugins-governance/dist/view-page.js.map +1 -0
  314. package/node_modules/@sumi/plugins-governance/instructions/boundary.md +35 -0
  315. package/node_modules/@sumi/plugins-governance/instructions/push.md +11 -8
  316. package/node_modules/@sumi/plugins-governance/package.json +6 -3
  317. package/node_modules/@sumi/plugins-governance/sumi-plugins.yaml +30 -1
  318. package/node_modules/@sumi/plugins-openspec/package.json +4 -4
  319. package/node_modules/@sumi/plugins-precedent/README.md +7 -5
  320. package/node_modules/@sumi/plugins-precedent/dist/after-edit-context.d.ts +12 -26
  321. package/node_modules/@sumi/plugins-precedent/dist/after-edit-context.js +90 -148
  322. package/node_modules/@sumi/plugins-precedent/dist/after-edit-context.js.map +1 -1
  323. package/node_modules/@sumi/plugins-precedent/dist/commands/after-edit-context.js +2 -3
  324. package/node_modules/@sumi/plugins-precedent/dist/commands/after-edit-context.js.map +1 -1
  325. package/node_modules/@sumi/plugins-precedent/dist/commands/before-edit-context.js +20 -9
  326. package/node_modules/@sumi/plugins-precedent/dist/commands/before-edit-context.js.map +1 -1
  327. package/node_modules/@sumi/plugins-precedent/dist/commands/context.js +2 -39
  328. package/node_modules/@sumi/plugins-precedent/dist/commands/context.js.map +1 -1
  329. package/node_modules/@sumi/plugins-precedent/dist/commands/impact-submit.js +2 -1
  330. package/node_modules/@sumi/plugins-precedent/dist/commands/impact-submit.js.map +1 -1
  331. package/node_modules/@sumi/plugins-precedent/dist/commands/on-prompt-context.js +4 -7
  332. package/node_modules/@sumi/plugins-precedent/dist/commands/on-prompt-context.js.map +1 -1
  333. package/node_modules/@sumi/plugins-precedent/dist/context-output.d.ts +65 -0
  334. package/node_modules/@sumi/plugins-precedent/dist/context-output.js +186 -0
  335. package/node_modules/@sumi/plugins-precedent/dist/context-output.js.map +1 -0
  336. package/node_modules/@sumi/plugins-precedent/dist/context-provider.d.ts +3 -0
  337. package/node_modules/@sumi/plugins-precedent/dist/context-provider.js +48 -0
  338. package/node_modules/@sumi/plugins-precedent/dist/context-provider.js.map +1 -0
  339. package/node_modules/@sumi/plugins-precedent/dist/impact-state.js +4 -6
  340. package/node_modules/@sumi/plugins-precedent/dist/impact-state.js.map +1 -1
  341. package/node_modules/@sumi/plugins-precedent/dist/impact.js +1 -2
  342. package/node_modules/@sumi/plugins-precedent/dist/impact.js.map +1 -1
  343. package/node_modules/@sumi/plugins-precedent/dist/index.d.ts +1 -0
  344. package/node_modules/@sumi/plugins-precedent/dist/index.js +1 -0
  345. package/node_modules/@sumi/plugins-precedent/dist/index.js.map +1 -1
  346. package/node_modules/@sumi/plugins-precedent/dist/model.d.ts +1 -0
  347. package/node_modules/@sumi/plugins-precedent/dist/model.js.map +1 -1
  348. package/node_modules/@sumi/plugins-precedent/dist/plugins/context-read.js +2 -1
  349. package/node_modules/@sumi/plugins-precedent/dist/plugins/context-read.js.map +1 -1
  350. package/node_modules/@sumi/plugins-precedent/package.json +3 -3
  351. package/node_modules/@sumi/plugins-precedent/sumi-plugins.yaml +5 -6
  352. package/node_modules/@sumi/plugins-review/README.md +17 -4
  353. package/node_modules/@sumi/plugins-review/dist/batch-request.d.ts +22 -0
  354. package/node_modules/@sumi/plugins-review/dist/batch-request.js +30 -0
  355. package/node_modules/@sumi/plugins-review/dist/batch-request.js.map +1 -0
  356. package/node_modules/@sumi/plugins-review/dist/claude-review-agent.d.ts +8 -0
  357. package/node_modules/@sumi/plugins-review/dist/claude-review-agent.js +51 -0
  358. package/node_modules/@sumi/plugins-review/dist/claude-review-agent.js.map +1 -0
  359. package/node_modules/@sumi/plugins-review/dist/command-hint.d.ts +7 -0
  360. package/node_modules/@sumi/plugins-review/dist/command-hint.js +21 -0
  361. package/node_modules/@sumi/plugins-review/dist/command-hint.js.map +1 -1
  362. package/node_modules/@sumi/plugins-review/dist/command-input.d.ts +3 -0
  363. package/node_modules/@sumi/plugins-review/dist/command-input.js +32 -0
  364. package/node_modules/@sumi/plugins-review/dist/command-input.js.map +1 -0
  365. package/node_modules/@sumi/plugins-review/dist/commands/context.js +2 -66
  366. package/node_modules/@sumi/plugins-review/dist/commands/context.js.map +1 -1
  367. package/node_modules/@sumi/plugins-review/dist/commands/host-model-hook.js +6 -6
  368. package/node_modules/@sumi/plugins-review/dist/commands/host-model-hook.js.map +1 -1
  369. package/node_modules/@sumi/plugins-review/dist/commands/model-recheck.js +40 -25
  370. package/node_modules/@sumi/plugins-review/dist/commands/model-recheck.js.map +1 -1
  371. package/node_modules/@sumi/plugins-review/dist/commands/preflight.d.ts +1 -0
  372. package/node_modules/@sumi/plugins-review/dist/commands/preflight.js +13 -0
  373. package/node_modules/@sumi/plugins-review/dist/commands/preflight.js.map +1 -0
  374. package/node_modules/@sumi/plugins-review/dist/commands/request-read.d.ts +1 -0
  375. package/node_modules/@sumi/plugins-review/dist/commands/request-read.js +6 -0
  376. package/node_modules/@sumi/plugins-review/dist/commands/request-read.js.map +1 -0
  377. package/node_modules/@sumi/plugins-review/dist/commands/review-batch.d.ts +1 -0
  378. package/node_modules/@sumi/plugins-review/dist/commands/review-batch.js +8 -0
  379. package/node_modules/@sumi/plugins-review/dist/commands/review-batch.js.map +1 -0
  380. package/node_modules/@sumi/plugins-review/dist/commands/startup-context.d.ts +1 -0
  381. package/node_modules/@sumi/plugins-review/dist/commands/startup-context.js +6 -0
  382. package/node_modules/@sumi/plugins-review/dist/commands/startup-context.js.map +1 -0
  383. package/node_modules/@sumi/plugins-review/dist/commands/stats.d.ts +1 -0
  384. package/node_modules/@sumi/plugins-review/dist/commands/stats.js +10 -0
  385. package/node_modules/@sumi/plugins-review/dist/commands/stats.js.map +1 -0
  386. package/node_modules/@sumi/plugins-review/dist/commands/submit.js +79 -32
  387. package/node_modules/@sumi/plugins-review/dist/commands/submit.js.map +1 -1
  388. package/node_modules/@sumi/plugins-review/dist/context-provider.d.ts +3 -0
  389. package/node_modules/@sumi/plugins-review/dist/context-provider.js +84 -0
  390. package/node_modules/@sumi/plugins-review/dist/context-provider.js.map +1 -0
  391. package/node_modules/@sumi/plugins-review/dist/convergence.d.ts +17 -0
  392. package/node_modules/@sumi/plugins-review/dist/convergence.js +114 -0
  393. package/node_modules/@sumi/plugins-review/dist/convergence.js.map +1 -0
  394. package/node_modules/@sumi/plugins-review/dist/cost-advice.d.ts +2 -0
  395. package/node_modules/@sumi/plugins-review/dist/cost-advice.js +35 -0
  396. package/node_modules/@sumi/plugins-review/dist/cost-advice.js.map +1 -0
  397. package/node_modules/@sumi/plugins-review/dist/dispatch.d.ts +38 -0
  398. package/node_modules/@sumi/plugins-review/dist/dispatch.js +235 -0
  399. package/node_modules/@sumi/plugins-review/dist/dispatch.js.map +1 -0
  400. package/node_modules/@sumi/plugins-review/dist/dispute.d.ts +4 -0
  401. package/node_modules/@sumi/plugins-review/dist/dispute.js +38 -4
  402. package/node_modules/@sumi/plugins-review/dist/dispute.js.map +1 -1
  403. package/node_modules/@sumi/plugins-review/dist/instructions.d.ts +1 -0
  404. package/node_modules/@sumi/plugins-review/dist/instructions.js +2 -0
  405. package/node_modules/@sumi/plugins-review/dist/instructions.js.map +1 -0
  406. package/node_modules/@sumi/plugins-review/dist/model-execution.d.ts +1 -0
  407. package/node_modules/@sumi/plugins-review/dist/model-execution.js +51 -46
  408. package/node_modules/@sumi/plugins-review/dist/model-execution.js.map +1 -1
  409. package/node_modules/@sumi/plugins-review/dist/plugins/dispatch.d.ts +1 -0
  410. package/node_modules/@sumi/plugins-review/dist/plugins/dispatch.js +41 -0
  411. package/node_modules/@sumi/plugins-review/dist/plugins/dispatch.js.map +1 -0
  412. package/node_modules/@sumi/plugins-review/dist/plugins/independent-recheck.js +62 -39
  413. package/node_modules/@sumi/plugins-review/dist/plugins/independent-recheck.js.map +1 -1
  414. package/node_modules/@sumi/plugins-review/dist/plugins/rubric.js +3 -326
  415. package/node_modules/@sumi/plugins-review/dist/plugins/rubric.js.map +1 -1
  416. package/node_modules/@sumi/plugins-review/dist/preflight.d.ts +18 -0
  417. package/node_modules/@sumi/plugins-review/dist/preflight.js +170 -0
  418. package/node_modules/@sumi/plugins-review/dist/preflight.js.map +1 -0
  419. package/node_modules/@sumi/plugins-review/dist/recheck-tickets.d.ts +26 -0
  420. package/node_modules/@sumi/plugins-review/dist/recheck-tickets.js +48 -0
  421. package/node_modules/@sumi/plugins-review/dist/recheck-tickets.js.map +1 -0
  422. package/node_modules/@sumi/plugins-review/dist/recheck.d.ts +16 -0
  423. package/node_modules/@sumi/plugins-review/dist/recheck.js +34 -9
  424. package/node_modules/@sumi/plugins-review/dist/recheck.js.map +1 -1
  425. package/node_modules/@sumi/plugins-review/dist/report.d.ts +5 -1
  426. package/node_modules/@sumi/plugins-review/dist/report.js +60 -6
  427. package/node_modules/@sumi/plugins-review/dist/report.js.map +1 -1
  428. package/node_modules/@sumi/plugins-review/dist/review-evidence.js +2 -2
  429. package/node_modules/@sumi/plugins-review/dist/review-evidence.js.map +1 -1
  430. package/node_modules/@sumi/plugins-review/dist/review.d.ts +62 -7
  431. package/node_modules/@sumi/plugins-review/dist/review.js +148 -38
  432. package/node_modules/@sumi/plugins-review/dist/review.js.map +1 -1
  433. package/node_modules/@sumi/plugins-review/dist/rubric-check.d.ts +4 -0
  434. package/node_modules/@sumi/plugins-review/dist/rubric-check.js +382 -0
  435. package/node_modules/@sumi/plugins-review/dist/rubric-check.js.map +1 -0
  436. package/node_modules/@sumi/plugins-review/dist/startup-context.d.ts +21 -0
  437. package/node_modules/@sumi/plugins-review/dist/startup-context.js +94 -0
  438. package/node_modules/@sumi/plugins-review/dist/startup-context.js.map +1 -0
  439. package/node_modules/@sumi/plugins-review/dist/stats.d.ts +19 -0
  440. package/node_modules/@sumi/plugins-review/dist/stats.js +99 -0
  441. package/node_modules/@sumi/plugins-review/dist/stats.js.map +1 -0
  442. package/node_modules/@sumi/plugins-review/dist/submission.js +46 -23
  443. package/node_modules/@sumi/plugins-review/dist/submission.js.map +1 -1
  444. package/node_modules/@sumi/plugins-review/dist/support-scope.d.ts +4 -0
  445. package/node_modules/@sumi/plugins-review/dist/support-scope.js +9 -0
  446. package/node_modules/@sumi/plugins-review/dist/support-scope.js.map +1 -0
  447. package/node_modules/@sumi/plugins-review/dist/tickets.d.ts +12 -0
  448. package/node_modules/@sumi/plugins-review/dist/tickets.js +98 -0
  449. package/node_modules/@sumi/plugins-review/dist/tickets.js.map +1 -0
  450. package/node_modules/@sumi/plugins-review/dist/upgrade-flow-plan.js +34 -9
  451. package/node_modules/@sumi/plugins-review/dist/upgrade-flow-plan.js.map +1 -1
  452. package/node_modules/@sumi/plugins-review/dist/upgrade-flow-render.js +2 -1
  453. package/node_modules/@sumi/plugins-review/dist/upgrade-flow-render.js.map +1 -1
  454. package/node_modules/@sumi/plugins-review/dist/upgrade.d.ts +2 -0
  455. package/node_modules/@sumi/plugins-review/dist/upgrade.js +12 -80
  456. package/node_modules/@sumi/plugins-review/dist/upgrade.js.map +1 -1
  457. package/node_modules/@sumi/plugins-review/package.json +6 -5
  458. package/node_modules/@sumi/plugins-review/sumi-plugins.yaml +22 -1
  459. package/package.json +10 -10
  460. package/node_modules/@sumi/create/template/control/rubrics/architecture.yaml +0 -15
  461. package/node_modules/@sumi/create/template/control/rubrics/business-impact.yaml +0 -6
  462. package/node_modules/@sumi/create/template/control/rubrics/device-acceptance.yaml +0 -10
  463. package/node_modules/@sumi/create/template/control/rubrics/domain.yaml +0 -9
  464. package/node_modules/@sumi/create/template/init/control/rubrics/architecture.yaml +0 -15
  465. package/node_modules/@sumi/create/template/init/control/rubrics/business-impact.yaml +0 -6
  466. package/node_modules/@sumi/plugins-precedent/dist/commands/session-start-context.js +0 -6
  467. package/node_modules/@sumi/plugins-precedent/dist/commands/session-start-context.js.map +0 -1
  468. /package/{node_modules/@sumi/plugins-precedent/dist/commands/session-start-context.d.ts → dist/context-providers.d.ts} +0 -0
@@ -1,10 +1,174 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { spawn } from 'node:child_process';
2
3
  import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
3
4
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
4
5
  import { loadConfig, loadRegistry, resolveArgv } from '@sumi/kernel';
5
- import { cleanEnv, parseAfterEditResult, recordTrace, spawnCommandSync } from '@sumi/plugin-sdk';
6
+ import { cleanEnv, isContextScope, saveContextScope, contextSession, firstHostString, hostEvent, parseAfterEditResult, readHookInput, recordDelivery, recordTrace, resetContextSession, spawnCommandSync, traceFields, } from '@sumi/plugin-sdk';
6
7
  import { registerCommand, requireRoot } from './cli.js';
7
- import { routeToOwners } from './hook-routing.js';
8
+ import { declaredHooks } from './adapters.js';
9
+ import { acknowledgeRouted, editTool, ROUTED_ENV, routeToOwners, withReceipt, } from './hook-routing.js';
10
+ import { inheritedSubagentHistory } from './subagent-history.js';
11
+ import { clearCompaction, markCompaction, takeCompaction } from './compaction-marker.js';
12
+ import { HOST_ADAPTERS, parseBeforeToolResponse } from './host-adapters.js';
13
+ import { writeHookOutput } from './hook-output.js';
14
+ import { stopHintMessages } from './stop-hint.js';
15
+ /** 约束正文几乎都是中文,上下文接近预算时也要远低于这个上限。 */
16
+ const MAX_COMMAND_OUTPUT = 1024 * 1024;
17
+ function runHookCommand(root, input, name, registry, timeout) {
18
+ const command = registry.commands.get(name);
19
+ if (!command)
20
+ return Promise.resolve({ code: null, stdout: '', stderr: `hook 命令 ${name} 未注册` });
21
+ const [bin, ...argv] = resolveArgv(command.argv, command.dir);
22
+ return new Promise((resolveResult) => {
23
+ const child = spawn(bin, argv, {
24
+ cwd: root,
25
+ env: { ...cleanEnv(), SUMI_ROOT: root, SUMI_BIN: process.env.SUMI_BIN ?? process.argv[1] ?? '' },
26
+ windowsHide: true,
27
+ stdio: ['pipe', 'pipe', 'pipe'],
28
+ });
29
+ let stdout = '';
30
+ let stderr = '';
31
+ let truncated = false;
32
+ let settled = false;
33
+ const finish = (code, diagnostic = '') => {
34
+ if (settled)
35
+ return;
36
+ settled = true;
37
+ if (timer)
38
+ clearTimeout(timer);
39
+ const notice = truncated ? `hook 命令 ${name} 的输出超过上限,已截断` : '';
40
+ resolveResult({ code, stdout, stderr: [stderr, diagnostic, notice].filter(Boolean).join('\n') });
41
+ };
42
+ const capped = (text, chunk) => {
43
+ truncated ||= text.length + chunk.length > MAX_COMMAND_OUTPUT;
44
+ return (text + chunk).slice(0, MAX_COMMAND_OUTPUT);
45
+ };
46
+ const timer = timeout === undefined
47
+ ? null
48
+ : setTimeout(() => {
49
+ child.kill();
50
+ finish(null, 'hook 命令超时');
51
+ }, timeout);
52
+ // 按流解码:多字节字符可能落在两个数据块之间,逐块转字符串会变成乱码
53
+ child.stdout.setEncoding('utf8').on('data', (chunk) => {
54
+ stdout = capped(stdout, chunk);
55
+ });
56
+ child.stderr.setEncoding('utf8').on('data', (chunk) => {
57
+ stderr = capped(stderr, chunk);
58
+ });
59
+ child.on('error', (error) => finish(null, error.message));
60
+ child.on('close', (code) => finish(code));
61
+ child.stdin.on('error', () => { });
62
+ child.stdin.end(input);
63
+ });
64
+ }
65
+ /** 插件命令并发运行,结果按声明顺序合并;宿主只见一个原生响应。 */
66
+ export async function runBeforeToolChecks(root, input, host) {
67
+ const config = loadConfig(root);
68
+ const registry = loadRegistry(root, config);
69
+ const event = HOST_ADAPTERS[host].normalizeInput('PreToolUse', input);
70
+ // 没有工具名说明负载损坏:不能当作无关工具放行,要让闭合命令判断
71
+ const ignored = event.tool !== null && event.tool !== 'Bash' && !editTool(event.tool);
72
+ if (ignored)
73
+ return { contexts: [], ownContexts: [], denied: null, diagnostics: [], deliveries: [], evidence: {}, receipts: [] };
74
+ const hooks = declaredHooks(registry, config).beforeTool.filter((hook) => hook.tools === 'all' || event.tool === null || editTool(event.tool));
75
+ const results = await Promise.all(hooks.map((hook) => runHookCommand(root, event.pluginInput, hook.command, registry, 10000)));
76
+ const contexts = [];
77
+ const diagnostics = [];
78
+ const denials = [];
79
+ const deliveries = [];
80
+ const evidence = {};
81
+ results.forEach((result, index) => {
82
+ const hook = hooks[index];
83
+ const reason = result.stderr.trim() || `前置命令 ${hook.command} 未正常完成`;
84
+ if (result.code === 2)
85
+ denials.push(reason);
86
+ else if (result.code !== 0 && hook.failure === 'closed')
87
+ denials.push(reason);
88
+ else if (result.code !== 0)
89
+ diagnostics.push(reason);
90
+ if (result.code !== 0 || !result.stdout.trim())
91
+ return;
92
+ try {
93
+ const native = parseBeforeToolResponse(result.stdout, reason);
94
+ if (native.context)
95
+ contexts.push(native.context);
96
+ const parsed = parseAfterEditResult(result.stdout);
97
+ if (parsed) {
98
+ if (parsed.warning)
99
+ diagnostics.push(parsed.warning);
100
+ mergeEvidence(evidence, parsed);
101
+ const command = registry.commands.get(hook.command);
102
+ if (command && parsed.deliveryKeys?.length) {
103
+ const [bin, ...argv] = resolveArgv(command.argv, command.dir);
104
+ deliveries.push({
105
+ argv: [bin, ...argv],
106
+ dir: command.dir,
107
+ keys: parsed.deliveryKeys,
108
+ scopes: parsed.deliveryScopes,
109
+ records: parsed.deliveryRecords,
110
+ });
111
+ }
112
+ }
113
+ if (native.denied)
114
+ denials.push(native.denied);
115
+ }
116
+ catch {
117
+ if (hook.failure === 'closed')
118
+ denials.push(`前置命令 ${hook.command} 输出无效 JSON`);
119
+ else
120
+ diagnostics.push(`前置命令 ${hook.command} 输出无效 JSON`);
121
+ }
122
+ });
123
+ const ownContexts = [...contexts];
124
+ const routed = denials.length
125
+ ? { denied: false, stderr: [], stdout: [], receipts: [] }
126
+ : routeToOwners(root, ['hook', 'before-tool', host], event.pluginInput);
127
+ if (routed.denied)
128
+ denials.push(...routed.stderr);
129
+ else
130
+ diagnostics.push(...routed.stderr);
131
+ for (const output of routed.stdout) {
132
+ try {
133
+ const value = JSON.parse(output);
134
+ const context = firstHostString([value.hookSpecificOutput?.additionalContext, value.additional_context]);
135
+ if (context && !routed.denied)
136
+ contexts.push(context);
137
+ }
138
+ catch {
139
+ diagnostics.push('转交的前置 hook 输出无效 JSON');
140
+ }
141
+ }
142
+ return {
143
+ contexts,
144
+ ownContexts,
145
+ denied: denials.length ? denials.join('\n') : null,
146
+ diagnostics,
147
+ deliveries,
148
+ evidence,
149
+ receipts: routed.receipts,
150
+ };
151
+ }
152
+ function acknowledgeBeforeTool(root, input, decision) {
153
+ for (const delivery of decision.deliveries) {
154
+ spawnCommandSync(delivery.argv[0], delivery.argv.slice(1), {
155
+ cwd: root,
156
+ input: JSON.stringify({ originalInput: input, keys: delivery.keys, scopes: delivery.scopes, records: delivery.records }),
157
+ encoding: 'utf8',
158
+ env: { ...cleanEnv(), SUMI_ROOT: root, SUMI_BEFORE_EDIT_DELIVERED: '1' },
159
+ windowsHide: true,
160
+ });
161
+ }
162
+ }
163
+ function mergeEvidence(evidence, result) {
164
+ const items = result.items ?? (result.deliveryKeys ?? []).map((key) => ({ key }));
165
+ if (items.length)
166
+ evidence.items = [...(evidence.items ?? []), ...items];
167
+ if (result.skipped)
168
+ evidence.skipped = [...(evidence.skipped ?? []), ...result.skipped];
169
+ if (result.paths)
170
+ evidence.paths = [...new Set([...(evidence.paths ?? []), ...result.paths])];
171
+ }
8
172
  /** Bash 负载只交给声明处理 shell 写入的插件。 */
9
173
  function afterEditCommands(registry, shell = false) {
10
174
  const commands = [];
@@ -20,84 +184,78 @@ function afterEditCommands(registry, shell = false) {
20
184
  return commands;
21
185
  }
22
186
  /** 提示词阶段只接受插件成功返回的上下文;失败不影响用户输入。 */
23
- export function runPromptChecks(root, input, registry = loadRegistry(root, loadConfig(root))) {
187
+ export async function runPromptChecks(root, input, registry) {
188
+ const config = loadConfig(root);
189
+ const activeRegistry = registry ?? loadRegistry(root, config);
190
+ const names = declaredHooks(activeRegistry, config).onPrompt;
191
+ const results = await Promise.all(names.map((name) => runHookCommand(root, input, name, activeRegistry, 10000)));
24
192
  const contexts = [];
25
193
  const deliveries = [];
26
- for (const { decl } of registry.plugins.values()) {
27
- const name = typeof decl.hooks?.agent?.onPrompt === 'string' ? decl.hooks.agent.onPrompt : decl.hooks?.agent?.onPrompt?.command;
28
- if (!name)
29
- continue;
30
- const command = registry.commands.get(name);
31
- if (!command)
32
- continue;
33
- const [bin, ...argv] = resolveArgv(command.argv, command.dir);
34
- const child = spawnCommandSync(bin, argv, {
35
- cwd: root,
36
- input,
37
- encoding: 'utf8',
38
- timeout: 10000,
39
- env: { ...cleanEnv(), SUMI_ROOT: root, SUMI_BIN: process.env.SUMI_BIN ?? process.argv[1] ?? '' },
40
- windowsHide: true,
41
- });
42
- if (child.status !== 0 || child.error)
43
- continue;
44
- const result = parseAfterEditResult(child.stdout ?? '');
45
- if (result) {
46
- contexts.push(result.additionalContext);
47
- if (result.deliveryKeys?.length)
48
- deliveries.push({ argv: [bin, ...argv], dir: command.dir, keys: result.deliveryKeys });
194
+ const evidence = {};
195
+ results.forEach((child, index) => {
196
+ if (child.code !== 0)
197
+ return;
198
+ const result = parseAfterEditResult(child.stdout);
199
+ if (!result)
200
+ return;
201
+ contexts.push(result.additionalContext);
202
+ mergeEvidence(evidence, result);
203
+ const command = activeRegistry.commands.get(names[index]);
204
+ if (command && result.deliveryKeys?.length) {
205
+ const [bin, ...argv] = resolveArgv(command.argv, command.dir);
206
+ deliveries.push({ argv: [bin, ...argv], dir: command.dir, keys: result.deliveryKeys, records: result.deliveryRecords });
49
207
  }
50
- }
51
- return { contexts, deliveries };
208
+ });
209
+ return { contexts, deliveries, evidence };
52
210
  }
53
211
  export function acknowledgePrompt(root, input, decision) {
54
212
  for (const delivery of decision.deliveries ?? []) {
55
213
  spawnCommandSync(delivery.argv[0], delivery.argv.slice(1), {
56
214
  cwd: root,
57
- input: JSON.stringify({ originalInput: input, keys: delivery.keys }),
215
+ input: JSON.stringify({ originalInput: input, keys: delivery.keys, records: delivery.records }),
58
216
  encoding: 'utf8',
59
217
  env: { ...cleanEnv(), SUMI_ROOT: root, SUMI_PROMPT_DELIVERED: '1' },
60
218
  windowsHide: true,
61
219
  });
62
220
  }
63
221
  }
64
- /** 插件成功结果可以补充上下文;只有显式退出码 2 才转为编辑后阻断反馈。 */
65
- export function runAfterEditChecks(root, input, registry = loadRegistry(root, loadConfig(root))) {
222
+ /** 编辑后插件并发执行;显式退出码 2 阻断。 */
223
+ export async function runAfterEditChecks(root, input) {
224
+ const registry = loadRegistry(root, loadConfig(root));
225
+ const commands = afterEditCommands(registry, hostEvent(input)?.tool === 'Bash');
226
+ const results = await Promise.all(commands.map((command) => runHookCommand(root, input, command.name, registry)));
66
227
  const contexts = [];
67
228
  const deliveries = [];
229
+ const evidence = {};
68
230
  const errors = [];
69
231
  let code = 0;
70
- for (const command of afterEditCommands(registry, toolName(input) === 'Bash')) {
71
- const [bin, ...argv] = resolveArgv(command.argv, command.dir);
72
- const child = spawnCommandSync(bin, argv, {
73
- cwd: root,
74
- input,
75
- encoding: 'utf8',
76
- env: { ...cleanEnv(), SUMI_ROOT: root, SUMI_BIN: process.env.SUMI_BIN ?? process.argv[1] ?? '' },
77
- windowsHide: true,
78
- });
79
- if (child.status !== 0) {
80
- const detail = child.stderr || child.error?.message || `编辑后命令 ${command.name} 被信号终止或未正常退出`;
81
- errors.push(detail);
82
- if (child.status === 2)
232
+ results.forEach((child, index) => {
233
+ const command = commands[index];
234
+ if (child.code !== 0) {
235
+ errors.push(child.stderr || `编辑后命令 ${command.name} 被信号终止或未正常退出`);
236
+ if (child.code === 2)
83
237
  code = 2;
84
- else if (code !== 2 && code === 0)
85
- code = child.status ?? 1;
86
- continue;
238
+ else if (code === 0)
239
+ code = child.code ?? 1;
240
+ return;
87
241
  }
88
- const result = parseAfterEditResult(child.stdout ?? '');
89
- if (result) {
90
- contexts.push(result.additionalContext);
91
- if (result.deliveryKeys?.length)
92
- deliveries.push({ argv: [bin, ...argv], dir: command.dir, keys: result.deliveryKeys });
242
+ const result = parseAfterEditResult(child.stdout);
243
+ if (!result)
244
+ return;
245
+ contexts.push(result.additionalContext);
246
+ mergeEvidence(evidence, result);
247
+ if (result.deliveryKeys?.length) {
248
+ const [bin, ...argv] = resolveArgv(command.argv, command.dir);
249
+ deliveries.push({ argv: [bin, ...argv], dir: command.dir, keys: result.deliveryKeys, records: result.deliveryRecords });
93
250
  }
94
- }
95
- const decision = {
251
+ });
252
+ return {
96
253
  code,
97
254
  contexts,
98
255
  stderr: errors.reduce((all, detail) => `${all}${all && !all.endsWith('\n') ? '\n' : ''}${detail}`, ''),
256
+ ...(deliveries.length ? { deliveries } : {}),
257
+ ...(Object.keys(evidence).length ? { evidence } : {}),
99
258
  };
100
- return deliveries.length ? { ...decision, deliveries } : decision;
101
259
  }
102
260
  export function renderAfterEditResponse(agent, decision) {
103
261
  if (decision.code !== 0) {
@@ -108,20 +266,17 @@ export function renderAfterEditResponse(agent, decision) {
108
266
  stderr: context ? `${decision.stderr}${decision.stderr.endsWith('\n') ? '' : '\n'}${context}` : decision.stderr,
109
267
  };
110
268
  }
111
- if (!decision.contexts.length || agent === 'cursor')
269
+ if (!decision.contexts.length)
112
270
  return { code: 0, stdout: '', stderr: '' };
113
- return {
114
- code: 0,
115
- stdout: JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: decision.contexts.join('\n\n') } }),
116
- stderr: '',
117
- };
271
+ const event = agent === 'cursor' ? 'postToolUse' : 'PostToolUse';
272
+ return { code: 0, stdout: HOST_ADAPTERS[agent].formatOutput(event, { contexts: decision.contexts }), stderr: '' };
118
273
  }
119
274
  /** 只有输出已交给适配层,才通知插件记录本次实际送达的键。 */
120
275
  export function acknowledgeAfterEdit(root, input, decision) {
121
276
  for (const delivery of decision.deliveries ?? []) {
122
277
  spawnCommandSync(delivery.argv[0], delivery.argv.slice(1), {
123
278
  cwd: root,
124
- input: JSON.stringify({ originalInput: input, keys: delivery.keys }),
279
+ input: JSON.stringify({ originalInput: input, keys: delivery.keys, records: delivery.records }),
125
280
  encoding: 'utf8',
126
281
  env: { ...cleanEnv(), SUMI_ROOT: root, SUMI_AFTER_EDIT_DELIVERED: '1' },
127
282
  windowsHide: true,
@@ -142,31 +297,24 @@ function stopCommands(registry) {
142
297
  }
143
298
  return commands;
144
299
  }
145
- /** 依次运行插件停止检查;仅显式退出码 2 请求阻断,命令故障作为诊断。 */
146
- export function runStopChecks(root, input, registry = loadRegistry(root, loadConfig(root))) {
300
+ /** 停止检查并发运行;没有固定超时,显式退出码 2 阻断。 */
301
+ export async function runStopChecks(root, input) {
302
+ const registry = loadRegistry(root, loadConfig(root));
303
+ const commands = stopCommands(registry);
304
+ const results = await Promise.all(commands.map((command) => runHookCommand(root, input, command.name, registry)));
147
305
  const reasons = [];
148
306
  const warnings = [];
149
- for (const command of stopCommands(registry)) {
150
- const [bin, ...argv] = resolveArgv(command.argv, command.dir);
151
- const child = spawnCommandSync(bin, argv, {
152
- cwd: root,
153
- input,
154
- encoding: 'utf8',
155
- env: { ...cleanEnv(), SUMI_ROOT: root, SUMI_BIN: process.env.SUMI_BIN ?? process.argv[1] ?? '' },
156
- windowsHide: true,
157
- });
158
- const detail = `${child.stderr ?? ''}${child.stdout ?? ''}`.trim();
159
- if (child.status === 0) {
307
+ results.forEach((child, index) => {
308
+ const detail = `${child.stderr}${child.stdout}`.trim();
309
+ if (child.code === 0) {
160
310
  if (detail)
161
311
  warnings.push(detail);
162
312
  }
163
- else if (child.status === 2) {
164
- reasons.push(detail || `停止检查 ${command.name} 请求继续处理`);
165
- }
166
- else {
167
- warnings.push(detail || `停止检查 ${command.name} 无法完成(退出码 ${child.status ?? '未知'})`);
168
- }
169
- }
313
+ else if (child.code === 2)
314
+ reasons.push(detail || `停止检查 ${commands[index].name} 请求继续处理`);
315
+ else
316
+ warnings.push(detail || `停止检查 ${commands[index].name} 无法完成(退出码 ${child.code ?? '未知'})`);
317
+ });
170
318
  return { blocked: reasons.length > 0, reasons, ...(warnings.length ? { warnings } : {}) };
171
319
  }
172
320
  function stopPayload(input) {
@@ -183,7 +331,8 @@ function retryFile(root, agent, session) {
183
331
  const common = spawnCommandSync('git', ['rev-parse', '--git-common-dir'], { cwd: root, encoding: 'utf8', windowsHide: true });
184
332
  const oid = head.stdout?.trim();
185
333
  const dir = common.stdout?.trim();
186
- if (head.status !== 0 || common.status !== 0 || !oid || !/^[0-9a-f]{40,64}$/i.test(oid) || !dir)
334
+ const validHead = head.status === 0 && Boolean(oid) && /^[0-9a-f]{40,64}$/i.test(oid ?? '');
335
+ if (!validHead || common.status !== 0 || !dir)
187
336
  return null;
188
337
  const key = createHash('sha256')
189
338
  .update(JSON.stringify([agent, session, oid.toLowerCase()]))
@@ -191,14 +340,14 @@ function retryFile(root, agent, session) {
191
340
  return join(resolve(root, dir), 'sumi', 'agent-stop-retries', key);
192
341
  }
193
342
  /** 跨进程 Stop 续跑熔断:稳定会话和同一 HEAD 最多阻断一次。 */
194
- export function runAgentStop(root, agent, input) {
343
+ export async function runAgentStop(root, agent, input, checks) {
195
344
  const payload = stopPayload(input);
196
345
  if (payload?.stop_hook_active === true || (typeof payload?.loop_count === 'number' && payload.loop_count > 0)) {
197
346
  return { blocked: false, reasons: [] };
198
347
  }
199
- const session = [payload?.session_id, payload?.thread_id, payload?.conversation_id].find((value) => typeof value === 'string' && value.length > 0 && value.length <= 512);
348
+ const session = firstHostString([payload?.session_id, payload?.thread_id, payload?.conversation_id], 512);
200
349
  const file = session ? retryFile(root, agent, session) : null;
201
- const decision = runStopChecks(root, input);
350
+ const decision = checks ?? (await runStopChecks(root, input));
202
351
  if (!decision.blocked)
203
352
  return decision;
204
353
  if (file && existsSync(file)) {
@@ -238,119 +387,352 @@ export function runAgentStop(root, agent, input) {
238
387
  }
239
388
  /** 把策略中立的阻断结论转换为各工具的原生 Stop 响应。 */
240
389
  export function renderStopResponse(agent, decision) {
241
- const reason = decision.reasons.join('\n\n');
242
- if (agent === 'cursor') {
243
- return { code: 0, stdout: JSON.stringify(decision.blocked ? { followup_message: reason } : {}), stderr: '' };
390
+ const denied = decision.blocked ? decision.reasons.join('\n\n') : undefined;
391
+ const warning = decision.warnings?.length ? `Sumi Stop 提醒:${decision.warnings.join('\n')}` : undefined;
392
+ return { code: 0, stdout: HOST_ADAPTERS[agent].formatOutput(agent === 'cursor' ? 'stop' : 'Stop', { denied, warning }), stderr: '' };
393
+ }
394
+ const NEW_EVENTS = {
395
+ 'before-tool': { claude: 'PreToolUse', codex: 'PreToolUse', cursor: 'preToolUse' },
396
+ 'after-tool': { claude: 'PostToolUse', codex: 'PostToolUse', cursor: 'postToolUse' },
397
+ 'session-start': { claude: 'SessionStart', codex: 'SessionStart', cursor: 'sessionStart' },
398
+ 'subagent-start': { claude: 'SubagentStart', codex: 'SubagentStart', cursor: 'subagentStart' },
399
+ 'post-compact': { claude: 'PostCompact', codex: 'PostCompact', cursor: 'postCompact' },
400
+ 'model-switch': { claude: 'PostModelSwitch', codex: 'PostModelSwitch', cursor: 'postModelSwitch' },
401
+ 'user-prompt': { claude: 'UserPromptSubmit', codex: 'UserPromptSubmit', cursor: 'beforeSubmitPrompt' },
402
+ stop: { claude: 'Stop', codex: 'Stop', cursor: 'stop' },
403
+ };
404
+ const HOOK_OPERATIONS = [
405
+ 'agent-stop',
406
+ 'agent-after-edit',
407
+ 'agent-after-read',
408
+ 'agent-user-prompt',
409
+ 'agent-session-start',
410
+ 'agent-subagent-start',
411
+ 'context-before-edit',
412
+ ...Object.keys(NEW_EVENTS),
413
+ ];
414
+ const HOOK_USAGE = `sumi hook <${HOOK_OPERATIONS.join('|')}> <claude|codex|cursor>`;
415
+ function recordContexts(ctx, channel, decision) {
416
+ if (!decision.contexts.length)
417
+ return;
418
+ recordDelivery(ctx.root, ctx.raw, {
419
+ channel,
420
+ method: 'additional-context',
421
+ content: decision.contexts.join('\n\n'),
422
+ host: ctx.host,
423
+ ...decision.evidence,
424
+ });
425
+ }
426
+ async function compactContext(ctx) {
427
+ const { root, raw, host, normalized } = ctx;
428
+ if (host !== 'codex' || !normalized.session)
429
+ return null;
430
+ if (!takeCompaction(root, normalized.session, normalized.agentId))
431
+ return null;
432
+ const session = contextSession(raw);
433
+ if (session)
434
+ resetContextSession(root, session);
435
+ return runPromptChecks(root, normalized.pluginInput);
436
+ }
437
+ async function writeOutcome(ctx, output, pending) {
438
+ try {
439
+ await writeHookOutput(ctx.io, output);
440
+ }
441
+ catch (error) {
442
+ if (pending && ctx.normalized.session)
443
+ markCompaction(ctx.root, ctx.normalized.session, ctx.normalized.agentId);
444
+ throw error;
244
445
  }
245
- const warning = decision.warnings?.length ? { systemMessage: `Sumi Stop 提醒:${decision.warnings.join('\n')}` } : {};
246
- return { code: 0, stdout: JSON.stringify(decision.blocked ? { decision: 'block', reason, ...warning } : warning), stderr: '' };
247
446
  }
248
- async function readStdin() {
249
- const chunks = [];
250
- for await (const chunk of process.stdin)
251
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
252
- return Buffer.concat(chunks).toString('utf8');
447
+ async function runBeforeTool(ctx) {
448
+ const decision = await runBeforeToolChecks(ctx.root, ctx.raw, ctx.host);
449
+ for (const diagnostic of decision.diagnostics)
450
+ ctx.io.err(diagnostic);
451
+ const routedChild = process.env[ROUTED_ENV] === '1';
452
+ if (decision.denied) {
453
+ await writeHookOutput(ctx.io, ctx.adapter.formatOutput(ctx.event, { denied: decision.denied }));
454
+ ctx.io.err(decision.denied);
455
+ // 转交子进程靠退出码把拒绝交回发起方,由发起方按宿主回应
456
+ return routedChild ? 2 : ctx.adapter.denyExitCode;
457
+ }
458
+ const pending = ctx.host === 'cursor' || routedChild ? null : await compactContext(ctx);
459
+ const contexts = [...decision.contexts, ...(pending?.contexts ?? [])];
460
+ const output = ctx.adapter.formatOutput(ctx.event, { contexts });
461
+ // Cursor 的 preToolUse 仅拒绝时能给代理消息,上下文留给 postToolUse,这里不算送达。
462
+ const delivered = ctx.host !== 'cursor' && decision.ownContexts.length > 0;
463
+ if (routedChild) {
464
+ const receipt = { kind: 'before', channel: 'before-edit', contexts: decision.ownContexts, deliveries: decision.deliveries };
465
+ await writeHookOutput(ctx.io, delivered ? withReceipt(output, { ...receipt, evidence: decision.evidence }) : output);
466
+ return 0;
467
+ }
468
+ await writeOutcome(ctx, output, pending);
469
+ if (delivered) {
470
+ recordContexts(ctx, 'before-edit', { contexts: decision.ownContexts, evidence: decision.evidence });
471
+ acknowledgeBeforeTool(ctx.root, ctx.raw, decision);
472
+ }
473
+ if (pending?.contexts.length) {
474
+ recordContexts(ctx, 'compact', pending);
475
+ acknowledgePrompt(ctx.root, ctx.raw, pending);
476
+ }
477
+ acknowledgeRouted(decision.receipts);
478
+ return 0;
253
479
  }
254
- registerCommand('hook', '运行工具适配 hook:sumi hook <agent-stop|agent-after-edit|agent-after-read|agent-user-prompt> <claude|codex|cursor>', async (args, io, root) => {
255
- const operation = args.positionals[0];
256
- if (!['agent-stop', 'agent-after-edit', 'agent-after-read', 'agent-user-prompt'].includes(operation ?? '') ||
257
- !['claude', 'codex', 'cursor'].includes(args.positionals[1] ?? '')) {
258
- io.err('用法:sumi hook <agent-stop|agent-after-edit|agent-after-read|agent-user-prompt> <claude|codex|cursor>');
259
- return 3;
480
+ async function selectContext(ctx, names, registry) {
481
+ const choices = await Promise.all(names.map((name) => runHookCommand(ctx.root, ctx.normalized.pluginInput, name, registry, 10_000)));
482
+ const selected = choices.flatMap((child) => {
483
+ if (child.code !== 0)
484
+ return [];
485
+ try {
486
+ const value = JSON.parse(child.stdout);
487
+ if (value.contextScope !== undefined && !isContextScope(value.contextScope))
488
+ return [];
489
+ return value.exclusive === true && typeof value.additionalContext === 'string'
490
+ ? [{ context: value.additionalContext, scope: isContextScope(value.contextScope) ? value.contextScope : undefined }]
491
+ : [];
492
+ }
493
+ catch {
494
+ return [];
495
+ }
496
+ });
497
+ return selected.length === 1 ? selected[0] : undefined;
498
+ }
499
+ function acknowledgeSelectedContext(ctx, choice, channel, merge = false) {
500
+ const session = contextSession(ctx.raw);
501
+ if (session)
502
+ saveContextScope(ctx.root, session, choice.scope, { merge });
503
+ if (choice.context)
504
+ recordContexts(ctx, channel, { contexts: [choice.context] });
505
+ }
506
+ async function runStart(ctx, subagent) {
507
+ const { root, raw, host, normalized } = ctx;
508
+ if (host === 'cursor' && subagent)
509
+ return 0;
510
+ if (subagent) {
511
+ const registry = loadRegistry(root, loadConfig(root));
512
+ const names = [...registry.plugins.values()].flatMap(({ decl }) => decl.hooks?.agent?.subagentContext ?? []);
513
+ const choice = await selectContext(ctx, names, registry);
514
+ if (choice) {
515
+ await writeHookOutput(ctx.io, ctx.adapter.formatOutput(ctx.event, { contexts: choice.context ? [choice.context] : [] }));
516
+ acknowledgeSelectedContext(ctx, choice, 'subagent-start');
517
+ return 0;
518
+ }
260
519
  }
261
- const agent = args.positionals[1];
262
- const input = await readStdin();
263
- const projectRoot = requireRoot(root);
264
- if (operation === 'agent-after-read') {
265
- const read = agentReadOf(projectRoot, input);
520
+ const sessionScope = contextSession(raw);
521
+ if (sessionScope)
522
+ saveContextScope(root, sessionScope);
523
+ if (!subagent) {
524
+ const config = loadConfig(root);
525
+ const registry = loadRegistry(root, config);
526
+ const names = declaredHooks(registry, config).sessionStart;
527
+ await Promise.all(names.map((name) => runHookCommand(root, normalized.pluginInput, name, registry)));
528
+ }
529
+ if (host === 'codex' && !subagent && normalized.session)
530
+ clearCompaction(root, normalized.session, normalized.agentId);
531
+ if (normalized.source === 'resume')
532
+ return 0;
533
+ if (host === 'codex' && subagent && inheritedSubagentHistory(normalized.transcript))
534
+ return 0;
535
+ const session = contextSession(raw);
536
+ if (session && (normalized.source === 'compact' || normalized.source === 'clear'))
537
+ resetContextSession(root, session);
538
+ const decision = await runPromptChecks(root, normalized.pluginInput);
539
+ if (!decision.contexts.length)
540
+ return 0;
541
+ await writeHookOutput(ctx.io, ctx.adapter.formatOutput(ctx.event, decision));
542
+ recordContexts(ctx, subagent ? 'subagent-start' : (normalized.source ?? 'session-start'), decision);
543
+ acknowledgePrompt(root, raw, decision);
544
+ return 0;
545
+ }
546
+ async function runAfterTool(ctx) {
547
+ const read = agentReadOf(ctx.root, ctx.normalized.pluginInput);
548
+ if (ctx.normalized.tool === 'Read') {
266
549
  if (read)
267
- recordTrace(projectRoot, {
268
- kind: 'agent-read',
269
- source: read.path,
270
- channel: agent,
271
- session: sessionOf(input),
272
- content: read.content,
273
- });
550
+ recordTrace(ctx.root, { kind: 'agent-read', source: read.path, channel: ctx.host, content: read.content, ...traceFields(ctx.raw) });
551
+ const pending = ctx.host === 'cursor' ? null : await compactContext(ctx);
552
+ const registry = loadRegistry(ctx.root, loadConfig(ctx.root));
553
+ const agentType = JSON.parse(ctx.normalized.pluginInput).agent_type;
554
+ const names = declaredHooks(registry)
555
+ .afterRead.filter((hook) => hook.agentType === undefined || hook.agentType === agentType)
556
+ .map((hook) => hook.command);
557
+ const choice = await selectContext(ctx, names, registry);
558
+ const contexts = [...(pending?.contexts ?? []), ...(choice?.context ? [choice.context] : [])];
559
+ await writeOutcome(ctx, ctx.adapter.formatOutput(ctx.event, { contexts }), pending);
560
+ if (choice)
561
+ acknowledgeSelectedContext(ctx, choice, 'after-read', true);
562
+ if (pending?.contexts.length) {
563
+ recordContexts(ctx, 'compact', pending);
564
+ acknowledgePrompt(ctx.root, ctx.raw, pending);
565
+ }
274
566
  return 0;
275
567
  }
276
- if (operation === 'agent-user-prompt') {
277
- const prompt = promptOf(input);
278
- if (prompt)
279
- recordTrace(projectRoot, { kind: 'prompt', source: agent, session: sessionOf(input), content: prompt });
280
- const decision = runPromptChecks(projectRoot, input);
281
- if (decision.contexts.length && agent !== 'cursor') {
282
- const context = decision.contexts.join('\n\n');
283
- io.out(JSON.stringify({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: context } }));
284
- recordTrace(projectRoot, { kind: 'injection', channel: 'prompt', session: sessionOf(input), content: context });
285
- acknowledgePrompt(projectRoot, input, decision);
286
- }
568
+ if (ctx.normalized.tool && ctx.normalized.tool !== 'Bash' && !editTool(ctx.normalized.tool)) {
569
+ await writeHookOutput(ctx.io, ctx.adapter.formatOutput(ctx.event, {}));
287
570
  return 0;
288
571
  }
289
- const afterEdit = operation === 'agent-after-edit' ? withRoutedAfterEdit(projectRoot, agent, input, runAfterEditChecks(projectRoot, input)) : null;
290
- const stop = afterEdit ? null : runAgentStop(projectRoot, agent, input);
291
- const response = afterEdit ? renderAfterEditResponse(agent, afterEdit) : renderStopResponse(agent, stop);
292
- if (response.stdout)
293
- io.out(response.stdout);
294
- if (response.stderr)
295
- io.err(response.stderr);
296
- for (const warning of stop?.warnings ?? [])
297
- io.err(`Sumi Stop 提醒:${warning}`);
298
- const delivered = agent !== 'cursor' && afterEdit?.contexts.length && (response.code === 2 || (response.code === 0 && Boolean(response.stdout)));
299
- if (delivered && afterEdit)
300
- acknowledgeAfterEdit(projectRoot, input, afterEdit);
301
- if (delivered && afterEdit)
302
- recordTrace(projectRoot, {
303
- kind: 'injection',
304
- channel: 'after-edit',
305
- session: sessionOf(input),
306
- content: afterEdit.contexts.join('\n\n'),
307
- });
308
- return response.code;
572
+ if (ctx.normalized.tool && editTool(ctx.normalized.tool))
573
+ recordTrace(ctx.root, { kind: 'agent-edit', ...traceFields(ctx.raw), host: ctx.host });
574
+ const local = await runAfterEditChecks(ctx.root, ctx.normalized.pluginInput);
575
+ const decision = withRoutedAfterEdit(ctx.root, ctx.host, ctx.normalized.pluginInput, local);
576
+ if (decision.code !== 0) {
577
+ const detail = renderAfterEditResponse(ctx.host, decision).stderr;
578
+ await writeHookOutput(ctx.io, ctx.adapter.formatOutput(ctx.event, { denied: decision.code === 2 ? detail : undefined }));
579
+ if (detail)
580
+ ctx.io.err(detail);
581
+ if (decision.code === 2 && detail)
582
+ recordDelivery(ctx.root, ctx.raw, { channel: 'after-edit', method: 'denial', content: detail, host: ctx.host });
583
+ // Cursor 只在退出 0 时读输出,非零退出会让上面写的上下文作废
584
+ return ctx.host === 'cursor' ? 0 : decision.code;
585
+ }
586
+ const routedChild = process.env[ROUTED_ENV] === '1';
587
+ const pending = ctx.host === 'cursor' || routedChild ? null : await compactContext(ctx);
588
+ const contexts = [...decision.contexts, ...(pending?.contexts ?? [])];
589
+ const output = ctx.adapter.formatOutput(ctx.event, { contexts });
590
+ if (routedChild) {
591
+ const receipt = { kind: 'after', channel: 'after-edit', contexts: local.contexts, deliveries: local.deliveries ?? [] };
592
+ await writeHookOutput(ctx.io, local.contexts.length ? withReceipt(output, { ...receipt, evidence: local.evidence }) : output);
593
+ return 0;
594
+ }
595
+ await writeOutcome(ctx, output, pending);
596
+ if (local.contexts.length) {
597
+ recordContexts(ctx, 'after-edit', local);
598
+ acknowledgeAfterEdit(ctx.root, ctx.raw, local);
599
+ }
600
+ if (pending?.contexts.length) {
601
+ recordContexts(ctx, 'compact', pending);
602
+ acknowledgePrompt(ctx.root, ctx.raw, pending);
603
+ }
604
+ acknowledgeRouted(decision.receipts ?? []);
605
+ return 0;
606
+ }
607
+ async function runUserPrompt(ctx) {
608
+ if (!ctx.normalized.valid)
609
+ return 0;
610
+ if (ctx.normalized.prompt)
611
+ recordTrace(ctx.root, { kind: 'prompt', source: ctx.host, content: ctx.normalized.prompt, ...traceFields(ctx.raw), host: ctx.host });
612
+ if (ctx.host === 'cursor')
613
+ return 0;
614
+ const pending = await compactContext(ctx);
615
+ const decision = pending ?? (await runPromptChecks(ctx.root, ctx.normalized.pluginInput));
616
+ if (!decision.contexts.length)
617
+ return 0;
618
+ await writeOutcome(ctx, ctx.adapter.formatOutput(ctx.event, decision), pending);
619
+ recordContexts(ctx, pending ? 'compact' : 'prompt', decision);
620
+ acknowledgePrompt(ctx.root, ctx.raw, decision);
621
+ return 0;
622
+ }
623
+ async function runStop(ctx) {
624
+ const stopState = stopPayload(ctx.raw);
625
+ const stopActive = stopState?.stop_hook_active === true || (typeof stopState?.loop_count === 'number' && stopState.loop_count > 0);
626
+ const checks = stopActive ? { blocked: false, reasons: [] } : await runStopChecks(ctx.root, ctx.normalized.pluginInput);
627
+ const decision = await runAgentStop(ctx.root, ctx.host, ctx.raw, checks);
628
+ const session = ctx.normalized.session;
629
+ const hints = stopHintMessages(ctx.root, session);
630
+ const response = renderStopResponse(ctx.host, { ...decision, warnings: [...hints, ...(decision.warnings ?? [])] });
631
+ await writeHookOutput(ctx.io, response.stdout);
632
+ for (const message of decision.warnings ?? [])
633
+ ctx.io.err(`Sumi Stop 提醒:${message}`);
634
+ if (ctx.host === 'cursor')
635
+ for (const message of hints)
636
+ ctx.io.err(`Sumi Stop 提醒:${message}`);
637
+ return 0;
638
+ }
639
+ async function runModelSwitch(ctx) {
640
+ const config = loadConfig(ctx.root);
641
+ const registry = loadRegistry(ctx.root, config);
642
+ const names = declaredHooks(registry, config).modelSwitch;
643
+ await Promise.all(names.map((name) => runHookCommand(ctx.root, ctx.normalized.pluginInput, name, registry)));
644
+ return 0;
645
+ }
646
+ async function runPostCompact(ctx) {
647
+ if (ctx.host === 'codex' && ctx.normalized.session)
648
+ markCompaction(ctx.root, ctx.normalized.session, ctx.normalized.agentId);
649
+ return 0;
650
+ }
651
+ const EVENT_HANDLERS = {
652
+ 'before-tool': runBeforeTool,
653
+ 'after-tool': runAfterTool,
654
+ 'session-start': (ctx) => runStart(ctx, false),
655
+ 'subagent-start': (ctx) => runStart(ctx, true),
656
+ 'post-compact': runPostCompact,
657
+ 'model-switch': runModelSwitch,
658
+ 'user-prompt': runUserPrompt,
659
+ stop: runStop,
660
+ };
661
+ async function runtimeHook(args, io, root) {
662
+ const operation = args.positionals[0];
663
+ const requestedHost = args.positionals[1];
664
+ if (!operation || !EVENT_HANDLERS[operation])
665
+ return 3;
666
+ const projectRoot = requireRoot(root);
667
+ // 身份错误必须在消费负载前交回 CLI,恢复处理才能读取同一次工具请求。
668
+ loadConfig(projectRoot);
669
+ const raw = await readHookInput();
670
+ const host = requestedHost === 'auto' ? (hostEvent(raw)?.host ?? 'claude') : requestedHost;
671
+ if (!HOST_ADAPTERS[host])
672
+ return 3;
673
+ const event = NEW_EVENTS[operation][host];
674
+ const adapter = HOST_ADAPTERS[host];
675
+ return EVENT_HANDLERS[operation]({ root: projectRoot, raw, host, event, adapter, io, normalized: adapter.normalizeInput(event, raw) });
676
+ }
677
+ /** 目标项目收到回执:父进程的输出已写出,这时才记账并标记已送达。回执里的命令必须是本项目注册的。 */
678
+ async function receiveRoutedReceipt(root) {
679
+ const { raw, receipt } = JSON.parse(await readHookInput());
680
+ const config = loadConfig(root);
681
+ const registered = [...loadRegistry(root, config).commands.values()].map((command) => JSON.stringify(resolveArgv(command.argv, command.dir)));
682
+ const deliveries = receipt.deliveries.filter((delivery) => registered.includes(JSON.stringify(delivery.argv)));
683
+ recordDelivery(root, raw, {
684
+ channel: receipt.channel,
685
+ method: 'additional-context',
686
+ content: receipt.contexts.join('\n\n'),
687
+ ...receipt.evidence,
688
+ });
689
+ if (receipt.kind === 'before')
690
+ acknowledgeBeforeTool(root, raw, { deliveries });
691
+ else
692
+ acknowledgeAfterEdit(root, raw, { deliveries });
693
+ return 0;
694
+ }
695
+ registerCommand('context-before-edit', '旧接线的前置 hook 别名', (_args, io, root) => runtimeHook({ positionals: ['before-tool', 'auto'] }, io, root));
696
+ registerCommand('hook', `运行工具适配 hook:${HOOK_USAGE}`, async (args, io, root) => {
697
+ const operation = args.positionals[0];
698
+ // 内部操作:父进程转交写入后回执给目标项目,不写进用法
699
+ if (operation === 'routed-receipt')
700
+ return receiveRoutedReceipt(requireRoot(root));
701
+ if (!HOOK_OPERATIONS.includes(operation ?? '') || !['claude', 'codex', 'cursor'].includes(args.positionals[1] ?? '')) {
702
+ io.err(`用法:${HOOK_USAGE}`);
703
+ return 3;
704
+ }
705
+ const agent = args.positionals[1];
706
+ if (NEW_EVENTS[operation])
707
+ return runtimeHook(args, io, root);
708
+ const alias = {
709
+ 'agent-stop': 'stop',
710
+ 'agent-after-edit': 'after-tool',
711
+ 'agent-after-read': 'after-tool',
712
+ 'agent-user-prompt': 'user-prompt',
713
+ 'agent-session-start': 'session-start',
714
+ 'agent-subagent-start': 'subagent-start',
715
+ 'context-before-edit': 'before-tool',
716
+ };
717
+ return runtimeHook({ positionals: [alias[operation], agent] }, io, root);
309
718
  });
310
- /** 写入目标属于其他已接入项目时,并入那些项目编辑后 hook 的补充上下文与阻断(它们各自记录送达)。 */
719
+ /** 写入目标属于其他已接入项目时,并入那些项目编辑后 hook 的补充上下文与阻断;它们的账本与回执在输出写出后再做。 */
311
720
  function withRoutedAfterEdit(root, agent, input, local) {
312
- const routed = routeToOwners(root, ['hook', 'agent-after-edit', agent], input);
721
+ const routed = routeToOwners(root, ['hook', 'after-tool', agent], input);
313
722
  const contexts = [...local.contexts];
314
723
  for (const out of routed.stdout) {
315
724
  try {
316
725
  const value = JSON.parse(out);
317
- if (typeof value.hookSpecificOutput?.additionalContext === 'string')
318
- contexts.push(value.hookSpecificOutput.additionalContext);
726
+ const context = firstHostString([value.hookSpecificOutput?.additionalContext, value.additional_context]);
727
+ if (context)
728
+ contexts.push(context);
319
729
  }
320
730
  catch {
321
731
  /* 没有补充上下文 */
322
732
  }
323
733
  }
324
734
  const stderr = [local.stderr, ...routed.stderr].filter(Boolean).join('\n');
325
- return { ...local, code: routed.denied ? 2 : local.code, contexts, stderr };
326
- }
327
- function toolName(input) {
328
- try {
329
- const value = JSON.parse(input);
330
- return typeof value.tool_name === 'string' ? value.tool_name : undefined;
331
- }
332
- catch {
333
- return undefined;
334
- }
335
- }
336
- function sessionOf(input) {
337
- try {
338
- const value = JSON.parse(input);
339
- const id = value.session_id ?? value.thread_id;
340
- return typeof id === 'string' ? id : undefined;
341
- }
342
- catch {
343
- return undefined;
344
- }
345
- }
346
- function promptOf(input) {
347
- try {
348
- const value = JSON.parse(input);
349
- return typeof value.prompt === 'string' && value.prompt.length ? value.prompt : undefined;
350
- }
351
- catch {
352
- return undefined;
353
- }
735
+ return { ...local, code: routed.denied ? 2 : local.code, contexts, stderr, receipts: routed.receipts };
354
736
  }
355
737
  function agentReadOf(root, input) {
356
738
  try {
@@ -360,7 +742,7 @@ function agentReadOf(root, input) {
360
742
  const path = relative(root, resolve(value.tool_input.file_path));
361
743
  if (!path || path === '..' || path.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`) || isAbsolute(path))
362
744
  return undefined;
363
- const response = value.tool_response;
745
+ const response = value.tool_response ?? value.tool_output;
364
746
  const content = typeof response === 'string'
365
747
  ? response
366
748
  : response && typeof response === 'object' && 'content' in response && typeof response.content === 'string'