dart-decimate 0.0.1

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 (188) hide show
  1. package/Cargo.lock +572 -0
  2. package/Cargo.toml +41 -0
  3. package/LICENSE +21 -0
  4. package/README.md +617 -0
  5. package/assets/dart-decimate-banner.png +0 -0
  6. package/npm/bin/dart-decimate-mcp.js +48 -0
  7. package/npm/bin/dart-decimate.js +48 -0
  8. package/npm/scripts/postinstall.js +46 -0
  9. package/npm/scripts/test-npx-local.js +54 -0
  10. package/npm/scripts/test-npx-mcp-local.js +56 -0
  11. package/package.json +45 -0
  12. package/src/baseline.rs +643 -0
  13. package/src/bin/dart-decimate-mcp.rs +11 -0
  14. package/src/boundaries/tests.rs +60 -0
  15. package/src/boundaries.rs +317 -0
  16. package/src/changed_scope.rs +117 -0
  17. package/src/ci_template.rs +399 -0
  18. package/src/cli/analyze.rs +462 -0
  19. package/src/cli/analyzer_options.rs +82 -0
  20. package/src/cli/audit_run.rs +327 -0
  21. package/src/cli/boundary_args.rs +44 -0
  22. package/src/cli/ci_template_run.rs +196 -0
  23. package/src/cli/command_name.rs +20 -0
  24. package/src/cli/common_args.rs +167 -0
  25. package/src/cli/config_run.rs +78 -0
  26. package/src/cli/coverage_run.rs +393 -0
  27. package/src/cli/decision_surface_run.rs +99 -0
  28. package/src/cli/default_command.rs +69 -0
  29. package/src/cli/dupes_args.rs +150 -0
  30. package/src/cli/entry_points.rs +121 -0
  31. package/src/cli/error.rs +149 -0
  32. package/src/cli/error_output.rs +68 -0
  33. package/src/cli/explain_run.rs +72 -0
  34. package/src/cli/fix_run.rs +162 -0
  35. package/src/cli/flags_args.rs +23 -0
  36. package/src/cli/health_args.rs +200 -0
  37. package/src/cli/hooks_run.rs +191 -0
  38. package/src/cli/impact_run.rs +95 -0
  39. package/src/cli/init_run.rs +49 -0
  40. package/src/cli/inspect_args.rs +20 -0
  41. package/src/cli/inspect_run.rs +66 -0
  42. package/src/cli/issue_filter_args.rs +240 -0
  43. package/src/cli/list_run.rs +311 -0
  44. package/src/cli/mode_args.rs +72 -0
  45. package/src/cli/output_format.rs +62 -0
  46. package/src/cli/regression_args.rs +156 -0
  47. package/src/cli/request_args.rs +175 -0
  48. package/src/cli/schema_commands.rs +72 -0
  49. package/src/cli/scope_args.rs +174 -0
  50. package/src/cli/security_args.rs +175 -0
  51. package/src/cli/security_gate_run.rs +66 -0
  52. package/src/cli/security_summary_run.rs +43 -0
  53. package/src/cli/summary_args.rs +12 -0
  54. package/src/cli/tests.rs +516 -0
  55. package/src/cli/trace_args.rs +67 -0
  56. package/src/cli/trace_run.rs +131 -0
  57. package/src/cli/trace_tests.rs +235 -0
  58. package/src/cli/unsupported_run.rs +116 -0
  59. package/src/cli/watch_run.rs +153 -0
  60. package/src/cli.rs +603 -0
  61. package/src/config/boundary_config.rs +235 -0
  62. package/src/config/cache.rs +25 -0
  63. package/src/config/dependencies.rs +114 -0
  64. package/src/config/health.rs +237 -0
  65. package/src/config/jsonc.rs +66 -0
  66. package/src/config/policy.rs +91 -0
  67. package/src/config/rule_aliases.rs +487 -0
  68. package/src/config/rules.rs +339 -0
  69. package/src/config.rs +635 -0
  70. package/src/coverage.rs +469 -0
  71. package/src/dart_parser.rs +673 -0
  72. package/src/decision_surface.rs +405 -0
  73. package/src/dependencies/analyze.rs +218 -0
  74. package/src/dependencies/codegen.rs +118 -0
  75. package/src/dependencies/discovery.rs +60 -0
  76. package/src/dependencies/overrides.rs +76 -0
  77. package/src/dependencies/private_src_imports.rs +32 -0
  78. package/src/dependencies/pubspec_document.rs +86 -0
  79. package/src/dependencies/pubspec_entry.rs +96 -0
  80. package/src/dependencies/tests.rs +544 -0
  81. package/src/dependencies/usage.rs +33 -0
  82. package/src/dependencies.rs +553 -0
  83. package/src/dependency_scripts.rs +91 -0
  84. package/src/dupes/lex.rs +236 -0
  85. package/src/dupes/tests.rs +119 -0
  86. package/src/dupes.rs +625 -0
  87. package/src/explain.rs +692 -0
  88. package/src/extract/directives.rs +252 -0
  89. package/src/extract/error_tests.rs +25 -0
  90. package/src/extract/members.rs +210 -0
  91. package/src/extract/primary_constructors.rs +421 -0
  92. package/src/extract/references.rs +151 -0
  93. package/src/extract/routes.rs +691 -0
  94. package/src/extract/signatures.rs +266 -0
  95. package/src/extract/string_tests.rs +18 -0
  96. package/src/extract/strings.rs +107 -0
  97. package/src/extract/tests.rs +697 -0
  98. package/src/extract.rs +680 -0
  99. package/src/feature_flags/tests.rs +76 -0
  100. package/src/feature_flags.rs +453 -0
  101. package/src/finding_identity.rs +60 -0
  102. package/src/fix.rs +551 -0
  103. package/src/generated.rs +53 -0
  104. package/src/graph/augment_tests.rs +212 -0
  105. package/src/graph/conditionals.rs +74 -0
  106. package/src/graph/package_config_tests.rs +100 -0
  107. package/src/graph/parts.rs +248 -0
  108. package/src/graph/pubspec_tests.rs +119 -0
  109. package/src/graph/tests.rs +837 -0
  110. package/src/graph/uri_tests.rs +102 -0
  111. package/src/graph.rs +644 -0
  112. package/src/health/coverage.rs +309 -0
  113. package/src/health/ownership.rs +175 -0
  114. package/src/health/runtime_coverage.rs +616 -0
  115. package/src/health/runtime_intelligence.rs +511 -0
  116. package/src/health/scores.rs +296 -0
  117. package/src/health/tests.rs +240 -0
  118. package/src/health/threshold_types.rs +163 -0
  119. package/src/health/thresholds.rs +229 -0
  120. package/src/health/types.rs +636 -0
  121. package/src/health.rs +597 -0
  122. package/src/hooks/agent_settings.rs +175 -0
  123. package/src/hooks/templates.rs +51 -0
  124. package/src/hooks.rs +569 -0
  125. package/src/impact.rs +287 -0
  126. package/src/init.rs +237 -0
  127. package/src/inspect.rs +142 -0
  128. package/src/intelligence/tests.rs +232 -0
  129. package/src/intelligence.rs +305 -0
  130. package/src/lib.rs +198 -0
  131. package/src/main.rs +5 -0
  132. package/src/manifest/mcp.rs +565 -0
  133. package/src/manifest.rs +552 -0
  134. package/src/mcp/cli_args/value_args.rs +175 -0
  135. package/src/mcp/cli_args.rs +658 -0
  136. package/src/mcp/cli_args_tests.rs +522 -0
  137. package/src/mcp/code_execute.rs +671 -0
  138. package/src/mcp/tools.rs +660 -0
  139. package/src/mcp.rs +325 -0
  140. package/src/output/audit_risk.rs +135 -0
  141. package/src/output/dependency_findings.rs +327 -0
  142. package/src/output/duplication_findings.rs +114 -0
  143. package/src/output/feature_flag_findings.rs +122 -0
  144. package/src/output/format.rs +31 -0
  145. package/src/output/graph_findings.rs +461 -0
  146. package/src/output/health_findings.rs +612 -0
  147. package/src/output/human.rs +27 -0
  148. package/src/output/next_steps.rs +92 -0
  149. package/src/output/route_findings.rs +76 -0
  150. package/src/output/runtime_coverage.rs +515 -0
  151. package/src/output/scope.rs +183 -0
  152. package/src/output/security_findings.rs +390 -0
  153. package/src/output/security_sarif.rs +150 -0
  154. package/src/output/suppressions.rs +323 -0
  155. package/src/output/symbol_findings.rs +257 -0
  156. package/src/output/tests.rs +114 -0
  157. package/src/output/types.rs +604 -0
  158. package/src/output/widget_findings.rs +213 -0
  159. package/src/output.rs +682 -0
  160. package/src/package_map.rs +495 -0
  161. package/src/policy/packs.rs +232 -0
  162. package/src/policy/tests.rs +134 -0
  163. package/src/policy.rs +640 -0
  164. package/src/project_list.rs +376 -0
  165. package/src/report_schema/inventory.rs +418 -0
  166. package/src/report_schema.rs +488 -0
  167. package/src/routes.rs +354 -0
  168. package/src/scan/tests.rs +250 -0
  169. package/src/scan.rs +275 -0
  170. package/src/security/detect.rs +639 -0
  171. package/src/security/tests.rs +178 -0
  172. package/src/security.rs +373 -0
  173. package/src/security_gate.rs +555 -0
  174. package/src/symbols/path_filters.rs +27 -0
  175. package/src/symbols/private_type_leaks.rs +125 -0
  176. package/src/symbols/riverpod.rs +113 -0
  177. package/src/symbols/tests.rs +692 -0
  178. package/src/symbols.rs +693 -0
  179. package/src/trace/tests.rs +225 -0
  180. package/src/trace.rs +690 -0
  181. package/src/unsupported.rs +47 -0
  182. package/src/widgets/lifecycle.rs +484 -0
  183. package/src/widgets/params.rs +236 -0
  184. package/src/widgets/tests.rs +430 -0
  185. package/src/widgets/top_level.rs +110 -0
  186. package/src/widgets/unrendered.rs +374 -0
  187. package/src/widgets.rs +590 -0
  188. package/src/workspace_scope.rs +358 -0
@@ -0,0 +1,671 @@
1
+ use std::collections::{BTreeMap, BTreeSet};
2
+
3
+ use serde::Deserialize;
4
+ use serde_json::{Map, Value, json};
5
+
6
+ use super::{CliToolOutput, run_cli_json, tool_result};
7
+ use crate::mcp::cli_args::cli_args_for_tool;
8
+
9
+ pub(crate) const CODE_EXECUTE_SCHEMA_VERSION: &str = "dart-decimate.mcp.code_execute.v1";
10
+
11
+ const DEFAULT_MAX_STEPS: usize = 8;
12
+ const HARD_MAX_STEPS: usize = 16;
13
+ const DEFAULT_MAX_TOOL_CALLS: usize = 4;
14
+ const HARD_MAX_TOOL_CALLS: usize = 8;
15
+ const DEFAULT_MAX_RESULT_BYTES: usize = 256 * 1024;
16
+ const HARD_MAX_RESULT_BYTES: usize = 4_000_000;
17
+ const MAX_SELECTION_ITEMS: usize = 100;
18
+
19
+ pub(super) fn execute(arguments: &Map<String, Value>) -> CliToolOutput {
20
+ match execute_inner(arguments) {
21
+ Ok(value) => CliToolOutput::json(0, value, false),
22
+ Err(message) => CliToolOutput::json(2, error_output(&message), true),
23
+ }
24
+ }
25
+
26
+ fn execute_inner(arguments: &Map<String, Value>) -> Result<Value, String> {
27
+ let request = CodeExecuteRequest::from_arguments(arguments)?;
28
+ let limits = Limits::from_request(&request)?;
29
+ let mut executor = Executor::new(limits);
30
+ executor.execute(&request.program)
31
+ }
32
+
33
+ fn error_output(message: &str) -> Value {
34
+ json!({
35
+ "schema_version": CODE_EXECUTE_SCHEMA_VERSION,
36
+ "ok": false,
37
+ "error": message,
38
+ "result": Value::Null,
39
+ "calls": [],
40
+ })
41
+ }
42
+
43
+ #[derive(Debug)]
44
+ struct CodeExecuteRequest {
45
+ program: Program,
46
+ max_steps: Option<usize>,
47
+ max_tool_calls: Option<usize>,
48
+ max_result_bytes: Option<usize>,
49
+ }
50
+
51
+ impl CodeExecuteRequest {
52
+ fn from_arguments(arguments: &Map<String, Value>) -> Result<Self, String> {
53
+ reject_unknown(
54
+ arguments,
55
+ &[
56
+ "code",
57
+ "program",
58
+ "max_steps",
59
+ "max_tool_calls",
60
+ "max_result_bytes",
61
+ ],
62
+ )?;
63
+ let program_value = match (arguments.get("program"), arguments.get("code")) {
64
+ (Some(_), Some(_)) => {
65
+ return Err("code_execute accepts either code or program, not both".to_owned());
66
+ }
67
+ (Some(program), None) | (None, Some(program)) => program.clone(),
68
+ (None, None) => return Err("code_execute requires code or program".to_owned()),
69
+ };
70
+ let program = serde_json::from_value::<Program>(program_value)
71
+ .map_err(|error| format!("invalid code_execute program: {error}"))?;
72
+ Ok(Self {
73
+ program,
74
+ max_steps: optional_usize(arguments, "max_steps")?,
75
+ max_tool_calls: optional_usize(arguments, "max_tool_calls")?,
76
+ max_result_bytes: optional_usize(arguments, "max_result_bytes")?,
77
+ })
78
+ }
79
+ }
80
+
81
+ #[derive(Debug, Clone, Deserialize)]
82
+ struct Program {
83
+ steps: Vec<Step>,
84
+ #[serde(rename = "return")]
85
+ return_value: ReturnSpec,
86
+ }
87
+
88
+ #[derive(Debug, Clone, Deserialize)]
89
+ struct Step {
90
+ id: String,
91
+ #[serde(default)]
92
+ call: Option<String>,
93
+ #[serde(default)]
94
+ arguments: Value,
95
+ #[serde(default)]
96
+ select: Option<SelectSpec>,
97
+ }
98
+
99
+ #[derive(Debug, Clone, Deserialize)]
100
+ struct SelectSpec {
101
+ from: String,
102
+ #[serde(default)]
103
+ pointer: String,
104
+ #[serde(default)]
105
+ fields: Vec<String>,
106
+ #[serde(default)]
107
+ limit: Option<usize>,
108
+ #[serde(default, rename = "where")]
109
+ where_clause: Option<WhereSpec>,
110
+ }
111
+
112
+ #[derive(Debug, Clone, Deserialize)]
113
+ struct WhereSpec {
114
+ equals: BTreeMap<String, Value>,
115
+ }
116
+
117
+ #[derive(Debug, Clone, Deserialize)]
118
+ #[serde(untagged)]
119
+ enum ReturnSpec {
120
+ Ref {
121
+ from: String,
122
+ pointer: Option<String>,
123
+ },
124
+ Value(Value),
125
+ }
126
+
127
+ #[derive(Debug, Clone, Deserialize)]
128
+ struct RefValue {
129
+ #[serde(rename = "$ref")]
130
+ reference: RefTarget,
131
+ }
132
+
133
+ #[derive(Debug, Clone, Deserialize)]
134
+ struct RefTarget {
135
+ from: String,
136
+ #[serde(default)]
137
+ pointer: String,
138
+ }
139
+
140
+ #[derive(Debug, Clone, Copy)]
141
+ struct Limits {
142
+ steps: usize,
143
+ tool_calls: usize,
144
+ result_bytes: usize,
145
+ }
146
+
147
+ impl Limits {
148
+ fn from_request(request: &CodeExecuteRequest) -> Result<Self, String> {
149
+ let max_steps = capped_limit(
150
+ request.max_steps.unwrap_or(DEFAULT_MAX_STEPS),
151
+ HARD_MAX_STEPS,
152
+ "max_steps",
153
+ )?;
154
+ let max_tool_calls = capped_limit(
155
+ request.max_tool_calls.unwrap_or(DEFAULT_MAX_TOOL_CALLS),
156
+ HARD_MAX_TOOL_CALLS,
157
+ "max_tool_calls",
158
+ )?;
159
+ let max_result_bytes = capped_limit(
160
+ request.max_result_bytes.unwrap_or(DEFAULT_MAX_RESULT_BYTES),
161
+ HARD_MAX_RESULT_BYTES,
162
+ "max_result_bytes",
163
+ )?;
164
+ Ok(Self {
165
+ steps: max_steps,
166
+ tool_calls: max_tool_calls,
167
+ result_bytes: max_result_bytes,
168
+ })
169
+ }
170
+ }
171
+
172
+ fn capped_limit(value: usize, hard_max: usize, name: &str) -> Result<usize, String> {
173
+ if value == 0 {
174
+ return Err(format!("{name} must be greater than zero"));
175
+ }
176
+ if value > hard_max {
177
+ return Err(format!("{name} exceeds hard limit {hard_max}"));
178
+ }
179
+ Ok(value)
180
+ }
181
+
182
+ struct Executor {
183
+ limits: Limits,
184
+ outputs: BTreeMap<String, Value>,
185
+ calls: Vec<CallRecord>,
186
+ total_result_bytes: usize,
187
+ }
188
+
189
+ impl Executor {
190
+ fn new(limits: Limits) -> Self {
191
+ Self {
192
+ limits,
193
+ outputs: BTreeMap::new(),
194
+ calls: Vec::new(),
195
+ total_result_bytes: 0,
196
+ }
197
+ }
198
+
199
+ fn execute(&mut self, program: &Program) -> Result<Value, String> {
200
+ self.validate(program)?;
201
+ for step in &program.steps {
202
+ let value = self.execute_step(step)?;
203
+ self.outputs.insert(step.id.clone(), value);
204
+ }
205
+ let result = self.return_value(&program.return_value)?;
206
+ self.track_result_bytes(&result)?;
207
+ Ok(json!({
208
+ "schema_version": CODE_EXECUTE_SCHEMA_VERSION,
209
+ "ok": true,
210
+ "result": result,
211
+ "calls": self.calls,
212
+ "limits": {
213
+ "max_steps": self.limits.steps,
214
+ "max_tool_calls": self.limits.tool_calls,
215
+ "max_result_bytes": self.limits.result_bytes,
216
+ "max_selection_items": MAX_SELECTION_ITEMS
217
+ }
218
+ }))
219
+ }
220
+
221
+ fn validate(&self, program: &Program) -> Result<(), String> {
222
+ if program.steps.is_empty() {
223
+ return Err("code_execute program requires at least one step".to_owned());
224
+ }
225
+ if program.steps.len() > self.limits.steps {
226
+ return Err(format!(
227
+ "code_execute program has {} steps but max_steps is {}",
228
+ program.steps.len(),
229
+ self.limits.steps
230
+ ));
231
+ }
232
+ let mut ids = BTreeSet::<&str>::new();
233
+ for step in &program.steps {
234
+ validate_step_id(&step.id)?;
235
+ if !ids.insert(&step.id) {
236
+ return Err(format!("duplicate code_execute step id {}", step.id));
237
+ }
238
+ match (&step.call, &step.select) {
239
+ (Some(_), None) | (None, Some(_)) => {}
240
+ (Some(_), Some(_)) => {
241
+ return Err(format!(
242
+ "step {} cannot contain both call and select",
243
+ step.id
244
+ ));
245
+ }
246
+ (None, None) => {
247
+ return Err(format!("step {} requires call or select", step.id));
248
+ }
249
+ }
250
+ }
251
+ Ok(())
252
+ }
253
+
254
+ fn execute_step(&mut self, step: &Step) -> Result<Value, String> {
255
+ if let Some(tool) = &step.call {
256
+ return self.call_tool(tool, &step.arguments);
257
+ }
258
+ let select = step
259
+ .select
260
+ .as_ref()
261
+ .ok_or_else(|| format!("step {} requires call or select", step.id))?;
262
+ self.select(select)
263
+ }
264
+
265
+ fn call_tool(&mut self, tool: &str, arguments: &Value) -> Result<Value, String> {
266
+ if self.calls.len() >= self.limits.tool_calls {
267
+ return Err(format!(
268
+ "code_execute child tool call limit exceeded ({})",
269
+ self.limits.tool_calls
270
+ ));
271
+ }
272
+ if !READ_ONLY_TOOLS.contains(&tool) {
273
+ return Err(format!("code_execute cannot call tool {tool}"));
274
+ }
275
+ let resolved = self.resolve_refs(arguments)?;
276
+ let args = resolved
277
+ .as_object()
278
+ .ok_or_else(|| format!("arguments for {tool} must resolve to an object"))?;
279
+ let cli_args = cli_args_for_tool(tool, args)?;
280
+ let output = run_cli_json(cli_args);
281
+ let result = tool_result(output);
282
+ let structured = result
283
+ .get("structuredContent")
284
+ .cloned()
285
+ .unwrap_or(Value::Null);
286
+ let is_error = result
287
+ .get("isError")
288
+ .and_then(Value::as_bool)
289
+ .unwrap_or(false);
290
+ let exit_code = result
291
+ .get("_meta")
292
+ .and_then(|meta| meta.get("exit_code"))
293
+ .and_then(Value::as_i64)
294
+ .unwrap_or(0);
295
+ self.calls.push(CallRecord {
296
+ tool: tool.to_owned(),
297
+ exit_code,
298
+ ok: !is_error,
299
+ output_bytes: serde_json::to_vec(&structured).map_or(0, |bytes| bytes.len()),
300
+ });
301
+ if is_error {
302
+ return Err(format!(
303
+ "code_execute child tool {tool} failed with exit code {exit_code}"
304
+ ));
305
+ }
306
+ self.track_result_bytes(&structured)?;
307
+ Ok(result)
308
+ }
309
+
310
+ fn select(&self, spec: &SelectSpec) -> Result<Value, String> {
311
+ let source = self.step_output(&spec.from)?;
312
+ let selected = if spec.pointer.is_empty() {
313
+ source
314
+ } else {
315
+ source.pointer(&spec.pointer).ok_or_else(|| {
316
+ format!("step {} pointer {} did not match", spec.from, spec.pointer)
317
+ })?
318
+ };
319
+ let mut value = selected.clone();
320
+ if let Some(where_clause) = &spec.where_clause {
321
+ value = filter_value(&value, where_clause)?;
322
+ }
323
+ if !spec.fields.is_empty() {
324
+ value = project_fields(value, &spec.fields)?;
325
+ }
326
+ if let Some(limit) = spec.limit {
327
+ value = limit_items(&value, limit)?;
328
+ }
329
+ Ok(value)
330
+ }
331
+
332
+ fn return_value(&self, return_spec: &ReturnSpec) -> Result<Value, String> {
333
+ match return_spec {
334
+ ReturnSpec::Ref { from, pointer } => {
335
+ let source = self.step_output(from)?;
336
+ let pointer = pointer.as_deref().unwrap_or("");
337
+ if pointer.is_empty() {
338
+ Ok(source.clone())
339
+ } else {
340
+ source.pointer(pointer).cloned().ok_or_else(|| {
341
+ format!("return pointer {pointer} did not match step {from}")
342
+ })
343
+ }
344
+ }
345
+ ReturnSpec::Value(value) => self.resolve_refs(value),
346
+ }
347
+ }
348
+
349
+ fn resolve_refs(&self, value: &Value) -> Result<Value, String> {
350
+ if let Some(reference) = parse_ref(value)? {
351
+ return self.resolve_ref_target(&reference);
352
+ }
353
+ match value {
354
+ Value::Array(items) => items
355
+ .iter()
356
+ .map(|item| self.resolve_refs(item))
357
+ .collect::<Result<Vec<_>, _>>()
358
+ .map(Value::Array),
359
+ Value::Object(object) => object
360
+ .iter()
361
+ .map(|(key, value)| Ok((key.clone(), self.resolve_refs(value)?)))
362
+ .collect::<Result<Map<_, _>, String>>()
363
+ .map(Value::Object),
364
+ _ => Ok(value.clone()),
365
+ }
366
+ }
367
+
368
+ fn resolve_ref_target(&self, target: &RefTarget) -> Result<Value, String> {
369
+ let source = self.step_output(&target.from)?;
370
+ if target.pointer.is_empty() {
371
+ return Ok(source.clone());
372
+ }
373
+ source.pointer(&target.pointer).cloned().ok_or_else(|| {
374
+ format!(
375
+ "reference from {} pointer {} did not match",
376
+ target.from, target.pointer
377
+ )
378
+ })
379
+ }
380
+
381
+ fn step_output(&self, id: &str) -> Result<&Value, String> {
382
+ self.outputs
383
+ .get(id)
384
+ .ok_or_else(|| format!("unknown code_execute step reference {id}"))
385
+ }
386
+
387
+ fn track_result_bytes(&mut self, value: &Value) -> Result<(), String> {
388
+ let bytes = serde_json::to_vec(value)
389
+ .map_err(|error| format!("failed to serialize code_execute result: {error}"))?
390
+ .len();
391
+ self.total_result_bytes = self
392
+ .total_result_bytes
393
+ .checked_add(bytes)
394
+ .ok_or_else(|| "code_execute result byte counter overflowed".to_owned())?;
395
+ if self.total_result_bytes > self.limits.result_bytes {
396
+ return Err(format!(
397
+ "code_execute result exceeded max_result_bytes {}",
398
+ self.limits.result_bytes
399
+ ));
400
+ }
401
+ Ok(())
402
+ }
403
+ }
404
+
405
+ #[derive(Debug, serde::Serialize)]
406
+ struct CallRecord {
407
+ tool: String,
408
+ exit_code: i64,
409
+ ok: bool,
410
+ output_bytes: usize,
411
+ }
412
+
413
+ const READ_ONLY_TOOLS: &[&str] = &[
414
+ "analyze",
415
+ "check_changed",
416
+ "project_info",
417
+ "list_boundaries",
418
+ "inspect_target",
419
+ "trace_file",
420
+ "trace_export",
421
+ "trace_dependency",
422
+ "trace_clone",
423
+ "find_dupes",
424
+ "check_health",
425
+ "check_runtime_coverage",
426
+ "get_hot_paths",
427
+ "get_blast_radius",
428
+ "get_importance",
429
+ "get_cleanup_candidates",
430
+ "security_candidates",
431
+ "feature_flags",
432
+ "impact",
433
+ "impact_all",
434
+ "audit",
435
+ "decision_surface",
436
+ "dart_decimate_explain",
437
+ "fallow_explain",
438
+ ];
439
+
440
+ fn parse_ref(value: &Value) -> Result<Option<RefTarget>, String> {
441
+ let Some(object) = value.as_object() else {
442
+ return Ok(None);
443
+ };
444
+ if !object.contains_key("$ref") {
445
+ return Ok(None);
446
+ }
447
+ if object.len() != 1 {
448
+ return Err("$ref objects cannot contain sibling keys".to_owned());
449
+ }
450
+ serde_json::from_value::<RefValue>(value.clone())
451
+ .map(|reference| Some(reference.reference))
452
+ .map_err(|error| format!("invalid $ref: {error}"))
453
+ }
454
+
455
+ fn filter_value(value: &Value, where_clause: &WhereSpec) -> Result<Value, String> {
456
+ let items = value
457
+ .as_array()
458
+ .ok_or_else(|| "where.equals can only filter arrays".to_owned())?;
459
+ let filtered = items
460
+ .iter()
461
+ .filter(|item| {
462
+ where_clause.equals.iter().all(|(pointer, expected)| {
463
+ item.pointer(pointer)
464
+ .is_some_and(|actual| actual == expected)
465
+ })
466
+ })
467
+ .take(MAX_SELECTION_ITEMS)
468
+ .cloned()
469
+ .collect::<Vec<_>>();
470
+ Ok(Value::Array(filtered))
471
+ }
472
+
473
+ fn project_fields(value: Value, fields: &[String]) -> Result<Value, String> {
474
+ match value {
475
+ Value::Array(items) => Ok(Value::Array(
476
+ items
477
+ .into_iter()
478
+ .take(MAX_SELECTION_ITEMS)
479
+ .map(|item| project_object_fields(&item, fields))
480
+ .collect::<Result<Vec<_>, _>>()?,
481
+ )),
482
+ Value::Object(_) => project_object_fields(&value, fields),
483
+ _ => Err("fields can only project objects or arrays of objects".to_owned()),
484
+ }
485
+ }
486
+
487
+ fn project_object_fields(value: &Value, fields: &[String]) -> Result<Value, String> {
488
+ let object = value
489
+ .as_object()
490
+ .ok_or_else(|| "fields can only project objects".to_owned())?;
491
+ let projected = fields
492
+ .iter()
493
+ .filter_map(|field| {
494
+ object
495
+ .get(field)
496
+ .map(|value| (field.clone(), value.clone()))
497
+ })
498
+ .collect::<Map<_, _>>();
499
+ Ok(Value::Object(projected))
500
+ }
501
+
502
+ fn limit_items(value: &Value, limit: usize) -> Result<Value, String> {
503
+ if limit > MAX_SELECTION_ITEMS {
504
+ return Err(format!(
505
+ "select limit exceeds max selection items {MAX_SELECTION_ITEMS}"
506
+ ));
507
+ }
508
+ let items = value
509
+ .as_array()
510
+ .ok_or_else(|| "limit can only apply to arrays".to_owned())?;
511
+ Ok(Value::Array(items.iter().take(limit).cloned().collect()))
512
+ }
513
+
514
+ fn validate_step_id(id: &str) -> Result<(), String> {
515
+ if id.is_empty() {
516
+ return Err("code_execute step id cannot be empty".to_owned());
517
+ }
518
+ if !id
519
+ .chars()
520
+ .all(|character| character.is_ascii_alphanumeric() || matches!(character, '_' | '-'))
521
+ {
522
+ return Err(format!("invalid code_execute step id {id}"));
523
+ }
524
+ Ok(())
525
+ }
526
+
527
+ fn reject_unknown(arguments: &Map<String, Value>, allowed: &[&str]) -> Result<(), String> {
528
+ for key in arguments.keys() {
529
+ if !allowed.contains(&key.as_str()) {
530
+ return Err(format!("code_execute does not accept argument {key}"));
531
+ }
532
+ }
533
+ Ok(())
534
+ }
535
+
536
+ fn optional_usize(arguments: &Map<String, Value>, key: &str) -> Result<Option<usize>, String> {
537
+ arguments
538
+ .get(key)
539
+ .map(|value| {
540
+ value
541
+ .as_u64()
542
+ .ok_or_else(|| format!("{key} must be an integer"))
543
+ .and_then(|number| {
544
+ usize::try_from(number).map_err(|_| format!("{key} is too large"))
545
+ })
546
+ })
547
+ .transpose()
548
+ }
549
+
550
+ #[cfg(test)]
551
+ mod tests {
552
+ use super::*;
553
+
554
+ #[test]
555
+ fn rejects_unknown_top_level_argument() {
556
+ let mut args = Map::new();
557
+ args.insert("code".to_owned(), json!({ "steps": [], "return": null }));
558
+ args.insert("timeout_ms".to_owned(), json!(100));
559
+
560
+ let output = execute(&args);
561
+
562
+ assert!(output.is_error);
563
+ assert!(
564
+ output
565
+ .structured
566
+ .as_ref()
567
+ .and_then(|json| json["error"].as_str())
568
+ .is_some_and(|error| error.contains("timeout_ms"))
569
+ );
570
+ }
571
+
572
+ #[test]
573
+ fn rejects_fix_tools() {
574
+ let args = request(json!({
575
+ "steps": [
576
+ { "id": "fix", "call": "fix_apply", "arguments": { "yes": true } }
577
+ ],
578
+ "return": { "from": "fix" }
579
+ }));
580
+
581
+ let output = execute(&args);
582
+
583
+ assert!(output.is_error);
584
+ assert!(
585
+ output
586
+ .structured
587
+ .as_ref()
588
+ .and_then(|json| json["error"].as_str())
589
+ .is_some_and(|error| error.contains("fix_apply"))
590
+ );
591
+ }
592
+
593
+ #[test]
594
+ fn rejects_duplicate_step_ids() {
595
+ let args = request(json!({
596
+ "steps": [
597
+ { "id": "same", "select": { "from": "same", "pointer": "" } },
598
+ { "id": "same", "select": { "from": "same", "pointer": "" } }
599
+ ],
600
+ "return": { "from": "same" }
601
+ }));
602
+
603
+ let output = execute(&args);
604
+
605
+ assert!(output.is_error);
606
+ assert!(
607
+ output
608
+ .structured
609
+ .as_ref()
610
+ .and_then(|json| json["error"].as_str())
611
+ .is_some_and(|error| error.contains("duplicate"))
612
+ );
613
+ }
614
+
615
+ #[test]
616
+ fn selects_projects_and_limits_arrays() -> Result<(), String> {
617
+ let mut executor = Executor::new(Limits {
618
+ steps: 4,
619
+ tool_calls: 1,
620
+ result_bytes: 10_000,
621
+ });
622
+ executor.outputs.insert(
623
+ "input".to_owned(),
624
+ json!({
625
+ "items": [
626
+ { "kind": "unused-file", "path": "lib/a.dart", "extra": true },
627
+ { "kind": "unused-export", "path": "lib/b.dart", "extra": true }
628
+ ]
629
+ }),
630
+ );
631
+
632
+ let value = executor.select(&SelectSpec {
633
+ from: "input".to_owned(),
634
+ pointer: "/items".to_owned(),
635
+ fields: vec!["path".to_owned()],
636
+ limit: Some(1),
637
+ where_clause: Some(WhereSpec {
638
+ equals: BTreeMap::from([(
639
+ "/kind".to_owned(),
640
+ Value::String("unused-export".to_owned()),
641
+ )]),
642
+ }),
643
+ })?;
644
+
645
+ assert_eq!(value, json!([{ "path": "lib/b.dart" }]));
646
+ Ok(())
647
+ }
648
+
649
+ #[test]
650
+ fn resolves_argument_refs() -> Result<(), String> {
651
+ let mut executor = Executor::new(Limits {
652
+ steps: 4,
653
+ tool_calls: 1,
654
+ result_bytes: 10_000,
655
+ });
656
+ executor
657
+ .outputs
658
+ .insert("pick".to_owned(), json!({ "path": "lib/main.dart" }));
659
+
660
+ let value = executor.resolve_refs(&json!({
661
+ "file": { "$ref": { "from": "pick", "pointer": "/path" } }
662
+ }))?;
663
+
664
+ assert_eq!(value, json!({ "file": "lib/main.dart" }));
665
+ Ok(())
666
+ }
667
+
668
+ fn request(program: Value) -> Map<String, Value> {
669
+ Map::from_iter([("code".to_owned(), program)])
670
+ }
671
+ }