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

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