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

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