@pugi/cli 0.1.0-beta.4 → 0.1.0-beta.41

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 (250) hide show
  1. package/THIRD_PARTY_NOTICES.md +40 -0
  2. package/assets/pugi-mascot.ansi +15 -25
  3. package/bin/run.js +33 -1
  4. package/dist/commands/jobs-watch.js +201 -0
  5. package/dist/commands/jobs.js +15 -0
  6. package/dist/commands/smoke.js +133 -0
  7. package/dist/core/agent-progress/cleanup.js +134 -0
  8. package/dist/core/agent-progress/schema.js +144 -0
  9. package/dist/core/agent-progress/writer.js +101 -0
  10. package/dist/core/artifact-chain/dispatcher.js +148 -0
  11. package/dist/core/artifact-chain/exporter.js +164 -0
  12. package/dist/core/artifact-chain/state.js +243 -0
  13. package/dist/core/artifact-chain/steps.js +169 -0
  14. package/dist/core/auth/ensure-authenticated.js +129 -0
  15. package/dist/core/auth/env-provider.js +238 -0
  16. package/dist/core/auto-update/channels.js +122 -0
  17. package/dist/core/auto-update/checker.js +241 -0
  18. package/dist/core/auto-update/state.js +235 -0
  19. package/dist/core/bare-mode/index.js +107 -0
  20. package/dist/core/bash-classifier.js +108 -1
  21. package/dist/core/checkpoint/resumer.js +149 -0
  22. package/dist/core/checkpoint/rewinder.js +291 -0
  23. package/dist/core/codegraph/decision-store.js +248 -0
  24. package/dist/core/codegraph/detect-repo.js +459 -0
  25. package/dist/core/codegraph/install.js +134 -0
  26. package/dist/core/codegraph/offer-hook.js +220 -0
  27. package/dist/core/compact/auto-trigger.js +96 -0
  28. package/dist/core/compact/buffer-rewriter.js +115 -0
  29. package/dist/core/compact/summarizer.js +208 -0
  30. package/dist/core/compact/token-counter.js +108 -0
  31. package/dist/core/consensus/diff-capture.js +73 -0
  32. package/dist/core/context/index.js +7 -0
  33. package/dist/core/context/markdown-traverse.js +255 -0
  34. package/dist/core/cost/rate-card.js +129 -0
  35. package/dist/core/cost/tracker.js +221 -0
  36. package/dist/core/denial-tracking/index.js +8 -0
  37. package/dist/core/denial-tracking/state.js +264 -0
  38. package/dist/core/diagnostics/probe-runner.js +93 -0
  39. package/dist/core/diagnostics/probes/api.js +46 -0
  40. package/dist/core/diagnostics/probes/auth.js +86 -0
  41. package/dist/core/diagnostics/probes/bare-mode.js +42 -0
  42. package/dist/core/diagnostics/probes/cli-version.js +127 -0
  43. package/dist/core/diagnostics/probes/config.js +72 -0
  44. package/dist/core/diagnostics/probes/denial-tracking.js +57 -0
  45. package/dist/core/diagnostics/probes/disk.js +81 -0
  46. package/dist/core/diagnostics/probes/git.js +65 -0
  47. package/dist/core/diagnostics/probes/mcp.js +75 -0
  48. package/dist/core/diagnostics/probes/node.js +59 -0
  49. package/dist/core/diagnostics/probes/pnpm.js +36 -0
  50. package/dist/core/diagnostics/probes/pugi-md.js +89 -0
  51. package/dist/core/diagnostics/probes/session.js +74 -0
  52. package/dist/core/diagnostics/probes/status-snapshot.js +488 -0
  53. package/dist/core/diagnostics/probes/workspace.js +63 -0
  54. package/dist/core/diagnostics/types.js +70 -0
  55. package/dist/core/dispatch/cache-cleanup.js +197 -0
  56. package/dist/core/dispatch/cache-handoff.js +295 -0
  57. package/dist/core/edits/dispatch.js +218 -2
  58. package/dist/core/edits/journal.js +199 -0
  59. package/dist/core/edits/layer-d-ast.js +557 -14
  60. package/dist/core/edits/verify-hook.js +273 -0
  61. package/dist/core/edits/worktree.js +322 -0
  62. package/dist/core/engine/anvil-client.js +115 -5
  63. package/dist/core/engine/budgets.js +98 -0
  64. package/dist/core/engine/context-prefix.js +155 -0
  65. package/dist/core/engine/intent.js +260 -0
  66. package/dist/core/engine/native-pugi.js +860 -211
  67. package/dist/core/engine/prompts.js +88 -2
  68. package/dist/core/engine/strip-internal-fields.js +124 -0
  69. package/dist/core/engine/tool-bridge.js +1045 -36
  70. package/dist/core/feedback/queue.js +177 -0
  71. package/dist/core/feedback/submitter.js +145 -0
  72. package/dist/core/file-cache.js +113 -1
  73. package/dist/core/hooks/events.js +44 -0
  74. package/dist/core/hooks/index.js +15 -0
  75. package/dist/core/hooks/registry.js +213 -0
  76. package/dist/core/hooks/runner.js +236 -0
  77. package/dist/core/hooks/v2/event-emitter.js +115 -0
  78. package/dist/core/hooks/v2/executor.js +282 -0
  79. package/dist/core/hooks/v2/index.js +25 -0
  80. package/dist/core/hooks/v2/lifecycle.js +104 -0
  81. package/dist/core/hooks/v2/loader.js +216 -0
  82. package/dist/core/hooks/v2/matcher.js +125 -0
  83. package/dist/core/hooks/v2/trust.js +143 -0
  84. package/dist/core/hooks/v2/types.js +86 -0
  85. package/dist/core/lsp/cache.js +105 -0
  86. package/dist/core/lsp/client.js +776 -0
  87. package/dist/core/lsp/language-detect.js +66 -0
  88. package/dist/core/lsp/post-edit-diagnostics.js +171 -0
  89. package/dist/core/mcp/client.js +75 -6
  90. package/dist/core/mcp/http-server.js +553 -0
  91. package/dist/core/mcp/orchestrator-tools.js +662 -0
  92. package/dist/core/mcp/permission.js +190 -0
  93. package/dist/core/mcp/registry.js +24 -2
  94. package/dist/core/mcp/server-tools.js +219 -0
  95. package/dist/core/mcp/server.js +397 -0
  96. package/dist/core/memory/dual-write.js +416 -0
  97. package/dist/core/memory/phase1-kinds.js +20 -0
  98. package/dist/core/memory-sync/queue.js +158 -0
  99. package/dist/core/onboarding/ensure-initialized.js +133 -0
  100. package/dist/core/onboarding/marker.js +111 -0
  101. package/dist/core/onboarding/telemetry-state.js +108 -0
  102. package/dist/core/output-style/presets.js +176 -0
  103. package/dist/core/output-style/state.js +185 -0
  104. package/dist/core/permissions/auto-classifier.js +124 -0
  105. package/dist/core/permissions/circuit-breaker.js +83 -0
  106. package/dist/core/permissions/gate.js +278 -0
  107. package/dist/core/permissions/index.js +20 -0
  108. package/dist/core/permissions/mode.js +174 -0
  109. package/dist/core/permissions/state.js +241 -0
  110. package/dist/core/permissions/tool-class.js +93 -0
  111. package/dist/core/prd-check/parser.js +215 -0
  112. package/dist/core/prd-check/reporter.js +127 -0
  113. package/dist/core/prd-check/session-review.js +557 -0
  114. package/dist/core/prd-check/verifiers.js +223 -0
  115. package/dist/core/pugi-md/context-injector.js +76 -0
  116. package/dist/core/pugi-md/walk-up.js +207 -0
  117. package/dist/core/release-notes/parser.js +241 -0
  118. package/dist/core/release-notes/state.js +116 -0
  119. package/dist/core/repl/history.js +11 -1
  120. package/dist/core/repl/model-pricing.js +135 -0
  121. package/dist/core/repl/session.js +1899 -38
  122. package/dist/core/repl/slash-commands.js +406 -21
  123. package/dist/core/repl/store/session-store.js +31 -2
  124. package/dist/core/repl/workspace-context.js +22 -0
  125. package/dist/core/repo-map/build.js +125 -0
  126. package/dist/core/repo-map/cache.js +185 -0
  127. package/dist/core/repo-map/extractor.js +254 -0
  128. package/dist/core/repo-map/formatter.js +145 -0
  129. package/dist/core/repo-map/scanner.js +211 -0
  130. package/dist/core/retry-budget/budget.js +284 -0
  131. package/dist/core/retry-budget/index.js +5 -0
  132. package/dist/core/session.js +92 -0
  133. package/dist/core/settings.js +80 -0
  134. package/dist/core/share/formatter.js +271 -0
  135. package/dist/core/share/redactor.js +221 -0
  136. package/dist/core/share/uploader.js +267 -0
  137. package/dist/core/skills/defaults.js +457 -0
  138. package/dist/core/smoke/headless-driver.js +174 -0
  139. package/dist/core/smoke/orchestrator.js +194 -0
  140. package/dist/core/smoke/runner.js +238 -0
  141. package/dist/core/smoke/scenario-parser.js +316 -0
  142. package/dist/core/subagents/dispatcher-real.js +600 -0
  143. package/dist/core/subagents/dispatcher.js +113 -24
  144. package/dist/core/subagents/index.js +18 -5
  145. package/dist/core/subagents/isolation-matrix.js +213 -0
  146. package/dist/core/subagents/spawn.js +19 -4
  147. package/dist/core/telemetry/emitter.js +229 -0
  148. package/dist/core/telemetry/queue.js +251 -0
  149. package/dist/core/theme/context.js +91 -0
  150. package/dist/core/theme/presets.js +228 -0
  151. package/dist/core/theme/state.js +181 -0
  152. package/dist/core/todos/invariant.js +10 -0
  153. package/dist/core/todos/state.js +177 -0
  154. package/dist/core/transport/version-interceptor.js +166 -0
  155. package/dist/core/vim/keymap.js +288 -0
  156. package/dist/core/vim/state.js +92 -0
  157. package/dist/index.js +28 -0
  158. package/dist/runtime/bootstrap.js +190 -0
  159. package/dist/runtime/cli.js +3073 -321
  160. package/dist/runtime/commands/cancel.js +231 -0
  161. package/dist/runtime/commands/chain.js +489 -0
  162. package/dist/runtime/commands/codegraph-status.js +227 -0
  163. package/dist/runtime/commands/compact.js +297 -0
  164. package/dist/runtime/commands/cost.js +199 -0
  165. package/dist/runtime/commands/delegate.js +242 -11
  166. package/dist/runtime/commands/dispatch.js +126 -0
  167. package/dist/runtime/commands/doctor.js +390 -0
  168. package/dist/runtime/commands/feedback.js +184 -0
  169. package/dist/runtime/commands/hooks.js +184 -0
  170. package/dist/runtime/commands/lsp.js +368 -0
  171. package/dist/runtime/commands/mcp.js +879 -0
  172. package/dist/runtime/commands/memory.js +508 -0
  173. package/dist/runtime/commands/model.js +237 -0
  174. package/dist/runtime/commands/onboarding.js +275 -0
  175. package/dist/runtime/commands/patch.js +128 -0
  176. package/dist/runtime/commands/permissions.js +112 -0
  177. package/dist/runtime/commands/plan.js +143 -0
  178. package/dist/runtime/commands/prd-check.js +285 -0
  179. package/dist/runtime/commands/redo-blob-store.js +92 -0
  180. package/dist/runtime/commands/redo.js +361 -0
  181. package/dist/runtime/commands/release-notes.js +229 -0
  182. package/dist/runtime/commands/repo-map.js +95 -0
  183. package/dist/runtime/commands/report.js +299 -0
  184. package/dist/runtime/commands/resume.js +118 -0
  185. package/dist/runtime/commands/review-consensus.js +17 -2
  186. package/dist/runtime/commands/rewind.js +333 -0
  187. package/dist/runtime/commands/sessions.js +163 -0
  188. package/dist/runtime/commands/share.js +316 -0
  189. package/dist/runtime/commands/status.js +186 -0
  190. package/dist/runtime/commands/stickers.js +82 -0
  191. package/dist/runtime/commands/style.js +194 -0
  192. package/dist/runtime/commands/theme.js +196 -0
  193. package/dist/runtime/commands/undo.js +32 -0
  194. package/dist/runtime/commands/update.js +289 -0
  195. package/dist/runtime/commands/vim.js +140 -0
  196. package/dist/runtime/commands/worktree.js +177 -0
  197. package/dist/runtime/headless-repl.js +195 -0
  198. package/dist/runtime/headless.js +543 -0
  199. package/dist/runtime/load-hooks-or-exit.js +71 -0
  200. package/dist/runtime/plan-decompose.js +531 -0
  201. package/dist/runtime/version.js +65 -0
  202. package/dist/tools/agent-tool.js +229 -0
  203. package/dist/tools/apply-patch.js +556 -0
  204. package/dist/tools/ask-user-question.js +213 -0
  205. package/dist/tools/ask-user.js +115 -0
  206. package/dist/tools/file-tools.js +85 -14
  207. package/dist/tools/lsp-tools.js +189 -0
  208. package/dist/tools/mcp-tool.js +260 -0
  209. package/dist/tools/multi-edit.js +361 -0
  210. package/dist/tools/powershell.js +156 -0
  211. package/dist/tools/registry.js +51 -0
  212. package/dist/tools/skill-tool.js +96 -0
  213. package/dist/tools/tasks.js +208 -0
  214. package/dist/tools/todo-write.js +184 -0
  215. package/dist/tools/web-fetch.js +147 -2
  216. package/dist/tools/web-search.js +458 -0
  217. package/dist/tui/agent-progress-card.js +111 -0
  218. package/dist/tui/agent-tree.js +10 -0
  219. package/dist/tui/ask-modal.js +2 -2
  220. package/dist/tui/ask-user-question-prompt.js +192 -0
  221. package/dist/tui/compact-banner.js +81 -0
  222. package/dist/tui/conversation-pane.js +82 -8
  223. package/dist/tui/cost-table.js +111 -0
  224. package/dist/tui/doctor-table.js +46 -0
  225. package/dist/tui/feedback-prompt.js +156 -0
  226. package/dist/tui/input-box.js +69 -2
  227. package/dist/tui/markdown-render.js +4 -4
  228. package/dist/tui/onboarding-wizard.js +240 -0
  229. package/dist/tui/permissions-picker.js +86 -0
  230. package/dist/tui/render.js +35 -0
  231. package/dist/tui/repl-render.js +303 -13
  232. package/dist/tui/repl-splash.js +2 -2
  233. package/dist/tui/repl.js +72 -14
  234. package/dist/tui/splash.js +1 -1
  235. package/dist/tui/status-bar.js +94 -16
  236. package/dist/tui/status-table.js +7 -0
  237. package/dist/tui/stickers-art.js +136 -0
  238. package/dist/tui/style-table.js +28 -0
  239. package/dist/tui/theme-table.js +29 -0
  240. package/dist/tui/tool-stream-pane.js +52 -3
  241. package/dist/tui/update-banner.js +20 -2
  242. package/dist/tui/vim-input.js +267 -0
  243. package/docs/examples/codegraph.mcp.json +10 -0
  244. package/package.json +12 -6
  245. package/test/scenarios/codegen-create-file.scenario.txt +13 -0
  246. package/test/scenarios/compact-force.scenario.txt +11 -0
  247. package/test/scenarios/identity.scenario.txt +11 -0
  248. package/test/scenarios/persona-handoff.scenario.txt +11 -0
  249. package/test/scenarios/walkback.scenario.txt +12 -0
  250. package/dist/core/engine/compaction-hook.js +0 -154
@@ -1,5 +1,21 @@
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
+ import { webFetchTool } from '../../tools/web-fetch.js';
10
+ import { webSearchTool } from '../../tools/web-search.js';
11
+ import { agentTool } from '../../tools/agent-tool.js';
12
+ import { multiEdit } from '../../tools/multi-edit.js';
13
+ import { buildMcpToolDefs, defaultNonInteractiveMcpPrompt, dispatchMcpTool, MCP_TOOL_PREFIX, } from '../../tools/mcp-tool.js';
14
+ import { buildDenialContext, DENIAL_REMINDER_THRESHOLD, } from '../denial-tracking/state.js';
15
+ import { stripInternalFields } from './strip-internal-fields.js';
16
+ import { applyAskAnswer, gate as permissionGate, getToolClass, PermissionDenied, } from '../permissions/index.js';
17
+ import { RetryBudget, RetryBudgetExhausted, hashArgs } from '../retry-budget/index.js';
18
+ import { runPostEditDiagnostics, } from '../lsp/post-edit-diagnostics.js';
3
19
  /**
4
20
  * Tool-bridge: turns the abstract tool registry into:
5
21
  * 1. An OpenAI-shaped tools schema for `EngineLoopClient.send`.
@@ -23,17 +39,86 @@ import { bashToolSync } from '../../tools/bash.js';
23
39
  /**
24
40
  * Read-only subset surfaced to plan-mode. Mutating tools (write, edit,
25
41
  * bash) are intentionally absent so the model rarely tries them.
42
+ *
43
+ * β1: task_* + skill + ask_user_question + web_fetch are all read-only
44
+ * from the workspace's perspective (no file writes), so they stay
45
+ * available in plan mode. The ledger writes for `task_*` land in
46
+ * `.pugi/sessions/<id>/tasks.jsonl` which is metadata, not source.
26
47
  */
27
- const READ_ONLY_TOOLS = new Set(['read', 'grep', 'glob']);
48
+ const READ_ONLY_TOOLS = new Set([
49
+ 'read',
50
+ 'grep',
51
+ 'glob',
52
+ 'ask_user_question',
53
+ 'skill',
54
+ 'skills_list',
55
+ 'task_create',
56
+ 'task_get',
57
+ 'task_list',
58
+ 'task_update',
59
+ // Leak L16 (2026-05-27): `todo_write` writes to `.pugi/todos.json`
60
+ // — metadata, not source. From the workspace's perspective it is
61
+ // read-only (no source mutation), so plan-mode keeps the tool
62
+ // available: planning a refactor frequently means writing the
63
+ // todo board BEFORE picking which file to touch.
64
+ 'todo_write',
65
+ 'web_fetch',
66
+ // β1b T4 (2026-05-26): web_search is read-only from the workspace's
67
+ // perspective (no file writes, no shell). Egress goes through the
68
+ // Anvil-proxied Brave Search API, gated by the same opt-in posture as
69
+ // web_fetch. Plan mode keeps the tool available because reading the
70
+ // web is part of how a plan is researched.
71
+ 'web_search',
72
+ ]);
28
73
  /**
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.
74
+ * Tools the engine loop dispatches. β1 expands the M1 cornerstone six
75
+ * (read/write/edit/grep/glob/bash) with task_* + ask_user_question +
76
+ * skill + skill list + web_fetch. The registry advertises these slots
77
+ * to the runtime; without dispatcher entries the model would call
78
+ * "unknown tool" errors.
33
79
  */
34
- const WIRED_TOOLS = new Set(['read', 'write', 'edit', 'grep', 'glob', 'bash']);
35
- export function buildToolsSchema(kind) {
80
+ const WIRED_TOOLS = new Set([
81
+ 'read',
82
+ 'write',
83
+ 'edit',
84
+ 'grep',
85
+ 'glob',
86
+ 'bash',
87
+ // Leak L6 (2026-05-28): PowerShell tool for Windows-first workflows.
88
+ // Same bash permission class — destructive-pattern classifier applies.
89
+ // Plan mode excludes shell tools by design (read-only); the planMode
90
+ // check on the schema side already handles that, so we just list it
91
+ // alongside 'bash' here.
92
+ 'powershell',
93
+ 'ask_user_question',
94
+ 'skill',
95
+ 'skills_list',
96
+ 'task_create',
97
+ 'task_get',
98
+ 'task_list',
99
+ 'task_update',
100
+ // Leak L16: see READ_ONLY_TOOLS above for the rationale.
101
+ 'todo_write',
102
+ 'web_fetch',
103
+ // β1b T4: see READ_ONLY_TOOLS above.
104
+ 'web_search',
105
+ // β2 S3 (2026-05-26): real subagent spawn primitive. Only advertised
106
+ // when buildToolsSchema is called with allowAgent=true (orchestrator
107
+ // / root Mira context); plan-mode also excludes it because spawning
108
+ // a write-capable child violates plan-mode's read-only contract.
109
+ 'agent',
110
+ // β7 L5+T11 (2026-05-26): transactional multi-file edit. Routes
111
+ // through the same security gate as Layer A/B/C; not advertised in
112
+ // plan mode (mutation surface).
113
+ 'multi_edit',
114
+ ]);
115
+ export function buildToolsSchema(kind, options = { allowFetch: false, allowSearch: false }) {
36
116
  const planMode = kind === 'plan';
117
+ // β4 M1/M3: splice MCP tools BEFORE the native list assembly so the
118
+ // engine-loop sees them in stable alphabetical order alongside native
119
+ // tools. We keep the entries appended after the native push so plan-
120
+ // mode can be filtered by namespace prefix in one place at the end.
121
+ const mcpDefs = buildMcpToolDefs(options.mcpRegistry);
37
122
  const toolDefs = [
38
123
  {
39
124
  name: 'read',
@@ -72,10 +157,214 @@ export function buildToolsSchema(kind) {
72
157
  },
73
158
  },
74
159
  ];
160
+ // β1 T1/T6: TodoWrite (Pugi grammar = `task_*`). Append-only ledger
161
+ // at `.pugi/sessions/<id>/tasks.jsonl`.
162
+ toolDefs.push({
163
+ name: 'task_create',
164
+ description: 'Append a new task to the session todo ledger. Returns the assigned task id and full record. Mirrors Claude Code TodoWrite/create.',
165
+ parameters: {
166
+ type: 'object',
167
+ additionalProperties: false,
168
+ required: ['title'],
169
+ properties: {
170
+ title: { type: 'string', description: 'Short imperative summary, max 2000 chars.' },
171
+ status: {
172
+ type: 'string',
173
+ enum: ['pending', 'in_progress', 'completed', 'cancelled'],
174
+ description: 'Initial status. Default pending.',
175
+ },
176
+ notes: { type: 'string', description: 'Optional free-form context.' },
177
+ },
178
+ },
179
+ }, {
180
+ name: 'task_get',
181
+ description: 'Fetch a single task record by id. Returns null when absent.',
182
+ parameters: {
183
+ type: 'object',
184
+ additionalProperties: false,
185
+ required: ['id'],
186
+ properties: { id: { type: 'string' } },
187
+ },
188
+ }, {
189
+ name: 'task_list',
190
+ description: 'List all tasks for the current session ordered by createdAt ascending.',
191
+ parameters: { type: 'object', additionalProperties: false, properties: {} },
192
+ }, {
193
+ name: 'task_update',
194
+ description: 'Mutate status/title/notes on an existing task. Throws on unknown id. Append-only journal.',
195
+ parameters: {
196
+ type: 'object',
197
+ additionalProperties: false,
198
+ required: ['id'],
199
+ properties: {
200
+ id: { type: 'string' },
201
+ title: { type: 'string' },
202
+ status: {
203
+ type: 'string',
204
+ enum: ['pending', 'in_progress', 'completed', 'cancelled'],
205
+ },
206
+ notes: { type: 'string' },
207
+ },
208
+ },
209
+ });
210
+ // Leak L16 (2026-05-27): `todo_write` — batch TodoWrite mirror of
211
+ // Claude Code's upstream tool. Whereas `task_*` above is granular
212
+ // (one mutation per call, JSONL append, session-scoped),
213
+ // `todo_write` snapshots the FULL board in one call, JSON snapshot
214
+ // at `.pugi/todos.json`, workspace-scoped. Enforces the single-
215
+ // in-progress invariant at dispatch time: a batch with >1
216
+ // `in_progress` rejects with `TODO_INVARIANT_VIOLATED` and the
217
+ // on-disk board is left unchanged.
218
+ toolDefs.push({
219
+ name: 'todo_write',
220
+ description: 'Replace the workspace todo board (batch snapshot, not incremental). Emit the FULL todo list every call. ' +
221
+ 'At most ONE item may carry status="in_progress" — violations reject with TODO_INVARIANT_VIOLATED. ' +
222
+ 'Persisted atomically to .pugi/todos.json. Mirrors Claude Code TodoWrite verbatim.',
223
+ parameters: todoWriteJsonSchema,
224
+ });
225
+ // β1 T2 → leak L5 (2026-05-27): structured AskUserQuestion bridge.
226
+ // Schema upgraded to openclaude's multi-choice form: header chip +
227
+ // {label, description} per option. Dispatcher accepts the structured
228
+ // form (preferred) AND the legacy string-array form so existing
229
+ // callers / tests keep working until the next major bump.
230
+ //
231
+ // Interactive TTY → returns the picked label(s).
232
+ // Non-TTY / no bridge → `[user_input_required]` envelope.
233
+ toolDefs.push({
234
+ name: 'ask_user_question',
235
+ 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.',
236
+ parameters: askUserQuestionJsonSchema,
237
+ });
238
+ // β1 T3: Skill tool — discover + invoke locally-installed skills.
239
+ toolDefs.push({
240
+ name: 'skills_list',
241
+ description: 'List installed skills (global + workspace). Returns name+description+scope.',
242
+ parameters: {
243
+ type: 'object',
244
+ additionalProperties: false,
245
+ properties: {
246
+ scope: { type: 'string', enum: ['all', 'global', 'workspace'] },
247
+ },
248
+ },
249
+ }, {
250
+ name: 'skill',
251
+ description: 'Load a skill body by name. Workspace scope wins over global. Body capped at 32KB.',
252
+ parameters: {
253
+ type: 'object',
254
+ additionalProperties: false,
255
+ required: ['name'],
256
+ properties: { name: { type: 'string' } },
257
+ },
258
+ });
259
+ // β1 T5 → β1a r1 (gating fix, 2026-05-26): WebFetch wire-in. Schema
260
+ // mirrors the existing tool surface in
261
+ // `apps/pugi-cli/src/tools/web-fetch.ts`. SSRF guard runs inside the
262
+ // tool itself, but advertising the tool to the model when the tenant
263
+ // has not opted in is itself a privacy leak — the model could infer
264
+ // URL patterns and try to exfiltrate via the refused call's argument
265
+ // bytes. Only push the schema entry when the operator has explicitly
266
+ // enabled fetch (either via `.pugi/settings.json::web.fetch.enabled`
267
+ // or via `--allow-fetch`).
268
+ if (options.allowFetch) {
269
+ toolDefs.push({
270
+ name: 'web_fetch',
271
+ 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.',
272
+ parameters: {
273
+ type: 'object',
274
+ additionalProperties: false,
275
+ required: ['url'],
276
+ properties: {
277
+ url: { type: 'string', description: 'Fully-qualified http(s) URL.' },
278
+ },
279
+ },
280
+ });
281
+ }
282
+ // β1b T4 (2026-05-26): web_search advertisement. Same off-by-default
283
+ // privacy posture as web_fetch — the query string itself is an egress
284
+ // event that can leak operator intent to the upstream Brave Search
285
+ // backend. The tool dispatcher applies SSRF guards (no localhost via
286
+ // the Anvil proxy URL), rate-limits (5 req/min per session), and caps
287
+ // the result payload at 1 MiB. Sentinel-wrapped results so the model
288
+ // treats every snippet as data, not instructions.
289
+ if (options.allowSearch) {
290
+ toolDefs.push({
291
+ name: 'web_search',
292
+ 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.',
293
+ parameters: {
294
+ type: 'object',
295
+ additionalProperties: false,
296
+ required: ['query'],
297
+ properties: {
298
+ query: {
299
+ type: 'string',
300
+ description: 'Search query, max 256 chars. Plain text — no operators.',
301
+ },
302
+ count: {
303
+ type: 'integer',
304
+ description: 'Optional result count (1..10, default 10).',
305
+ },
306
+ },
307
+ },
308
+ });
309
+ }
310
+ // β2 S3 (2026-05-26): `agent` tool — subagent spawn primitive.
311
+ // Off by default; surfaced only when the caller explicitly opts in
312
+ // (orchestrator parents pass allowAgent=true via the engine adapter).
313
+ // Plan mode FORCES the tool off regardless because a write-capable
314
+ // child would violate plan-mode's read-only contract.
315
+ if (options.allowAgent && !planMode) {
316
+ toolDefs.push({
317
+ name: 'agent',
318
+ description: 'Spawn a specialist subagent under a Cyber-Zoo brand persona. '
319
+ + 'Role selects the persona + isolation tier: '
320
+ + 'researcher/reviewer/architect are read-only, verifier reads + runs tests, '
321
+ + 'coder/release/devops/design_qa get write + bash. '
322
+ + 'The child runs a fresh Anvil engine loop with its own transcript and '
323
+ + 'returns a JSON envelope (filesChanged, toolCallCount, status, summary). '
324
+ + 'Use this when the work needs a specialist persona OR write isolation via a scratch worktree.',
325
+ parameters: {
326
+ type: 'object',
327
+ additionalProperties: false,
328
+ required: ['role', 'brief'],
329
+ properties: {
330
+ role: {
331
+ type: 'string',
332
+ enum: [
333
+ 'orchestrator',
334
+ 'architect',
335
+ 'coder',
336
+ 'verifier',
337
+ 'reviewer',
338
+ 'researcher',
339
+ 'release',
340
+ 'devops',
341
+ 'design_qa',
342
+ ],
343
+ description: 'SubagentRole — selects persona + isolation tier.',
344
+ },
345
+ brief: {
346
+ type: 'string',
347
+ maxLength: 8000,
348
+ description: 'One-paragraph task description forwarded to the child as the user prompt. '
349
+ + 'Be concrete: include filenames, expected behavior, and acceptance criteria.',
350
+ },
351
+ isolation: {
352
+ type: 'string',
353
+ enum: ['worktree', 'shared_fs', 'auto'],
354
+ description: 'Optional override. `worktree` forces a scratch git worktree for write isolation; '
355
+ + '`shared_fs` forces same-tree execution; `auto` (default) defers to the role tier.',
356
+ },
357
+ },
358
+ },
359
+ });
360
+ }
75
361
  if (!planMode) {
76
362
  toolDefs.push({
77
363
  name: 'write',
78
- description: 'Create or overwrite a workspace file. Use for new files only — prefer edit for existing files. Workspace-scoped.',
364
+ description: 'Create or overwrite a workspace file. Prefer edit for existing files. ' +
365
+ 'For OVERWRITE of an existing file, you MUST read the file first in this session — ' +
366
+ 'write refuses with STALE_READ if the file changed since your last read, or if you ' +
367
+ 'never read it. New-file creation (path does not exist) skips that gate. Workspace-scoped.',
79
368
  parameters: {
80
369
  type: 'object',
81
370
  additionalProperties: false,
@@ -87,7 +376,10 @@ export function buildToolsSchema(kind) {
87
376
  },
88
377
  }, {
89
378
  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.',
379
+ description: 'Replace exactly one occurrence of oldString with newString inside an already-read file. ' +
380
+ 'Refuses with STALE_READ if the file was never read this session or the on-disk contents ' +
381
+ 'drifted since the read (mtime+sha gate). Recovery: re-read with the `read` tool, then ' +
382
+ 'retry the edit. Also fails if oldString is missing or duplicate.',
91
383
  parameters: {
92
384
  type: 'object',
93
385
  additionalProperties: false,
@@ -109,9 +401,105 @@ export function buildToolsSchema(kind) {
109
401
  command: { type: 'string', description: 'Single shell command to execute.' },
110
402
  },
111
403
  },
404
+ }, {
405
+ name: 'powershell',
406
+ 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.',
407
+ parameters: {
408
+ type: 'object',
409
+ additionalProperties: false,
410
+ required: ['command'],
411
+ properties: {
412
+ command: { type: 'string', description: 'Single PowerShell command or script.' },
413
+ cwd: { type: 'string', description: 'Optional cwd; defaults to workspace root.' },
414
+ timeoutMs: { type: 'number', description: 'Hard timeout (default 30000, max 120000).' },
415
+ },
416
+ },
417
+ },
418
+ // β7 L5+T11 (2026-05-26): transactional multi-file edit. Either
419
+ // all entries land or none do — failures roll the workspace back
420
+ // via the same journal + snapshot machinery the dispatcher uses.
421
+ // Cap is 50 entries; beyond that the operator (or model) should
422
+ // split the refactor or use Layer C rewrites.
423
+ {
424
+ name: 'multi_edit',
425
+ description: 'Apply an ordered batch of single-occurrence file edits as one transaction. ' +
426
+ 'Each entry is {file, oldString, newString} like the `edit` tool. Either every ' +
427
+ 'edit lands or none do — a failure rolls the workspace back to the pre-dispatch ' +
428
+ 'state via journal + snapshot. Cap 50 edits per call. Use this for coordinated ' +
429
+ 'refactors (rename across files, add an import to many modules).',
430
+ parameters: {
431
+ type: 'object',
432
+ additionalProperties: false,
433
+ required: ['edits'],
434
+ properties: {
435
+ edits: {
436
+ type: 'array',
437
+ minItems: 1,
438
+ maxItems: 50,
439
+ items: {
440
+ type: 'object',
441
+ additionalProperties: false,
442
+ required: ['file', 'oldString', 'newString'],
443
+ properties: {
444
+ file: { type: 'string', description: 'Workspace-relative file path.' },
445
+ oldString: { type: 'string', description: 'Verbatim substring; must be unique in the pre-edit file.' },
446
+ newString: { type: 'string', description: 'Replacement string. Empty string means delete.' },
447
+ },
448
+ },
449
+ },
450
+ },
451
+ },
112
452
  });
113
453
  }
114
- return toolDefs;
454
+ // β4 M1/M3: append MCP tools last. Plan mode skips them because every
455
+ // MCP tool is treated as medium-risk until per-tool annotations land
456
+ // in the MCP spec; treating MCP read-as-read would require server-
457
+ // side metadata we cannot trust today (a misconfigured server could
458
+ // claim `read` while running a destructive op).
459
+ if (!planMode) {
460
+ for (const def of mcpDefs) {
461
+ toolDefs.push({
462
+ name: def.name,
463
+ description: def.description,
464
+ parameters: def.parameters,
465
+ });
466
+ }
467
+ }
468
+ // α7 L3 (2026-05-27): leak-parity underscore-prefix filter. Every
469
+ // tool's parameter schema is scrubbed of `_`-prefixed fields before
470
+ // the model ever sees it. Native tool schemas above currently declare
471
+ // no `_*` fields, but MCP tools surfaced through buildMcpToolDefs
472
+ // come from third-party servers whose authors may follow the same
473
+ // convention (an MCP tool can declare `_sessionId` knowing the CLI
474
+ // dispatcher will inject it before forwarding). The dispatcher
475
+ // (buildExecutor below) does NOT strip these from the args record at
476
+ // call time — `_internal*` keys still flow through to tool handlers
477
+ // when an upstream layer populates them.
478
+ return toolDefs.map((tool) => ({
479
+ name: tool.name,
480
+ description: tool.description,
481
+ parameters: stripInternalFields(tool.parameters),
482
+ }));
483
+ }
484
+ /**
485
+ * α7 L11: tolerant args-parse for the denial fingerprint. Unlike
486
+ * `parseArgs` (which throws on malformed JSON so the model sees a
487
+ * parse error), this swallows failures and returns `{}` — the denial
488
+ * tracker needs SOME key even when the raw payload is unparseable,
489
+ * because malformed-args spam is itself a pattern operators want to
490
+ * see in `/permissions denials`.
491
+ */
492
+ function safeParseForTracking(raw) {
493
+ if (!raw || raw.trim() === '')
494
+ return {};
495
+ try {
496
+ return JSON.parse(raw);
497
+ }
498
+ catch {
499
+ // Use the raw string as the fingerprint payload so repeated
500
+ // identical malformed dispatches still cluster.
501
+ return { _rawArgs: raw.slice(0, 512) };
502
+ }
115
503
  }
116
504
  function parseArgs(raw) {
117
505
  if (!raw || raw.trim() === '')
@@ -127,25 +515,156 @@ function parseArgs(raw) {
127
515
  throw new Error(`invalid JSON in tool arguments: ${error.message}`);
128
516
  }
129
517
  }
518
+ /**
519
+ * Strict canonical-only argument coercion (leak P0 L2, 2026-05-27).
520
+ *
521
+ * Reverts the beta.17 alias acceptance (`file` / `filename` / `filepath`
522
+ * / `file_path` → `path`). The alias shim was the wrong direction: it
523
+ * paved over a model-side prompt-drift bug at the runtime layer, weakened
524
+ * the strict JSON-Schema contract one layer up (`additionalProperties:
525
+ * false`), and drifted away from the openclaude reference (research memo
526
+ * §1.1 — `z.strictObject` rejects aliased fields).
527
+ *
528
+ * The compensating change ships in the persona prompts: Mira's system
529
+ * prompt and Hiroshi's persona body now declare canonical parameter
530
+ * names with few-shot wrong/right contrasts so the model learns the
531
+ * grammar upstream of the bridge.
532
+ */
130
533
  function requireString(obj, key) {
131
534
  const v = obj[key];
132
- if (typeof v !== 'string') {
133
- throw new Error(`tool argument "${key}" must be a string`);
134
- }
135
- return v;
535
+ if (typeof v === 'string')
536
+ return v;
537
+ throw new Error(`tool argument "${key}" must be a string`);
538
+ }
539
+ /**
540
+ * Accept `path` (canonical) or `filePath` (Claude Code convention) for
541
+ * write/edit/read tool arguments. Models trained on CC system prompts
542
+ * emit `filePath`; insisting on `path` only forces 2-3 retry waste on
543
+ * every file write (CEO live smoke 2026-05-28: snake.html dispatch
544
+ * burned 2 turns retrying `{filePath: ...}` payloads before falling
545
+ * back к bash heredoc). Defense-in-depth alias keeps canonical name
546
+ * (so persona prompts can still teach `path` as the right answer) AND
547
+ * tolerates the CC-trained variant without operator-visible failure.
548
+ */
549
+ function requirePathArg(obj) {
550
+ if (typeof obj['path'] === 'string')
551
+ return obj['path'];
552
+ if (typeof obj['filePath'] === 'string')
553
+ return obj['filePath'];
554
+ throw new Error('tool argument "path" must be a string (alias "filePath" also accepted)');
136
555
  }
137
556
  export function buildExecutor(input) {
138
- const { kind, ctx, hooks, sessionId } = input;
557
+ const { kind, ctx, hooks, mvpHooksConfig, sessionId, askUserBridge, interactive, allowFetch, allowSearch, agentDispatch, mcpRegistry, permissionMode, permissionAlwaysCache, permissionAsk, } = input;
558
+ // Leak L31: per-cycle budget. Default to a fresh instance scoped to
559
+ // this executor's closure lifetime; tests pass their own.
560
+ const retryBudget = input.retryBudget ?? new RetryBudget();
561
+ const mcpPrompt = input.mcpPrompt ?? defaultNonInteractiveMcpPrompt;
562
+ const workspaceRoot = input.workspaceRoot ?? ctx.root;
139
563
  const planMode = kind === 'plan';
564
+ const denialTracking = input.denialTracking;
565
+ // α7 L11: helper that records a denial (when tracking is wired) and
566
+ // ALWAYS returns an Error whose message includes a compact
567
+ // `<denial-context>` reminder when the same (tool, args) pair has
568
+ // already been refused at least once before in this session.
569
+ //
570
+ // The reminder is appended to the THROWN message — the engine loop
571
+ // appends thrown messages to the transcript as tool-result strings,
572
+ // so the model sees the aggregate the next time it considers a
573
+ // dispatch. Without this every retry would only see the latest
574
+ // single-turn reason and could loop indefinitely.
575
+ //
576
+ // Best-effort: a hash/clone failure inside the tracker MUST NOT
577
+ // mask the original refusal. The catch path falls back to a bare
578
+ // Error with the reason text.
579
+ const recordDenial = (toolName, args, reason) => {
580
+ if (!denialTracking)
581
+ return new Error(reason);
582
+ try {
583
+ const record = denialTracking.recordDenial(toolName, args, reason);
584
+ // Only inject the reminder once the threshold is hit — the very
585
+ // first denial is the model's first chance to learn, no need to
586
+ // shout. From the 2nd repeat onwards the model has demonstrated
587
+ // it is not learning from the single-turn sentinel, so we splice
588
+ // the aggregate context.
589
+ if (record.count >= DENIAL_REMINDER_THRESHOLD) {
590
+ const reminder = buildDenialContext(denialTracking);
591
+ if (reminder.length > 0) {
592
+ return new Error(`${reason}\n\n${reminder}`);
593
+ }
594
+ }
595
+ }
596
+ catch {
597
+ // Tracking is best-effort. Fall through to the bare Error so
598
+ // the refusal still propagates.
599
+ }
600
+ return new Error(reason);
601
+ };
140
602
  return async ({ name, arguments: argsRaw }) => {
141
- if (!WIRED_TOOLS.has(name)) {
142
- throw new Error(`unknown tool: ${name}`);
603
+ // β4 M1/M3: MCP tool names live outside WIRED_TOOLS. They are
604
+ // validated lazily by the dispatcher (the registry knows which
605
+ // names are actually exposed). The namespace check happens FIRST
606
+ // so a bad `mcp__bogus__foo` does not collide with the native
607
+ // unknown-tool branch.
608
+ const isMcpName = name.startsWith(MCP_TOOL_PREFIX);
609
+ // α7 L11: parse-or-empty args once up-front so every deny path
610
+ // below can fingerprint the call against the denial tracker. We
611
+ // tolerate parse failure — `{}` keys still produce a stable hash
612
+ // (the model may have sent malformed JSON, but the refusal is
613
+ // semantic, not parse-driven).
614
+ const argsForTracking = safeParseForTracking(argsRaw);
615
+ if (!isMcpName && !WIRED_TOOLS.has(name)) {
616
+ throw recordDenial(name, argsForTracking, `unknown tool: ${name}`);
143
617
  }
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`);
618
+ // Leak L6 — canonical 4-mode permission gate. Routes the dispatch
619
+ // decision BEFORE the legacy plan-mode-only enforcement so the new
620
+ // surface is the source of truth when the caller opted in. Absent
621
+ // `permissionMode` falls through to the legacy plan-mode branch
622
+ // (existing semantics preserved for callsites that have not
623
+ // migrated yet).
624
+ let hooksBypassed = false;
625
+ if (permissionMode) {
626
+ const decision = permissionGate(name, argsRaw, {
627
+ permissionMode,
628
+ ...(permissionAlwaysCache ? { alwaysCache: permissionAlwaysCache } : {}),
629
+ });
630
+ if (decision.decision === 'deny') {
631
+ throw new PermissionDenied(name, getToolClass(name), permissionMode, decision.reason);
632
+ }
633
+ if (decision.decision === 'ask') {
634
+ if (!permissionAsk) {
635
+ // Non-interactive caller (CI / pipes / agent-as-tool) cannot
636
+ // surface a prompt. Collapse to deny so the loop receives a
637
+ // deterministic refusal instead of hanging.
638
+ throw new PermissionDenied(name, decision.toolClass, permissionMode, `Ask mode: no operator prompt available for ${name} (non-interactive caller)`);
639
+ }
640
+ const answer = await permissionAsk({
641
+ toolName: name,
642
+ toolClass: decision.toolClass,
643
+ question: decision.question,
644
+ options: decision.options,
645
+ });
646
+ const verdict = permissionAlwaysCache
647
+ ? applyAskAnswer(permissionAlwaysCache, name, answer)
648
+ : applyAskAnswer({ alwaysAllowed: new Set(), alwaysDenied: new Set() }, name, answer);
649
+ if (verdict.decision === 'deny') {
650
+ throw new PermissionDenied(name, decision.toolClass, permissionMode, verdict.reason);
651
+ }
652
+ // verdict.decision === 'allow' falls through to dispatch.
653
+ }
654
+ else {
655
+ // allow — honour the bypass flag for the hook layer below.
656
+ hooksBypassed = decision.hooksBypassed === true;
657
+ }
658
+ }
659
+ else if (planMode) {
660
+ // Legacy plan-mode enforcement (kind === 'plan') stays in place
661
+ // for callers that have not opted into the canonical gate.
662
+ // MCP tools are uniformly refused in plan mode (see schema-side
663
+ // rationale in buildToolsSchema). Native tools split via
664
+ // READ_ONLY_TOOLS as before.
665
+ if (isMcpName || !READ_ONLY_TOOLS.has(name)) {
666
+ throw recordDenial(name, argsForTracking, `PLAN_MODE_REFUSED: ${name} is not allowed in plan mode`);
667
+ }
149
668
  }
150
669
  // α6.9: refuse cancelled-token tool dispatch BEFORE PreToolUse
151
670
  // hooks fire so a cancelled brief never reaches user-defined
@@ -153,13 +672,32 @@ export function buildExecutor(input) {
153
672
  // by `runEngineLoop` as a terminal-cancel signal so the loop
154
673
  // returns control to the caller rather than retrying the model.
155
674
  if (ctx.cancellation && ctx.cancellation.isAborted) {
156
- throw new Error(`OPERATOR_ABORTED: ${name} refused — operator cancelled the dispatch.`);
675
+ throw recordDenial(name, argsForTracking, `OPERATOR_ABORTED: ${name} refused — operator cancelled the dispatch.`);
676
+ }
677
+ // Leak L31 — per-cycle tool retry budget. Same tool + same canonical
678
+ // args = same bucket. Once the cap is hit we throw a typed sentinel
679
+ // so the model is forced out of a repair loop. We gate AFTER
680
+ // permission (denied calls do not burn budget) and BEFORE PreToolUse
681
+ // hooks (hook-blocked retries DO count — the model still issued the
682
+ // same call). The `recordAttempt` fires unconditionally so warn-only
683
+ // mode (PUGI_RETRY_BUDGET_DISABLED=1) still tracks the pattern for
684
+ // diagnostics.
685
+ const argHash = hashArgs(argsRaw);
686
+ const budgetDecision = retryBudget.shouldAllow(name, argHash);
687
+ retryBudget.recordAttempt(name, argHash);
688
+ if (!budgetDecision.allowed) {
689
+ throw new RetryBudgetExhausted(name, budgetDecision.cap, argHash);
157
690
  }
158
691
  // Fire PreToolUse hooks. The match grammar takes the tool name and
159
692
  // (when extractable) the target path. Each new tool dispatch starts a
160
693
  // fresh dedup batch so a hook fires once per dispatch, not once per
161
694
  // session.
162
- if (hooks && sessionId) {
695
+ //
696
+ // Leak L6 — bypass mode skips the entire hook layer (PreToolUse +
697
+ // PostToolUse + PostToolUseFailure). The gate's allow decision
698
+ // carries the `hooksBypassed` flag; we honour it here so the
699
+ // executor stays single-pass.
700
+ if (hooks && sessionId && !hooksBypassed) {
163
701
  hooks.resetBatch();
164
702
  const path = extractToolPath(name, argsRaw);
165
703
  const preCtx = {
@@ -179,29 +717,152 @@ export function buildExecutor(input) {
179
717
  const hook = matchingPreHooks[i];
180
718
  const result = preResults[i];
181
719
  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})`);
720
+ // α7 L11: record the PreToolUse hook denial so the model
721
+ // sees the pattern reminder on subsequent turns. Without
722
+ // this the model would re-issue the same refused call and
723
+ // burn a turn each time before noticing the loop.
724
+ throw recordDenial(name, argsForTracking, `HOOK_BLOCKED: PreToolUse hook (${hook.run.slice(0, 80)}) refused ${name} (exit=${result.exitCode})`);
183
725
  }
184
726
  }
185
727
  }
186
- const args = parseArgs(argsRaw);
728
+ // Leak L12 MVP: fire `hooks-mvp.json` PreToolUse hooks. Distinct
729
+ // config file from the legacy `hooks.json` system so operator
730
+ // configs do not collide. Same blocking semantics — a non-zero
731
+ // exit from a hook declared `blocking: true` refuses the dispatch
732
+ // with `HOOK_BLOCKED:` sentinel. Bypass mode skips this surface
733
+ // identically to the legacy hooks block above.
734
+ if (mvpHooksConfig && sessionId && !hooksBypassed && !mvpHooksConfig.isEmpty()) {
735
+ const { fireHooks } = await import('../hooks/index.js');
736
+ const outcome = await fireHooks({
737
+ config: mvpHooksConfig,
738
+ event: 'PreToolUse',
739
+ payload: {
740
+ event: 'PreToolUse',
741
+ sessionId,
742
+ toolName: name,
743
+ toolInputSummary: hashArgs(argsRaw),
744
+ },
745
+ toolName: name,
746
+ workspaceRoot: ctx.root,
747
+ });
748
+ if (outcome.anyBlocked) {
749
+ const blocking = outcome.results.find((r) => r.blocked);
750
+ const sentinel = blocking?.blockSentinel ??
751
+ `HOOK_BLOCKED: PreToolUse MVP-hook refused ${name}`;
752
+ throw recordDenial(name, argsForTracking, sentinel);
753
+ }
754
+ }
755
+ // β4 M1/M3: MCP dispatch deferred to the `dispatch` closure below so
756
+ // PostToolUse / PostToolUseFailure hooks observe MCP calls just like
757
+ // native calls. The dispatcher does its own argument parsing — MCP
758
+ // arg errors surface as model-visible `[MCP dispatch error] ...`
759
+ // strings, not throws.
760
+ const args = isMcpName ? {} : parseArgs(argsRaw);
187
761
  const dispatch = async () => {
762
+ if (isMcpName) {
763
+ return dispatchMcpTool({
764
+ name,
765
+ argumentsRaw: argsRaw,
766
+ registry: mcpRegistry,
767
+ prompt: mcpPrompt,
768
+ });
769
+ }
770
+ // β1 T1/T2/T3/T5/T6: async-dispatch the new tool surface.
771
+ // task_*, skill, ask_user_question, web_fetch all live behind
772
+ // an async or async-compatible boundary.
773
+ if (name === 'task_create' || name === 'task_get' || name === 'task_list' || name === 'task_update') {
774
+ return dispatchTaskTool(name, args, { workspaceRoot, sessionId });
775
+ }
776
+ if (name === 'todo_write') {
777
+ // Leak L16: batch TodoWrite. The dispatcher delegates the
778
+ // Zod validation + atomic persist to the tool module — any
779
+ // ZodError or `TODO_INVARIANT_VIOLATED` sentinel surfaces here
780
+ // as a thrown Error and lands on the catch arm below, which
781
+ // re-emits it through the PostToolUseFailure hook.
782
+ return dispatchTodoWrite({ workspaceRoot }, args);
783
+ }
784
+ if (name === 'ask_user_question') {
785
+ return dispatchAskUser(args, { interactive: Boolean(interactive), bridge: askUserBridge });
786
+ }
787
+ if (name === 'skill' || name === 'skills_list') {
788
+ return dispatchSkillTool(name, args, { workspaceRoot });
789
+ }
790
+ if (name === 'web_fetch') {
791
+ return dispatchWebFetch(args, { ctx, allowFetch: Boolean(allowFetch) });
792
+ }
793
+ if (name === 'web_search') {
794
+ return dispatchWebSearch(args, {
795
+ ctx,
796
+ allowSearch: Boolean(allowSearch),
797
+ sessionId,
798
+ });
799
+ }
800
+ if (name === 'multi_edit') {
801
+ return dispatchMultiEdit(args, ctx);
802
+ }
803
+ if (name === 'agent') {
804
+ // β2a r1 (Backend Architect P1, 2026-05-26): defense in depth.
805
+ // `WIRED_TOOLS` includes `agent`, so a plan-mode model that
806
+ // fabricates an `agent` tool call would otherwise be routed
807
+ // here. The plan-mode refusal at the top of the executor only
808
+ // fires for tools NOT in READ_ONLY_TOOLS; `agent` is
809
+ // intentionally absent from both sets, so we explicitly refuse
810
+ // it here. This pairs with `native-pugi.ts` hard-gating
811
+ // `agentDispatch` itself off in plan mode — without this
812
+ // defensive throw a future schema bug could let a plan-mode
813
+ // model spawn a write-capable child and break the read-only
814
+ // contract.
815
+ if (planMode) {
816
+ throw recordDenial(name, argsForTracking, 'PLAN_MODE_REFUSED: agent is not allowed in plan mode');
817
+ }
818
+ return dispatchAgent(args, agentDispatch);
819
+ }
188
820
  return dispatchTool(name, args, ctx);
189
821
  };
190
822
  try {
191
823
  const result = await dispatch();
192
- if (hooks && sessionId) {
824
+ // Leak L15 (2026-05-27): post-edit LSP diagnostics. After a
825
+ // successful `edit` / `write` / `multi_edit`, ask the cached
826
+ // language server for diagnostics on the touched file(s) and
827
+ // append the result to the tool envelope so the model can
828
+ // self-correct in the same turn. Silent skip when the language
829
+ // is unsupported, no server is installed, or the request times
830
+ // out — agent throughput beats diagnostic recall.
831
+ const augmented = await appendPostEditDiagnostics(name, args, ctx, result);
832
+ if (hooks && sessionId && !hooksBypassed) {
193
833
  const path = extractToolPath(name, argsRaw);
194
834
  await hooks.fire({
195
835
  sessionId,
196
836
  event: 'PostToolUse',
197
837
  tool: name,
198
838
  path,
199
- payload: { tool: name, arguments: argsRaw, ok: true, result: result.slice(0, 1024) },
839
+ payload: { tool: name, arguments: argsRaw, ok: true, result: augmented.slice(0, 1024) },
200
840
  });
201
841
  }
202
- return result;
842
+ return augmented;
203
843
  }
204
844
  catch (error) {
845
+ // Leak L6 — surface the PermissionDenied sentinel as a model-
846
+ // readable message instead of leaking the raw Error type. The
847
+ // string format is stable so the engine adapter / spec layer
848
+ // can pattern-match against it.
849
+ if (error instanceof PermissionDenied) {
850
+ // PostToolUseFailure fires for visibility unless bypass is on.
851
+ if (hooks && sessionId && !hooksBypassed) {
852
+ await hooks.fire({
853
+ sessionId,
854
+ event: 'PostToolUseFailure',
855
+ tool: name,
856
+ payload: {
857
+ tool: name,
858
+ arguments: argsRaw,
859
+ ok: false,
860
+ error: error.toModelMessage(),
861
+ },
862
+ });
863
+ }
864
+ throw new Error(error.toModelMessage());
865
+ }
205
866
  // α6.9: re-shape OperatorAbortedError throws from the
206
867
  // file-tools layer into the same `OPERATOR_ABORTED:` sentinel
207
868
  // the upstream cancellation gate uses so `runEngineLoop` sees
@@ -209,7 +870,7 @@ export function buildExecutor(input) {
209
870
  // the abort landed pre-dispatch or mid-tool (e.g. inside the
210
871
  // grep file-loop).
211
872
  if (error instanceof OperatorAbortedError) {
212
- if (hooks && sessionId) {
873
+ if (hooks && sessionId && !hooksBypassed) {
213
874
  const path = extractToolPath(name, argsRaw);
214
875
  await hooks.fire({
215
876
  sessionId,
@@ -224,9 +885,35 @@ export function buildExecutor(input) {
224
885
  },
225
886
  });
226
887
  }
227
- throw new Error(`OPERATOR_ABORTED: ${name} aborted mid-execution.`);
888
+ throw recordDenial(name, argsForTracking, `OPERATOR_ABORTED: ${name} aborted mid-execution.`);
228
889
  }
229
- if (hooks && sessionId) {
890
+ // Leak L1 (2026-05-27): re-shape StaleReadError into a
891
+ // deterministic STALE_READ:<reason> sentinel so the model's
892
+ // retry policy can pattern-match on a stable prefix instead of
893
+ // free-form prose. The model is expected to re-read the file and
894
+ // retry the edit — the message points it at exactly that recovery
895
+ // path. PostToolUseFailure hooks observe the typed error so an
896
+ // operator can build a "warn me when stale edits keep happening"
897
+ // hook (likely a concurrency / multi-agent indicator).
898
+ if (error instanceof StaleReadError) {
899
+ if (hooks && sessionId && !hooksBypassed) {
900
+ const path = extractToolPath(name, argsRaw);
901
+ await hooks.fire({
902
+ sessionId,
903
+ event: 'PostToolUseFailure',
904
+ tool: name,
905
+ path,
906
+ payload: {
907
+ tool: name,
908
+ arguments: argsRaw,
909
+ ok: false,
910
+ error: `STALE_READ: ${error.reason} on ${error.path}`,
911
+ },
912
+ });
913
+ }
914
+ 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}.`);
915
+ }
916
+ if (hooks && sessionId && !hooksBypassed) {
230
917
  const path = extractToolPath(name, argsRaw);
231
918
  await hooks.fire({
232
919
  sessionId,
@@ -266,7 +953,7 @@ function extractToolPath(name, argsRaw) {
266
953
  function dispatchTool(name, args, ctx) {
267
954
  switch (name) {
268
955
  case 'read': {
269
- const { path } = { path: requireString(args, 'path') };
956
+ const { path } = { path: requirePathArg(args) };
270
957
  const content = readTool(ctx, path);
271
958
  // Cap the content surfaced back to the model so a 10MB file
272
959
  // does not blow the context window. The model sees the head
@@ -279,7 +966,7 @@ function dispatchTool(name, args, ctx) {
279
966
  }
280
967
  case 'write': {
281
968
  const wargs = {
282
- path: requireString(args, 'path'),
969
+ path: requirePathArg(args),
283
970
  content: requireString(args, 'content'),
284
971
  };
285
972
  writeTool(ctx, wargs.path, wargs.content);
@@ -287,7 +974,7 @@ function dispatchTool(name, args, ctx) {
287
974
  }
288
975
  case 'edit': {
289
976
  const eargs = {
290
- path: requireString(args, 'path'),
977
+ path: requirePathArg(args),
291
978
  oldString: requireString(args, 'oldString'),
292
979
  newString: requireString(args, 'newString'),
293
980
  };
@@ -337,9 +1024,331 @@ function dispatchTool(name, args, ctx) {
337
1024
  const body = parts.filter(Boolean).join('\n');
338
1025
  return body || '(no output)';
339
1026
  }
1027
+ case 'powershell': {
1028
+ // Leak L6 (2026-05-28): pwsh dispatcher. Permission gate reuses the
1029
+ // bash classifier so destructive patterns block the same way.
1030
+ const command = requireString(args, 'command');
1031
+ const cwd = optionalString(args, 'cwd');
1032
+ const timeoutMs = optionalNumber(args, 'timeoutMs');
1033
+ const psResult = powerShellToolSync({ cmd: command, ...(cwd !== undefined ? { cwd } : {}), ...(timeoutMs !== undefined ? { timeoutMs } : {}) }, {
1034
+ root: ctx.root,
1035
+ settings: ctx.settings,
1036
+ session: ctx.session,
1037
+ source: 'agent',
1038
+ });
1039
+ const parts = [
1040
+ `exit=${psResult.exitCode}`,
1041
+ `shell=${psResult.shellBinary}`,
1042
+ psResult.stdout ? `stdout:\n${psResult.stdout}` : '',
1043
+ psResult.stderr ? `stderr:\n${psResult.stderr}` : '',
1044
+ ];
1045
+ if (psResult.truncated)
1046
+ parts.push('truncated=true');
1047
+ if (psResult.timedOut)
1048
+ parts.push('timedOut=true');
1049
+ return parts.filter(Boolean).join('\n') || '(no output)';
1050
+ }
340
1051
  default:
341
1052
  // Exhaustive; unreachable because of the WIRED_TOOLS guard above.
342
1053
  throw new Error(`unhandled tool: ${name}`);
343
1054
  }
344
1055
  }
1056
+ /* ----------------------------- β1 dispatchers ----------------------------- */
1057
+ function dispatchTaskTool(name, args, opts) {
1058
+ if (!opts.sessionId) {
1059
+ throw new Error(`${name}: no sessionId in scope — task ledger requires a session`);
1060
+ }
1061
+ const tctx = { workspaceRoot: opts.workspaceRoot, sessionId: opts.sessionId };
1062
+ switch (name) {
1063
+ case 'task_create': {
1064
+ const title = requireString(args, 'title');
1065
+ const status = optionalString(args, 'status');
1066
+ const notes = optionalString(args, 'notes');
1067
+ const record = taskCreate(tctx, {
1068
+ title,
1069
+ ...(status !== undefined ? { status: status } : {}),
1070
+ ...(notes !== undefined ? { notes } : {}),
1071
+ });
1072
+ return JSON.stringify(record);
1073
+ }
1074
+ case 'task_get': {
1075
+ const id = requireString(args, 'id');
1076
+ const record = taskGet(tctx, id);
1077
+ return record ? JSON.stringify(record) : 'null';
1078
+ }
1079
+ case 'task_list': {
1080
+ const list = taskList(tctx);
1081
+ return JSON.stringify(list);
1082
+ }
1083
+ case 'task_update': {
1084
+ const id = requireString(args, 'id');
1085
+ const title = optionalString(args, 'title');
1086
+ const status = optionalString(args, 'status');
1087
+ const notes = optionalString(args, 'notes');
1088
+ const record = taskUpdate(tctx, {
1089
+ id,
1090
+ ...(title !== undefined ? { title } : {}),
1091
+ ...(status !== undefined ? { status: status } : {}),
1092
+ ...(notes !== undefined ? { notes } : {}),
1093
+ });
1094
+ return JSON.stringify(record);
1095
+ }
1096
+ }
1097
+ }
1098
+ async function dispatchAskUser(args, opts) {
1099
+ const rawOptions = args['options'];
1100
+ if (!Array.isArray(rawOptions)) {
1101
+ throw new Error('ask_user_question: options must be an array');
1102
+ }
1103
+ // Leak L5 (2026-05-27): detect structured vs legacy form. Structured
1104
+ // entries are objects with {label, description}; legacy entries are
1105
+ // plain strings. The structured path validates via Zod and emits the
1106
+ // [ask_user_question:answered|cancelled|timeout] envelope. The legacy
1107
+ // path stays for back-compat with the existing β1 T2 tests + the
1108
+ // <pugi-ask> prompt envelope (which still feeds string options).
1109
+ const looksStructured = rawOptions.length > 0
1110
+ && typeof rawOptions[0] === 'object'
1111
+ && rawOptions[0] !== null
1112
+ && !Array.isArray(rawOptions[0]);
1113
+ if (looksStructured) {
1114
+ const result = await dispatchAskUserQuestion({ interactive: opts.interactive, ...(opts.bridge ? { bridge: opts.bridge } : {}) }, args);
1115
+ return result.envelope;
1116
+ }
1117
+ // Legacy string-array form.
1118
+ const question = requireString(args, 'question');
1119
+ const options = rawOptions.map((o, i) => {
1120
+ if (typeof o !== 'string') {
1121
+ throw new Error(`ask_user_question: options[${i}] must be a string`);
1122
+ }
1123
+ return o;
1124
+ });
1125
+ const multiSelect = args['multiSelect'] === true;
1126
+ const result = await askUser({ interactive: opts.interactive, ...(opts.bridge ? { bridge: opts.bridge } : {}) }, { question, options, multiSelect });
1127
+ return result.envelope;
1128
+ }
1129
+ async function dispatchSkillTool(name, args, opts) {
1130
+ if (name === 'skills_list') {
1131
+ const scopeArg = optionalString(args, 'scope');
1132
+ const scope = scopeArg === 'global' || scopeArg === 'workspace' ? scopeArg : 'all';
1133
+ const list = skillList({ workspaceRoot: opts.workspaceRoot }, { scope });
1134
+ return JSON.stringify(list);
1135
+ }
1136
+ // name === 'skill' (invoke).
1137
+ // β1a r1 (2026-05-26): `skillInvoke` is now async — it re-verifies
1138
+ // the trust manifest sha256 against the on-disk body on every call.
1139
+ // Bubble up `await` so a post-install tamper surfaces as a tool
1140
+ // error the model sees, not a swallowed Promise<SkillInvokeResult>.
1141
+ const skName = requireString(args, 'name');
1142
+ const result = await skillInvoke({ workspaceRoot: opts.workspaceRoot }, { name: skName });
1143
+ return JSON.stringify(result);
1144
+ }
1145
+ async function dispatchWebFetch(args, opts) {
1146
+ const url = requireString(args, 'url');
1147
+ const result = await webFetchTool({ url }, {
1148
+ settings: opts.ctx.settings,
1149
+ allowFetch: opts.allowFetch,
1150
+ });
1151
+ return JSON.stringify(result);
1152
+ }
1153
+ async function dispatchWebSearch(args, opts) {
1154
+ const query = requireString(args, 'query');
1155
+ // `count` is optional integer 1..10. Validate here so the tool layer
1156
+ // gets a clean value (the tool clamps internally too — defense in
1157
+ // depth, since the model can pass anything).
1158
+ let count;
1159
+ if (args['count'] !== undefined && args['count'] !== null) {
1160
+ const n = args['count'];
1161
+ if (typeof n !== 'number' || !Number.isInteger(n)) {
1162
+ throw new Error('web_search: count must be an integer');
1163
+ }
1164
+ count = n;
1165
+ }
1166
+ const result = await webSearchTool({ query, ...(count !== undefined ? { count } : {}) }, {
1167
+ settings: opts.ctx.settings,
1168
+ allowSearch: opts.allowSearch,
1169
+ sessionId: opts.sessionId,
1170
+ });
1171
+ return JSON.stringify(result);
1172
+ }
1173
+ /**
1174
+ * β2 S3 dispatch — wire the model-emitted `agent` tool call to the
1175
+ * real subagent spawn primitive. When the executor was built without
1176
+ * `agentDispatch` (e.g. a child loop, or a parent that explicitly
1177
+ * disabled subagent spawn), the call is refused with a structured
1178
+ * envelope so the model can adapt instead of crashing the parent loop.
1179
+ */
1180
+ async function dispatchAgent(args, opts) {
1181
+ if (!opts) {
1182
+ // No dispatch context — return a structured refusal envelope.
1183
+ // This matches the agent-tool.ts no-engine-client path and lets
1184
+ // the model decide whether to retry inline or abandon the
1185
+ // delegation. Throwing here would terminate the parent on a tool
1186
+ // error frame which is the wrong UX when the issue is config.
1187
+ return JSON.stringify({
1188
+ ok: false,
1189
+ status: 'failed',
1190
+ summary: 'agent tool refused: dispatch not wired in this engine adapter. '
1191
+ + 'Re-run from a parent loop with agentDispatch configured.',
1192
+ });
1193
+ }
1194
+ const parsed = parseAgentArgs(args);
1195
+ const result = await agentTool(parsed, {
1196
+ session: opts.parentSession,
1197
+ engineClient: opts.engineClient,
1198
+ ...(opts.parentBudgetRemaining
1199
+ ? { parentBudgetRemaining: opts.parentBudgetRemaining }
1200
+ : {}),
1201
+ });
1202
+ return JSON.stringify(result);
1203
+ }
1204
+ function parseAgentArgs(args) {
1205
+ // Surface a clean error message to the model when the args don't
1206
+ // match the schema. agentTool itself also validates via Zod; this
1207
+ // pre-parse layer keeps the error stack short.
1208
+ const role = requireString(args, 'role');
1209
+ const brief = requireString(args, 'brief');
1210
+ const isolationRaw = optionalString(args, 'isolation');
1211
+ const out = {
1212
+ role: role,
1213
+ brief,
1214
+ ...(isolationRaw ? { isolation: isolationRaw } : {}),
1215
+ };
1216
+ return out;
1217
+ }
1218
+ function optionalString(obj, key) {
1219
+ const v = obj[key];
1220
+ if (v === undefined || v === null)
1221
+ return undefined;
1222
+ if (typeof v !== 'string') {
1223
+ throw new Error(`tool argument "${key}" must be a string when present`);
1224
+ }
1225
+ return v;
1226
+ }
1227
+ function optionalNumber(obj, key) {
1228
+ const v = obj[key];
1229
+ if (v === undefined || v === null)
1230
+ return undefined;
1231
+ if (typeof v !== 'number' || !Number.isFinite(v)) {
1232
+ throw new Error(`tool argument "${key}" must be a finite number when present`);
1233
+ }
1234
+ return v;
1235
+ }
1236
+ /**
1237
+ * β7 L5+T11: dispatch the model-emitted `multi_edit` tool call. The
1238
+ * tool returns a structured result envelope; we serialize it to JSON
1239
+ * for the engine loop. A refused dispatch (security, no_match,
1240
+ * ambiguous_match, etc.) surfaces as `ok: false` in the envelope —
1241
+ * the model can re-strategise rather than crashing the loop.
1242
+ */
1243
+ function dispatchMultiEdit(args, ctx) {
1244
+ const raw = args['edits'];
1245
+ if (!Array.isArray(raw)) {
1246
+ throw new Error('multi_edit: edits must be an array');
1247
+ }
1248
+ const edits = raw.map((item, i) => {
1249
+ if (!item || typeof item !== 'object') {
1250
+ throw new Error(`multi_edit: edits[${i}] must be an object`);
1251
+ }
1252
+ const obj = item;
1253
+ const file = obj['file'];
1254
+ const oldString = obj['oldString'];
1255
+ const newString = obj['newString'];
1256
+ if (typeof file !== 'string') {
1257
+ throw new Error(`multi_edit: edits[${i}].file must be a string`);
1258
+ }
1259
+ if (typeof oldString !== 'string') {
1260
+ throw new Error(`multi_edit: edits[${i}].oldString must be a string`);
1261
+ }
1262
+ if (typeof newString !== 'string') {
1263
+ throw new Error(`multi_edit: edits[${i}].newString must be a string`);
1264
+ }
1265
+ return { file, oldString, newString };
1266
+ });
1267
+ const result = multiEdit(ctx, edits);
1268
+ return JSON.stringify(result);
1269
+ }
1270
+ /* ---------------------------- Leak L15 hook ---------------------------- */
1271
+ /**
1272
+ * Tool names that mutate workspace files. After a successful dispatch
1273
+ * of any of these, the L15 post-edit diagnostics hook fires. The set
1274
+ * is intentionally tight — `task_*` / `todo_write` write to ledger
1275
+ * files (not workspace source) so they stay out, and `bash` is too
1276
+ * coarse (a `bash` call can write any path, and we'd need to parse
1277
+ * the command to know which — out of scope for L15).
1278
+ */
1279
+ const POST_EDIT_TOOLS = new Set(['edit', 'write', 'multi_edit']);
1280
+ /**
1281
+ * Append LSP diagnostics to the tool envelope after a successful
1282
+ * edit / write / multi_edit. Silent skip is the default — missing
1283
+ * binary, unsupported language, request timeout, and "no diagnostics"
1284
+ * all leave the envelope unchanged.
1285
+ *
1286
+ * Opt-in via `.pugi/settings.json::lsp.postEditDiagnostics = true`
1287
+ * OR `PUGI_LSP_POST_EDIT=1`. Off by default until dogfood validates
1288
+ * the cold-start cost vs the model-loop benefit (Leak L15).
1289
+ */
1290
+ async function appendPostEditDiagnostics(name, args, ctx, result) {
1291
+ if (!POST_EDIT_TOOLS.has(name))
1292
+ return result;
1293
+ if (!isPostEditEnabled(ctx))
1294
+ return result;
1295
+ const paths = extractEditedPaths(name, args);
1296
+ if (paths.length === 0)
1297
+ return result;
1298
+ const tails = [];
1299
+ for (const filePath of paths) {
1300
+ const opts = {
1301
+ cwd: ctx.root,
1302
+ ...(ctx.settings.lsp ? { lspSettings: ctx.settings.lsp } : {}),
1303
+ };
1304
+ try {
1305
+ const diag = await runPostEditDiagnostics(filePath, opts);
1306
+ if (!diag.skip) {
1307
+ tails.push(diag.tail);
1308
+ }
1309
+ }
1310
+ catch {
1311
+ // Belt-and-suspenders: any unexpected throw from the hook is
1312
+ // swallowed. The model never blocks on LSP.
1313
+ }
1314
+ }
1315
+ if (tails.length === 0)
1316
+ return result;
1317
+ return `${result}\n${tails.join('\n')}`;
1318
+ }
1319
+ function isPostEditEnabled(ctx) {
1320
+ const envFlag = process.env.PUGI_LSP_POST_EDIT;
1321
+ if (envFlag === '1' || envFlag === 'true')
1322
+ return true;
1323
+ if (envFlag === '0' || envFlag === 'false')
1324
+ return false;
1325
+ return ctx.settings.lsp?.postEditDiagnostics === true;
1326
+ }
1327
+ /**
1328
+ * Pull the workspace-relative file path(s) the tool just touched.
1329
+ * Each branch mirrors the args shape its `dispatch*` handler reads;
1330
+ * a deformed args object yields an empty list so the hook silently
1331
+ * skips instead of throwing inside the augmentation layer.
1332
+ */
1333
+ function extractEditedPaths(name, args) {
1334
+ if (name === 'edit' || name === 'write') {
1335
+ const path = args['path'];
1336
+ return typeof path === 'string' && path.length > 0 ? [path] : [];
1337
+ }
1338
+ if (name === 'multi_edit') {
1339
+ const edits = args['edits'];
1340
+ if (!Array.isArray(edits))
1341
+ return [];
1342
+ const seen = new Set();
1343
+ for (const entry of edits) {
1344
+ if (!entry || typeof entry !== 'object')
1345
+ continue;
1346
+ const file = entry['file'];
1347
+ if (typeof file === 'string' && file.length > 0)
1348
+ seen.add(file);
1349
+ }
1350
+ return Array.from(seen);
1351
+ }
1352
+ return [];
1353
+ }
345
1354
  //# sourceMappingURL=tool-bridge.js.map