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
package/src/impact.rs ADDED
@@ -0,0 +1,287 @@
1
+ use std::fmt::Write as _;
2
+ use std::fs;
3
+ use std::path::{Path, PathBuf};
4
+
5
+ use serde::{Deserialize, Serialize};
6
+
7
+ /// Stable schema version for local impact reports.
8
+ pub const IMPACT_SCHEMA_VERSION: &str = "dart-decimate.impact.v1";
9
+ const IMPACT_HISTORY_PATH: &str = ".dart-decimate/impact.jsonl";
10
+
11
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12
+ pub struct ImpactReport {
13
+ pub schema_version: String,
14
+ pub kind: String,
15
+ pub tool: String,
16
+ pub command: String,
17
+ pub enabled: bool,
18
+ pub enabled_source: String,
19
+ pub explicit_decision: bool,
20
+ pub onboarding_declined: bool,
21
+ pub record_count: usize,
22
+ pub project: ImpactProject,
23
+ pub totals: ImpactTotals,
24
+ pub trend: ImpactTrend,
25
+ pub gate: ImpactGate,
26
+ pub records: Vec<ImpactRecord>,
27
+ }
28
+
29
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30
+ pub struct ImpactAllReport {
31
+ pub schema_version: String,
32
+ pub kind: String,
33
+ pub tool: String,
34
+ pub command: String,
35
+ pub summary: ImpactAllSummary,
36
+ pub projects: Vec<ImpactProjectSummary>,
37
+ }
38
+
39
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40
+ pub struct ImpactProject {
41
+ pub id: String,
42
+ pub label: String,
43
+ pub root_hint: String,
44
+ }
45
+
46
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47
+ pub struct ImpactTotals {
48
+ pub surfaced: usize,
49
+ pub resolved: usize,
50
+ pub suppressed: usize,
51
+ pub contained_commits: usize,
52
+ }
53
+
54
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55
+ pub struct ImpactTrend {
56
+ pub surfaced_delta: isize,
57
+ pub resolved_delta: isize,
58
+ pub suppressed_delta: isize,
59
+ }
60
+
61
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62
+ pub struct ImpactGate {
63
+ pub contained_commits: usize,
64
+ }
65
+
66
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67
+ pub struct ImpactRecord {
68
+ pub timestamp: String,
69
+ pub surfaced: usize,
70
+ pub resolved: usize,
71
+ pub suppressed: usize,
72
+ pub contained_commits: usize,
73
+ }
74
+
75
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76
+ pub struct ImpactAllSummary {
77
+ pub projects: usize,
78
+ pub enabled_projects: usize,
79
+ pub record_count: usize,
80
+ pub surfaced: usize,
81
+ pub contained_commits: usize,
82
+ }
83
+
84
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
85
+ pub struct ImpactProjectSummary {
86
+ pub project: ImpactProject,
87
+ pub enabled: bool,
88
+ pub record_count: usize,
89
+ pub surfaced: usize,
90
+ pub contained_commits: usize,
91
+ }
92
+
93
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
94
+ pub enum ImpactSort {
95
+ Label,
96
+ Surfaced,
97
+ ContainedCommits,
98
+ RecordCount,
99
+ }
100
+
101
+ #[must_use]
102
+ pub fn impact_report(root: impl AsRef<Path>) -> ImpactReport {
103
+ let root = normalize_root_hint(root.as_ref());
104
+ let project = impact_project(&root);
105
+ let records = load_impact_history(&root);
106
+ let enabled = !records.is_empty();
107
+ let totals = impact_totals(&records);
108
+ ImpactReport {
109
+ schema_version: IMPACT_SCHEMA_VERSION.to_owned(),
110
+ kind: "impact".to_owned(),
111
+ tool: "dart-decimate".to_owned(),
112
+ command: "impact".to_owned(),
113
+ enabled,
114
+ enabled_source: if enabled {
115
+ "local-history".to_owned()
116
+ } else {
117
+ "default".to_owned()
118
+ },
119
+ explicit_decision: false,
120
+ onboarding_declined: false,
121
+ record_count: records.len(),
122
+ project,
123
+ trend: impact_trend(&records),
124
+ gate: ImpactGate {
125
+ contained_commits: totals.contained_commits,
126
+ },
127
+ totals,
128
+ records,
129
+ }
130
+ }
131
+
132
+ #[must_use]
133
+ pub fn impact_all_report(sort: ImpactSort, limit: usize) -> ImpactAllReport {
134
+ let mut projects = Vec::<ImpactProjectSummary>::new();
135
+ sort_project_summaries(&mut projects, sort);
136
+ projects.truncate(limit);
137
+ ImpactAllReport {
138
+ schema_version: IMPACT_SCHEMA_VERSION.to_owned(),
139
+ kind: "impact-all".to_owned(),
140
+ tool: "dart-decimate".to_owned(),
141
+ command: "impact --all".to_owned(),
142
+ summary: ImpactAllSummary {
143
+ projects: projects.len(),
144
+ enabled_projects: projects.iter().filter(|project| project.enabled).count(),
145
+ record_count: projects.iter().map(|project| project.record_count).sum(),
146
+ surfaced: projects.iter().map(|project| project.surfaced).sum(),
147
+ contained_commits: projects
148
+ .iter()
149
+ .map(|project| project.contained_commits)
150
+ .sum(),
151
+ },
152
+ projects,
153
+ }
154
+ }
155
+
156
+ #[must_use]
157
+ pub fn render_impact_report(report: &ImpactReport) -> String {
158
+ if !report.enabled {
159
+ return format!(
160
+ "impact enabled=false project={} records=0\n",
161
+ report.project.label
162
+ );
163
+ }
164
+
165
+ format!(
166
+ "impact enabled=true project={} surfaced={} contained_commits={}\n",
167
+ report.project.label, report.totals.surfaced, report.totals.contained_commits
168
+ )
169
+ }
170
+
171
+ #[must_use]
172
+ pub fn render_impact_all_report(report: &ImpactAllReport) -> String {
173
+ let mut rendered = String::new();
174
+ let _ = writeln!(
175
+ rendered,
176
+ "impact-all projects={} enabled_projects={} records={}",
177
+ report.summary.projects, report.summary.enabled_projects, report.summary.record_count
178
+ );
179
+ for project in &report.projects {
180
+ let _ = writeln!(
181
+ rendered,
182
+ "- {} surfaced={} contained_commits={}",
183
+ project.project.label, project.surfaced, project.contained_commits
184
+ );
185
+ }
186
+ rendered
187
+ }
188
+
189
+ fn impact_project(root: &Path) -> ImpactProject {
190
+ ImpactProject {
191
+ id: stable_project_id(root),
192
+ label: project_label(root),
193
+ root_hint: root.to_string_lossy().into_owned(),
194
+ }
195
+ }
196
+
197
+ fn load_impact_history(root: &Path) -> Vec<ImpactRecord> {
198
+ let Ok(contents) = fs::read_to_string(root.join(IMPACT_HISTORY_PATH)) else {
199
+ return Vec::new();
200
+ };
201
+
202
+ contents
203
+ .lines()
204
+ .filter_map(|line| {
205
+ let line = line.trim();
206
+ if line.is_empty() {
207
+ None
208
+ } else {
209
+ serde_json::from_str::<ImpactRecord>(line).ok()
210
+ }
211
+ })
212
+ .collect()
213
+ }
214
+
215
+ fn impact_totals(records: &[ImpactRecord]) -> ImpactTotals {
216
+ ImpactTotals {
217
+ surfaced: records.iter().map(|record| record.surfaced).sum(),
218
+ resolved: records.iter().map(|record| record.resolved).sum(),
219
+ suppressed: records.iter().map(|record| record.suppressed).sum(),
220
+ contained_commits: records.iter().map(|record| record.contained_commits).sum(),
221
+ }
222
+ }
223
+
224
+ fn impact_trend(records: &[ImpactRecord]) -> ImpactTrend {
225
+ let (Some(first), Some(last)) = (records.first(), records.last()) else {
226
+ return ImpactTrend {
227
+ surfaced_delta: 0,
228
+ resolved_delta: 0,
229
+ suppressed_delta: 0,
230
+ };
231
+ };
232
+
233
+ ImpactTrend {
234
+ surfaced_delta: usize_delta(last.surfaced, first.surfaced),
235
+ resolved_delta: usize_delta(last.resolved, first.resolved),
236
+ suppressed_delta: usize_delta(last.suppressed, first.suppressed),
237
+ }
238
+ }
239
+
240
+ fn usize_delta(current: usize, previous: usize) -> isize {
241
+ let current = isize::try_from(current).unwrap_or(isize::MAX);
242
+ let previous = isize::try_from(previous).unwrap_or(isize::MAX);
243
+ current.saturating_sub(previous)
244
+ }
245
+
246
+ fn normalize_root_hint(root: &Path) -> PathBuf {
247
+ root.canonicalize().unwrap_or_else(|_| root.to_path_buf())
248
+ }
249
+
250
+ fn project_label(root: &Path) -> String {
251
+ root.file_name()
252
+ .and_then(std::ffi::OsStr::to_str)
253
+ .filter(|label| !label.is_empty())
254
+ .unwrap_or("project")
255
+ .to_owned()
256
+ }
257
+
258
+ fn stable_project_id(root: &Path) -> String {
259
+ format!("dart-decimate:impact:{:016x}", stable_hash(root))
260
+ }
261
+
262
+ fn stable_hash(root: &Path) -> u64 {
263
+ let mut hash = 0xcbf2_9ce4_8422_2325u64;
264
+ for byte in root.to_string_lossy().as_bytes() {
265
+ hash ^= u64::from(*byte);
266
+ hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
267
+ }
268
+ hash
269
+ }
270
+
271
+ fn sort_project_summaries(projects: &mut [ImpactProjectSummary], sort: ImpactSort) {
272
+ projects.sort_by(|left, right| match sort {
273
+ ImpactSort::Label => left.project.label.cmp(&right.project.label),
274
+ ImpactSort::Surfaced => right
275
+ .surfaced
276
+ .cmp(&left.surfaced)
277
+ .then_with(|| left.project.label.cmp(&right.project.label)),
278
+ ImpactSort::ContainedCommits => right
279
+ .contained_commits
280
+ .cmp(&left.contained_commits)
281
+ .then_with(|| left.project.label.cmp(&right.project.label)),
282
+ ImpactSort::RecordCount => right
283
+ .record_count
284
+ .cmp(&left.record_count)
285
+ .then_with(|| left.project.label.cmp(&right.project.label)),
286
+ });
287
+ }
package/src/init.rs ADDED
@@ -0,0 +1,237 @@
1
+ use std::fmt::Write as _;
2
+ use std::fs;
3
+ use std::path::{Path, PathBuf};
4
+
5
+ use serde::{Deserialize, Serialize};
6
+ use thiserror::Error;
7
+
8
+ /// Stable schema version for project initialization output.
9
+ pub const INIT_SCHEMA_VERSION: &str = "dart-decimate.init.v1";
10
+
11
+ /// Project initialization options.
12
+ #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
13
+ pub struct InitOptions {
14
+ /// Overwrite existing files.
15
+ pub force: bool,
16
+ /// Write agent guidance.
17
+ pub agents: bool,
18
+ }
19
+
20
+ /// Machine-readable initialization report.
21
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
22
+ pub struct InitReport {
23
+ /// Schema identifier.
24
+ pub schema_version: String,
25
+ /// Typed JSON envelope discriminator.
26
+ pub kind: String,
27
+ /// Tool name.
28
+ pub tool: String,
29
+ /// Command that produced this report.
30
+ pub command: String,
31
+ /// Root that was initialized.
32
+ pub root: PathBuf,
33
+ /// Files written or overwritten.
34
+ pub files: Vec<InitFile>,
35
+ /// Suggested follow-up commands.
36
+ pub next_steps: Vec<String>,
37
+ }
38
+
39
+ /// File produced by `dart-decimate init`.
40
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41
+ pub struct InitFile {
42
+ /// Path relative to the initialized root.
43
+ pub path: String,
44
+ /// File purpose.
45
+ pub kind: InitFileKind,
46
+ /// Write action performed.
47
+ pub action: InitFileAction,
48
+ }
49
+
50
+ /// Type of initialized file.
51
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
52
+ #[serde(rename_all = "kebab-case")]
53
+ pub enum InitFileKind {
54
+ /// Dart Decimate configuration.
55
+ Config,
56
+ /// Agent workflow guidance.
57
+ Agents,
58
+ }
59
+
60
+ /// Write action performed for an initialized file.
61
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
62
+ #[serde(rename_all = "kebab-case")]
63
+ pub enum InitFileAction {
64
+ /// File did not exist and was created.
65
+ Created,
66
+ /// File existed and was overwritten because `force` was set.
67
+ Overwritten,
68
+ }
69
+
70
+ /// Errors returned while initializing a project.
71
+ #[derive(Debug, Error)]
72
+ pub enum InitError {
73
+ /// A target file already exists and `force` was not set.
74
+ #[error("refusing to overwrite existing init file {path}; pass --force")]
75
+ AlreadyExists {
76
+ /// Existing path.
77
+ path: PathBuf,
78
+ },
79
+ /// A directory could not be created.
80
+ #[error("failed to create init directory {path}: {source}")]
81
+ CreateDir {
82
+ /// Directory path.
83
+ path: PathBuf,
84
+ /// Underlying IO error.
85
+ source: std::io::Error,
86
+ },
87
+ /// A file could not be written.
88
+ #[error("failed to write init file {path}: {source}")]
89
+ Write {
90
+ /// File path.
91
+ path: PathBuf,
92
+ /// Underlying IO error.
93
+ source: std::io::Error,
94
+ },
95
+ }
96
+
97
+ /// Initialize Dart Decimate config and optional agent guidance under `root`.
98
+ ///
99
+ /// # Errors
100
+ ///
101
+ /// Returns [`InitError`] when an initialized file already exists without
102
+ /// `force`, or when directories/files cannot be written.
103
+ pub fn init_project(root: impl AsRef<Path>, options: InitOptions) -> Result<InitReport, InitError> {
104
+ let root = root.as_ref();
105
+ let files = init_files(options.agents);
106
+ let mut written = Vec::with_capacity(files.len());
107
+
108
+ for file in files {
109
+ let path = root.join(file.path);
110
+ let action = write_init_file(&path, file.content, options.force)?;
111
+ written.push(InitFile {
112
+ path: file.path.to_owned(),
113
+ kind: file.kind,
114
+ action,
115
+ });
116
+ }
117
+
118
+ Ok(InitReport {
119
+ schema_version: INIT_SCHEMA_VERSION.to_owned(),
120
+ kind: "init".to_owned(),
121
+ tool: "dart-decimate".to_owned(),
122
+ command: "init".to_owned(),
123
+ root: root.to_path_buf(),
124
+ files: written,
125
+ next_steps: vec![
126
+ "dart-decimate check --format json".to_owned(),
127
+ "dart-decimate audit --format json --base origin/main".to_owned(),
128
+ ],
129
+ })
130
+ }
131
+
132
+ /// Render a human-readable initialization report.
133
+ #[must_use]
134
+ pub fn render_init_report(report: &InitReport) -> String {
135
+ let mut output = format!("Initialized Dart Decimate in {}\n", report.root.display());
136
+ for file in &report.files {
137
+ let action = match file.action {
138
+ InitFileAction::Created => "created",
139
+ InitFileAction::Overwritten => "overwrote",
140
+ };
141
+ let _ = writeln!(output, "{action} {}", file.path);
142
+ }
143
+ output.push_str("Next:\n");
144
+ for step in &report.next_steps {
145
+ let _ = writeln!(output, " {step}");
146
+ }
147
+ output
148
+ }
149
+
150
+ struct InitTemplate {
151
+ path: &'static str,
152
+ kind: InitFileKind,
153
+ content: &'static str,
154
+ }
155
+
156
+ fn init_files(agents: bool) -> Vec<InitTemplate> {
157
+ let mut files = vec![InitTemplate {
158
+ path: ".dart-decimaterc",
159
+ kind: InitFileKind::Config,
160
+ content: DART_DECIMATE_RC,
161
+ }];
162
+ if agents {
163
+ files.push(InitTemplate {
164
+ path: "AGENTS.md",
165
+ kind: InitFileKind::Agents,
166
+ content: AGENTS_MD,
167
+ });
168
+ }
169
+ files
170
+ }
171
+
172
+ fn write_init_file(path: &Path, content: &str, force: bool) -> Result<InitFileAction, InitError> {
173
+ let action = if path.exists() {
174
+ if !force {
175
+ return Err(InitError::AlreadyExists {
176
+ path: path.to_path_buf(),
177
+ });
178
+ }
179
+ InitFileAction::Overwritten
180
+ } else {
181
+ InitFileAction::Created
182
+ };
183
+
184
+ if let Some(parent) = path.parent() {
185
+ fs::create_dir_all(parent).map_err(|source| InitError::CreateDir {
186
+ path: parent.to_path_buf(),
187
+ source,
188
+ })?;
189
+ }
190
+ fs::write(path, content).map_err(|source| InitError::Write {
191
+ path: path.to_path_buf(),
192
+ source,
193
+ })?;
194
+ Ok(action)
195
+ }
196
+
197
+ const DART_DECIMATE_RC: &str = r#"{
198
+ "cli": {
199
+ "format": "json",
200
+ "entry": ["lib/main.dart"],
201
+ "production": true
202
+ },
203
+ "ignorePatterns": [
204
+ "**/.dart_tool/**",
205
+ "**/build/**",
206
+ "**/generated/**",
207
+ "**/*.g.dart",
208
+ "**/*.freezed.dart",
209
+ "**/*.gen.dart",
210
+ "**/*.gr.dart",
211
+ "**/*.mocks.dart"
212
+ ],
213
+ "health": {
214
+ "fileScores": true,
215
+ "hotspots": true,
216
+ "targets": true
217
+ },
218
+ "security": {
219
+ "surface": true
220
+ },
221
+ "rules": {
222
+ "dart-decimate/missing-suppression-reason": "warn"
223
+ }
224
+ }
225
+ "#;
226
+
227
+ const AGENTS_MD: &str = r"# Dart Decimate Agent Guide
228
+
229
+ Use Dart Decimate as the first static codebase-intelligence pass for Dart and Flutter changes.
230
+
231
+ - Run `dart-decimate check --format json` for cleanup, dependency, health, flag, security, and graph findings.
232
+ - Run `dart-decimate audit --format json --base origin/main` for changed-code review.
233
+ - Inspect before editing with `dart-decimate inspect --format json --file <path>` or `dart-decimate inspect --format json --symbol <file>:<symbol>`.
234
+ - Apply only actions with `safe_to_delete: true`, then rerun the same command that produced the finding.
235
+
236
+ Dart Decimate is graph-first. Treat unresolved dependencies, generated files, build outputs, and runtime-only entry points as evidence to verify before deleting code.
237
+ ";
package/src/inspect.rs ADDED
@@ -0,0 +1,142 @@
1
+ use std::fmt::Write as _;
2
+ use std::path::Path;
3
+
4
+ use serde::{Deserialize, Serialize};
5
+
6
+ use crate::graph::normalize_against;
7
+ use crate::{
8
+ DeadCodeReport, FileTraceReport, JsonReport, ScannedProject, SymbolTraceReport, trace_file,
9
+ trace_symbol,
10
+ };
11
+
12
+ /// Stable inspect schema version for composed evidence bundles.
13
+ pub const INSPECT_SCHEMA_VERSION: &str = "dart-decimate.inspect.v1";
14
+
15
+ /// A targeted evidence bundle for one file or top-level symbol.
16
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17
+ pub struct InspectReport {
18
+ /// Schema identifier.
19
+ pub schema_version: String,
20
+ /// Typed JSON envelope discriminator.
21
+ pub kind: String,
22
+ /// Tool name.
23
+ pub tool: String,
24
+ /// Command that produced this report.
25
+ pub command: String,
26
+ /// Requested inspect target.
27
+ pub target: InspectTarget,
28
+ /// File-level graph trace for the target file.
29
+ pub file_trace: FileTraceReport,
30
+ /// Symbol-level trace when inspecting a symbol target.
31
+ pub symbol_trace: Option<SymbolTraceReport>,
32
+ /// Normal report output scoped to the target file.
33
+ pub scoped_report: JsonReport,
34
+ /// Conservative caveats an agent should preserve before editing.
35
+ pub warnings: Vec<String>,
36
+ }
37
+
38
+ /// Inspect target metadata.
39
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40
+ pub struct InspectTarget {
41
+ /// `file` or `symbol`.
42
+ pub kind: String,
43
+ /// Root-relative file path where possible.
44
+ pub path: String,
45
+ /// Symbol name for symbol targets.
46
+ pub symbol: Option<String>,
47
+ }
48
+
49
+ /// Build an inspect bundle for one file.
50
+ #[must_use]
51
+ pub fn inspect_file(
52
+ project: &ScannedProject,
53
+ dead_code: &DeadCodeReport,
54
+ scoped_report: JsonReport,
55
+ path: impl AsRef<Path>,
56
+ ) -> InspectReport {
57
+ let path = normalize_against(&project.root, path.as_ref());
58
+ let file_trace = trace_file(project, dead_code, &path);
59
+
60
+ InspectReport {
61
+ schema_version: INSPECT_SCHEMA_VERSION.to_owned(),
62
+ kind: "inspect".to_owned(),
63
+ tool: "dart-decimate".to_owned(),
64
+ command: "inspect".to_owned(),
65
+ target: InspectTarget {
66
+ kind: "file".to_owned(),
67
+ path: display_path(&project.root, &path),
68
+ symbol: None,
69
+ },
70
+ file_trace,
71
+ symbol_trace: None,
72
+ scoped_report,
73
+ warnings: inspect_warnings(),
74
+ }
75
+ }
76
+
77
+ /// Build an inspect bundle for one top-level symbol.
78
+ #[must_use]
79
+ pub fn inspect_symbol(
80
+ project: &ScannedProject,
81
+ dead_code: &DeadCodeReport,
82
+ scoped_report: JsonReport,
83
+ path: impl AsRef<Path>,
84
+ symbol: &str,
85
+ ) -> InspectReport {
86
+ let path = normalize_against(&project.root, path.as_ref());
87
+ let file_trace = trace_file(project, dead_code, &path);
88
+ let symbol_trace = trace_symbol(project, dead_code, &path, symbol);
89
+
90
+ InspectReport {
91
+ schema_version: INSPECT_SCHEMA_VERSION.to_owned(),
92
+ kind: "inspect".to_owned(),
93
+ tool: "dart-decimate".to_owned(),
94
+ command: "inspect".to_owned(),
95
+ target: InspectTarget {
96
+ kind: "symbol".to_owned(),
97
+ path: display_path(&project.root, &path),
98
+ symbol: Some(symbol.to_owned()),
99
+ },
100
+ file_trace,
101
+ symbol_trace: Some(symbol_trace),
102
+ scoped_report,
103
+ warnings: inspect_warnings(),
104
+ }
105
+ }
106
+
107
+ /// Render a concise human inspect summary.
108
+ #[must_use]
109
+ pub fn render_inspect_report(report: &InspectReport) -> String {
110
+ let mut rendered = String::new();
111
+ let _ = writeln!(
112
+ rendered,
113
+ "inspect {}{}: findings={} reachable={}",
114
+ report.target.path,
115
+ report
116
+ .target
117
+ .symbol
118
+ .as_ref()
119
+ .map_or_else(String::new, |symbol| format!(":{symbol}")),
120
+ report.scoped_report.summary.findings,
121
+ report.file_trace.reachable
122
+ );
123
+ let _ = writeln!(rendered, "{}", report.file_trace.reason);
124
+ if let Some(symbol_trace) = &report.symbol_trace {
125
+ let _ = writeln!(rendered, "{}", symbol_trace.reason);
126
+ }
127
+ rendered
128
+ }
129
+
130
+ fn inspect_warnings() -> Vec<String> {
131
+ vec![
132
+ "Inspect is graph-based and syntactic; verify dynamic framework entry points before deleting code."
133
+ .to_owned(),
134
+ ]
135
+ }
136
+
137
+ fn display_path(root: &Path, path: &Path) -> String {
138
+ path.strip_prefix(root)
139
+ .unwrap_or(path)
140
+ .to_string_lossy()
141
+ .replace('\\', "/")
142
+ }