@pugi/cli 0.1.0-beta.9 → 0.1.0-beta.90

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 (409) hide show
  1. package/CHANGELOG.md +132 -0
  2. package/LICENSE +1 -1
  3. package/assets/pugi-prozr2-mascot.ansi +9 -0
  4. package/bin/run.js +33 -1
  5. package/dist/commands/deploy.js +40 -40
  6. package/dist/commands/flatten.js +191 -0
  7. package/dist/commands/jobs-watch.js +201 -0
  8. package/dist/commands/jobs.js +42 -27
  9. package/dist/commands/smoke.js +133 -0
  10. package/dist/core/agent-progress/cleanup.js +134 -0
  11. package/dist/core/agent-progress/schema.js +144 -0
  12. package/dist/core/agent-progress/writer.js +101 -0
  13. package/dist/core/agents/adaptive-router.js +330 -0
  14. package/dist/core/agents/query-decomposer.js +297 -0
  15. package/dist/core/agents/registry.js +3 -3
  16. package/dist/core/approvals/shortcut-resolver.js +98 -0
  17. package/dist/core/artifact-chain/dispatcher.js +148 -0
  18. package/dist/core/artifact-chain/exporter.js +164 -0
  19. package/dist/core/artifact-chain/state.js +243 -0
  20. package/dist/core/artifact-chain/steps.js +169 -0
  21. package/dist/core/ask-user/question.js +92 -0
  22. package/dist/core/audit/audit-trail.js +275 -0
  23. package/dist/core/auth/ensure-authenticated.js +129 -0
  24. package/dist/core/auth/env-provider.js +238 -0
  25. package/dist/core/auto-open-browser.js +4 -4
  26. package/dist/core/auto-update/channels.js +122 -0
  27. package/dist/core/auto-update/checker.js +241 -0
  28. package/dist/core/auto-update/state.js +235 -0
  29. package/dist/core/bare-mode/index.js +107 -0
  30. package/dist/core/bash/redirect.js +281 -0
  31. package/dist/core/bash-classifier.js +436 -40
  32. package/dist/core/checkpoint/resumer.js +149 -0
  33. package/dist/core/checkpoint/rewinder.js +291 -0
  34. package/dist/core/checkpoints/shadow-git.js +670 -0
  35. package/dist/core/citations/parser.js +109 -0
  36. package/dist/core/classifier/yolo-classifier.js +88 -0
  37. package/dist/core/codegraph/decision-store.js +248 -0
  38. package/dist/core/codegraph/detect-repo.js +459 -0
  39. package/dist/core/codegraph/install.js +134 -0
  40. package/dist/core/codegraph/offer-hook.js +220 -0
  41. package/dist/core/compact/auto-trigger.js +96 -0
  42. package/dist/core/compact/buffer-rewriter.js +115 -0
  43. package/dist/core/compact/summarizer.js +208 -0
  44. package/dist/core/compact/token-counter.js +108 -0
  45. package/dist/core/consensus/anvil-fanout.js +25 -25
  46. package/dist/core/consensus/diff-capture.js +121 -12
  47. package/dist/core/consensus/rubric.js +21 -21
  48. package/dist/core/context/builder.js +6 -6
  49. package/dist/core/context/compaction-events.js +8 -8
  50. package/dist/core/context/compaction.js +31 -31
  51. package/dist/core/context/index.js +15 -8
  52. package/dist/core/context/invariants.js +51 -51
  53. package/dist/core/context/markdown-loader.js +28 -10
  54. package/dist/core/context/markdown-traverse.js +255 -0
  55. package/dist/core/context/pugiignore.js +41 -41
  56. package/dist/core/context/repo-skeleton.js +37 -37
  57. package/dist/core/context/tool-eviction.js +55 -0
  58. package/dist/core/context/watcher.js +32 -32
  59. package/dist/core/context/working-set.js +23 -23
  60. package/dist/core/coordinator/agent-tools.js +77 -0
  61. package/dist/core/coordinator/agent-toolset.js +65 -0
  62. package/dist/core/coordinator/fsm.js +73 -0
  63. package/dist/core/coordinator/mode-fsm.js +70 -0
  64. package/dist/core/cost/rate-card.js +129 -0
  65. package/dist/core/cost/tracker.js +221 -0
  66. package/dist/core/credentials.js +13 -13
  67. package/dist/core/cron/scheduler.js +138 -0
  68. package/dist/core/denial-tracking/index.js +8 -0
  69. package/dist/core/denial-tracking/state.js +264 -0
  70. package/dist/core/diagnostics/probe-runner.js +93 -0
  71. package/dist/core/diagnostics/probes/api.js +46 -0
  72. package/dist/core/diagnostics/probes/auth.js +93 -0
  73. package/dist/core/diagnostics/probes/bare-mode.js +42 -0
  74. package/dist/core/diagnostics/probes/cli-version.js +127 -0
  75. package/dist/core/diagnostics/probes/config.js +72 -0
  76. package/dist/core/diagnostics/probes/denial-tracking.js +57 -0
  77. package/dist/core/diagnostics/probes/disk.js +81 -0
  78. package/dist/core/diagnostics/probes/engine-live.js +46 -0
  79. package/dist/core/diagnostics/probes/git.js +65 -0
  80. package/dist/core/diagnostics/probes/hooks.js +118 -0
  81. package/dist/core/diagnostics/probes/mcp.js +75 -0
  82. package/dist/core/diagnostics/probes/node.js +59 -0
  83. package/dist/core/diagnostics/probes/pnpm.js +36 -0
  84. package/dist/core/diagnostics/probes/pugi-md.js +89 -0
  85. package/dist/core/diagnostics/probes/sandbox.js +40 -0
  86. package/dist/core/diagnostics/probes/session.js +74 -0
  87. package/dist/core/diagnostics/probes/status-snapshot.js +488 -0
  88. package/dist/core/diagnostics/probes/workspace.js +63 -0
  89. package/dist/core/diagnostics/types.js +70 -0
  90. package/dist/core/dispatch/cache-cleanup.js +197 -0
  91. package/dist/core/dispatch/cache-handoff.js +295 -0
  92. package/dist/core/edits/apply-patch-layer-e.js +189 -0
  93. package/dist/core/edits/dispatch.js +333 -7
  94. package/dist/core/edits/format-detector.js +260 -0
  95. package/dist/core/edits/format-matrix.js +26 -0
  96. package/dist/core/edits/fuzzy-ladder.js +650 -0
  97. package/dist/core/edits/index.js +5 -1
  98. package/dist/core/edits/journal.js +199 -0
  99. package/dist/core/edits/layer-a-apply.js +15 -15
  100. package/dist/core/edits/layer-a-fuzzy-apply.js +198 -0
  101. package/dist/core/edits/layer-b-apply.js +9 -9
  102. package/dist/core/edits/layer-c-apply.js +6 -6
  103. package/dist/core/edits/layer-d-ast.js +557 -14
  104. package/dist/core/edits/marker-parser.js +12 -12
  105. package/dist/core/edits/security-gate.js +27 -27
  106. package/dist/core/edits/verify-hook.js +273 -0
  107. package/dist/core/edits/worktree.js +29 -29
  108. package/dist/core/engine/anvil-client.js +214 -26
  109. package/dist/core/engine/auto-compact.js +179 -0
  110. package/dist/core/engine/budgets.js +186 -0
  111. package/dist/core/engine/context-prefix.js +155 -0
  112. package/dist/core/engine/index.js +1 -1
  113. package/dist/core/engine/intensity.js +158 -0
  114. package/dist/core/engine/intent.js +260 -0
  115. package/dist/core/engine/native-pugi.js +1295 -227
  116. package/dist/core/engine/prompts.js +129 -19
  117. package/dist/core/engine/strip-internal-fields.js +124 -0
  118. package/dist/core/engine/tool-bridge.js +1731 -59
  119. package/dist/core/evaluation/golden-dataset.js +293 -0
  120. package/dist/core/feedback/queue.js +177 -0
  121. package/dist/core/feedback/submitter.js +145 -0
  122. package/dist/core/file-cache.js +113 -1
  123. package/dist/core/flatten/flatten-repo.js +439 -0
  124. package/dist/core/format/osc8-link.js +28 -0
  125. package/dist/core/hook-chains.js +392 -0
  126. package/dist/core/hooks/citation-verify-hook.js +138 -0
  127. package/dist/core/hooks/citation-verify.js +112 -0
  128. package/dist/core/hooks/events.js +46 -0
  129. package/dist/core/hooks/index.js +15 -0
  130. package/dist/core/hooks/registry.js +216 -0
  131. package/dist/core/hooks/runner.js +236 -0
  132. package/dist/core/hooks/v2/event-emitter.js +115 -0
  133. package/dist/core/hooks/v2/executor.js +282 -0
  134. package/dist/core/hooks/v2/index.js +25 -0
  135. package/dist/core/hooks/v2/lifecycle.js +104 -0
  136. package/dist/core/hooks/v2/loader.js +216 -0
  137. package/dist/core/hooks/v2/matcher.js +125 -0
  138. package/dist/core/hooks/v2/trust.js +143 -0
  139. package/dist/core/hooks/v2/types.js +86 -0
  140. package/dist/core/hooks/worktree-events.js +158 -0
  141. package/dist/core/image/renderer.js +71 -0
  142. package/dist/core/init/detector.js +582 -0
  143. package/dist/core/init/template-renderer.js +242 -0
  144. package/dist/core/jobs/registry.js +18 -18
  145. package/dist/core/ledger/results-tsv.js +142 -0
  146. package/dist/core/log-discipline/stdout-redirect.js +51 -0
  147. package/dist/core/lsp/cache.js +105 -0
  148. package/dist/core/lsp/client.js +551 -41
  149. package/dist/core/lsp/language-detect.js +66 -0
  150. package/dist/core/lsp/post-edit-diagnostics.js +171 -0
  151. package/dist/core/lsp/server-detect.js +173 -0
  152. package/dist/core/lsp/symbol-cache.js +162 -0
  153. package/dist/core/lsp/symbol-tools.js +664 -0
  154. package/dist/core/mcp/client.js +97 -28
  155. package/dist/core/mcp/http-server.js +553 -0
  156. package/dist/core/mcp/orchestrator-tools.js +662 -0
  157. package/dist/core/mcp/permission.js +190 -0
  158. package/dist/core/mcp/registry.js +39 -17
  159. package/dist/core/mcp/server-tools.js +219 -0
  160. package/dist/core/mcp/server.js +397 -0
  161. package/dist/core/mcp/trust.js +10 -10
  162. package/dist/core/memory/dual-write.js +416 -0
  163. package/dist/core/memory/passive-extract.js +130 -0
  164. package/dist/core/memory/phase1-kinds.js +20 -0
  165. package/dist/core/memory/secret-scanner.js +304 -0
  166. package/dist/core/memory-sync/queue.js +170 -0
  167. package/dist/core/metrics/extract.js +113 -0
  168. package/dist/core/modes/roo-modes.js +68 -0
  169. package/dist/core/onboarding/ensure-initialized.js +133 -0
  170. package/dist/core/onboarding/marker.js +111 -0
  171. package/dist/core/onboarding/telemetry-state.js +108 -0
  172. package/dist/core/output-style/presets.js +176 -0
  173. package/dist/core/output-style/state.js +185 -0
  174. package/dist/core/path-security.js +287 -5
  175. package/dist/core/permission.js +82 -22
  176. package/dist/core/permissions/auto-classifier.js +124 -0
  177. package/dist/core/permissions/bash-parser.js +371 -0
  178. package/dist/core/permissions/circuit-breaker.js +83 -0
  179. package/dist/core/permissions/constrained-edit.js +91 -0
  180. package/dist/core/permissions/gate.js +278 -0
  181. package/dist/core/permissions/index.js +20 -0
  182. package/dist/core/permissions/mode.js +174 -0
  183. package/dist/core/permissions/network-egress.js +137 -0
  184. package/dist/core/permissions/state.js +241 -0
  185. package/dist/core/permissions/tool-class.js +93 -0
  186. package/dist/core/plan-mode/ui-state.js +51 -0
  187. package/dist/core/plans/plan-artifact.js +721 -0
  188. package/dist/core/policy-limits/etag-store.js +122 -0
  189. package/dist/core/prd-check/parser.js +215 -0
  190. package/dist/core/prd-check/reporter.js +127 -0
  191. package/dist/core/prd-check/session-review.js +557 -0
  192. package/dist/core/prd-check/verifiers.js +223 -0
  193. package/dist/core/prompt-cache/client-cache.js +99 -0
  194. package/dist/core/prompts/assembly.js +29 -0
  195. package/dist/core/prompts/registry.js +364 -0
  196. package/dist/core/pugi-md/cc-compat-rules.js +735 -0
  197. package/dist/core/pugi-md/context-injector.js +76 -0
  198. package/dist/core/pugi-md/walk-up.js +207 -0
  199. package/dist/core/python/uv-installer.js +270 -0
  200. package/dist/core/python/uv-resolver.js +83 -0
  201. package/dist/core/rate-limit/narrator.js +146 -0
  202. package/dist/core/recipes/cli-types.js +20 -0
  203. package/dist/core/recipes/loader.js +103 -0
  204. package/dist/core/recipes/runner.js +345 -0
  205. package/dist/core/recipes/schema.js +587 -0
  206. package/dist/core/release-notes/parser.js +241 -0
  207. package/dist/core/release-notes/state.js +116 -0
  208. package/dist/core/repl/ask.js +37 -37
  209. package/dist/core/repl/cancellation.js +26 -26
  210. package/dist/core/repl/cap-warning.js +4 -4
  211. package/dist/core/repl/clipboard-read.js +11 -11
  212. package/dist/core/repl/dispatch-fsm.js +12 -12
  213. package/dist/core/repl/history-search.js +15 -15
  214. package/dist/core/repl/history.js +28 -18
  215. package/dist/core/repl/kill-ring.js +5 -5
  216. package/dist/core/repl/model-pricing.js +135 -0
  217. package/dist/core/repl/privacy-banner.js +22 -22
  218. package/dist/core/repl/session.js +2148 -217
  219. package/dist/core/repl/slash-commands.js +501 -41
  220. package/dist/core/repl/store/index.js +1 -1
  221. package/dist/core/repl/store/jsonl-log.js +22 -22
  222. package/dist/core/repl/store/lockfile.js +10 -10
  223. package/dist/core/repl/store/session-store.js +136 -107
  224. package/dist/core/repl/store/types.js +15 -15
  225. package/dist/core/repl/store/uuid-v7.js +12 -12
  226. package/dist/core/repl/workspace-context.js +43 -21
  227. package/dist/core/repo-map/build.js +125 -0
  228. package/dist/core/repo-map/cache.js +185 -0
  229. package/dist/core/repo-map/extractor.js +254 -0
  230. package/dist/core/repo-map/formatter.js +145 -0
  231. package/dist/core/repo-map/page-rank.js +105 -0
  232. package/dist/core/repo-map/scanner.js +211 -0
  233. package/dist/core/retry-budget/budget.js +284 -0
  234. package/dist/core/retry-budget/index.js +5 -0
  235. package/dist/core/retry-budget/retry-cap.js +74 -0
  236. package/dist/core/routing/lead-worker.js +43 -0
  237. package/dist/core/routing/pre-flight-estimator.js +108 -0
  238. package/dist/core/runs/run-tree.js +103 -0
  239. package/dist/core/security/injection-scanner.js +367 -0
  240. package/dist/core/security/output-filter.js +418 -0
  241. package/dist/core/session/env-file.js +105 -0
  242. package/dist/core/session/section-budgets.js +140 -0
  243. package/dist/core/session.js +92 -0
  244. package/dist/core/settings.js +324 -5
  245. package/dist/core/share/formatter.js +271 -0
  246. package/dist/core/share/redactor.js +221 -0
  247. package/dist/core/share/uploader.js +267 -0
  248. package/dist/core/skills/defaults.js +30 -30
  249. package/dist/core/skills/loader.js +22 -22
  250. package/dist/core/skills/sources.js +27 -27
  251. package/dist/core/smoke/headless-driver.js +174 -0
  252. package/dist/core/smoke/orchestrator.js +194 -0
  253. package/dist/core/smoke/runner.js +238 -0
  254. package/dist/core/smoke/scenario-parser.js +316 -0
  255. package/dist/core/statusline.js +99 -0
  256. package/dist/core/subagents/dispatcher-real.js +600 -0
  257. package/dist/core/subagents/dispatcher.js +132 -43
  258. package/dist/core/subagents/index.js +19 -6
  259. package/dist/core/subagents/isolation-matrix.js +213 -0
  260. package/dist/core/subagents/spawn.js +19 -4
  261. package/dist/core/telemetry/emitter.js +229 -0
  262. package/dist/core/telemetry/queue.js +251 -0
  263. package/dist/core/theme/context.js +91 -0
  264. package/dist/core/theme/presets.js +228 -0
  265. package/dist/core/theme/state.js +181 -0
  266. package/dist/core/todos/invariant.js +10 -0
  267. package/dist/core/todos/state.js +177 -0
  268. package/dist/core/tool-schema/compressor.js +89 -0
  269. package/dist/core/transport/version-interceptor.js +166 -0
  270. package/dist/core/trust.js +2 -2
  271. package/dist/core/tui/thinking-block.js +64 -0
  272. package/dist/core/vim/keymap.js +288 -0
  273. package/dist/core/vim/state.js +92 -0
  274. package/dist/core/watch-markers/marker-watcher.js +133 -0
  275. package/dist/core/worktree/include-parser.js +249 -0
  276. package/dist/core/worktree-manager/cleanup.js +123 -0
  277. package/dist/core/worktree-manager/manager.js +303 -0
  278. package/dist/index.js +36 -0
  279. package/dist/runtime/bootstrap.js +190 -0
  280. package/dist/runtime/cli.js +4185 -549
  281. package/dist/runtime/commands/agents.js +31 -31
  282. package/dist/runtime/commands/budget.js +5 -5
  283. package/dist/runtime/commands/cancel.js +231 -0
  284. package/dist/runtime/commands/chain.js +489 -0
  285. package/dist/runtime/commands/codegraph-status.js +227 -0
  286. package/dist/runtime/commands/compact.js +297 -0
  287. package/dist/runtime/commands/config.js +73 -39
  288. package/dist/runtime/commands/cost.js +199 -0
  289. package/dist/runtime/commands/delegate.js +27 -4
  290. package/dist/runtime/commands/dispatch.js +126 -0
  291. package/dist/runtime/commands/doctor.js +579 -0
  292. package/dist/runtime/commands/feedback.js +184 -0
  293. package/dist/runtime/commands/hooks.js +187 -0
  294. package/dist/runtime/commands/init.js +254 -0
  295. package/dist/runtime/commands/lsp.js +200 -38
  296. package/dist/runtime/commands/mcp.js +879 -0
  297. package/dist/runtime/commands/memory.js +582 -0
  298. package/dist/runtime/commands/model.js +237 -0
  299. package/dist/runtime/commands/onboarding.js +275 -0
  300. package/dist/runtime/commands/patch.js +12 -12
  301. package/dist/runtime/commands/permissions.js +112 -0
  302. package/dist/runtime/commands/plan.js +143 -0
  303. package/dist/runtime/commands/prd-check.js +285 -0
  304. package/dist/runtime/commands/privacy.js +17 -17
  305. package/dist/runtime/commands/recipe.js +325 -0
  306. package/dist/runtime/commands/redo-blob-store.js +92 -0
  307. package/dist/runtime/commands/redo.js +361 -0
  308. package/dist/runtime/commands/release-notes.js +229 -0
  309. package/dist/runtime/commands/repo-map.js +95 -0
  310. package/dist/runtime/commands/report.js +299 -0
  311. package/dist/runtime/commands/resume.js +118 -0
  312. package/dist/runtime/commands/review-consensus.js +68 -53
  313. package/dist/runtime/commands/rewind.js +333 -0
  314. package/dist/runtime/commands/roster.js +14 -14
  315. package/dist/runtime/commands/sessions.js +163 -0
  316. package/dist/runtime/commands/share.js +316 -0
  317. package/dist/runtime/commands/skills.js +31 -31
  318. package/dist/runtime/commands/status.js +186 -0
  319. package/dist/runtime/commands/stickers.js +82 -0
  320. package/dist/runtime/commands/style.js +194 -0
  321. package/dist/runtime/commands/theme.js +196 -0
  322. package/dist/runtime/commands/undo.js +54 -22
  323. package/dist/runtime/commands/update.js +289 -0
  324. package/dist/runtime/commands/vim.js +140 -0
  325. package/dist/runtime/commands/worktree.js +8 -8
  326. package/dist/runtime/commands/worktrees.js +155 -0
  327. package/dist/runtime/headless-repl.js +195 -0
  328. package/dist/runtime/headless.js +543 -0
  329. package/dist/runtime/load-hooks-or-exit.js +71 -0
  330. package/dist/runtime/plan-decompose.js +22 -22
  331. package/dist/runtime/sigint-guard.js +272 -0
  332. package/dist/runtime/update-check.js +28 -28
  333. package/dist/runtime/version.js +65 -0
  334. package/dist/runtime/worktree-bootstrap.js +579 -0
  335. package/dist/skills/bundled/batch.js +617 -0
  336. package/dist/skills/bundled/index.js +45 -0
  337. package/dist/skills/bundled/loop.js +358 -0
  338. package/dist/skills/bundled/remember.js +383 -0
  339. package/dist/skills/bundled/simplify.js +289 -0
  340. package/dist/skills/bundled/skillify.js +373 -0
  341. package/dist/skills/bundled/stuck.js +558 -0
  342. package/dist/skills/bundled/verify.js +439 -0
  343. package/dist/testing/vcr.js +486 -0
  344. package/dist/tools/agent-tool.js +229 -0
  345. package/dist/tools/apply-patch.js +89 -28
  346. package/dist/tools/ask-user-question.js +337 -0
  347. package/dist/tools/ask-user.js +115 -0
  348. package/dist/tools/bash.js +624 -46
  349. package/dist/tools/brief.js +224 -0
  350. package/dist/tools/enter-worktree.js +250 -0
  351. package/dist/tools/exit-worktree.js +147 -0
  352. package/dist/tools/file-tools.js +161 -44
  353. package/dist/tools/lsp-tools.js +377 -1
  354. package/dist/tools/mcp-tool.js +260 -0
  355. package/dist/tools/multi-edit.js +361 -0
  356. package/dist/tools/powershell.js +268 -0
  357. package/dist/tools/registry.js +86 -4
  358. package/dist/tools/skill-tool.js +96 -0
  359. package/dist/tools/sleep.js +99 -0
  360. package/dist/tools/synthetic-output.js +133 -0
  361. package/dist/tools/tasks.js +208 -0
  362. package/dist/tools/todo-write.js +184 -0
  363. package/dist/tools/verify-plan-execution.js +295 -0
  364. package/dist/tools/web-fetch-injection-scanner.js +207 -0
  365. package/dist/tools/web-fetch.js +195 -10
  366. package/dist/tools/web-search.js +458 -0
  367. package/dist/tui/agent-progress-card.js +111 -0
  368. package/dist/tui/agent-tree.js +11 -1
  369. package/dist/tui/ask-modal.js +14 -14
  370. package/dist/tui/ask-user-question-chips.js +315 -0
  371. package/dist/tui/ask-user-question-prompt.js +203 -0
  372. package/dist/tui/compact-banner.js +81 -0
  373. package/dist/tui/conversation-pane.js +85 -11
  374. package/dist/tui/cost-table.js +111 -0
  375. package/dist/tui/device-flow.js +2 -2
  376. package/dist/tui/doctor-table.js +46 -0
  377. package/dist/tui/feedback-prompt.js +156 -0
  378. package/dist/tui/input-box.js +247 -32
  379. package/dist/tui/login-picker.js +3 -3
  380. package/dist/tui/markdown-render.js +6 -6
  381. package/dist/tui/onboarding-wizard.js +240 -0
  382. package/dist/tui/permissions-picker.js +86 -0
  383. package/dist/tui/render.js +36 -1
  384. package/dist/tui/repl-render.js +176 -25
  385. package/dist/tui/repl-splash-art.js +16 -16
  386. package/dist/tui/repl-splash-mascot.js +48 -24
  387. package/dist/tui/repl-splash.js +22 -22
  388. package/dist/tui/repl.js +125 -45
  389. package/dist/tui/slash-palette.js +6 -6
  390. package/dist/tui/splash.js +2 -2
  391. package/dist/tui/status-bar.js +109 -31
  392. package/dist/tui/status-table.js +7 -0
  393. package/dist/tui/stickers-art.js +136 -0
  394. package/dist/tui/style-table.js +28 -0
  395. package/dist/tui/theme-table.js +29 -0
  396. package/dist/tui/thinking-spinner.js +123 -0
  397. package/dist/tui/tool-stream-pane.js +53 -4
  398. package/dist/tui/update-banner.js +27 -2
  399. package/dist/tui/vim-input.js +267 -0
  400. package/dist/tui/welcome-banner.js +107 -0
  401. package/dist/tui/welcome-data.js +293 -0
  402. package/dist/tui/workspace-context.js +2 -2
  403. package/package.json +31 -16
  404. package/test/scenarios/codegen-create-file.scenario.txt +13 -0
  405. package/test/scenarios/compact-force.scenario.txt +12 -0
  406. package/test/scenarios/identity.scenario.txt +12 -0
  407. package/test/scenarios/persona-handoff.scenario.txt +12 -0
  408. package/test/scenarios/walkback.scenario.txt +12 -0
  409. package/dist/core/engine/compaction-hook.js +0 -154
@@ -1,20 +1,55 @@
1
- import { editTool, globTool, grepTool, OperatorAbortedError, readTool, writeTool, } from '../../tools/file-tools.js';
1
+ import { editTool, globTool, grepTool, OperatorAbortedError, readTool, StaleReadError, writeTool, } from '../../tools/file-tools.js';
2
2
  import { bashToolSync } from '../../tools/bash.js';
3
+ import { powerShellToolSync } from '../../tools/powershell.js';
4
+ import { askUser } from '../../tools/ask-user.js';
5
+ import { askUserQuestionJsonSchema, dispatchAskUserQuestion, } from '../../tools/ask-user-question.js';
6
+ import { skillInvoke, skillList } from '../../tools/skill-tool.js';
7
+ import { taskCreate, taskGet, taskList, taskUpdate, } from '../../tools/tasks.js';
8
+ import { dispatchTodoWrite, todoWriteJsonSchema, } from '../../tools/todo-write.js';
9
+ // Tool gap pack : Brief/Sleep/SyntheticOutput/
10
+ // EnterWorktree/ExitWorktree. Each tool exports a Zod-free hand-rolled
11
+ // JSON-schema fragment + a sentinel-returning dispatcher, matching the
12
+ // `todo_write` / `ask_user_question` conventions.
13
+ import { briefJsonSchema, dispatchBrief } from '../../tools/brief.js';
14
+ import { dispatchVerifyPlanExecution, verifyPlanExecutionJsonSchema, } from '../../tools/verify-plan-execution.js';
15
+ import { dispatchSleep, sleepJsonSchema } from '../../tools/sleep.js';
16
+ import { dispatchSyntheticOutput, syntheticOutputJsonSchema, } from '../../tools/synthetic-output.js';
17
+ import { dispatchEnterWorktree, enterWorktreeJsonSchema, } from '../../tools/enter-worktree.js';
18
+ import { dispatchExitWorktree, exitWorktreeJsonSchema, } from '../../tools/exit-worktree.js';
19
+ import { webFetchTool } from '../../tools/web-fetch.js';
20
+ import { webSearchTool } from '../../tools/web-search.js';
21
+ import { agentTool } from '../../tools/agent-tool.js';
22
+ import { multiEdit } from '../../tools/multi-edit.js';
23
+ import { buildMcpToolDefs, defaultNonInteractiveMcpPrompt, dispatchMcpTool, MCP_TOOL_PREFIX, } from '../../tools/mcp-tool.js';
24
+ import { firePostToolUseFailureChain } from '../hook-chains.js';
25
+ import { buildDenialContext, DENIAL_REMINDER_THRESHOLD, } from '../denial-tracking/state.js';
26
+ import { stripInternalFields } from './strip-internal-fields.js';
27
+ import { applyAskAnswer, gate as permissionGate, getToolClass, PermissionDenied, } from '../permissions/index.js';
28
+ import { RetryBudget, RetryBudgetExhausted, hashArgs } from '../retry-budget/index.js';
29
+ import { runPostEditDiagnostics, } from '../lsp/post-edit-diagnostics.js';
30
+ // PUGI-78 Phase 1: symbols.* tool wrappers + LSP client cache. The
31
+ // dispatcher resolves the LSP client by `lang` via `getOrStartLspClient`
32
+ // (cold-start cost amortised across the session) and hands it to the
33
+ // matching wrapper. The wrappers serialise the result for the engine
34
+ // envelope.
35
+ import { getOrStartLspClient } from '../lsp/cache.js';
36
+ import { symbolsCallHierarchyTool, symbolsCodeActionsTool, symbolsDiagnosticsTool, symbolsFindDefinitionTool, symbolsFindReferencesTool, symbolsFormatTool, symbolsHoverTool, symbolsImplementationsTool, symbolsListInFileTool, symbolsRenameTool, symbolsSignatureTool, symbolsTypeDefinitionTool, symbolsWorkspaceSymbolsTool, } from '../../tools/lsp-tools.js';
37
+ import { getGlobalSymbolCache } from '../lsp/symbol-cache.js';
3
38
  /**
4
39
  * Tool-bridge: turns the abstract tool registry into:
5
- * 1. An OpenAI-shaped tools schema for `EngineLoopClient.send`.
6
- * 2. A single executor callback that dispatches each tool_call to the
7
- * concrete `file-tools.ts` handler under workspace permissions.
40
+ * 1. An OpenAI-shaped tools schema for `EngineLoopClient.send`.
41
+ * 2. A single executor callback that dispatches each tool_call to the
42
+ * concrete `file-tools.ts` handler under workspace permissions.
8
43
  *
9
44
  * The bridge enforces two CLI-side invariants that the runtime cannot:
10
- * - Plan-mode refusal. When `kind === 'plan'`, the executor refuses
11
- * write/edit/bash by throwing `PLAN_MODE_REFUSED:<tool>` (sentinel
12
- * recognised by `runEngineLoop` to terminate with status
13
- * `tool_refused`). The schema also omits the mutating tools so the
14
- * model is unlikely to attempt them in the first place.
15
- * - Argument validation. Each call's `arguments` string is JSON-parsed
16
- * and shape-checked here; bad JSON or missing fields are surfaced
17
- * to the model as a tool error string so it can correct itself.
45
+ * - Plan-mode refusal. When `kind === 'plan'`, the executor refuses
46
+ * write/edit/bash by throwing `PLAN_MODE_REFUSED:<tool>` (sentinel
47
+ * recognised by `runEngineLoop` to terminate with status
48
+ * `tool_refused`). The schema also omits the mutating tools so the
49
+ * model is unlikely to attempt them in the first place.
50
+ * - Argument validation. Each call's `arguments` string is JSON-parsed
51
+ * and shape-checked here; bad JSON or missing fields are surfaced
52
+ * to the model as a tool error string so it can correct itself.
18
53
  *
19
54
  * The bridge does NOT touch session.ts directly — `file-tools.ts`
20
55
  * already records every call. The engine adapter wires a hook layer on
@@ -23,17 +58,155 @@ import { bashToolSync } from '../../tools/bash.js';
23
58
  /**
24
59
  * Read-only subset surfaced to plan-mode. Mutating tools (write, edit,
25
60
  * bash) are intentionally absent so the model rarely tries them.
61
+ *
62
+ * β1: task_* + skill + ask_user_question + web_fetch are all read-only
63
+ * from the workspace's perspective (no file writes), so they stay
64
+ * available in plan mode. The ledger writes for `task_*` land in
65
+ * `.pugi/sessions/<id>/tasks.jsonl` which is metadata, not source.
26
66
  */
27
- const READ_ONLY_TOOLS = new Set(['read', 'grep', 'glob']);
67
+ const READ_ONLY_TOOLS = new Set([
68
+ 'read',
69
+ 'grep',
70
+ 'glob',
71
+ 'ask_user_question',
72
+ 'skill',
73
+ 'skills_list',
74
+ 'task_create',
75
+ 'task_get',
76
+ 'task_list',
77
+ 'task_update',
78
+ // `todo_write` writes to `.pugi/todos.json`
79
+ // — metadata, not source. From the workspace's perspective it is
80
+ // read-only (no source mutation), so plan-mode keeps the tool
81
+ // available: planning a refactor frequently means writing the
82
+ // todo board BEFORE picking which file to touch.
83
+ 'todo_write',
84
+ // Tool gap pack : `brief` persists structured
85
+ // status notes to `.pugi/briefs/<session>.jsonl`. Like `todo_write`
86
+ // the writes land in metadata, not source, so plan mode keeps the
87
+ // tool available — planning frequently means emitting a "planning"
88
+ // brief first.
89
+ 'brief',
90
+ // Backlog #5 P0 : verify_plan_execution reads session
91
+ // audit log (metadata, not source). Safe in plan mode — a planning
92
+ // loop needs to verify its plan-capture steps before any writes.
93
+ 'verify_plan_execution',
94
+ // Tool gap pack : `sleep` is a no-op as far as the
95
+ // workspace is concerned (wall-clock delay only). Plan mode keeps it
96
+ // available so a planning loop can throttle its own polling.
97
+ 'sleep',
98
+ 'web_fetch',
99
+ // β1b T4 : web_search is read-only from the workspace's
100
+ // perspective (no file writes, no shell). Egress goes through the
101
+ // Anvil-proxied Brave Search API, gated by the same opt-in posture as
102
+ // web_fetch. Plan mode keeps the tool available because reading the
103
+ // web is part of how a plan is researched.
104
+ 'web_search',
105
+ // PUGI-78 Phase 1: symbols.* namespace is read-only in Phase 1
106
+ // (rename / format / code_actions return PREVIEW edits, the
107
+ // dispatcher applies via apply_patch in Phase 2). Plan-mode KEEPS
108
+ // these tools available — navigation / outline / call-hierarchy
109
+ // questions are the bread-and-butter of a planning loop, and the
110
+ // surface explicitly never mutates source in this phase. When Phase
111
+ // 2 lifts to "apply on confirm", the apply path moves OUT of
112
+ // symbols.* and into apply_patch, which is already plan-mode-gated.
113
+ 'symbols_call_hierarchy',
114
+ 'symbols_code_actions',
115
+ 'symbols_diagnostics',
116
+ 'symbols_find_definition',
117
+ 'symbols_find_references',
118
+ 'symbols_format',
119
+ 'symbols_hover',
120
+ 'symbols_implementations',
121
+ 'symbols_list_in_file',
122
+ 'symbols_rename',
123
+ 'symbols_signature',
124
+ 'symbols_type_definition',
125
+ 'symbols_workspace_symbols',
126
+ ]);
28
127
  /**
29
- * Tools we actually wire today. The registry has more entries
30
- * (task_*, skill, question) those route through the runtime layer, not
31
- * the local filesystem, so they ship in a follow-up PR. M1 cornerstone is
32
- * the six core tools.
128
+ * Tools the engine loop dispatches. β1 expands the M1 cornerstone six
129
+ * (read/write/edit/grep/glob/bash) with task_* + ask_user_question +
130
+ * skill + skill list + web_fetch. The registry advertises these slots
131
+ * to the runtime; without dispatcher entries the model would call
132
+ * "unknown tool" errors.
33
133
  */
34
- const WIRED_TOOLS = new Set(['read', 'write', 'edit', 'grep', 'glob', 'bash']);
35
- export function buildToolsSchema(kind) {
134
+ const WIRED_TOOLS = new Set([
135
+ 'read',
136
+ 'write',
137
+ 'edit',
138
+ 'grep',
139
+ 'glob',
140
+ 'bash',
141
+ // PowerShell tool for Windows-first workflows.
142
+ // Same bash permission class — destructive-pattern classifier applies.
143
+ // Plan mode excludes shell tools by design (read-only); the planMode
144
+ // check on the schema side already handles that, so we just list it
145
+ // alongside 'bash' here.
146
+ 'powershell',
147
+ 'ask_user_question',
148
+ 'skill',
149
+ 'skills_list',
150
+ 'task_create',
151
+ 'task_get',
152
+ 'task_list',
153
+ 'task_update',
154
+ // see READ_ONLY_TOOLS above for the rationale.
155
+ 'todo_write',
156
+ // Tool gap pack: see READ_ONLY_TOOLS above for `brief` / `sleep`.
157
+ 'brief',
158
+ // Backlog #5 P0 : verify_plan_execution anti-fake-dispatch gate.
159
+ 'verify_plan_execution',
160
+ 'sleep',
161
+ // Tool gap pack: scratch-worktree primitives. Not in
162
+ // READ_ONLY_TOOLS — they mutate workspace state (a new git worktree
163
+ // is a workspace change even though the touched subtree is
164
+ // `.pugi`-scoped). Plan mode excludes them just like write/edit/bash.
165
+ 'enter_worktree',
166
+ 'exit_worktree',
167
+ // Tool gap pack: experimental engine-only echo helper. Gated
168
+ // behind allowSyntheticOutput; the schema layer omits it unless the
169
+ // caller opted in, but we list the name here so a deliberately-opted
170
+ // executor passes the WIRED_TOOLS guard.
171
+ 'synthetic_output',
172
+ 'web_fetch',
173
+ // β1b T4: see READ_ONLY_TOOLS above.
174
+ 'web_search',
175
+ // β2 S3 : real subagent spawn primitive. Only advertised
176
+ // when buildToolsSchema is called with allowAgent=true (orchestrator
177
+ // / root Pugi context); plan-mode also excludes it because spawning
178
+ // a write-capable child violates plan-mode's read-only contract.
179
+ 'agent',
180
+ // β7 L5+T11 : transactional multi-file edit. Routes
181
+ // through the same security gate as Layer A/B/C; not advertised in
182
+ // plan mode (mutation surface).
183
+ 'multi_edit',
184
+ // PUGI-78 Phase 1: symbols.* namespace (13 LSP-bridged tools). All
185
+ // read-only in Phase 1 — `rename` / `format` / `code_actions`
186
+ // return PREVIEW edits; the dispatcher applies via apply_patch in
187
+ // Phase 2 (PUGI-134). The executor dispatch wires each name to the
188
+ // matching `symbols*Tool` wrapper in `src/tools/lsp-tools.ts`.
189
+ 'symbols_call_hierarchy',
190
+ 'symbols_code_actions',
191
+ 'symbols_diagnostics',
192
+ 'symbols_find_definition',
193
+ 'symbols_find_references',
194
+ 'symbols_format',
195
+ 'symbols_hover',
196
+ 'symbols_implementations',
197
+ 'symbols_list_in_file',
198
+ 'symbols_rename',
199
+ 'symbols_signature',
200
+ 'symbols_type_definition',
201
+ 'symbols_workspace_symbols',
202
+ ]);
203
+ export function buildToolsSchema(kind, options = { allowFetch: false, allowSearch: false }) {
36
204
  const planMode = kind === 'plan';
205
+ // β4 M1/M3: splice MCP tools BEFORE the native list assembly so the
206
+ // engine-loop sees them in stable alphabetical order alongside native
207
+ // tools. We keep the entries appended after the native push so plan-
208
+ // mode can be filtered by namespace prefix in one place at the end.
209
+ const mcpDefs = buildMcpToolDefs(options.mcpRegistry);
37
210
  const toolDefs = [
38
211
  {
39
212
  name: 'read',
@@ -49,13 +222,16 @@ export function buildToolsSchema(kind) {
49
222
  },
50
223
  {
51
224
  name: 'grep',
52
- description: 'Substring-match every workspace file. Returns up to 200 matches with {path, line, text}. Use this to locate code by symbol/keyword.',
225
+ description: 'Substring-match every workspace file. Returns up to 200 matches with {path, line, text}. Canonical arg: `query`. Aliases accepted: text, pattern, q, search.',
53
226
  parameters: {
54
227
  type: 'object',
55
- additionalProperties: false,
56
- required: ['query'],
228
+ additionalProperties: true,
57
229
  properties: {
58
- query: { type: 'string', description: 'Substring to search for.' },
230
+ query: { type: 'string', description: 'Substring to search for (canonical).' },
231
+ text: { type: 'string', description: 'Alias for query.' },
232
+ pattern: { type: 'string', description: 'Alias for query.' },
233
+ q: { type: 'string', description: 'Alias for query.' },
234
+ search: { type: 'string', description: 'Alias for query.' },
59
235
  },
60
236
  },
61
237
  },
@@ -72,10 +248,442 @@ export function buildToolsSchema(kind) {
72
248
  },
73
249
  },
74
250
  ];
251
+ // β1 T1/T6: TodoWrite (Pugi grammar = `task_*`). Append-only ledger
252
+ // at `.pugi/sessions/<id>/tasks.jsonl`.
253
+ toolDefs.push({
254
+ name: 'task_create',
255
+ description: 'Append a new task to the session todo ledger. Returns the assigned task id and full record. Mirrors the standard tool TodoWrite/create.',
256
+ parameters: {
257
+ type: 'object',
258
+ additionalProperties: false,
259
+ required: ['title'],
260
+ properties: {
261
+ title: { type: 'string', description: 'Short imperative summary, max 2000 chars.' },
262
+ status: {
263
+ type: 'string',
264
+ enum: ['pending', 'in_progress', 'completed', 'cancelled'],
265
+ description: 'Initial status. Default pending.',
266
+ },
267
+ notes: { type: 'string', description: 'Optional free-form context.' },
268
+ },
269
+ },
270
+ }, {
271
+ name: 'task_get',
272
+ description: 'Fetch a single task record by id. Returns null when absent.',
273
+ parameters: {
274
+ type: 'object',
275
+ additionalProperties: false,
276
+ required: ['id'],
277
+ properties: { id: { type: 'string' } },
278
+ },
279
+ }, {
280
+ name: 'task_list',
281
+ description: 'List all tasks for the current session ordered by createdAt ascending.',
282
+ parameters: { type: 'object', additionalProperties: false, properties: {} },
283
+ }, {
284
+ name: 'task_update',
285
+ description: 'Mutate status/title/notes on an existing task. Throws on unknown id. Append-only journal.',
286
+ parameters: {
287
+ type: 'object',
288
+ additionalProperties: false,
289
+ required: ['id'],
290
+ properties: {
291
+ id: { type: 'string' },
292
+ title: { type: 'string' },
293
+ status: {
294
+ type: 'string',
295
+ enum: ['pending', 'in_progress', 'completed', 'cancelled'],
296
+ },
297
+ notes: { type: 'string' },
298
+ },
299
+ },
300
+ });
301
+ // `todo_write` — batch TodoWrite mirror of
302
+ // the upstream tool's upstream tool. Whereas `task_*` above is granular
303
+ // (one mutation per call, JSONL append, session-scoped),
304
+ // `todo_write` snapshots the FULL board in one call, JSON snapshot
305
+ // at `.pugi/todos.json`, workspace-scoped. Enforces the single-
306
+ // in-progress invariant at dispatch time: a batch with >1
307
+ // `in_progress` rejects with `TODO_INVARIANT_VIOLATED` and the
308
+ // on-disk board is left unchanged.
309
+ toolDefs.push({
310
+ name: 'todo_write',
311
+ description: 'Replace the workspace todo board (batch snapshot, not incremental). Emit the FULL todo list every call. ' +
312
+ 'At most ONE item may carry status="in_progress" — violations reject with TODO_INVARIANT_VIOLATED. ' +
313
+ 'Persisted atomically to .pugi/todos.json. Mirrors the standard tool TodoWrite verbatim.',
314
+ parameters: todoWriteJsonSchema,
315
+ });
316
+ // Tool gap pack : `brief` — structured operator
317
+ // progress note. JSONL-append к `.pugi/briefs/<session>.jsonl` via
318
+ // the atomic tmp+rename pattern. Plan-mode safe (metadata only, no
319
+ // source mutation).
320
+ toolDefs.push({
321
+ name: 'brief',
322
+ description: 'Emit a short structured progress note to the operator. Use INSTEAD of narrating in prose ' +
323
+ 'when you want to surface "what I am doing now". One JSON record per call, persisted к ' +
324
+ '.pugi/briefs/<session>.jsonl. Required: headline (<=120 chars), status (planning|working|blocked|done). ' +
325
+ 'Optional: detail (<=2000 chars).',
326
+ parameters: briefJsonSchema,
327
+ });
328
+ // Backlog #5 P0 : verify_plan_execution — anti-fake-dispatch gate.
329
+ // Reads the session audit log (metadata only, no source mutation). Plan-mode
330
+ // safe: a plan-loop frequently needs к verify its plan-capture steps before
331
+ // any write turn fires. Surface это as a tool the model can call right
332
+ // before emitting а "done" message on multi-step turns.
333
+ toolDefs.push({
334
+ name: 'verify_plan_execution',
335
+ description: 'Assert that every step in a previously-stated plan actually executed. ' +
336
+ 'Reads the session audit log (tool calls + file mutations recorded this session) ' +
337
+ 'and checks each step\'s declared requirements. Returns { status: "verified" | "gap", gaps: [...] }. ' +
338
+ 'When status is "gap" the engine loop continues so the model can fill the missing ' +
339
+ 'steps or explicitly explain why they were skipped. Call this BEFORE emitting а ' +
340
+ 'final "done" message when you stated а multi-step plan at the start of the turn.',
341
+ parameters: verifyPlanExecutionJsonSchema,
342
+ });
343
+ // Tool gap pack : `sleep` — wall-clock pause primitive.
344
+ // Counts against --max-turns like any other dispatch; the model should
345
+ // prefer a real poll loop (read + grep + retry) over blind sleep.
346
+ toolDefs.push({
347
+ name: 'sleep',
348
+ description: 'Pause the engine loop for an integer number of seconds (1..600). ' +
349
+ 'Counts against the turn budget. Prefer a real poll loop over blind sleep — ' +
350
+ 'this tool exists only for fixed cooldowns the operator owns.',
351
+ parameters: sleepJsonSchema,
352
+ });
353
+ if (!planMode) {
354
+ // Tool gap pack : scratch-worktree primitives.
355
+ // `enter_worktree` materialises a fresh git worktree at
356
+ // `.pugi/worktrees/<taskId>/` so a long task can land its edits in
357
+ // isolation; `exit_worktree` is the cleanup primitive. Both are
358
+ // workspace mutations, so plan mode excludes them.
359
+ toolDefs.push({
360
+ name: 'enter_worktree',
361
+ description: 'Open a scratch git worktree at .pugi/worktrees/<taskId>/ for write-isolated work. ' +
362
+ 'Required: taskId (lowercase slug). Optional: baseRef (defaults to main). ' +
363
+ 'Returns { worktreePath, branchName }. Pair with exit_worktree for cleanup.',
364
+ parameters: enterWorktreeJsonSchema,
365
+ });
366
+ toolDefs.push({
367
+ name: 'exit_worktree',
368
+ description: 'Tear down a scratch worktree previously opened by enter_worktree. ' +
369
+ 'The worktreePath MUST live under <workspaceRoot>/.pugi/worktrees/ — anything else refuses. ' +
370
+ 'Runs `git worktree remove --force` then rmSync. Idempotent.',
371
+ parameters: exitWorktreeJsonSchema,
372
+ });
373
+ }
374
+ // Tool gap pack : experimental engine-only echo
375
+ // helper. Advertised only when the caller explicitly opted in via
376
+ // `allowSyntheticOutput: true`. Off-by-default mirrors the privacy
377
+ // posture used for `allowFetch` / `allowSearch` — every customer-side
378
+ // CLI omits this so the model cannot use it as a side-channel that
379
+ // bypasses the normal tool-result logging.
380
+ if (options.allowSyntheticOutput) {
381
+ toolDefs.push({
382
+ name: 'synthetic_output',
383
+ description: 'Engine-only echo helper. Writes verbatim text to the requested stream (stdout|stderr). ' +
384
+ `Capped at ${(16 * 1024).toString()} bytes per call. Test fixture, not for production agent flows.`,
385
+ parameters: syntheticOutputJsonSchema,
386
+ });
387
+ }
388
+ // β1 T2 → structured AskUserQuestion bridge.
389
+ // Schema upgraded to 's multi-choice form: header chip +
390
+ // {label, description} per option. Dispatcher accepts the structured
391
+ // form (preferred) AND the legacy string-array form so existing
392
+ // callers / tests keep working until the next major bump.
393
+ //
394
+ // Interactive TTY → returns the picked label(s).
395
+ // Non-TTY / no bridge → `[user_input_required]` envelope.
396
+ toolDefs.push({
397
+ name: 'ask_user_question',
398
+ description: 'Clarifying multi-choice question to the operator. Use INSTEAD of asking in prose when one parameter is missing. Required: question (?-ended), header (≤12 chars), 2-4 options each with {label, description}. NEVER include "Other" — UI auto-adds. Budget: max 1 per turn.',
399
+ parameters: askUserQuestionJsonSchema,
400
+ });
401
+ // β1 T3: Skill tool — discover + invoke locally-installed skills.
402
+ toolDefs.push({
403
+ name: 'skills_list',
404
+ description: 'List installed skills (global + workspace). Returns name+description+scope.',
405
+ parameters: {
406
+ type: 'object',
407
+ additionalProperties: false,
408
+ properties: {
409
+ scope: { type: 'string', enum: ['all', 'global', 'workspace'] },
410
+ },
411
+ },
412
+ }, {
413
+ name: 'skill',
414
+ description: 'Load a skill body by name. Workspace scope wins over global. Body capped at 32KB.',
415
+ parameters: {
416
+ type: 'object',
417
+ additionalProperties: false,
418
+ required: ['name'],
419
+ properties: { name: { type: 'string' } },
420
+ },
421
+ });
422
+ // PUGI-78 Phase 1: symbols.* namespace (13 tools). LSP-bridged
423
+ // symbol-aware operations that replace whole-file reads for
424
+ // navigation questions. Each tool returns 1-2 KB of shaped JSON
425
+ // vs 5-50 KB for the raw file read it replaces — 10-100x token
426
+ // savings per refactor turn. All read-only in Phase 1 — `rename`
427
+ // / `format` / `code_actions` return PREVIEW edits the dispatcher
428
+ // applies via apply_patch in a future ticket.
429
+ //
430
+ // Schemas use the same JSON-Schema shape as the rest of the
431
+ // toolbox: required positional args, additionalProperties: false.
432
+ // The `lang` field is a closed enum of the 5 supported language
433
+ // server slugs (ts/js/py/go/rust). The dispatcher resolves the
434
+ // LSP client by lang BEFORE calling the underlying primitive.
435
+ const symbolsLangEnum = { type: 'string', enum: ['ts', 'js', 'py', 'go', 'rust'], description: 'LSP language slug.' };
436
+ const symbolsPosArgs = {
437
+ lang: symbolsLangEnum,
438
+ file: { type: 'string', description: 'Workspace-relative file path.' },
439
+ line: { type: 'integer', minimum: 0, description: 'Zero-based line index.' },
440
+ col: { type: 'integer', minimum: 0, description: 'Zero-based character index.' },
441
+ };
442
+ toolDefs.push({
443
+ name: 'symbols_find_definition',
444
+ description: 'Locate the definition of the symbol at (line, col) in <file>. Returns {file, line, character}. PREFER over read for "where is X defined?" questions.',
445
+ parameters: {
446
+ type: 'object',
447
+ additionalProperties: false,
448
+ required: ['lang', 'file', 'line', 'col'],
449
+ properties: symbolsPosArgs,
450
+ },
451
+ }, {
452
+ name: 'symbols_find_references',
453
+ description: 'List every reference to the symbol at (line, col). Returns {file, line, character}[]. PREFER over grep for "find callers of X" questions.',
454
+ parameters: {
455
+ type: 'object',
456
+ additionalProperties: false,
457
+ required: ['lang', 'file', 'line', 'col'],
458
+ properties: symbolsPosArgs,
459
+ },
460
+ }, {
461
+ name: 'symbols_list_in_file',
462
+ description: 'Outline the symbols (functions, classes, methods) defined in <file>. Returns flat {name, kind, line, character, containerName}[]. PREFER over read for "outline" questions.',
463
+ parameters: {
464
+ type: 'object',
465
+ additionalProperties: false,
466
+ required: ['lang', 'file'],
467
+ properties: { lang: symbolsLangEnum, file: { type: 'string' } },
468
+ },
469
+ }, {
470
+ name: 'symbols_rename',
471
+ description: 'Preview a rename refactor for the symbol at (line, col) to <newName>. Returns {files, edits}[]. PREVIEW ONLY in Phase 1 — operator confirms then dispatches apply_patch.',
472
+ parameters: {
473
+ type: 'object',
474
+ additionalProperties: false,
475
+ required: ['lang', 'file', 'line', 'col', 'newName'],
476
+ properties: {
477
+ ...symbolsPosArgs,
478
+ newName: { type: 'string', minLength: 1, description: 'New symbol name.' },
479
+ },
480
+ },
481
+ }, {
482
+ name: 'symbols_hover',
483
+ description: 'Type info + docstring at (line, col). Returns {content, range?}. Body capped at 4 KB.',
484
+ parameters: {
485
+ type: 'object',
486
+ additionalProperties: false,
487
+ required: ['lang', 'file', 'line', 'col'],
488
+ properties: symbolsPosArgs,
489
+ },
490
+ }, {
491
+ name: 'symbols_signature',
492
+ description: 'Function signature at a call site. Returns {label, parameters, activeParameter?}. NULL when cursor is not inside a call.',
493
+ parameters: {
494
+ type: 'object',
495
+ additionalProperties: false,
496
+ required: ['lang', 'file', 'line', 'col'],
497
+ properties: symbolsPosArgs,
498
+ },
499
+ }, {
500
+ name: 'symbols_workspace_symbols',
501
+ description: 'Workspace-wide fuzzy symbol search. Server-defined match (substring / fuzzy / prefix). Returns {name, file, line, kind, containerName?}[].',
502
+ parameters: {
503
+ type: 'object',
504
+ additionalProperties: false,
505
+ required: ['lang', 'query'],
506
+ properties: {
507
+ lang: symbolsLangEnum,
508
+ query: { type: 'string', minLength: 1, description: 'Symbol query.' },
509
+ },
510
+ },
511
+ }, {
512
+ name: 'symbols_call_hierarchy',
513
+ description: 'Incoming + outgoing callers for the symbol at (line, col). Returns {incoming, outgoing}[].',
514
+ parameters: {
515
+ type: 'object',
516
+ additionalProperties: false,
517
+ required: ['lang', 'file', 'line', 'col'],
518
+ properties: symbolsPosArgs,
519
+ },
520
+ }, {
521
+ name: 'symbols_implementations',
522
+ description: 'Concrete implementations of the interface / abstract method at (line, col). Returns flat references list.',
523
+ parameters: {
524
+ type: 'object',
525
+ additionalProperties: false,
526
+ required: ['lang', 'file', 'line', 'col'],
527
+ properties: symbolsPosArgs,
528
+ },
529
+ }, {
530
+ name: 'symbols_type_definition',
531
+ description: 'Type definition (vs value definition) of the symbol at (line, col). Returns the type declaration location.',
532
+ parameters: {
533
+ type: 'object',
534
+ additionalProperties: false,
535
+ required: ['lang', 'file', 'line', 'col'],
536
+ properties: symbolsPosArgs,
537
+ },
538
+ }, {
539
+ name: 'symbols_code_actions',
540
+ description: 'Quick-fix list at the given range. Returns {title, kind?, isPreferred?}[].',
541
+ parameters: {
542
+ type: 'object',
543
+ additionalProperties: false,
544
+ required: ['lang', 'file', 'startLine', 'startChar', 'endLine', 'endChar'],
545
+ properties: {
546
+ lang: symbolsLangEnum,
547
+ file: { type: 'string' },
548
+ startLine: { type: 'integer', minimum: 0 },
549
+ startChar: { type: 'integer', minimum: 0 },
550
+ endLine: { type: 'integer', minimum: 0 },
551
+ endChar: { type: 'integer', minimum: 0 },
552
+ },
553
+ },
554
+ }, {
555
+ name: 'symbols_format',
556
+ description: 'Formatter — returns the text edits the LSP server would apply. PREVIEW ONLY in Phase 1.',
557
+ parameters: {
558
+ type: 'object',
559
+ additionalProperties: false,
560
+ required: ['lang', 'file'],
561
+ properties: {
562
+ lang: symbolsLangEnum,
563
+ file: { type: 'string' },
564
+ tabSize: { type: 'integer', minimum: 1 },
565
+ insertSpaces: { type: 'boolean' },
566
+ },
567
+ },
568
+ }, {
569
+ name: 'symbols_diagnostics',
570
+ description: 'Cached LSP diagnostics (error / warning / info / hint) for <file>. Returns up to ~50 entries.',
571
+ parameters: {
572
+ type: 'object',
573
+ additionalProperties: false,
574
+ required: ['lang', 'file'],
575
+ properties: { lang: symbolsLangEnum, file: { type: 'string' } },
576
+ },
577
+ });
578
+ // β1 T5 → β1a r1 (gating fix): WebFetch wire-in. Schema
579
+ // mirrors the existing tool surface in
580
+ // `apps/pugi-cli/src/tools/web-fetch.ts`. SSRF guard runs inside the
581
+ // tool itself, but advertising the tool to the model when the tenant
582
+ // has not opted in is itself a privacy leak — the model could infer
583
+ // URL patterns and try to exfiltrate via the refused call's argument
584
+ // bytes. Only push the schema entry when the operator has explicitly
585
+ // enabled fetch (either via `.pugi/settings.json::web.fetch.enabled`
586
+ // or via `--allow-fetch`).
587
+ if (options.allowFetch) {
588
+ toolDefs.push({
589
+ name: 'web_fetch',
590
+ description: 'One-shot HTTP GET against an operator-supplied URL. Response is parsed to Markdown and wrapped in <untrusted-content> sentinel. Gated off by default.',
591
+ parameters: {
592
+ type: 'object',
593
+ additionalProperties: false,
594
+ required: ['url'],
595
+ properties: {
596
+ url: { type: 'string', description: 'Fully-qualified http(s) URL.' },
597
+ },
598
+ },
599
+ });
600
+ }
601
+ // β1b T4 : web_search advertisement. Same off-by-default
602
+ // privacy posture as web_fetch — the query string itself is an egress
603
+ // event that can leak operator intent to the upstream Brave Search
604
+ // backend. The tool dispatcher applies SSRF guards (no localhost via
605
+ // the Anvil proxy URL), rate-limits (5 req/min per session), and caps
606
+ // the result payload at 1 MiB. Sentinel-wrapped results so the model
607
+ // treats every snippet as data, not instructions.
608
+ if (options.allowSearch) {
609
+ toolDefs.push({
610
+ name: 'web_search',
611
+ description: 'Search the web via Brave Search (Anvil-proxied). Returns up to 10 sentinel-wrapped {title, url, snippet} results. Rate-limited to 5 calls/min per session. Gated off by default.',
612
+ parameters: {
613
+ type: 'object',
614
+ additionalProperties: false,
615
+ required: ['query'],
616
+ properties: {
617
+ query: {
618
+ type: 'string',
619
+ description: 'Search query, max 256 chars. Plain text — no operators.',
620
+ },
621
+ count: {
622
+ type: 'integer',
623
+ description: 'Optional result count (1..10, default 10).',
624
+ },
625
+ },
626
+ },
627
+ });
628
+ }
629
+ // β2 S3 : `agent` tool — subagent spawn primitive.
630
+ // Off by default; surfaced only when the caller explicitly opts in
631
+ // (orchestrator parents pass allowAgent=true via the engine adapter).
632
+ // Plan mode FORCES the tool off regardless because a write-capable
633
+ // child would violate plan-mode's read-only contract.
634
+ if (options.allowAgent && !planMode) {
635
+ toolDefs.push({
636
+ name: 'agent',
637
+ description: 'Spawn a specialist subagent under a Cyber-Zoo brand persona. '
638
+ + 'Role selects the persona + isolation tier: '
639
+ + 'researcher/reviewer/architect are read-only, verifier reads + runs tests, '
640
+ + 'coder/release/devops/design_qa get write + bash. '
641
+ + 'The child runs a fresh Anvil engine loop with its own transcript and '
642
+ + 'returns a JSON envelope (filesChanged, toolCallCount, status, summary). '
643
+ + 'Use this when the work needs a specialist persona OR write isolation via a scratch worktree.',
644
+ parameters: {
645
+ type: 'object',
646
+ additionalProperties: false,
647
+ required: ['role', 'brief'],
648
+ properties: {
649
+ role: {
650
+ type: 'string',
651
+ enum: [
652
+ 'orchestrator',
653
+ 'architect',
654
+ 'coder',
655
+ 'verifier',
656
+ 'reviewer',
657
+ 'researcher',
658
+ 'release',
659
+ 'devops',
660
+ 'design_qa',
661
+ ],
662
+ description: 'SubagentRole — selects persona + isolation tier.',
663
+ },
664
+ brief: {
665
+ type: 'string',
666
+ maxLength: 8000,
667
+ description: 'One-paragraph task description forwarded to the child as the user prompt. '
668
+ + 'Be concrete: include filenames, expected behavior, and acceptance criteria.',
669
+ },
670
+ isolation: {
671
+ type: 'string',
672
+ enum: ['worktree', 'shared_fs', 'auto'],
673
+ description: 'Optional override. `worktree` forces a scratch git worktree for write isolation; '
674
+ + '`shared_fs` forces same-tree execution; `auto` (default) defers to the role tier.',
675
+ },
676
+ },
677
+ },
678
+ });
679
+ }
75
680
  if (!planMode) {
76
681
  toolDefs.push({
77
682
  name: 'write',
78
- description: 'Create or overwrite a workspace file. Use for new files only — prefer edit for existing files. Workspace-scoped.',
683
+ description: 'Create or overwrite a workspace file. Prefer edit for existing files. ' +
684
+ 'For OVERWRITE of an existing file, you MUST read the file first in this session — ' +
685
+ 'write refuses with STALE_READ if the file changed since your last read, or if you ' +
686
+ 'never read it. New-file creation (path does not exist) skips that gate. Workspace-scoped.',
79
687
  parameters: {
80
688
  type: 'object',
81
689
  additionalProperties: false,
@@ -87,7 +695,10 @@ export function buildToolsSchema(kind) {
87
695
  },
88
696
  }, {
89
697
  name: 'edit',
90
- description: 'Replace exactly one occurrence of oldString with newString inside an already-read file. Fails if the file changed since you read it or if oldString is missing/duplicate.',
698
+ description: 'Replace exactly one occurrence of oldString with newString inside an already-read file. ' +
699
+ 'Refuses with STALE_READ if the file was never read this session or the on-disk contents ' +
700
+ 'drifted since the read (mtime+sha gate). Recovery: re-read with the `read` tool, then ' +
701
+ 'retry the edit. Also fails if oldString is missing or duplicate.',
91
702
  parameters: {
92
703
  type: 'object',
93
704
  additionalProperties: false,
@@ -100,18 +711,131 @@ export function buildToolsSchema(kind) {
100
711
  },
101
712
  }, {
102
713
  name: 'bash',
103
- description: 'Run a shell command inside the workspace root via /bin/sh -c. Inherits a sanitized env (PUGI_API_KEY/PUGI_LOGIN_TOKEN stripped). 30s timeout. Output capped at 64KB. Returns {exitCode, stdout, stderr, truncated}.',
714
+ description: 'Run a shell command inside the workspace root via /bin/sh -c. Inherits a sanitized env (PUGI_API_KEY/PUGI_LOGIN_TOKEN stripped). 60s timeout. Output capped at 32KB combined stdout+stderr. ' +
715
+ 'Optional `redirect` opts the call into log-discipline mode: stdout+stderr are written to a file on disk (default `.pugi/runs/<sessionId>/bash-<hash>.log` or a workspace-relative override) and the response carries the path + last N lines (default 20, max 200) instead of the full output. Use redirect for long-running scripts (builds, training loops, agentic stdout dumps) where the trailing lines + a path to the full log saves thousands of tokens vs the truncated head. ' +
716
+ 'Returns {exitCode, stdout, stderr, truncated} on the buffered path, or {exitCode, stdout:\'\', stderr:\'\', logPath, tail, truncated:false} when redirect is set.',
104
717
  parameters: {
105
718
  type: 'object',
106
719
  additionalProperties: false,
107
720
  required: ['command'],
108
721
  properties: {
109
722
  command: { type: 'string', description: 'Single shell command to execute.' },
723
+ redirect: {
724
+ type: 'object',
725
+ additionalProperties: false,
726
+ description: 'When set, redirect stdout+stderr to a file instead of returning content. Use for long-running scripts that produce thousands of lines.',
727
+ properties: {
728
+ path: {
729
+ type: 'string',
730
+ description: 'Workspace-relative path to write the log file. Defaults to `.pugi/runs/<sessionId>/bash-<commandHash>.log`. Absolute paths or `..` traversal are rejected.',
731
+ },
732
+ tailLines: {
733
+ type: 'number',
734
+ description: 'Number of trailing lines to fold into the response tail. Default 20, max 200.',
735
+ },
736
+ },
737
+ },
738
+ },
739
+ },
740
+ }, {
741
+ name: 'powershell',
742
+ description: 'Run a PowerShell command via `pwsh -NoProfile -Command` (or `powershell.exe` fallback on Windows). Same security posture as bash — destructive pattern gate applies. 30s default timeout, 120s max. Output capped at 64KB. Returns {exitCode, stdout, stderr, truncated, shellBinary}. Prefer the dedicated bash tool for /bin/sh scripts; use this when the operator needs native pwsh cmdlets or *.ps1 syntax.',
743
+ parameters: {
744
+ type: 'object',
745
+ additionalProperties: false,
746
+ required: ['command'],
747
+ properties: {
748
+ command: { type: 'string', description: 'Single PowerShell command or script.' },
749
+ cwd: { type: 'string', description: 'Optional cwd; defaults to workspace root.' },
750
+ timeoutMs: { type: 'number', description: 'Hard timeout (default 30000, max 120000).' },
751
+ },
752
+ },
753
+ },
754
+ // β7 L5+T11 : transactional multi-file edit. Either
755
+ // all entries land or none do — failures roll the workspace back
756
+ // via the same journal + snapshot machinery the dispatcher uses.
757
+ // Cap is 50 entries; beyond that the operator (or model) should
758
+ // split the refactor or use Layer C rewrites.
759
+ {
760
+ name: 'multi_edit',
761
+ description: 'Apply an ordered batch of single-occurrence file edits as one transaction. ' +
762
+ 'Each entry is {file, oldString, newString} like the `edit` tool. Either every ' +
763
+ 'edit lands or none do — a failure rolls the workspace back to the pre-dispatch ' +
764
+ 'state via journal + snapshot. Cap 50 edits per call. Use this for coordinated ' +
765
+ 'refactors (rename across files, add an import to many modules).',
766
+ parameters: {
767
+ type: 'object',
768
+ additionalProperties: false,
769
+ required: ['edits'],
770
+ properties: {
771
+ edits: {
772
+ type: 'array',
773
+ minItems: 1,
774
+ maxItems: 50,
775
+ items: {
776
+ type: 'object',
777
+ additionalProperties: false,
778
+ required: ['file', 'oldString', 'newString'],
779
+ properties: {
780
+ file: { type: 'string', description: 'Workspace-relative file path.' },
781
+ oldString: { type: 'string', description: 'Verbatim substring; must be unique in the pre-edit file.' },
782
+ newString: { type: 'string', description: 'Replacement string. Empty string means delete.' },
783
+ },
784
+ },
785
+ },
110
786
  },
111
787
  },
112
788
  });
113
789
  }
114
- return toolDefs;
790
+ // β4 M1/M3: append MCP tools last. Plan mode skips them because every
791
+ // MCP tool is treated as medium-risk until per-tool annotations land
792
+ // in the MCP spec; treating MCP read-as-read would require server-
793
+ // side metadata we cannot trust today (a misconfigured server could
794
+ // claim `read` while running a destructive op).
795
+ if (!planMode) {
796
+ for (const def of mcpDefs) {
797
+ toolDefs.push({
798
+ name: def.name,
799
+ description: def.description,
800
+ parameters: def.parameters,
801
+ });
802
+ }
803
+ }
804
+ // L3 : leak-parity underscore-prefix filter. Every
805
+ // tool's parameter schema is scrubbed of `_`-prefixed fields before
806
+ // the model ever sees it. Native tool schemas above currently declare
807
+ // no `_*` fields, but MCP tools surfaced through buildMcpToolDefs
808
+ // come from third-party servers whose authors may follow the same
809
+ // convention (an MCP tool can declare `_sessionId` knowing the CLI
810
+ // dispatcher will inject it before forwarding). The dispatcher
811
+ // (buildExecutor below) does NOT strip these from the args record at
812
+ // call time — `_internal*` keys still flow through to tool handlers
813
+ // when an upstream layer populates them.
814
+ return toolDefs.map((tool) => ({
815
+ name: tool.name,
816
+ description: tool.description,
817
+ parameters: stripInternalFields(tool.parameters),
818
+ }));
819
+ }
820
+ /**
821
+ * L11: tolerant args-parse for the denial fingerprint. Unlike
822
+ * `parseArgs` (which throws on malformed JSON so the model sees a
823
+ * parse error), this swallows failures and returns `{}` — the denial
824
+ * tracker needs SOME key even when the raw payload is unparseable,
825
+ * because malformed-args spam is itself a pattern operators want to
826
+ * see in `/permissions denials`.
827
+ */
828
+ function safeParseForTracking(raw) {
829
+ if (!raw || raw.trim() === '')
830
+ return {};
831
+ try {
832
+ return JSON.parse(raw);
833
+ }
834
+ catch {
835
+ // Use the raw string as the fingerprint payload so repeated
836
+ // identical malformed dispatches still cluster.
837
+ return { _rawArgs: raw.slice(0, 512) };
838
+ }
115
839
  }
116
840
  function parseArgs(raw) {
117
841
  if (!raw || raw.trim() === '')
@@ -127,39 +851,189 @@ function parseArgs(raw) {
127
851
  throw new Error(`invalid JSON in tool arguments: ${error.message}`);
128
852
  }
129
853
  }
854
+ /**
855
+ * Strict canonical-only argument coercion (leak P0 L2).
856
+ *
857
+ * Reverts the beta.17 alias acceptance (`file` / `filename` / `filepath`
858
+ * / `file_path` → `path`). The alias shim was the wrong direction: it
859
+ * paved over a model-side prompt-drift bug at the runtime layer, weakened
860
+ * the strict JSON-Schema contract one layer up (`additionalProperties:
861
+ * false`), and drifted away from the upstream reference (research memo
862
+ * §1.1 — `z.strictObject` rejects aliased fields).
863
+ *
864
+ * The compensating change ships in the persona prompts: Pugi's system
865
+ * prompt and Hiroshi's persona body now declare canonical parameter
866
+ * names with few-shot wrong/right contrasts so the model learns the
867
+ * grammar upstream of the bridge.
868
+ */
130
869
  function requireString(obj, key) {
131
870
  const v = obj[key];
132
- if (typeof v !== 'string') {
133
- throw new Error(`tool argument "${key}" must be a string`);
134
- }
135
- return v;
871
+ if (typeof v === 'string')
872
+ return v;
873
+ throw new Error(`tool argument "${key}" must be a string`);
874
+ }
875
+ /**
876
+ * Accept `path` (canonical) or `filePath` (the upstream tool convention) for
877
+ * write/edit/read tool arguments. Models trained on CC system prompts
878
+ * emit `filePath`; insisting on `path` only forces 2-3 retry waste on
879
+ * every file write (CEO live smoke: snake.html dispatch
880
+ * burned 2 turns retrying `{filePath: ...}` payloads before falling
881
+ * back к bash heredoc). Defense-in-depth alias keeps canonical name
882
+ * (so persona prompts can still teach `path` as the right answer) AND
883
+ * tolerates the CC-trained variant without operator-visible failure.
884
+ */
885
+ function requirePathArg(obj) {
886
+ if (typeof obj['path'] === 'string')
887
+ return obj['path'];
888
+ if (typeof obj['filePath'] === 'string')
889
+ return obj['filePath'];
890
+ throw new Error('tool argument "path" must be a string (alias "filePath" also accepted)');
136
891
  }
137
892
  export function buildExecutor(input) {
138
- const { kind, ctx, hooks, sessionId } = input;
893
+ const { kind, ctx, hooks, mvpHooksConfig, sessionId, askUserBridge, interactive, allowFetch, allowSearch, allowSyntheticOutput, agentDispatch, mcpRegistry, permissionMode, permissionAlwaysCache, permissionAsk, } = input;
894
+ // per-cycle budget. Default to a fresh instance scoped to
895
+ // this executor's closure lifetime; tests pass their own.
896
+ const retryBudget = input.retryBudget ?? new RetryBudget();
897
+ const mcpPrompt = input.mcpPrompt ?? defaultNonInteractiveMcpPrompt;
898
+ const workspaceRoot = input.workspaceRoot ?? ctx.root;
139
899
  const planMode = kind === 'plan';
900
+ const denialTracking = input.denialTracking;
901
+ // L11: helper that records a denial (when tracking is wired) and
902
+ // ALWAYS returns an Error whose message includes a compact
903
+ // `<denial-context>` reminder when the same (tool, args) pair has
904
+ // already been refused at least once before in this session.
905
+ //
906
+ // The reminder is appended to the THROWN message — the engine loop
907
+ // appends thrown messages to the transcript as tool-result strings,
908
+ // so the model sees the aggregate the next time it considers a
909
+ // dispatch. Without this every retry would only see the latest
910
+ // single-turn reason and could loop indefinitely.
911
+ //
912
+ // Best-effort: a hash/clone failure inside the tracker MUST NOT
913
+ // mask the original refusal. The catch path falls back to a bare
914
+ // Error with the reason text.
915
+ const recordDenial = (toolName, args, reason) => {
916
+ if (!denialTracking)
917
+ return new Error(reason);
918
+ try {
919
+ const record = denialTracking.recordDenial(toolName, args, reason);
920
+ // Only inject the reminder once the threshold is hit — the very
921
+ // first denial is the model's first chance to learn, no need to
922
+ // shout. From the 2nd repeat onwards the model has demonstrated
923
+ // it is not learning from the single-turn sentinel, so we splice
924
+ // the aggregate context.
925
+ if (record.count >= DENIAL_REMINDER_THRESHOLD) {
926
+ const reminder = buildDenialContext(denialTracking);
927
+ if (reminder.length > 0) {
928
+ return new Error(`${reason}\n\n${reminder}`);
929
+ }
930
+ }
931
+ }
932
+ catch {
933
+ // Tracking is best-effort. Fall through to the bare Error so
934
+ // the refusal still propagates.
935
+ }
936
+ return new Error(reason);
937
+ };
140
938
  return async ({ name, arguments: argsRaw }) => {
141
- if (!WIRED_TOOLS.has(name)) {
142
- throw new Error(`unknown tool: ${name}`);
939
+ // β4 M1/M3: MCP tool names live outside WIRED_TOOLS. They are
940
+ // validated lazily by the dispatcher (the registry knows which
941
+ // names are actually exposed). The namespace check happens FIRST
942
+ // so a bad `mcp__bogus__foo` does not collide with the native
943
+ // unknown-tool branch.
944
+ const isMcpName = name.startsWith(MCP_TOOL_PREFIX);
945
+ // L11: parse-or-empty args once up-front so every deny path
946
+ // below can fingerprint the call against the denial tracker. We
947
+ // tolerate parse failure — `{}` keys still produce a stable hash
948
+ // (the model may have sent malformed JSON, but the refusal is
949
+ // semantic, not parse-driven).
950
+ const argsForTracking = safeParseForTracking(argsRaw);
951
+ if (!isMcpName && !WIRED_TOOLS.has(name)) {
952
+ throw recordDenial(name, argsForTracking, `unknown tool: ${name}`);
953
+ }
954
+ // — canonical 4-mode permission gate. Routes the dispatch
955
+ // decision BEFORE the legacy plan-mode-only enforcement so the new
956
+ // surface is the source of truth when the caller opted in. Absent
957
+ // `permissionMode` falls through to the legacy plan-mode branch
958
+ // (existing semantics preserved for callsites that have not
959
+ // migrated yet).
960
+ let hooksBypassed = false;
961
+ if (permissionMode) {
962
+ const decision = permissionGate(name, argsRaw, {
963
+ permissionMode,
964
+ ...(permissionAlwaysCache ? { alwaysCache: permissionAlwaysCache } : {}),
965
+ });
966
+ if (decision.decision === 'deny') {
967
+ throw new PermissionDenied(name, getToolClass(name), permissionMode, decision.reason);
968
+ }
969
+ if (decision.decision === 'ask') {
970
+ if (!permissionAsk) {
971
+ // Non-interactive caller (CI / pipes / agent-as-tool) cannot
972
+ // surface a prompt. Collapse to deny so the loop receives a
973
+ // deterministic refusal instead of hanging.
974
+ throw new PermissionDenied(name, decision.toolClass, permissionMode, `Ask mode: no operator prompt available for ${name} (non-interactive caller)`);
975
+ }
976
+ const answer = await permissionAsk({
977
+ toolName: name,
978
+ toolClass: decision.toolClass,
979
+ question: decision.question,
980
+ options: decision.options,
981
+ });
982
+ const verdict = permissionAlwaysCache
983
+ ? applyAskAnswer(permissionAlwaysCache, name, answer)
984
+ : applyAskAnswer({ alwaysAllowed: new Set(), alwaysDenied: new Set() }, name, answer);
985
+ if (verdict.decision === 'deny') {
986
+ throw new PermissionDenied(name, decision.toolClass, permissionMode, verdict.reason);
987
+ }
988
+ // verdict.decision === 'allow' falls through to dispatch.
989
+ }
990
+ else {
991
+ // allow — honour the bypass flag for the hook layer below.
992
+ hooksBypassed = decision.hooksBypassed === true;
993
+ }
143
994
  }
144
- if (planMode && !READ_ONLY_TOOLS.has(name)) {
145
- // Sentinel recognised by `runEngineLoop` terminates the loop
146
- // with status `tool_refused`. The CLI surfaces this as a blocked
147
- // outcome, not a failure, because plan mode is doing its job.
148
- throw new Error(`PLAN_MODE_REFUSED: ${name} is not allowed in plan mode`);
995
+ else if (planMode) {
996
+ // Legacy plan-mode enforcement (kind === 'plan') stays in place
997
+ // for callers that have not opted into the canonical gate.
998
+ // MCP tools are uniformly refused in plan mode (see schema-side
999
+ // rationale in buildToolsSchema). Native tools split via
1000
+ // READ_ONLY_TOOLS as before.
1001
+ if (isMcpName || !READ_ONLY_TOOLS.has(name)) {
1002
+ throw recordDenial(name, argsForTracking, `PLAN_MODE_REFUSED: ${name} is not allowed in plan mode`);
1003
+ }
149
1004
  }
150
- // α6.9: refuse cancelled-token tool dispatch BEFORE PreToolUse
1005
+ // : refuse cancelled-token tool dispatch BEFORE PreToolUse
151
1006
  // hooks fire so a cancelled brief never reaches user-defined
152
1007
  // hook scripts. Sentinel `OPERATOR_ABORTED:<tool>` is recognised
153
1008
  // by `runEngineLoop` as a terminal-cancel signal so the loop
154
1009
  // returns control to the caller rather than retrying the model.
155
1010
  if (ctx.cancellation && ctx.cancellation.isAborted) {
156
- throw new Error(`OPERATOR_ABORTED: ${name} refused — operator cancelled the dispatch.`);
1011
+ throw recordDenial(name, argsForTracking, `OPERATOR_ABORTED: ${name} refused — operator cancelled the dispatch.`);
1012
+ }
1013
+ // — per-cycle tool retry budget. Same tool + same canonical
1014
+ // args = same bucket. Once the cap is hit we throw a typed sentinel
1015
+ // so the model is forced out of a repair loop. We gate AFTER
1016
+ // permission (denied calls do not burn budget) and BEFORE PreToolUse
1017
+ // hooks (hook-blocked retries DO count — the model still issued the
1018
+ // same call). The `recordAttempt` fires unconditionally so warn-only
1019
+ // mode (PUGI_RETRY_BUDGET_DISABLED=1) still tracks the pattern for
1020
+ // diagnostics.
1021
+ const argHash = hashArgs(argsRaw);
1022
+ const budgetDecision = retryBudget.shouldAllow(name, argHash);
1023
+ retryBudget.recordAttempt(name, argHash);
1024
+ if (!budgetDecision.allowed) {
1025
+ throw new RetryBudgetExhausted(name, budgetDecision.cap, argHash);
157
1026
  }
158
1027
  // Fire PreToolUse hooks. The match grammar takes the tool name and
159
1028
  // (when extractable) the target path. Each new tool dispatch starts a
160
1029
  // fresh dedup batch so a hook fires once per dispatch, not once per
161
1030
  // session.
162
- if (hooks && sessionId) {
1031
+ //
1032
+ // — bypass mode skips the entire hook layer (PreToolUse +
1033
+ // PostToolUse + PostToolUseFailure). The gate's allow decision
1034
+ // carries the `hooksBypassed` flag; we honour it here so the
1035
+ // executor stays single-pass.
1036
+ if (hooks && sessionId && !hooksBypassed) {
163
1037
  hooks.resetBatch();
164
1038
  const path = extractToolPath(name, argsRaw);
165
1039
  const preCtx = {
@@ -179,37 +1053,228 @@ export function buildExecutor(input) {
179
1053
  const hook = matchingPreHooks[i];
180
1054
  const result = preResults[i];
181
1055
  if (hook && result && hook.onFailure === 'block' && !result.ok) {
182
- throw new Error(`HOOK_BLOCKED: PreToolUse hook (${hook.run.slice(0, 80)}) refused ${name} (exit=${result.exitCode})`);
1056
+ // L11: record the PreToolUse hook denial so the model
1057
+ // sees the pattern reminder on subsequent turns. Without
1058
+ // this the model would re-issue the same refused call and
1059
+ // burn a turn each time before noticing the loop.
1060
+ throw recordDenial(name, argsForTracking, `HOOK_BLOCKED: PreToolUse hook (${hook.run.slice(0, 80)}) refused ${name} (exit=${result.exitCode})`);
183
1061
  }
184
1062
  }
185
1063
  }
186
- const args = parseArgs(argsRaw);
1064
+ // MVP: fire `hooks-mvp.json` PreToolUse hooks. Distinct
1065
+ // config file from the legacy `hooks.json` system so operator
1066
+ // configs do not collide. Same blocking semantics — a non-zero
1067
+ // exit from a hook declared `blocking: true` refuses the dispatch
1068
+ // with `HOOK_BLOCKED:` sentinel. Bypass mode skips this surface
1069
+ // identically to the legacy hooks block above.
1070
+ if (mvpHooksConfig && sessionId && !hooksBypassed && !mvpHooksConfig.isEmpty()) {
1071
+ const { fireHooks } = await import('../hooks/index.js');
1072
+ const outcome = await fireHooks({
1073
+ config: mvpHooksConfig,
1074
+ event: 'PreToolUse',
1075
+ payload: {
1076
+ event: 'PreToolUse',
1077
+ sessionId,
1078
+ toolName: name,
1079
+ toolInputSummary: hashArgs(argsRaw),
1080
+ },
1081
+ toolName: name,
1082
+ workspaceRoot: ctx.root,
1083
+ });
1084
+ if (outcome.anyBlocked) {
1085
+ const blocking = outcome.results.find((r) => r.blocked);
1086
+ const sentinel = blocking?.blockSentinel ??
1087
+ `HOOK_BLOCKED: PreToolUse MVP-hook refused ${name}`;
1088
+ throw recordDenial(name, argsForTracking, sentinel);
1089
+ }
1090
+ }
1091
+ // β4 M1/M3: MCP dispatch deferred to the `dispatch` closure below so
1092
+ // PostToolUse / PostToolUseFailure hooks observe MCP calls just like
1093
+ // native calls. The dispatcher does its own argument parsing — MCP
1094
+ // arg errors surface as model-visible `[MCP dispatch error] ...`
1095
+ // strings, not throws.
1096
+ const args = isMcpName ? {} : parseArgs(argsRaw);
187
1097
  const dispatch = async () => {
1098
+ if (isMcpName) {
1099
+ return dispatchMcpTool({
1100
+ name,
1101
+ argumentsRaw: argsRaw,
1102
+ registry: mcpRegistry,
1103
+ prompt: mcpPrompt,
1104
+ });
1105
+ }
1106
+ // β1 T1/T2/T3/T5/T6: async-dispatch the new tool surface.
1107
+ // task_*, skill, ask_user_question, web_fetch all live behind
1108
+ // an async or async-compatible boundary.
1109
+ if (name === 'task_create' || name === 'task_get' || name === 'task_list' || name === 'task_update') {
1110
+ return dispatchTaskTool(name, args, { workspaceRoot, sessionId });
1111
+ }
1112
+ if (name === 'todo_write') {
1113
+ // batch TodoWrite. The dispatcher delegates the
1114
+ // Zod validation + atomic persist to the tool module — any
1115
+ // ZodError or `TODO_INVARIANT_VIOLATED` sentinel surfaces here
1116
+ // as a thrown Error and lands on the catch arm below, which
1117
+ // re-emits it through the PostToolUseFailure hook.
1118
+ return dispatchTodoWrite({ workspaceRoot }, args);
1119
+ }
1120
+ // Tool gap pack : brief / sleep / synthetic_output /
1121
+ // enter_worktree / exit_worktree dispatchers. Each tool returns a
1122
+ // sentinel string on recoverable validation failures (no throw)
1123
+ // so the engine adapter surfaces them as plain tool results and
1124
+ // the model can self-correct.
1125
+ if (name === 'brief') {
1126
+ return dispatchBrief({
1127
+ workspaceRoot,
1128
+ // Fallback when running outside an audit session (CI, smoke
1129
+ // tests, one-shot CLI commands) — keep the JSONL writes
1130
+ // grouped under a stable basename instead of dropping them.
1131
+ sessionId: sessionId ?? 'no-session',
1132
+ }, args);
1133
+ }
1134
+ if (name === 'verify_plan_execution') {
1135
+ // Backlog #5 P0 : anti-fake-dispatch gate. Reads
1136
+ // the session audit log accumulated during this dispatch (and
1137
+ // earlier turns in the same engine loop invocation).
1138
+ return dispatchVerifyPlanExecution(ctx.session, args);
1139
+ }
1140
+ if (name === 'sleep') {
1141
+ return dispatchSleep({}, args);
1142
+ }
1143
+ if (name === 'synthetic_output') {
1144
+ if (!allowSyntheticOutput) {
1145
+ // Mirrors the `web_fetch` / `agent` defense-in-depth posture:
1146
+ // a stale schema must never let the model invoke an opt-in
1147
+ // tool. Surface a clear refusal sentinel the dispatcher can
1148
+ // record for denial tracking.
1149
+ throw new Error('synthetic_output: tool not enabled in this executor. Engine-only fixture; opt in via allowSyntheticOutput.');
1150
+ }
1151
+ return dispatchSyntheticOutput({}, args);
1152
+ }
1153
+ if (name === 'enter_worktree') {
1154
+ return dispatchEnterWorktree({ workspaceRoot }, args);
1155
+ }
1156
+ if (name === 'exit_worktree') {
1157
+ return dispatchExitWorktree({ workspaceRoot }, args);
1158
+ }
1159
+ if (name === 'ask_user_question') {
1160
+ return dispatchAskUser(args, { interactive: Boolean(interactive), bridge: askUserBridge });
1161
+ }
1162
+ if (name === 'skill' || name === 'skills_list') {
1163
+ return dispatchSkillTool(name, args, { workspaceRoot });
1164
+ }
1165
+ if (name === 'web_fetch') {
1166
+ return dispatchWebFetch(args, { ctx, allowFetch: Boolean(allowFetch) });
1167
+ }
1168
+ if (name === 'web_search') {
1169
+ return dispatchWebSearch(args, {
1170
+ ctx,
1171
+ allowSearch: Boolean(allowSearch),
1172
+ sessionId,
1173
+ });
1174
+ }
1175
+ if (name === 'multi_edit') {
1176
+ return dispatchMultiEdit(args, ctx);
1177
+ }
1178
+ if (name === 'agent') {
1179
+ // β2a r1 (Backend Architect P1): defense in depth.
1180
+ // `WIRED_TOOLS` includes `agent`, so a plan-mode model that
1181
+ // fabricates an `agent` tool call would otherwise be routed
1182
+ // here. The plan-mode refusal at the top of the executor only
1183
+ // fires for tools NOT in READ_ONLY_TOOLS; `agent` is
1184
+ // intentionally absent from both sets, so we explicitly refuse
1185
+ // it here. This pairs with `native-pugi.ts` hard-gating
1186
+ // `agentDispatch` itself off in plan mode — without this
1187
+ // defensive throw a future schema bug could let a plan-mode
1188
+ // model spawn a write-capable child and break the read-only
1189
+ // contract.
1190
+ if (planMode) {
1191
+ throw recordDenial(name, argsForTracking, 'PLAN_MODE_REFUSED: agent is not allowed in plan mode');
1192
+ }
1193
+ return dispatchAgent(args, agentDispatch);
1194
+ }
1195
+ // PUGI-78 Phase 1: symbols.* namespace dispatch. Every name in
1196
+ // SYMBOLS_TOOL_NAMES routes through `dispatchSymbolsTool` which
1197
+ // resolves the LSP client by `lang`, calls the matching
1198
+ // `symbols*Tool` wrapper in `src/tools/lsp-tools.ts`, and
1199
+ // serialises the result for the engine envelope. Read-only —
1200
+ // matches the registry posture; the post-edit diagnostics hook
1201
+ // below is the only mutation the symbols.* surface participates in.
1202
+ if (SYMBOLS_TOOL_NAMES.has(name)) {
1203
+ return dispatchSymbolsTool(name, args, ctx);
1204
+ }
188
1205
  return dispatchTool(name, args, ctx);
189
1206
  };
190
1207
  try {
191
1208
  const result = await dispatch();
192
- if (hooks && sessionId) {
1209
+ // post-edit LSP diagnostics. After a
1210
+ // successful `edit` / `write` / `multi_edit`, ask the cached
1211
+ // language server for diagnostics on the touched file(s) and
1212
+ // append the result to the tool envelope so the model can
1213
+ // self-correct in the same turn. Silent skip when the language
1214
+ // is unsupported, no server is installed, or the request times
1215
+ // out — agent throughput beats diagnostic recall.
1216
+ const augmented = await appendPostEditDiagnostics(name, args, ctx, result);
1217
+ if (hooks && sessionId && !hooksBypassed) {
193
1218
  const path = extractToolPath(name, argsRaw);
194
1219
  await hooks.fire({
195
1220
  sessionId,
196
1221
  event: 'PostToolUse',
197
1222
  tool: name,
198
1223
  path,
199
- payload: { tool: name, arguments: argsRaw, ok: true, result: result.slice(0, 1024) },
1224
+ payload: { tool: name, arguments: argsRaw, ok: true, result: augmented.slice(0, 1024) },
200
1225
  });
201
1226
  }
202
- return result;
1227
+ return augmented;
203
1228
  }
204
1229
  catch (error) {
205
- // α6.9: re-shape OperatorAbortedError throws from the
1230
+ // #24 (CEO P1) hook chains. After the legacy
1231
+ // PostToolUseFailure registry fire (per-error-class block below),
1232
+ // ALSO fire the settings.json hook chain. Chains are best-effort:
1233
+ // a chain command crash never propagates back here so the engine
1234
+ // loop sees the original throw unchanged.
1235
+ const fireFailureChain = async (errorMessage) => {
1236
+ try {
1237
+ await firePostToolUseFailureChain(ctx.root, {
1238
+ toolName: name,
1239
+ args: argsForTracking,
1240
+ error: errorMessage,
1241
+ exitCode: 1,
1242
+ });
1243
+ }
1244
+ catch (chainError) {
1245
+ process.stderr.write(`[pugi hook-chains] PostToolUseFailure chain crashed: ${chainError.message}\n`);
1246
+ }
1247
+ };
1248
+ // — surface the PermissionDenied sentinel as a model-
1249
+ // readable message instead of leaking the raw Error type. The
1250
+ // string format is stable so the engine adapter / spec layer
1251
+ // can pattern-match against it.
1252
+ if (error instanceof PermissionDenied) {
1253
+ // PostToolUseFailure fires for visibility unless bypass is on.
1254
+ if (hooks && sessionId && !hooksBypassed) {
1255
+ await hooks.fire({
1256
+ sessionId,
1257
+ event: 'PostToolUseFailure',
1258
+ tool: name,
1259
+ payload: {
1260
+ tool: name,
1261
+ arguments: argsRaw,
1262
+ ok: false,
1263
+ error: error.toModelMessage(),
1264
+ },
1265
+ });
1266
+ }
1267
+ await fireFailureChain(error.toModelMessage());
1268
+ throw new Error(error.toModelMessage());
1269
+ }
1270
+ // : re-shape OperatorAbortedError throws from the
206
1271
  // file-tools layer into the same `OPERATOR_ABORTED:` sentinel
207
1272
  // the upstream cancellation gate uses so `runEngineLoop` sees
208
1273
  // a consistent terminal-cancel signal regardless of whether
209
1274
  // the abort landed pre-dispatch or mid-tool (e.g. inside the
210
1275
  // grep file-loop).
211
1276
  if (error instanceof OperatorAbortedError) {
212
- if (hooks && sessionId) {
1277
+ if (hooks && sessionId && !hooksBypassed) {
213
1278
  const path = extractToolPath(name, argsRaw);
214
1279
  await hooks.fire({
215
1280
  sessionId,
@@ -224,9 +1289,37 @@ export function buildExecutor(input) {
224
1289
  },
225
1290
  });
226
1291
  }
227
- throw new Error(`OPERATOR_ABORTED: ${name} aborted mid-execution.`);
1292
+ await fireFailureChain(`OPERATOR_ABORTED: ${name}`);
1293
+ throw recordDenial(name, argsForTracking, `OPERATOR_ABORTED: ${name} aborted mid-execution.`);
228
1294
  }
229
- if (hooks && sessionId) {
1295
+ // re-shape StaleReadError into a
1296
+ // deterministic STALE_READ:<reason> sentinel so the model's
1297
+ // retry policy can pattern-match on a stable prefix instead of
1298
+ // free-form prose. The model is expected to re-read the file and
1299
+ // retry the edit — the message points it at exactly that recovery
1300
+ // path. PostToolUseFailure hooks observe the typed error so an
1301
+ // operator can build a "warn me when stale edits keep happening"
1302
+ // hook (likely a concurrency / multi-agent indicator).
1303
+ if (error instanceof StaleReadError) {
1304
+ if (hooks && sessionId && !hooksBypassed) {
1305
+ const path = extractToolPath(name, argsRaw);
1306
+ await hooks.fire({
1307
+ sessionId,
1308
+ event: 'PostToolUseFailure',
1309
+ tool: name,
1310
+ path,
1311
+ payload: {
1312
+ tool: name,
1313
+ arguments: argsRaw,
1314
+ ok: false,
1315
+ error: `STALE_READ: ${error.reason} on ${error.path}`,
1316
+ },
1317
+ });
1318
+ }
1319
+ await fireFailureChain(`STALE_READ: ${error.reason} on ${error.path}`);
1320
+ throw recordDenial(name, argsForTracking, `STALE_READ: ${name} on ${error.path} refused (${error.reason}). Re-read the file with the \`read\` tool, then retry the ${name}.`);
1321
+ }
1322
+ if (hooks && sessionId && !hooksBypassed) {
230
1323
  const path = extractToolPath(name, argsRaw);
231
1324
  await hooks.fire({
232
1325
  sessionId,
@@ -241,6 +1334,7 @@ export function buildExecutor(input) {
241
1334
  },
242
1335
  });
243
1336
  }
1337
+ await fireFailureChain(error instanceof Error ? error.message : String(error));
244
1338
  throw error;
245
1339
  }
246
1340
  };
@@ -266,7 +1360,7 @@ function extractToolPath(name, argsRaw) {
266
1360
  function dispatchTool(name, args, ctx) {
267
1361
  switch (name) {
268
1362
  case 'read': {
269
- const { path } = { path: requireString(args, 'path') };
1363
+ const { path } = { path: requirePathArg(args) };
270
1364
  const content = readTool(ctx, path);
271
1365
  // Cap the content surfaced back to the model so a 10MB file
272
1366
  // does not blow the context window. The model sees the head
@@ -279,7 +1373,7 @@ function dispatchTool(name, args, ctx) {
279
1373
  }
280
1374
  case 'write': {
281
1375
  const wargs = {
282
- path: requireString(args, 'path'),
1376
+ path: requirePathArg(args),
283
1377
  content: requireString(args, 'content'),
284
1378
  };
285
1379
  writeTool(ctx, wargs.path, wargs.content);
@@ -287,7 +1381,7 @@ function dispatchTool(name, args, ctx) {
287
1381
  }
288
1382
  case 'edit': {
289
1383
  const eargs = {
290
- path: requireString(args, 'path'),
1384
+ path: requirePathArg(args),
291
1385
  oldString: requireString(args, 'oldString'),
292
1386
  newString: requireString(args, 'newString'),
293
1387
  };
@@ -295,7 +1389,11 @@ function dispatchTool(name, args, ctx) {
295
1389
  return `edited ${eargs.path}`;
296
1390
  }
297
1391
  case 'grep': {
298
- const gargs = { query: requireString(args, 'query') };
1392
+ const queryRaw = args.query ?? args.text ?? args.pattern ?? args.q ?? args.search;
1393
+ if (typeof queryRaw !== 'string' || queryRaw.length === 0) {
1394
+ throw new Error('tool argument "query" must be a non-empty string (aliases: text/pattern/q/search)');
1395
+ }
1396
+ const gargs = { query: queryRaw };
299
1397
  const matches = grepTool(ctx, gargs.query);
300
1398
  if (matches.length === 0)
301
1399
  return `no matches for ${gargs.query}`;
@@ -312,12 +1410,37 @@ function dispatchTool(name, args, ctx) {
312
1410
  return `${results.length} path(s):\n${results.slice(0, 100).join('\n')}${results.length > 100 ? `\n(... ${results.length - 100} more)` : ''}`;
313
1411
  }
314
1412
  case 'bash': {
315
- const bargs = { command: requireString(args, 'command') };
316
- // The class-aware bash tool (sprint α5.2) replaces the legacy
1413
+ const command = requireString(args, 'command');
1414
+ // Pugi backlog P2 parse the optional redirect block. We
1415
+ // accept either no field, an empty object (== "use defaults"),
1416
+ // or `{path?, tailLines?}`. The bash tool's helper layer
1417
+ // normalises both values; we only do the outer-shape parse
1418
+ // here so a malformed arg surfaces as a model-readable error.
1419
+ const rawRedirect = args['redirect'];
1420
+ let redirect;
1421
+ if (rawRedirect !== undefined && rawRedirect !== null) {
1422
+ if (typeof rawRedirect !== 'object' || Array.isArray(rawRedirect)) {
1423
+ throw new Error('tool argument "redirect" must be an object when present');
1424
+ }
1425
+ const r = rawRedirect;
1426
+ const pathArg = r['path'];
1427
+ const tailArg = r['tailLines'];
1428
+ if (pathArg !== undefined && typeof pathArg !== 'string') {
1429
+ throw new Error('redirect.path must be a string when present');
1430
+ }
1431
+ if (tailArg !== undefined && (typeof tailArg !== 'number' || !Number.isFinite(tailArg))) {
1432
+ throw new Error('redirect.tailLines must be a finite number when present');
1433
+ }
1434
+ redirect = {
1435
+ ...(pathArg !== undefined ? { path: pathArg } : {}),
1436
+ ...(tailArg !== undefined ? { tailLines: tailArg } : {}),
1437
+ };
1438
+ }
1439
+ // The class-aware bash tool (sprint ) replaces the legacy
317
1440
  // file-tools entry point. We use the sync variant here because
318
1441
  // dispatchTool's signature is sync; the async tool is reserved
319
- // for the REPL path (sprint α5.7) where promises are first class.
320
- const result = bashToolSync({ cmd: bargs.command }, {
1442
+ // for the REPL path (sprint ) where promises are first class.
1443
+ const result = bashToolSync({ cmd: command, ...(redirect !== undefined ? { redirect } : {}) }, {
321
1444
  root: ctx.root,
322
1445
  settings: ctx.settings,
323
1446
  session: ctx.session,
@@ -330,6 +1453,10 @@ function dispatchTool(name, args, ctx) {
330
1453
  ];
331
1454
  if (result.artifactRef)
332
1455
  parts.push(`artifactRef=${result.artifactRef}`);
1456
+ if (result.logPath)
1457
+ parts.push(`logPath=${result.logPath}`);
1458
+ if (result.tail)
1459
+ parts.push(`tail:\n${result.tail}`);
333
1460
  if (result.truncated)
334
1461
  parts.push('truncated=true');
335
1462
  if (result.timedOut)
@@ -337,9 +1464,554 @@ function dispatchTool(name, args, ctx) {
337
1464
  const body = parts.filter(Boolean).join('\n');
338
1465
  return body || '(no output)';
339
1466
  }
1467
+ case 'powershell': {
1468
+ // pwsh dispatcher. Permission gate reuses the
1469
+ // bash classifier so destructive patterns block the same way.
1470
+ const command = requireString(args, 'command');
1471
+ const cwd = optionalString(args, 'cwd');
1472
+ const timeoutMs = optionalNumber(args, 'timeoutMs');
1473
+ const psResult = powerShellToolSync({ cmd: command, ...(cwd !== undefined ? { cwd } : {}), ...(timeoutMs !== undefined ? { timeoutMs } : {}) }, {
1474
+ root: ctx.root,
1475
+ settings: ctx.settings,
1476
+ session: ctx.session,
1477
+ source: 'agent',
1478
+ });
1479
+ const parts = [
1480
+ `exit=${psResult.exitCode}`,
1481
+ `shell=${psResult.shellBinary}`,
1482
+ psResult.stdout ? `stdout:\n${psResult.stdout}` : '',
1483
+ psResult.stderr ? `stderr:\n${psResult.stderr}` : '',
1484
+ ];
1485
+ if (psResult.truncated)
1486
+ parts.push('truncated=true');
1487
+ if (psResult.timedOut)
1488
+ parts.push('timedOut=true');
1489
+ return parts.filter(Boolean).join('\n') || '(no output)';
1490
+ }
340
1491
  default:
341
1492
  // Exhaustive; unreachable because of the WIRED_TOOLS guard above.
342
1493
  throw new Error(`unhandled tool: ${name}`);
343
1494
  }
344
1495
  }
1496
+ /* ----------------------------- β1 dispatchers ----------------------------- */
1497
+ function dispatchTaskTool(name, args, opts) {
1498
+ if (!opts.sessionId) {
1499
+ throw new Error(`${name}: no sessionId in scope — task ledger requires a session`);
1500
+ }
1501
+ const tctx = { workspaceRoot: opts.workspaceRoot, sessionId: opts.sessionId };
1502
+ switch (name) {
1503
+ case 'task_create': {
1504
+ const title = requireString(args, 'title');
1505
+ const status = optionalString(args, 'status');
1506
+ const notes = optionalString(args, 'notes');
1507
+ const record = taskCreate(tctx, {
1508
+ title,
1509
+ ...(status !== undefined ? { status: status } : {}),
1510
+ ...(notes !== undefined ? { notes } : {}),
1511
+ });
1512
+ return JSON.stringify(record);
1513
+ }
1514
+ case 'task_get': {
1515
+ const id = requireString(args, 'id');
1516
+ const record = taskGet(tctx, id);
1517
+ return record ? JSON.stringify(record) : 'null';
1518
+ }
1519
+ case 'task_list': {
1520
+ const list = taskList(tctx);
1521
+ return JSON.stringify(list);
1522
+ }
1523
+ case 'task_update': {
1524
+ const id = requireString(args, 'id');
1525
+ const title = optionalString(args, 'title');
1526
+ const status = optionalString(args, 'status');
1527
+ const notes = optionalString(args, 'notes');
1528
+ const record = taskUpdate(tctx, {
1529
+ id,
1530
+ ...(title !== undefined ? { title } : {}),
1531
+ ...(status !== undefined ? { status: status } : {}),
1532
+ ...(notes !== undefined ? { notes } : {}),
1533
+ });
1534
+ return JSON.stringify(record);
1535
+ }
1536
+ }
1537
+ }
1538
+ async function dispatchAskUser(args, opts) {
1539
+ const rawOptions = args['options'];
1540
+ if (!Array.isArray(rawOptions)) {
1541
+ throw new Error('ask_user_question: options must be an array');
1542
+ }
1543
+ // detect structured vs legacy form. Structured
1544
+ // entries are objects with {label, description}; legacy entries are
1545
+ // plain strings. The structured path validates via Zod and emits the
1546
+ // [ask_user_question:answered|cancelled|timeout] envelope. The legacy
1547
+ // path stays for back-compat with the existing β1 T2 tests + the
1548
+ // <pugi-ask> prompt envelope (which still feeds string options).
1549
+ const looksStructured = rawOptions.length > 0
1550
+ && typeof rawOptions[0] === 'object'
1551
+ && rawOptions[0] !== null
1552
+ && !Array.isArray(rawOptions[0]);
1553
+ if (looksStructured) {
1554
+ const result = await dispatchAskUserQuestion({ interactive: opts.interactive, ...(opts.bridge ? { bridge: opts.bridge } : {}) }, args);
1555
+ return result.envelope;
1556
+ }
1557
+ // Legacy string-array form.
1558
+ const question = requireString(args, 'question');
1559
+ const options = rawOptions.map((o, i) => {
1560
+ if (typeof o !== 'string') {
1561
+ throw new Error(`ask_user_question: options[${i}] must be a string`);
1562
+ }
1563
+ return o;
1564
+ });
1565
+ const multiSelect = args['multiSelect'] === true;
1566
+ const result = await askUser({ interactive: opts.interactive, ...(opts.bridge ? { bridge: opts.bridge } : {}) }, { question, options, multiSelect });
1567
+ return result.envelope;
1568
+ }
1569
+ async function dispatchSkillTool(name, args, opts) {
1570
+ if (name === 'skills_list') {
1571
+ const scopeArg = optionalString(args, 'scope');
1572
+ const scope = scopeArg === 'global' || scopeArg === 'workspace' ? scopeArg : 'all';
1573
+ const list = skillList({ workspaceRoot: opts.workspaceRoot }, { scope });
1574
+ return JSON.stringify(list);
1575
+ }
1576
+ // name === 'skill' (invoke).
1577
+ // β1a r1 : `skillInvoke` is now async — it re-verifies
1578
+ // the trust manifest sha256 against the on-disk body on every call.
1579
+ // Bubble up `await` so a post-install tamper surfaces as a tool
1580
+ // error the model sees, not a swallowed Promise<SkillInvokeResult>.
1581
+ const skName = requireString(args, 'name');
1582
+ const result = await skillInvoke({ workspaceRoot: opts.workspaceRoot }, { name: skName });
1583
+ return JSON.stringify(result);
1584
+ }
1585
+ async function dispatchWebFetch(args, opts) {
1586
+ const url = requireString(args, 'url');
1587
+ const result = await webFetchTool({ url }, {
1588
+ settings: opts.ctx.settings,
1589
+ allowFetch: opts.allowFetch,
1590
+ });
1591
+ return JSON.stringify(result);
1592
+ }
1593
+ async function dispatchWebSearch(args, opts) {
1594
+ const query = requireString(args, 'query');
1595
+ // `count` is optional integer 1..10. Validate here so the tool layer
1596
+ // gets a clean value (the tool clamps internally too — defense in
1597
+ // depth, since the model can pass anything).
1598
+ let count;
1599
+ if (args['count'] !== undefined && args['count'] !== null) {
1600
+ const n = args['count'];
1601
+ if (typeof n !== 'number' || !Number.isInteger(n)) {
1602
+ throw new Error('web_search: count must be an integer');
1603
+ }
1604
+ count = n;
1605
+ }
1606
+ const result = await webSearchTool({ query, ...(count !== undefined ? { count } : {}) }, {
1607
+ settings: opts.ctx.settings,
1608
+ allowSearch: opts.allowSearch,
1609
+ sessionId: opts.sessionId,
1610
+ });
1611
+ return JSON.stringify(result);
1612
+ }
1613
+ /**
1614
+ * β2 S3 dispatch — wire the model-emitted `agent` tool call to the
1615
+ * real subagent spawn primitive. When the executor was built without
1616
+ * `agentDispatch` (e.g. a child loop, or a parent that explicitly
1617
+ * disabled subagent spawn), the call is refused with a structured
1618
+ * envelope so the model can adapt instead of crashing the parent loop.
1619
+ */
1620
+ async function dispatchAgent(args, opts) {
1621
+ if (!opts) {
1622
+ // No dispatch context — return a structured refusal envelope.
1623
+ // This matches the agent-tool.ts no-engine-client path and lets
1624
+ // the model decide whether to retry inline or abandon the
1625
+ // delegation. Throwing here would terminate the parent on a tool
1626
+ // error frame which is the wrong UX when the issue is config.
1627
+ return JSON.stringify({
1628
+ ok: false,
1629
+ status: 'failed',
1630
+ summary: 'agent tool refused: dispatch not wired in this engine adapter. '
1631
+ + 'Re-run from a parent loop with agentDispatch configured.',
1632
+ });
1633
+ }
1634
+ const parsed = parseAgentArgs(args);
1635
+ const result = await agentTool(parsed, {
1636
+ session: opts.parentSession,
1637
+ engineClient: opts.engineClient,
1638
+ ...(opts.parentBudgetRemaining
1639
+ ? { parentBudgetRemaining: opts.parentBudgetRemaining }
1640
+ : {}),
1641
+ });
1642
+ return JSON.stringify(result);
1643
+ }
1644
+ function parseAgentArgs(args) {
1645
+ // Surface a clean error message to the model when the args don't
1646
+ // match the schema. agentTool itself also validates via Zod; this
1647
+ // pre-parse layer keeps the error stack short.
1648
+ const role = requireString(args, 'role');
1649
+ const brief = requireString(args, 'brief');
1650
+ const isolationRaw = optionalString(args, 'isolation');
1651
+ const out = {
1652
+ role: role,
1653
+ brief,
1654
+ ...(isolationRaw ? { isolation: isolationRaw } : {}),
1655
+ };
1656
+ return out;
1657
+ }
1658
+ function optionalString(obj, key) {
1659
+ const v = obj[key];
1660
+ if (v === undefined || v === null)
1661
+ return undefined;
1662
+ if (typeof v !== 'string') {
1663
+ throw new Error(`tool argument "${key}" must be a string when present`);
1664
+ }
1665
+ return v;
1666
+ }
1667
+ function optionalNumber(obj, key) {
1668
+ const v = obj[key];
1669
+ if (v === undefined || v === null)
1670
+ return undefined;
1671
+ if (typeof v !== 'number' || !Number.isFinite(v)) {
1672
+ throw new Error(`tool argument "${key}" must be a finite number when present`);
1673
+ }
1674
+ return v;
1675
+ }
1676
+ /**
1677
+ * β7 L5+T11: dispatch the model-emitted `multi_edit` tool call. The
1678
+ * tool returns a structured result envelope; we serialize it to JSON
1679
+ * for the engine loop. A refused dispatch (security, no_match,
1680
+ * ambiguous_match, etc.) surfaces as `ok: false` in the envelope —
1681
+ * the model can re-strategise rather than crashing the loop.
1682
+ */
1683
+ function dispatchMultiEdit(args, ctx) {
1684
+ const raw = args['edits'];
1685
+ if (!Array.isArray(raw)) {
1686
+ throw new Error('multi_edit: edits must be an array');
1687
+ }
1688
+ const edits = raw.map((item, i) => {
1689
+ if (!item || typeof item !== 'object') {
1690
+ throw new Error(`multi_edit: edits[${i}] must be an object`);
1691
+ }
1692
+ const obj = item;
1693
+ const file = obj['file'];
1694
+ const oldString = obj['oldString'];
1695
+ const newString = obj['newString'];
1696
+ if (typeof file !== 'string') {
1697
+ throw new Error(`multi_edit: edits[${i}].file must be a string`);
1698
+ }
1699
+ if (typeof oldString !== 'string') {
1700
+ throw new Error(`multi_edit: edits[${i}].oldString must be a string`);
1701
+ }
1702
+ if (typeof newString !== 'string') {
1703
+ throw new Error(`multi_edit: edits[${i}].newString must be a string`);
1704
+ }
1705
+ return { file, oldString, newString };
1706
+ });
1707
+ const result = multiEdit(ctx, edits);
1708
+ return JSON.stringify(result);
1709
+ }
1710
+ /* ---------------------------- hook ---------------------------- */
1711
+ /**
1712
+ * Tool names that mutate workspace files. After a successful dispatch
1713
+ * of any of these, the L15 post-edit diagnostics hook fires. The set
1714
+ * is intentionally tight — `task_*` / `todo_write` write to ledger
1715
+ * files (not workspace source) so they stay out, and `bash` is too
1716
+ * coarse (a `bash` call can write any path, and we'd need to parse
1717
+ * the command to know which — out of scope for L15).
1718
+ */
1719
+ const POST_EDIT_TOOLS = new Set(['edit', 'write', 'multi_edit']);
1720
+ /**
1721
+ * Append LSP diagnostics to the tool envelope after a successful
1722
+ * edit / write / multi_edit. Silent skip is the default — missing
1723
+ * binary, unsupported language, request timeout, and "no diagnostics"
1724
+ * all leave the envelope unchanged.
1725
+ *
1726
+ * Opt-in via `.pugi/settings.json::lsp.postEditDiagnostics = true`
1727
+ * OR `PUGI_LSP_POST_EDIT=1`. Off by default until dogfood validates
1728
+ * the cold-start cost vs the model-loop benefit ().
1729
+ */
1730
+ /**
1731
+ * PUGI-78 Phase 1: dispatched-name allowlist for the symbols.* router.
1732
+ * Sourced from the same list as the JSON-schema additions in
1733
+ * `buildToolsSchema` + the registry entries in `tools/registry.ts` — a
1734
+ * mismatch would surface as either an advertised-but-unrouted tool
1735
+ * (codex review P1 from this PR) or an unknown-tool denial.
1736
+ */
1737
+ const SYMBOLS_TOOL_NAMES = new Set([
1738
+ 'symbols_call_hierarchy',
1739
+ 'symbols_code_actions',
1740
+ 'symbols_diagnostics',
1741
+ 'symbols_find_definition',
1742
+ 'symbols_find_references',
1743
+ 'symbols_format',
1744
+ 'symbols_hover',
1745
+ 'symbols_implementations',
1746
+ 'symbols_list_in_file',
1747
+ 'symbols_rename',
1748
+ 'symbols_signature',
1749
+ 'symbols_type_definition',
1750
+ 'symbols_workspace_symbols',
1751
+ ]);
1752
+ /**
1753
+ * PUGI-78 Phase 1: dispatch a symbols.* tool call. Common pre-flight
1754
+ * (validate `lang`, resolve / spawn the LSP client via the warm cache,
1755
+ * build an `LspToolContext` from the engine `ToolContext`) lives here so
1756
+ * each per-tool branch stays a thin shim around the matching wrapper.
1757
+ *
1758
+ * Failure shape: the wrappers return a structured `{ok, value, reason}`
1759
+ * record — we JSON-stringify it for the engine envelope. The engine
1760
+ * adapter treats a string return as the tool result text; the wrappers
1761
+ * never throw (errors are caught and folded into the structured
1762
+ * `ok: false` record), so the dispatch path is safe to call without a
1763
+ * try/catch wrapper here.
1764
+ */
1765
+ async function dispatchSymbolsTool(name, args, ctx) {
1766
+ const langRaw = args['lang'];
1767
+ const validLangs = ['ts', 'js', 'py', 'go', 'rust'];
1768
+ if (typeof langRaw !== 'string' || !validLangs.includes(langRaw)) {
1769
+ return JSON.stringify({
1770
+ ok: false,
1771
+ reason: 'invalid_argument',
1772
+ detail: `${name}: 'lang' must be one of ts | js | py | go | rust (got: ${langRaw})`,
1773
+ });
1774
+ }
1775
+ const lang = langRaw;
1776
+ // Resolve (and lazily start) the LSP client. The cache holds the
1777
+ // client across the session so the cold start is paid once.
1778
+ const lspOpts = {
1779
+ cwd: ctx.root,
1780
+ ...(ctx.settings.lsp ? { lspSettings: ctx.settings.lsp } : {}),
1781
+ };
1782
+ const lspResult = await getOrStartLspClient(lang, lspOpts);
1783
+ const lspToolCtx = {
1784
+ ...ctx,
1785
+ ...(lspResult.ok
1786
+ ? { lspClients: new Map([[lang, lspResult.client]]) }
1787
+ : {}),
1788
+ symbolCache: getGlobalSymbolCache(),
1789
+ };
1790
+ // Validate required positional args per tool. Each tool that needs
1791
+ // a position rejects missing / non-finite / negative coordinates
1792
+ // with a structured `invalid_argument` envelope so the model sees
1793
+ // a clear correction signal instead of a silent (0,0) coercion that
1794
+ // would otherwise yield `lsp_not_found`.
1795
+ const requiresFile = name !== 'symbols_workspace_symbols';
1796
+ const requiresPosition = name === 'symbols_find_definition' ||
1797
+ name === 'symbols_find_references' ||
1798
+ name === 'symbols_hover' ||
1799
+ name === 'symbols_signature' ||
1800
+ name === 'symbols_implementations' ||
1801
+ name === 'symbols_type_definition' ||
1802
+ name === 'symbols_call_hierarchy' ||
1803
+ name === 'symbols_rename';
1804
+ const file = typeof args['file'] === 'string' ? args['file'] : '';
1805
+ if (requiresFile && file.length === 0) {
1806
+ return JSON.stringify({
1807
+ ok: false,
1808
+ reason: 'invalid_argument',
1809
+ detail: `${name}: 'file' must be a non-empty workspace-relative path`,
1810
+ });
1811
+ }
1812
+ const lineRaw = args['line'];
1813
+ const colRaw = args['col'];
1814
+ if (requiresPosition) {
1815
+ if (typeof lineRaw !== 'number' || !Number.isFinite(lineRaw) || lineRaw < 0) {
1816
+ return JSON.stringify({
1817
+ ok: false,
1818
+ reason: 'invalid_argument',
1819
+ detail: `${name}: 'line' must be a non-negative integer`,
1820
+ });
1821
+ }
1822
+ if (typeof colRaw !== 'number' || !Number.isFinite(colRaw) || colRaw < 0) {
1823
+ return JSON.stringify({
1824
+ ok: false,
1825
+ reason: 'invalid_argument',
1826
+ detail: `${name}: 'col' must be a non-negative integer`,
1827
+ });
1828
+ }
1829
+ }
1830
+ const line = typeof lineRaw === 'number' ? lineRaw : 0;
1831
+ const col = typeof colRaw === 'number' ? colRaw : 0;
1832
+ try {
1833
+ switch (name) {
1834
+ case 'symbols_find_definition': {
1835
+ const result = await symbolsFindDefinitionTool(lspToolCtx, lang, file, line, col);
1836
+ return JSON.stringify(result);
1837
+ }
1838
+ case 'symbols_find_references': {
1839
+ const result = await symbolsFindReferencesTool(lspToolCtx, lang, file, line, col);
1840
+ return JSON.stringify(result);
1841
+ }
1842
+ case 'symbols_list_in_file': {
1843
+ const result = await symbolsListInFileTool(lspToolCtx, lang, file);
1844
+ return JSON.stringify(result);
1845
+ }
1846
+ case 'symbols_rename': {
1847
+ const newName = typeof args['newName'] === 'string' ? args['newName'] : '';
1848
+ const result = await symbolsRenameTool(lspToolCtx, lang, file, line, col, newName);
1849
+ return JSON.stringify(result);
1850
+ }
1851
+ case 'symbols_hover': {
1852
+ const result = await symbolsHoverTool(lspToolCtx, lang, file, line, col);
1853
+ return JSON.stringify(result);
1854
+ }
1855
+ case 'symbols_signature': {
1856
+ const result = await symbolsSignatureTool(lspToolCtx, lang, file, line, col);
1857
+ return JSON.stringify(result);
1858
+ }
1859
+ case 'symbols_workspace_symbols': {
1860
+ const query = typeof args['query'] === 'string' ? args['query'] : '';
1861
+ const result = await symbolsWorkspaceSymbolsTool(lspToolCtx, lang, query);
1862
+ return JSON.stringify(result);
1863
+ }
1864
+ case 'symbols_call_hierarchy': {
1865
+ const result = await symbolsCallHierarchyTool(lspToolCtx, lang, file, line, col);
1866
+ return JSON.stringify(result);
1867
+ }
1868
+ case 'symbols_implementations': {
1869
+ const result = await symbolsImplementationsTool(lspToolCtx, lang, file, line, col);
1870
+ return JSON.stringify(result);
1871
+ }
1872
+ case 'symbols_type_definition': {
1873
+ const result = await symbolsTypeDefinitionTool(lspToolCtx, lang, file, line, col);
1874
+ return JSON.stringify(result);
1875
+ }
1876
+ case 'symbols_code_actions': {
1877
+ // Validate every coordinate of the range. Same gate as the
1878
+ // position-args check above — silent (0,0,0,0) coercion would
1879
+ // hide schema-noncompliant calls and yield an empty action
1880
+ // list instead of a clear correction signal.
1881
+ const coords = ['startLine', 'startChar', 'endLine', 'endChar'];
1882
+ for (const k of coords) {
1883
+ const v = args[k];
1884
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < 0) {
1885
+ return JSON.stringify({
1886
+ ok: false,
1887
+ reason: 'invalid_argument',
1888
+ detail: `symbols_code_actions: '${k}' must be a non-negative integer`,
1889
+ });
1890
+ }
1891
+ }
1892
+ const startLine = args['startLine'];
1893
+ const startChar = args['startChar'];
1894
+ const endLine = args['endLine'];
1895
+ const endChar = args['endChar'];
1896
+ const result = await symbolsCodeActionsTool(lspToolCtx, lang, file, startLine, startChar, endLine, endChar);
1897
+ return JSON.stringify(result);
1898
+ }
1899
+ case 'symbols_format': {
1900
+ const tabSize = typeof args['tabSize'] === 'number' ? args['tabSize'] : undefined;
1901
+ const insertSpaces = typeof args['insertSpaces'] === 'boolean' ? args['insertSpaces'] : undefined;
1902
+ const options = {};
1903
+ if (typeof tabSize === 'number')
1904
+ options.tabSize = tabSize;
1905
+ if (typeof insertSpaces === 'boolean')
1906
+ options.insertSpaces = insertSpaces;
1907
+ const result = await symbolsFormatTool(lspToolCtx, lang, file, options);
1908
+ return JSON.stringify(result);
1909
+ }
1910
+ case 'symbols_diagnostics': {
1911
+ const result = await symbolsDiagnosticsTool(lspToolCtx, lang, file);
1912
+ return JSON.stringify(result);
1913
+ }
1914
+ default:
1915
+ return JSON.stringify({
1916
+ ok: false,
1917
+ reason: 'unknown_symbols_tool',
1918
+ detail: `${name} is not a recognised symbols.* tool`,
1919
+ });
1920
+ }
1921
+ }
1922
+ catch (error) {
1923
+ // The wrappers fold errors into structured ok:false records, so
1924
+ // this branch is defense-in-depth for a refactor regression. If
1925
+ // any wrapper ever throws, we surface a stable shape to the model
1926
+ // instead of leaking the raw exception type.
1927
+ return JSON.stringify({
1928
+ ok: false,
1929
+ reason: 'symbols_dispatch_error',
1930
+ detail: error instanceof Error ? error.message : String(error),
1931
+ });
1932
+ }
1933
+ }
1934
+ async function appendPostEditDiagnostics(name, args, ctx, result) {
1935
+ if (!POST_EDIT_TOOLS.has(name))
1936
+ return result;
1937
+ // PUGI-78 Phase 1 (codex P2 fix): a successful edit / write / multi_edit
1938
+ // invalidates the symbol cache for this workspace. Without this, a
1939
+ // subsequent symbols.* query inside the same 5-minute TTL window could
1940
+ // return stale line numbers / outlines / references / hover from
1941
+ // before the edit. We invalidate BEFORE the post-edit diagnostics
1942
+ // gate so the invalidation fires even when post-edit-diagnostics is
1943
+ // disabled (the cache concern is independent of the diagnostics
1944
+ // surface). The invalidation is process-global; subagents that share
1945
+ // the same Node process share the cache, so the invalidation
1946
+ // propagates without an additional hop.
1947
+ try {
1948
+ const cache = getGlobalSymbolCache();
1949
+ cache.invalidateWorkspace(ctx.root);
1950
+ }
1951
+ catch {
1952
+ // Defense-in-depth — cache invalidation must never block the
1953
+ // engine's tool envelope. A throw here is a soft contract
1954
+ // violation but recoverable.
1955
+ }
1956
+ if (!isPostEditEnabled(ctx))
1957
+ return result;
1958
+ const paths = extractEditedPaths(name, args);
1959
+ if (paths.length === 0)
1960
+ return result;
1961
+ const tails = [];
1962
+ for (const filePath of paths) {
1963
+ const opts = {
1964
+ cwd: ctx.root,
1965
+ ...(ctx.settings.lsp ? { lspSettings: ctx.settings.lsp } : {}),
1966
+ };
1967
+ try {
1968
+ const diag = await runPostEditDiagnostics(filePath, opts);
1969
+ if (!diag.skip) {
1970
+ tails.push(diag.tail);
1971
+ }
1972
+ }
1973
+ catch {
1974
+ // Belt-and-suspenders: any unexpected throw from the hook is
1975
+ // swallowed. The model never blocks on LSP.
1976
+ }
1977
+ }
1978
+ if (tails.length === 0)
1979
+ return result;
1980
+ return `${result}\n${tails.join('\n')}`;
1981
+ }
1982
+ function isPostEditEnabled(ctx) {
1983
+ const envFlag = process.env.PUGI_LSP_POST_EDIT;
1984
+ if (envFlag === '1' || envFlag === 'true')
1985
+ return true;
1986
+ if (envFlag === '0' || envFlag === 'false')
1987
+ return false;
1988
+ return ctx.settings.lsp?.postEditDiagnostics === true;
1989
+ }
1990
+ /**
1991
+ * Pull the workspace-relative file path(s) the tool just touched.
1992
+ * Each branch mirrors the args shape its `dispatch*` handler reads;
1993
+ * a deformed args object yields an empty list so the hook silently
1994
+ * skips instead of throwing inside the augmentation layer.
1995
+ */
1996
+ function extractEditedPaths(name, args) {
1997
+ if (name === 'edit' || name === 'write') {
1998
+ const path = args['path'];
1999
+ return typeof path === 'string' && path.length > 0 ? [path] : [];
2000
+ }
2001
+ if (name === 'multi_edit') {
2002
+ const edits = args['edits'];
2003
+ if (!Array.isArray(edits))
2004
+ return [];
2005
+ const seen = new Set();
2006
+ for (const entry of edits) {
2007
+ if (!entry || typeof entry !== 'object')
2008
+ continue;
2009
+ const file = entry['file'];
2010
+ if (typeof file === 'string' && file.length > 0)
2011
+ seen.add(file);
2012
+ }
2013
+ return Array.from(seen);
2014
+ }
2015
+ return [];
2016
+ }
345
2017
  //# sourceMappingURL=tool-bridge.js.map