@pugi/cli 0.1.0-beta.3 → 0.1.0-beta.30

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 (218) hide show
  1. package/THIRD_PARTY_NOTICES.md +40 -0
  2. package/assets/pugi-mascot.ansi +15 -40
  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/core/agent-progress/cleanup.js +134 -0
  7. package/dist/core/agent-progress/schema.js +144 -0
  8. package/dist/core/agent-progress/writer.js +101 -0
  9. package/dist/core/artifact-chain/dispatcher.js +148 -0
  10. package/dist/core/artifact-chain/exporter.js +164 -0
  11. package/dist/core/artifact-chain/state.js +243 -0
  12. package/dist/core/artifact-chain/steps.js +169 -0
  13. package/dist/core/auth/env-provider.js +238 -0
  14. package/dist/core/auto-update/channels.js +122 -0
  15. package/dist/core/auto-update/checker.js +241 -0
  16. package/dist/core/auto-update/state.js +235 -0
  17. package/dist/core/bare-mode/index.js +107 -0
  18. package/dist/core/checkpoint/resumer.js +149 -0
  19. package/dist/core/checkpoint/rewinder.js +291 -0
  20. package/dist/core/compact/auto-trigger.js +96 -0
  21. package/dist/core/compact/buffer-rewriter.js +115 -0
  22. package/dist/core/compact/summarizer.js +208 -0
  23. package/dist/core/compact/token-counter.js +108 -0
  24. package/dist/core/consensus/diff-capture.js +73 -0
  25. package/dist/core/context/index.js +7 -0
  26. package/dist/core/context/markdown-traverse.js +255 -0
  27. package/dist/core/cost/rate-card.js +129 -0
  28. package/dist/core/cost/tracker.js +221 -0
  29. package/dist/core/denial-tracking/index.js +8 -0
  30. package/dist/core/denial-tracking/state.js +264 -0
  31. package/dist/core/diagnostics/probe-runner.js +93 -0
  32. package/dist/core/diagnostics/probes/api.js +46 -0
  33. package/dist/core/diagnostics/probes/auth.js +86 -0
  34. package/dist/core/diagnostics/probes/bare-mode.js +42 -0
  35. package/dist/core/diagnostics/probes/cli-version.js +127 -0
  36. package/dist/core/diagnostics/probes/config.js +72 -0
  37. package/dist/core/diagnostics/probes/denial-tracking.js +57 -0
  38. package/dist/core/diagnostics/probes/disk.js +81 -0
  39. package/dist/core/diagnostics/probes/git.js +65 -0
  40. package/dist/core/diagnostics/probes/mcp.js +75 -0
  41. package/dist/core/diagnostics/probes/node.js +59 -0
  42. package/dist/core/diagnostics/probes/pnpm.js +36 -0
  43. package/dist/core/diagnostics/probes/pugi-md.js +89 -0
  44. package/dist/core/diagnostics/probes/session.js +74 -0
  45. package/dist/core/diagnostics/probes/status-snapshot.js +442 -0
  46. package/dist/core/diagnostics/probes/workspace.js +63 -0
  47. package/dist/core/diagnostics/types.js +70 -0
  48. package/dist/core/dispatch/cache-cleanup.js +197 -0
  49. package/dist/core/dispatch/cache-handoff.js +295 -0
  50. package/dist/core/edits/dispatch.js +218 -2
  51. package/dist/core/edits/journal.js +199 -0
  52. package/dist/core/edits/layer-d-ast.js +557 -14
  53. package/dist/core/edits/verify-hook.js +273 -0
  54. package/dist/core/edits/worktree.js +111 -18
  55. package/dist/core/engine/anvil-client.js +115 -5
  56. package/dist/core/engine/budgets.js +89 -0
  57. package/dist/core/engine/context-prefix.js +155 -0
  58. package/dist/core/engine/intent.js +260 -0
  59. package/dist/core/engine/native-pugi.js +852 -210
  60. package/dist/core/engine/prompts.js +89 -6
  61. package/dist/core/engine/strip-internal-fields.js +124 -0
  62. package/dist/core/engine/tool-bridge.js +972 -33
  63. package/dist/core/feedback/queue.js +177 -0
  64. package/dist/core/feedback/submitter.js +145 -0
  65. package/dist/core/file-cache.js +113 -1
  66. package/dist/core/hooks/events.js +44 -0
  67. package/dist/core/hooks/index.js +15 -0
  68. package/dist/core/hooks/registry.js +213 -0
  69. package/dist/core/hooks/runner.js +236 -0
  70. package/dist/core/init/scaffold.js +195 -0
  71. package/dist/core/lsp/cache.js +105 -0
  72. package/dist/core/lsp/client.js +174 -29
  73. package/dist/core/lsp/language-detect.js +66 -0
  74. package/dist/core/lsp/post-edit-diagnostics.js +171 -0
  75. package/dist/core/mcp/client.js +75 -6
  76. package/dist/core/mcp/http-server.js +553 -0
  77. package/dist/core/mcp/permission.js +190 -0
  78. package/dist/core/mcp/registry.js +24 -2
  79. package/dist/core/mcp/server-tools.js +219 -0
  80. package/dist/core/mcp/server.js +397 -0
  81. package/dist/core/memory/dual-write.js +416 -0
  82. package/dist/core/memory/dual-write.spec.js +297 -0
  83. package/dist/core/memory/phase1-kinds.js +20 -0
  84. package/dist/core/memory-sync/queue.js +158 -0
  85. package/dist/core/memory-sync/queue.spec.js +105 -0
  86. package/dist/core/onboarding/marker.js +111 -0
  87. package/dist/core/onboarding/telemetry-state.js +108 -0
  88. package/dist/core/output-style/presets.js +176 -0
  89. package/dist/core/output-style/state.js +185 -0
  90. package/dist/core/permissions/gate.js +187 -0
  91. package/dist/core/permissions/index.js +18 -0
  92. package/dist/core/permissions/mode.js +102 -0
  93. package/dist/core/permissions/state.js +215 -0
  94. package/dist/core/permissions/tool-class.js +93 -0
  95. package/dist/core/prd-check/parser.js +215 -0
  96. package/dist/core/prd-check/reporter.js +127 -0
  97. package/dist/core/prd-check/verifiers.js +223 -0
  98. package/dist/core/pugi-md/context-injector.js +76 -0
  99. package/dist/core/pugi-md/walk-up.js +207 -0
  100. package/dist/core/release-notes/parser.js +241 -0
  101. package/dist/core/release-notes/state.js +116 -0
  102. package/dist/core/repl/codebase-survey.js +308 -0
  103. package/dist/core/repl/history.js +11 -1
  104. package/dist/core/repl/init-interview.js +457 -0
  105. package/dist/core/repl/model-pricing.js +135 -0
  106. package/dist/core/repl/onboarding-state.js +297 -0
  107. package/dist/core/repl/session.js +1486 -30
  108. package/dist/core/repl/slash-commands.js +345 -9
  109. package/dist/core/repl/store/session-store.js +31 -2
  110. package/dist/core/repl/workspace-context.js +22 -0
  111. package/dist/core/repo-map/build.js +125 -0
  112. package/dist/core/repo-map/cache.js +185 -0
  113. package/dist/core/repo-map/extractor.js +254 -0
  114. package/dist/core/repo-map/formatter.js +145 -0
  115. package/dist/core/repo-map/scanner.js +211 -0
  116. package/dist/core/retry-budget/budget.js +284 -0
  117. package/dist/core/retry-budget/index.js +5 -0
  118. package/dist/core/session.js +44 -0
  119. package/dist/core/settings.js +80 -0
  120. package/dist/core/share/formatter.js +271 -0
  121. package/dist/core/share/redactor.js +221 -0
  122. package/dist/core/share/uploader.js +267 -0
  123. package/dist/core/skills/defaults.js +457 -0
  124. package/dist/core/subagents/dispatcher-real.js +600 -0
  125. package/dist/core/subagents/dispatcher.js +113 -24
  126. package/dist/core/subagents/index.js +18 -5
  127. package/dist/core/subagents/isolation-matrix.js +213 -0
  128. package/dist/core/subagents/spawn.js +19 -4
  129. package/dist/core/telemetry/emitter.js +229 -0
  130. package/dist/core/telemetry/queue.js +251 -0
  131. package/dist/core/theme/context.js +91 -0
  132. package/dist/core/theme/presets.js +228 -0
  133. package/dist/core/theme/state.js +181 -0
  134. package/dist/core/todos/invariant.js +10 -0
  135. package/dist/core/todos/state.js +177 -0
  136. package/dist/core/transport/version-interceptor.js +166 -0
  137. package/dist/core/vim/keymap.js +288 -0
  138. package/dist/core/vim/state.js +92 -0
  139. package/dist/index.js +28 -0
  140. package/dist/runtime/bootstrap.js +190 -0
  141. package/dist/runtime/cli.js +2595 -278
  142. package/dist/runtime/commands/chain.js +489 -0
  143. package/dist/runtime/commands/compact.js +297 -0
  144. package/dist/runtime/commands/cost.js +199 -0
  145. package/dist/runtime/commands/delegate.js +312 -0
  146. package/dist/runtime/commands/dispatch.js +126 -0
  147. package/dist/runtime/commands/doctor.js +390 -0
  148. package/dist/runtime/commands/feedback.js +184 -0
  149. package/dist/runtime/commands/hooks.js +184 -0
  150. package/dist/runtime/commands/lsp.js +212 -28
  151. package/dist/runtime/commands/mcp.js +824 -0
  152. package/dist/runtime/commands/memory.js +508 -0
  153. package/dist/runtime/commands/memory.spec.js +174 -0
  154. package/dist/runtime/commands/model.js +237 -0
  155. package/dist/runtime/commands/onboarding.js +275 -0
  156. package/dist/runtime/commands/patch.js +17 -0
  157. package/dist/runtime/commands/permissions.js +87 -0
  158. package/dist/runtime/commands/plan.js +143 -0
  159. package/dist/runtime/commands/prd-check.js +235 -0
  160. package/dist/runtime/commands/release-notes.js +229 -0
  161. package/dist/runtime/commands/repo-map.js +95 -0
  162. package/dist/runtime/commands/report.js +299 -0
  163. package/dist/runtime/commands/resume.js +118 -0
  164. package/dist/runtime/commands/review-consensus.js +17 -2
  165. package/dist/runtime/commands/rewind.js +333 -0
  166. package/dist/runtime/commands/roster.js +117 -0
  167. package/dist/runtime/commands/sessions.js +163 -0
  168. package/dist/runtime/commands/share.js +316 -0
  169. package/dist/runtime/commands/status.js +178 -0
  170. package/dist/runtime/commands/stickers.js +82 -0
  171. package/dist/runtime/commands/style.js +194 -0
  172. package/dist/runtime/commands/theme.js +196 -0
  173. package/dist/runtime/commands/update.js +289 -0
  174. package/dist/runtime/commands/vim.js +140 -0
  175. package/dist/runtime/commands/worktree.js +50 -6
  176. package/dist/runtime/headless.js +543 -0
  177. package/dist/runtime/load-hooks-or-exit.js +71 -0
  178. package/dist/runtime/plan-decompose.js +531 -0
  179. package/dist/runtime/version.js +65 -0
  180. package/dist/tools/agent-tool.js +229 -0
  181. package/dist/tools/apply-patch.js +281 -39
  182. package/dist/tools/ask-user-question.js +213 -0
  183. package/dist/tools/ask-user.js +115 -0
  184. package/dist/tools/file-tools.js +85 -14
  185. package/dist/tools/mcp-tool.js +260 -0
  186. package/dist/tools/multi-edit.js +361 -0
  187. package/dist/tools/registry.js +30 -2
  188. package/dist/tools/skill-tool.js +96 -0
  189. package/dist/tools/tasks.js +208 -0
  190. package/dist/tools/todo-write.js +184 -0
  191. package/dist/tools/web-fetch.js +147 -2
  192. package/dist/tools/web-search.js +458 -0
  193. package/dist/tui/agent-progress-card.js +111 -0
  194. package/dist/tui/agent-tree.js +10 -0
  195. package/dist/tui/ask-modal.js +2 -2
  196. package/dist/tui/ask-user-question-prompt.js +192 -0
  197. package/dist/tui/compact-banner.js +81 -0
  198. package/dist/tui/conversation-pane.js +82 -8
  199. package/dist/tui/cost-table.js +111 -0
  200. package/dist/tui/doctor-table.js +46 -0
  201. package/dist/tui/feedback-prompt.js +156 -0
  202. package/dist/tui/input-box.js +46 -2
  203. package/dist/tui/markdown-render.js +4 -4
  204. package/dist/tui/onboarding-wizard.js +240 -0
  205. package/dist/tui/repl-render.js +293 -35
  206. package/dist/tui/repl-splash.js +2 -2
  207. package/dist/tui/repl.js +45 -13
  208. package/dist/tui/splash.js +1 -1
  209. package/dist/tui/status-bar.js +94 -16
  210. package/dist/tui/status-table.js +7 -0
  211. package/dist/tui/stickers-art.js +136 -0
  212. package/dist/tui/style-table.js +28 -0
  213. package/dist/tui/theme-table.js +29 -0
  214. package/dist/tui/tool-stream-pane.js +7 -0
  215. package/dist/tui/update-banner.js +20 -2
  216. package/dist/tui/vim-input.js +267 -0
  217. package/docs/examples/codegraph.mcp.json +10 -0
  218. package/package.json +9 -6
@@ -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,139 @@ 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`);
136
518
  }
137
519
  export function buildExecutor(input) {
138
- const { kind, ctx, hooks, sessionId } = input;
520
+ const { kind, ctx, hooks, mvpHooksConfig, sessionId, askUserBridge, interactive, allowFetch, allowSearch, agentDispatch, mcpRegistry, permissionMode, permissionAlwaysCache, permissionAsk, } = input;
521
+ // Leak L31: per-cycle budget. Default to a fresh instance scoped to
522
+ // this executor's closure lifetime; tests pass their own.
523
+ const retryBudget = input.retryBudget ?? new RetryBudget();
524
+ const mcpPrompt = input.mcpPrompt ?? defaultNonInteractiveMcpPrompt;
525
+ const workspaceRoot = input.workspaceRoot ?? ctx.root;
139
526
  const planMode = kind === 'plan';
527
+ const denialTracking = input.denialTracking;
528
+ // α7 L11: helper that records a denial (when tracking is wired) and
529
+ // ALWAYS returns an Error whose message includes a compact
530
+ // `<denial-context>` reminder when the same (tool, args) pair has
531
+ // already been refused at least once before in this session.
532
+ //
533
+ // The reminder is appended to the THROWN message — the engine loop
534
+ // appends thrown messages to the transcript as tool-result strings,
535
+ // so the model sees the aggregate the next time it considers a
536
+ // dispatch. Without this every retry would only see the latest
537
+ // single-turn reason and could loop indefinitely.
538
+ //
539
+ // Best-effort: a hash/clone failure inside the tracker MUST NOT
540
+ // mask the original refusal. The catch path falls back to a bare
541
+ // Error with the reason text.
542
+ const recordDenial = (toolName, args, reason) => {
543
+ if (!denialTracking)
544
+ return new Error(reason);
545
+ try {
546
+ const record = denialTracking.recordDenial(toolName, args, reason);
547
+ // Only inject the reminder once the threshold is hit — the very
548
+ // first denial is the model's first chance to learn, no need to
549
+ // shout. From the 2nd repeat onwards the model has demonstrated
550
+ // it is not learning from the single-turn sentinel, so we splice
551
+ // the aggregate context.
552
+ if (record.count >= DENIAL_REMINDER_THRESHOLD) {
553
+ const reminder = buildDenialContext(denialTracking);
554
+ if (reminder.length > 0) {
555
+ return new Error(`${reason}\n\n${reminder}`);
556
+ }
557
+ }
558
+ }
559
+ catch {
560
+ // Tracking is best-effort. Fall through to the bare Error so
561
+ // the refusal still propagates.
562
+ }
563
+ return new Error(reason);
564
+ };
140
565
  return async ({ name, arguments: argsRaw }) => {
141
- if (!WIRED_TOOLS.has(name)) {
142
- throw new Error(`unknown tool: ${name}`);
566
+ // β4 M1/M3: MCP tool names live outside WIRED_TOOLS. They are
567
+ // validated lazily by the dispatcher (the registry knows which
568
+ // names are actually exposed). The namespace check happens FIRST
569
+ // so a bad `mcp__bogus__foo` does not collide with the native
570
+ // unknown-tool branch.
571
+ const isMcpName = name.startsWith(MCP_TOOL_PREFIX);
572
+ // α7 L11: parse-or-empty args once up-front so every deny path
573
+ // below can fingerprint the call against the denial tracker. We
574
+ // tolerate parse failure — `{}` keys still produce a stable hash
575
+ // (the model may have sent malformed JSON, but the refusal is
576
+ // semantic, not parse-driven).
577
+ const argsForTracking = safeParseForTracking(argsRaw);
578
+ if (!isMcpName && !WIRED_TOOLS.has(name)) {
579
+ throw recordDenial(name, argsForTracking, `unknown tool: ${name}`);
580
+ }
581
+ // Leak L6 — canonical 4-mode permission gate. Routes the dispatch
582
+ // decision BEFORE the legacy plan-mode-only enforcement so the new
583
+ // surface is the source of truth when the caller opted in. Absent
584
+ // `permissionMode` falls through to the legacy plan-mode branch
585
+ // (existing semantics preserved for callsites that have not
586
+ // migrated yet).
587
+ let hooksBypassed = false;
588
+ if (permissionMode) {
589
+ const decision = permissionGate(name, argsRaw, {
590
+ permissionMode,
591
+ ...(permissionAlwaysCache ? { alwaysCache: permissionAlwaysCache } : {}),
592
+ });
593
+ if (decision.decision === 'deny') {
594
+ throw new PermissionDenied(name, getToolClass(name), permissionMode, decision.reason);
595
+ }
596
+ if (decision.decision === 'ask') {
597
+ if (!permissionAsk) {
598
+ // Non-interactive caller (CI / pipes / agent-as-tool) cannot
599
+ // surface a prompt. Collapse to deny so the loop receives a
600
+ // deterministic refusal instead of hanging.
601
+ throw new PermissionDenied(name, decision.toolClass, permissionMode, `Ask mode: no operator prompt available for ${name} (non-interactive caller)`);
602
+ }
603
+ const answer = await permissionAsk({
604
+ toolName: name,
605
+ toolClass: decision.toolClass,
606
+ question: decision.question,
607
+ options: decision.options,
608
+ });
609
+ const verdict = permissionAlwaysCache
610
+ ? applyAskAnswer(permissionAlwaysCache, name, answer)
611
+ : applyAskAnswer({ alwaysAllowed: new Set(), alwaysDenied: new Set() }, name, answer);
612
+ if (verdict.decision === 'deny') {
613
+ throw new PermissionDenied(name, decision.toolClass, permissionMode, verdict.reason);
614
+ }
615
+ // verdict.decision === 'allow' falls through to dispatch.
616
+ }
617
+ else {
618
+ // allow — honour the bypass flag for the hook layer below.
619
+ hooksBypassed = decision.hooksBypassed === true;
620
+ }
143
621
  }
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`);
622
+ else if (planMode) {
623
+ // Legacy plan-mode enforcement (kind === 'plan') stays in place
624
+ // for callers that have not opted into the canonical gate.
625
+ // MCP tools are uniformly refused in plan mode (see schema-side
626
+ // rationale in buildToolsSchema). Native tools split via
627
+ // READ_ONLY_TOOLS as before.
628
+ if (isMcpName || !READ_ONLY_TOOLS.has(name)) {
629
+ throw recordDenial(name, argsForTracking, `PLAN_MODE_REFUSED: ${name} is not allowed in plan mode`);
630
+ }
149
631
  }
150
632
  // α6.9: refuse cancelled-token tool dispatch BEFORE PreToolUse
151
633
  // hooks fire so a cancelled brief never reaches user-defined
@@ -153,13 +635,32 @@ export function buildExecutor(input) {
153
635
  // by `runEngineLoop` as a terminal-cancel signal so the loop
154
636
  // returns control to the caller rather than retrying the model.
155
637
  if (ctx.cancellation && ctx.cancellation.isAborted) {
156
- throw new Error(`OPERATOR_ABORTED: ${name} refused — operator cancelled the dispatch.`);
638
+ throw recordDenial(name, argsForTracking, `OPERATOR_ABORTED: ${name} refused — operator cancelled the dispatch.`);
639
+ }
640
+ // Leak L31 — per-cycle tool retry budget. Same tool + same canonical
641
+ // args = same bucket. Once the cap is hit we throw a typed sentinel
642
+ // so the model is forced out of a repair loop. We gate AFTER
643
+ // permission (denied calls do not burn budget) and BEFORE PreToolUse
644
+ // hooks (hook-blocked retries DO count — the model still issued the
645
+ // same call). The `recordAttempt` fires unconditionally so warn-only
646
+ // mode (PUGI_RETRY_BUDGET_DISABLED=1) still tracks the pattern for
647
+ // diagnostics.
648
+ const argHash = hashArgs(argsRaw);
649
+ const budgetDecision = retryBudget.shouldAllow(name, argHash);
650
+ retryBudget.recordAttempt(name, argHash);
651
+ if (!budgetDecision.allowed) {
652
+ throw new RetryBudgetExhausted(name, budgetDecision.cap, argHash);
157
653
  }
158
654
  // Fire PreToolUse hooks. The match grammar takes the tool name and
159
655
  // (when extractable) the target path. Each new tool dispatch starts a
160
656
  // fresh dedup batch so a hook fires once per dispatch, not once per
161
657
  // session.
162
- if (hooks && sessionId) {
658
+ //
659
+ // Leak L6 — bypass mode skips the entire hook layer (PreToolUse +
660
+ // PostToolUse + PostToolUseFailure). The gate's allow decision
661
+ // carries the `hooksBypassed` flag; we honour it here so the
662
+ // executor stays single-pass.
663
+ if (hooks && sessionId && !hooksBypassed) {
163
664
  hooks.resetBatch();
164
665
  const path = extractToolPath(name, argsRaw);
165
666
  const preCtx = {
@@ -179,29 +680,152 @@ export function buildExecutor(input) {
179
680
  const hook = matchingPreHooks[i];
180
681
  const result = preResults[i];
181
682
  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})`);
683
+ // α7 L11: record the PreToolUse hook denial so the model
684
+ // sees the pattern reminder on subsequent turns. Without
685
+ // this the model would re-issue the same refused call and
686
+ // burn a turn each time before noticing the loop.
687
+ throw recordDenial(name, argsForTracking, `HOOK_BLOCKED: PreToolUse hook (${hook.run.slice(0, 80)}) refused ${name} (exit=${result.exitCode})`);
183
688
  }
184
689
  }
185
690
  }
186
- const args = parseArgs(argsRaw);
691
+ // Leak L12 MVP: fire `hooks-mvp.json` PreToolUse hooks. Distinct
692
+ // config file from the legacy `hooks.json` system so operator
693
+ // configs do not collide. Same blocking semantics — a non-zero
694
+ // exit from a hook declared `blocking: true` refuses the dispatch
695
+ // with `HOOK_BLOCKED:` sentinel. Bypass mode skips this surface
696
+ // identically to the legacy hooks block above.
697
+ if (mvpHooksConfig && sessionId && !hooksBypassed && !mvpHooksConfig.isEmpty()) {
698
+ const { fireHooks } = await import('../hooks/index.js');
699
+ const outcome = await fireHooks({
700
+ config: mvpHooksConfig,
701
+ event: 'PreToolUse',
702
+ payload: {
703
+ event: 'PreToolUse',
704
+ sessionId,
705
+ toolName: name,
706
+ toolInputSummary: hashArgs(argsRaw),
707
+ },
708
+ toolName: name,
709
+ workspaceRoot: ctx.root,
710
+ });
711
+ if (outcome.anyBlocked) {
712
+ const blocking = outcome.results.find((r) => r.blocked);
713
+ const sentinel = blocking?.blockSentinel ??
714
+ `HOOK_BLOCKED: PreToolUse MVP-hook refused ${name}`;
715
+ throw recordDenial(name, argsForTracking, sentinel);
716
+ }
717
+ }
718
+ // β4 M1/M3: MCP dispatch deferred to the `dispatch` closure below so
719
+ // PostToolUse / PostToolUseFailure hooks observe MCP calls just like
720
+ // native calls. The dispatcher does its own argument parsing — MCP
721
+ // arg errors surface as model-visible `[MCP dispatch error] ...`
722
+ // strings, not throws.
723
+ const args = isMcpName ? {} : parseArgs(argsRaw);
187
724
  const dispatch = async () => {
725
+ if (isMcpName) {
726
+ return dispatchMcpTool({
727
+ name,
728
+ argumentsRaw: argsRaw,
729
+ registry: mcpRegistry,
730
+ prompt: mcpPrompt,
731
+ });
732
+ }
733
+ // β1 T1/T2/T3/T5/T6: async-dispatch the new tool surface.
734
+ // task_*, skill, ask_user_question, web_fetch all live behind
735
+ // an async or async-compatible boundary.
736
+ if (name === 'task_create' || name === 'task_get' || name === 'task_list' || name === 'task_update') {
737
+ return dispatchTaskTool(name, args, { workspaceRoot, sessionId });
738
+ }
739
+ if (name === 'todo_write') {
740
+ // Leak L16: batch TodoWrite. The dispatcher delegates the
741
+ // Zod validation + atomic persist to the tool module — any
742
+ // ZodError or `TODO_INVARIANT_VIOLATED` sentinel surfaces here
743
+ // as a thrown Error and lands on the catch arm below, which
744
+ // re-emits it through the PostToolUseFailure hook.
745
+ return dispatchTodoWrite({ workspaceRoot }, args);
746
+ }
747
+ if (name === 'ask_user_question') {
748
+ return dispatchAskUser(args, { interactive: Boolean(interactive), bridge: askUserBridge });
749
+ }
750
+ if (name === 'skill' || name === 'skills_list') {
751
+ return dispatchSkillTool(name, args, { workspaceRoot });
752
+ }
753
+ if (name === 'web_fetch') {
754
+ return dispatchWebFetch(args, { ctx, allowFetch: Boolean(allowFetch) });
755
+ }
756
+ if (name === 'web_search') {
757
+ return dispatchWebSearch(args, {
758
+ ctx,
759
+ allowSearch: Boolean(allowSearch),
760
+ sessionId,
761
+ });
762
+ }
763
+ if (name === 'multi_edit') {
764
+ return dispatchMultiEdit(args, ctx);
765
+ }
766
+ if (name === 'agent') {
767
+ // β2a r1 (Backend Architect P1, 2026-05-26): defense in depth.
768
+ // `WIRED_TOOLS` includes `agent`, so a plan-mode model that
769
+ // fabricates an `agent` tool call would otherwise be routed
770
+ // here. The plan-mode refusal at the top of the executor only
771
+ // fires for tools NOT in READ_ONLY_TOOLS; `agent` is
772
+ // intentionally absent from both sets, so we explicitly refuse
773
+ // it here. This pairs with `native-pugi.ts` hard-gating
774
+ // `agentDispatch` itself off in plan mode — without this
775
+ // defensive throw a future schema bug could let a plan-mode
776
+ // model spawn a write-capable child and break the read-only
777
+ // contract.
778
+ if (planMode) {
779
+ throw recordDenial(name, argsForTracking, 'PLAN_MODE_REFUSED: agent is not allowed in plan mode');
780
+ }
781
+ return dispatchAgent(args, agentDispatch);
782
+ }
188
783
  return dispatchTool(name, args, ctx);
189
784
  };
190
785
  try {
191
786
  const result = await dispatch();
192
- if (hooks && sessionId) {
787
+ // Leak L15 (2026-05-27): post-edit LSP diagnostics. After a
788
+ // successful `edit` / `write` / `multi_edit`, ask the cached
789
+ // language server for diagnostics on the touched file(s) and
790
+ // append the result to the tool envelope so the model can
791
+ // self-correct in the same turn. Silent skip when the language
792
+ // is unsupported, no server is installed, or the request times
793
+ // out — agent throughput beats diagnostic recall.
794
+ const augmented = await appendPostEditDiagnostics(name, args, ctx, result);
795
+ if (hooks && sessionId && !hooksBypassed) {
193
796
  const path = extractToolPath(name, argsRaw);
194
797
  await hooks.fire({
195
798
  sessionId,
196
799
  event: 'PostToolUse',
197
800
  tool: name,
198
801
  path,
199
- payload: { tool: name, arguments: argsRaw, ok: true, result: result.slice(0, 1024) },
802
+ payload: { tool: name, arguments: argsRaw, ok: true, result: augmented.slice(0, 1024) },
200
803
  });
201
804
  }
202
- return result;
805
+ return augmented;
203
806
  }
204
807
  catch (error) {
808
+ // Leak L6 — surface the PermissionDenied sentinel as a model-
809
+ // readable message instead of leaking the raw Error type. The
810
+ // string format is stable so the engine adapter / spec layer
811
+ // can pattern-match against it.
812
+ if (error instanceof PermissionDenied) {
813
+ // PostToolUseFailure fires for visibility unless bypass is on.
814
+ if (hooks && sessionId && !hooksBypassed) {
815
+ await hooks.fire({
816
+ sessionId,
817
+ event: 'PostToolUseFailure',
818
+ tool: name,
819
+ payload: {
820
+ tool: name,
821
+ arguments: argsRaw,
822
+ ok: false,
823
+ error: error.toModelMessage(),
824
+ },
825
+ });
826
+ }
827
+ throw new Error(error.toModelMessage());
828
+ }
205
829
  // α6.9: re-shape OperatorAbortedError throws from the
206
830
  // file-tools layer into the same `OPERATOR_ABORTED:` sentinel
207
831
  // the upstream cancellation gate uses so `runEngineLoop` sees
@@ -209,7 +833,7 @@ export function buildExecutor(input) {
209
833
  // the abort landed pre-dispatch or mid-tool (e.g. inside the
210
834
  // grep file-loop).
211
835
  if (error instanceof OperatorAbortedError) {
212
- if (hooks && sessionId) {
836
+ if (hooks && sessionId && !hooksBypassed) {
213
837
  const path = extractToolPath(name, argsRaw);
214
838
  await hooks.fire({
215
839
  sessionId,
@@ -224,9 +848,35 @@ export function buildExecutor(input) {
224
848
  },
225
849
  });
226
850
  }
227
- throw new Error(`OPERATOR_ABORTED: ${name} aborted mid-execution.`);
851
+ throw recordDenial(name, argsForTracking, `OPERATOR_ABORTED: ${name} aborted mid-execution.`);
228
852
  }
229
- if (hooks && sessionId) {
853
+ // Leak L1 (2026-05-27): re-shape StaleReadError into a
854
+ // deterministic STALE_READ:<reason> sentinel so the model's
855
+ // retry policy can pattern-match on a stable prefix instead of
856
+ // free-form prose. The model is expected to re-read the file and
857
+ // retry the edit — the message points it at exactly that recovery
858
+ // path. PostToolUseFailure hooks observe the typed error so an
859
+ // operator can build a "warn me when stale edits keep happening"
860
+ // hook (likely a concurrency / multi-agent indicator).
861
+ if (error instanceof StaleReadError) {
862
+ if (hooks && sessionId && !hooksBypassed) {
863
+ const path = extractToolPath(name, argsRaw);
864
+ await hooks.fire({
865
+ sessionId,
866
+ event: 'PostToolUseFailure',
867
+ tool: name,
868
+ path,
869
+ payload: {
870
+ tool: name,
871
+ arguments: argsRaw,
872
+ ok: false,
873
+ error: `STALE_READ: ${error.reason} on ${error.path}`,
874
+ },
875
+ });
876
+ }
877
+ 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}.`);
878
+ }
879
+ if (hooks && sessionId && !hooksBypassed) {
230
880
  const path = extractToolPath(name, argsRaw);
231
881
  await hooks.fire({
232
882
  sessionId,
@@ -342,4 +992,293 @@ function dispatchTool(name, args, ctx) {
342
992
  throw new Error(`unhandled tool: ${name}`);
343
993
  }
344
994
  }
995
+ /* ----------------------------- β1 dispatchers ----------------------------- */
996
+ function dispatchTaskTool(name, args, opts) {
997
+ if (!opts.sessionId) {
998
+ throw new Error(`${name}: no sessionId in scope — task ledger requires a session`);
999
+ }
1000
+ const tctx = { workspaceRoot: opts.workspaceRoot, sessionId: opts.sessionId };
1001
+ switch (name) {
1002
+ case 'task_create': {
1003
+ const title = requireString(args, 'title');
1004
+ const status = optionalString(args, 'status');
1005
+ const notes = optionalString(args, 'notes');
1006
+ const record = taskCreate(tctx, {
1007
+ title,
1008
+ ...(status !== undefined ? { status: status } : {}),
1009
+ ...(notes !== undefined ? { notes } : {}),
1010
+ });
1011
+ return JSON.stringify(record);
1012
+ }
1013
+ case 'task_get': {
1014
+ const id = requireString(args, 'id');
1015
+ const record = taskGet(tctx, id);
1016
+ return record ? JSON.stringify(record) : 'null';
1017
+ }
1018
+ case 'task_list': {
1019
+ const list = taskList(tctx);
1020
+ return JSON.stringify(list);
1021
+ }
1022
+ case 'task_update': {
1023
+ const id = requireString(args, 'id');
1024
+ const title = optionalString(args, 'title');
1025
+ const status = optionalString(args, 'status');
1026
+ const notes = optionalString(args, 'notes');
1027
+ const record = taskUpdate(tctx, {
1028
+ id,
1029
+ ...(title !== undefined ? { title } : {}),
1030
+ ...(status !== undefined ? { status: status } : {}),
1031
+ ...(notes !== undefined ? { notes } : {}),
1032
+ });
1033
+ return JSON.stringify(record);
1034
+ }
1035
+ }
1036
+ }
1037
+ async function dispatchAskUser(args, opts) {
1038
+ const rawOptions = args['options'];
1039
+ if (!Array.isArray(rawOptions)) {
1040
+ throw new Error('ask_user_question: options must be an array');
1041
+ }
1042
+ // Leak L5 (2026-05-27): detect structured vs legacy form. Structured
1043
+ // entries are objects with {label, description}; legacy entries are
1044
+ // plain strings. The structured path validates via Zod and emits the
1045
+ // [ask_user_question:answered|cancelled|timeout] envelope. The legacy
1046
+ // path stays for back-compat with the existing β1 T2 tests + the
1047
+ // <pugi-ask> prompt envelope (which still feeds string options).
1048
+ const looksStructured = rawOptions.length > 0
1049
+ && typeof rawOptions[0] === 'object'
1050
+ && rawOptions[0] !== null
1051
+ && !Array.isArray(rawOptions[0]);
1052
+ if (looksStructured) {
1053
+ const result = await dispatchAskUserQuestion({ interactive: opts.interactive, ...(opts.bridge ? { bridge: opts.bridge } : {}) }, args);
1054
+ return result.envelope;
1055
+ }
1056
+ // Legacy string-array form.
1057
+ const question = requireString(args, 'question');
1058
+ const options = rawOptions.map((o, i) => {
1059
+ if (typeof o !== 'string') {
1060
+ throw new Error(`ask_user_question: options[${i}] must be a string`);
1061
+ }
1062
+ return o;
1063
+ });
1064
+ const multiSelect = args['multiSelect'] === true;
1065
+ const result = await askUser({ interactive: opts.interactive, ...(opts.bridge ? { bridge: opts.bridge } : {}) }, { question, options, multiSelect });
1066
+ return result.envelope;
1067
+ }
1068
+ async function dispatchSkillTool(name, args, opts) {
1069
+ if (name === 'skills_list') {
1070
+ const scopeArg = optionalString(args, 'scope');
1071
+ const scope = scopeArg === 'global' || scopeArg === 'workspace' ? scopeArg : 'all';
1072
+ const list = skillList({ workspaceRoot: opts.workspaceRoot }, { scope });
1073
+ return JSON.stringify(list);
1074
+ }
1075
+ // name === 'skill' (invoke).
1076
+ // β1a r1 (2026-05-26): `skillInvoke` is now async — it re-verifies
1077
+ // the trust manifest sha256 against the on-disk body on every call.
1078
+ // Bubble up `await` so a post-install tamper surfaces as a tool
1079
+ // error the model sees, not a swallowed Promise<SkillInvokeResult>.
1080
+ const skName = requireString(args, 'name');
1081
+ const result = await skillInvoke({ workspaceRoot: opts.workspaceRoot }, { name: skName });
1082
+ return JSON.stringify(result);
1083
+ }
1084
+ async function dispatchWebFetch(args, opts) {
1085
+ const url = requireString(args, 'url');
1086
+ const result = await webFetchTool({ url }, {
1087
+ settings: opts.ctx.settings,
1088
+ allowFetch: opts.allowFetch,
1089
+ });
1090
+ return JSON.stringify(result);
1091
+ }
1092
+ async function dispatchWebSearch(args, opts) {
1093
+ const query = requireString(args, 'query');
1094
+ // `count` is optional integer 1..10. Validate here so the tool layer
1095
+ // gets a clean value (the tool clamps internally too — defense in
1096
+ // depth, since the model can pass anything).
1097
+ let count;
1098
+ if (args['count'] !== undefined && args['count'] !== null) {
1099
+ const n = args['count'];
1100
+ if (typeof n !== 'number' || !Number.isInteger(n)) {
1101
+ throw new Error('web_search: count must be an integer');
1102
+ }
1103
+ count = n;
1104
+ }
1105
+ const result = await webSearchTool({ query, ...(count !== undefined ? { count } : {}) }, {
1106
+ settings: opts.ctx.settings,
1107
+ allowSearch: opts.allowSearch,
1108
+ sessionId: opts.sessionId,
1109
+ });
1110
+ return JSON.stringify(result);
1111
+ }
1112
+ /**
1113
+ * β2 S3 dispatch — wire the model-emitted `agent` tool call to the
1114
+ * real subagent spawn primitive. When the executor was built without
1115
+ * `agentDispatch` (e.g. a child loop, or a parent that explicitly
1116
+ * disabled subagent spawn), the call is refused with a structured
1117
+ * envelope so the model can adapt instead of crashing the parent loop.
1118
+ */
1119
+ async function dispatchAgent(args, opts) {
1120
+ if (!opts) {
1121
+ // No dispatch context — return a structured refusal envelope.
1122
+ // This matches the agent-tool.ts no-engine-client path and lets
1123
+ // the model decide whether to retry inline or abandon the
1124
+ // delegation. Throwing here would terminate the parent on a tool
1125
+ // error frame which is the wrong UX when the issue is config.
1126
+ return JSON.stringify({
1127
+ ok: false,
1128
+ status: 'failed',
1129
+ summary: 'agent tool refused: dispatch not wired in this engine adapter. '
1130
+ + 'Re-run from a parent loop with agentDispatch configured.',
1131
+ });
1132
+ }
1133
+ const parsed = parseAgentArgs(args);
1134
+ const result = await agentTool(parsed, {
1135
+ session: opts.parentSession,
1136
+ engineClient: opts.engineClient,
1137
+ ...(opts.parentBudgetRemaining
1138
+ ? { parentBudgetRemaining: opts.parentBudgetRemaining }
1139
+ : {}),
1140
+ });
1141
+ return JSON.stringify(result);
1142
+ }
1143
+ function parseAgentArgs(args) {
1144
+ // Surface a clean error message to the model when the args don't
1145
+ // match the schema. agentTool itself also validates via Zod; this
1146
+ // pre-parse layer keeps the error stack short.
1147
+ const role = requireString(args, 'role');
1148
+ const brief = requireString(args, 'brief');
1149
+ const isolationRaw = optionalString(args, 'isolation');
1150
+ const out = {
1151
+ role: role,
1152
+ brief,
1153
+ ...(isolationRaw ? { isolation: isolationRaw } : {}),
1154
+ };
1155
+ return out;
1156
+ }
1157
+ function optionalString(obj, key) {
1158
+ const v = obj[key];
1159
+ if (v === undefined || v === null)
1160
+ return undefined;
1161
+ if (typeof v !== 'string') {
1162
+ throw new Error(`tool argument "${key}" must be a string when present`);
1163
+ }
1164
+ return v;
1165
+ }
1166
+ /**
1167
+ * β7 L5+T11: dispatch the model-emitted `multi_edit` tool call. The
1168
+ * tool returns a structured result envelope; we serialize it to JSON
1169
+ * for the engine loop. A refused dispatch (security, no_match,
1170
+ * ambiguous_match, etc.) surfaces as `ok: false` in the envelope —
1171
+ * the model can re-strategise rather than crashing the loop.
1172
+ */
1173
+ function dispatchMultiEdit(args, ctx) {
1174
+ const raw = args['edits'];
1175
+ if (!Array.isArray(raw)) {
1176
+ throw new Error('multi_edit: edits must be an array');
1177
+ }
1178
+ const edits = raw.map((item, i) => {
1179
+ if (!item || typeof item !== 'object') {
1180
+ throw new Error(`multi_edit: edits[${i}] must be an object`);
1181
+ }
1182
+ const obj = item;
1183
+ const file = obj['file'];
1184
+ const oldString = obj['oldString'];
1185
+ const newString = obj['newString'];
1186
+ if (typeof file !== 'string') {
1187
+ throw new Error(`multi_edit: edits[${i}].file must be a string`);
1188
+ }
1189
+ if (typeof oldString !== 'string') {
1190
+ throw new Error(`multi_edit: edits[${i}].oldString must be a string`);
1191
+ }
1192
+ if (typeof newString !== 'string') {
1193
+ throw new Error(`multi_edit: edits[${i}].newString must be a string`);
1194
+ }
1195
+ return { file, oldString, newString };
1196
+ });
1197
+ const result = multiEdit(ctx, edits);
1198
+ return JSON.stringify(result);
1199
+ }
1200
+ /* ---------------------------- Leak L15 hook ---------------------------- */
1201
+ /**
1202
+ * Tool names that mutate workspace files. After a successful dispatch
1203
+ * of any of these, the L15 post-edit diagnostics hook fires. The set
1204
+ * is intentionally tight — `task_*` / `todo_write` write to ledger
1205
+ * files (not workspace source) so they stay out, and `bash` is too
1206
+ * coarse (a `bash` call can write any path, and we'd need to parse
1207
+ * the command to know which — out of scope for L15).
1208
+ */
1209
+ const POST_EDIT_TOOLS = new Set(['edit', 'write', 'multi_edit']);
1210
+ /**
1211
+ * Append LSP diagnostics to the tool envelope after a successful
1212
+ * edit / write / multi_edit. Silent skip is the default — missing
1213
+ * binary, unsupported language, request timeout, and "no diagnostics"
1214
+ * all leave the envelope unchanged.
1215
+ *
1216
+ * Opt-in via `.pugi/settings.json::lsp.postEditDiagnostics = true`
1217
+ * OR `PUGI_LSP_POST_EDIT=1`. Off by default until dogfood validates
1218
+ * the cold-start cost vs the model-loop benefit (Leak L15).
1219
+ */
1220
+ async function appendPostEditDiagnostics(name, args, ctx, result) {
1221
+ if (!POST_EDIT_TOOLS.has(name))
1222
+ return result;
1223
+ if (!isPostEditEnabled(ctx))
1224
+ return result;
1225
+ const paths = extractEditedPaths(name, args);
1226
+ if (paths.length === 0)
1227
+ return result;
1228
+ const tails = [];
1229
+ for (const filePath of paths) {
1230
+ const opts = {
1231
+ cwd: ctx.root,
1232
+ ...(ctx.settings.lsp ? { lspSettings: ctx.settings.lsp } : {}),
1233
+ };
1234
+ try {
1235
+ const diag = await runPostEditDiagnostics(filePath, opts);
1236
+ if (!diag.skip) {
1237
+ tails.push(diag.tail);
1238
+ }
1239
+ }
1240
+ catch {
1241
+ // Belt-and-suspenders: any unexpected throw from the hook is
1242
+ // swallowed. The model never blocks on LSP.
1243
+ }
1244
+ }
1245
+ if (tails.length === 0)
1246
+ return result;
1247
+ return `${result}\n${tails.join('\n')}`;
1248
+ }
1249
+ function isPostEditEnabled(ctx) {
1250
+ const envFlag = process.env.PUGI_LSP_POST_EDIT;
1251
+ if (envFlag === '1' || envFlag === 'true')
1252
+ return true;
1253
+ if (envFlag === '0' || envFlag === 'false')
1254
+ return false;
1255
+ return ctx.settings.lsp?.postEditDiagnostics === true;
1256
+ }
1257
+ /**
1258
+ * Pull the workspace-relative file path(s) the tool just touched.
1259
+ * Each branch mirrors the args shape its `dispatch*` handler reads;
1260
+ * a deformed args object yields an empty list so the hook silently
1261
+ * skips instead of throwing inside the augmentation layer.
1262
+ */
1263
+ function extractEditedPaths(name, args) {
1264
+ if (name === 'edit' || name === 'write') {
1265
+ const path = args['path'];
1266
+ return typeof path === 'string' && path.length > 0 ? [path] : [];
1267
+ }
1268
+ if (name === 'multi_edit') {
1269
+ const edits = args['edits'];
1270
+ if (!Array.isArray(edits))
1271
+ return [];
1272
+ const seen = new Set();
1273
+ for (const entry of edits) {
1274
+ if (!entry || typeof entry !== 'object')
1275
+ continue;
1276
+ const file = entry['file'];
1277
+ if (typeof file === 'string' && file.length > 0)
1278
+ seen.add(file);
1279
+ }
1280
+ return Array.from(seen);
1281
+ }
1282
+ return [];
1283
+ }
345
1284
  //# sourceMappingURL=tool-bridge.js.map