Skip to main content

fallow_types/
audit_cache.rs

1//! Typed audit cache-key inputs.
2
3use serde::Serialize;
4
5use crate::source_fingerprint::SourceFingerprint;
6
7/// Filesystem state of one bounded audit context input.
8#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
9#[serde(rename_all = "snake_case")]
10pub enum AuditContextPathState {
11    /// The path does not exist.
12    Missing,
13    /// The path exists and was read successfully.
14    Present,
15    /// The path exists, but its metadata or contents could not be read.
16    Unreadable(String),
17}
18
19/// Fingerprint of one file that can affect base-worktree resolution.
20#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
21pub struct AuditContextFileFingerprint {
22    /// Project-root-relative, forward-slash path.
23    pub path: String,
24    /// Presence or read-error state.
25    pub state: AuditContextPathState,
26    /// Source metadata when readable.
27    pub source: Option<SourceFingerprint>,
28    /// Stable content hash when readable.
29    pub content_hash: Option<String>,
30}
31
32/// Fingerprint of one host directory materialized into an audit base worktree.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
34pub struct AuditContextDirectoryFingerprint {
35    /// Directory name relative to the analysis root.
36    pub name: String,
37    /// Presence or metadata-error state.
38    pub state: AuditContextPathState,
39    /// Canonical source identity when available.
40    pub canonical_path: Option<String>,
41    /// Root directory metadata when readable.
42    pub source: Option<SourceFingerprint>,
43    /// Bounded marker files whose contents affect resolution.
44    pub markers: Vec<AuditContextFileFingerprint>,
45}
46
47/// Bounded host context shared with an audit base worktree.
48#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
49pub struct AuditMaterializedContextFingerprint {
50    /// Current package-manager lockfiles at the analysis root.
51    pub lockfiles: Vec<AuditContextFileFingerprint>,
52    /// Dependency and generated-context directories shared with the base view.
53    pub directories: Vec<AuditContextDirectoryFingerprint>,
54}
55
56/// Fingerprint of the resolved config that can affect audit output.
57#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
58pub struct AuditConfigFingerprint {
59    /// Path of the config file that was loaded, or `None` when no config exists.
60    pub path: Option<String>,
61    /// Stable hash of the resolved config object.
62    pub resolved_hash: Option<String>,
63}
64
65/// Fingerprint of the coverage input of the base pass.
66#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
67pub struct AuditCoverageFingerprint {
68    /// The coverage path that the base pass gets.
69    pub path: String,
70    /// Each file that the coverage reader selects for `path`, in the order
71    /// of the reader.
72    pub files: Vec<AuditCoverageFileFingerprint>,
73    /// The selection error, when the reader selects no file.
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub error: Option<String>,
76}
77
78/// Fingerprint of one selected coverage file.
79#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
80pub struct AuditCoverageFileFingerprint {
81    /// Path of the selected file.
82    pub path: String,
83    /// Metadata freshness of the file, when it was readable.
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub source: Option<SourceFingerprint>,
86    /// Stable content hash of the file, when it was readable.
87    #[serde(skip_serializing_if = "Option::is_none")]
88    pub content_hash: Option<String>,
89    /// File length in bytes, when it was readable.
90    #[serde(skip_serializing_if = "Option::is_none")]
91    pub len: Option<usize>,
92    /// I/O error kind, when the file was not readable.
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub error: Option<String>,
95}
96
97/// The type-aware selection of a base pass that runs the type-aware
98/// companion.
99#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
100pub struct AuditTypeAwareFingerprint {
101    /// The TypeScript project configs, in the order of the run.
102    pub projects: Vec<String>,
103    /// The completeness policy.
104    pub require: String,
105}
106
107/// Typed payload hashed to address an audit base-snapshot cache entry.
108#[derive(Debug, Clone, PartialEq, Serialize)]
109pub struct AuditCacheKeyPayload {
110    /// Audit base snapshot cache schema version.
111    pub cache_version: u8,
112    /// Fallow CLI version that produced the key.
113    pub cli_version: String,
114    /// Resolved git SHA for the base ref.
115    pub base_sha: String,
116    /// Config fingerprint.
117    pub config_file: AuditConfigFingerprint,
118    /// Changed files normalized to git-root-relative, forward-slash paths.
119    pub changed_files: Vec<String>,
120    /// Host dependency and generated context materialized into the base view.
121    pub materialized_context: AuditMaterializedContextFingerprint,
122    /// Global production mode.
123    pub production: bool,
124    /// Dead-code-specific production override.
125    pub production_dead_code: Option<bool>,
126    /// Health-specific production override.
127    pub production_health: Option<bool>,
128    /// Duplication-specific production override.
129    pub production_dupes: Option<bool>,
130    /// Workspace filters.
131    pub workspace: Option<Vec<String>>,
132    /// Changed-workspaces base ref, when enabled.
133    pub changed_workspaces: Option<String>,
134    /// Grouping mode.
135    pub group_by: Option<String>,
136    /// Whether entry exports are analyzed.
137    pub include_entry_exports: bool,
138    /// Keep the export and member findings of unused files (`--show-cascade`).
139    pub show_cascade: bool,
140    /// Whether the base pass ran for the review brief (`--brief`). Only a
141    /// brief base pass computes the public-export set of the snapshot.
142    pub brief: bool,
143    /// CRAP threshold override.
144    pub max_crap: Option<f64>,
145    /// Coverage input fingerprint.
146    pub coverage: Option<AuditCoverageFingerprint>,
147    /// Coverage root override.
148    pub coverage_root: Option<String>,
149    /// Whether audit ran the dead-code sub-analysis for the base snapshot.
150    pub dead_code: bool,
151    /// Whether audit ran the health sub-analysis for the base snapshot.
152    pub health: bool,
153    /// Whether audit ran the duplication sub-analysis for the base snapshot.
154    pub dupes: bool,
155    /// Which dead-code findings the selection keeps: `all`, `only` (the
156    /// architecture findings) or `exclude` (all but the architecture findings).
157    pub architecture: String,
158    /// Whether audit health computed styling keys for the base snapshot.
159    pub css: bool,
160    /// Whether audit health used deep CSS analysis for the base snapshot.
161    pub css_deep: bool,
162    /// Experimental type-aware backend selection. The default backend leaves
163    /// it out, so the key bytes of a default run do not change.
164    #[serde(skip_serializing_if = "Option::is_none")]
165    pub type_aware_backend: Option<String>,
166    /// The effective type-aware selection. A syntactic base pass leaves
167    /// it out.
168    #[serde(skip_serializing_if = "Option::is_none")]
169    pub type_aware: Option<AuditTypeAwareFingerprint>,
170}
171
172/// Builder for audit base-snapshot cache keys.
173#[derive(Debug, Clone)]
174pub struct AuditCacheKeyBuilder {
175    payload: AuditCacheKeyPayload,
176}
177
178impl AuditCacheKeyBuilder {
179    /// Start a cache-key payload with the invariant identity fields.
180    #[must_use]
181    pub fn new(
182        cache_version: u8,
183        cli_version: impl Into<String>,
184        base_sha: impl Into<String>,
185        config_file: AuditConfigFingerprint,
186        changed_files: Vec<String>,
187        materialized_context: AuditMaterializedContextFingerprint,
188    ) -> Self {
189        Self {
190            payload: AuditCacheKeyPayload {
191                cache_version,
192                cli_version: cli_version.into(),
193                base_sha: base_sha.into(),
194                config_file,
195                changed_files,
196                materialized_context,
197                production: false,
198                production_dead_code: None,
199                production_health: None,
200                production_dupes: None,
201                workspace: None,
202                changed_workspaces: None,
203                group_by: None,
204                include_entry_exports: false,
205                show_cascade: false,
206                brief: false,
207                max_crap: None,
208                coverage: None,
209                coverage_root: None,
210                dead_code: true,
211                health: true,
212                dupes: true,
213                architecture: "all".to_string(),
214                css: false,
215                css_deep: false,
216                type_aware_backend: None,
217                type_aware: None,
218            },
219        }
220    }
221
222    /// Set production-mode options.
223    #[must_use]
224    pub const fn production(
225        mut self,
226        production: bool,
227        dead_code: Option<bool>,
228        health: Option<bool>,
229        dupes: Option<bool>,
230    ) -> Self {
231        self.payload.production = production;
232        self.payload.production_dead_code = dead_code;
233        self.payload.production_health = health;
234        self.payload.production_dupes = dupes;
235        self
236    }
237
238    /// Set scope and grouping options.
239    #[must_use]
240    pub fn scope(
241        mut self,
242        workspace: Option<Vec<String>>,
243        changed_workspaces: Option<String>,
244        group_by: Option<String>,
245        include_entry_exports: bool,
246    ) -> Self {
247        self.payload.workspace = workspace;
248        self.payload.changed_workspaces = changed_workspaces;
249        self.payload.group_by = group_by;
250        self.payload.include_entry_exports = include_entry_exports;
251        self
252    }
253
254    /// Set whether the export and member findings of unused files stay in
255    /// the report.
256    #[must_use]
257    pub const fn show_cascade(mut self, show_cascade: bool) -> Self {
258        self.payload.show_cascade = show_cascade;
259        self
260    }
261
262    /// Set whether the base pass ran for the review brief (`--brief`).
263    #[must_use]
264    pub const fn brief(mut self, brief: bool) -> Self {
265        self.payload.brief = brief;
266        self
267    }
268
269    /// Set health and coverage options.
270    #[must_use]
271    pub fn health(
272        mut self,
273        max_crap: Option<f64>,
274        coverage: Option<AuditCoverageFingerprint>,
275        coverage_root: Option<String>,
276    ) -> Self {
277        self.payload.max_crap = max_crap;
278        self.payload.coverage = coverage;
279        self.payload.coverage_root = coverage_root;
280        self
281    }
282
283    /// Set which sub-analyses ran for the base snapshot, and which dead-code
284    /// findings the architecture selection kept.
285    #[must_use]
286    pub fn analyses(
287        mut self,
288        dead_code: bool,
289        health: bool,
290        dupes: bool,
291        architecture: impl Into<String>,
292    ) -> Self {
293        self.payload.dead_code = dead_code;
294        self.payload.health = health;
295        self.payload.dupes = dupes;
296        self.payload.architecture = architecture.into();
297        self
298    }
299
300    /// Set styling-analysis options that affect base health snapshot keys.
301    #[must_use]
302    pub const fn styling(mut self, css: bool, css_deep: bool) -> Self {
303        self.payload.css = css;
304        self.payload.css_deep = css_deep;
305        self
306    }
307
308    /// Set the type-aware backend selection.
309    #[must_use]
310    pub fn type_aware_backend(mut self, backend: Option<String>) -> Self {
311        self.payload.type_aware_backend = backend;
312        self
313    }
314
315    /// Set the effective type-aware selection.
316    #[must_use]
317    pub fn type_aware(mut self, selection: Option<AuditTypeAwareFingerprint>) -> Self {
318        self.payload.type_aware = selection;
319        self
320    }
321
322    /// Borrow the completed payload.
323    #[must_use]
324    pub const fn payload(&self) -> &AuditCacheKeyPayload {
325        &self.payload
326    }
327
328    /// Serialize the completed payload into stable JSON bytes for hashing.
329    ///
330    /// # Errors
331    ///
332    /// Returns a serde error when a payload field cannot be serialized.
333    pub fn to_json_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
334        serde_json::to_vec(&self.payload)
335    }
336}
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341
342    fn config() -> AuditConfigFingerprint {
343        AuditConfigFingerprint {
344            path: Some("fallow.toml".to_string()),
345            resolved_hash: Some("abc".to_string()),
346        }
347    }
348
349    fn context() -> AuditMaterializedContextFingerprint {
350        AuditMaterializedContextFingerprint {
351            lockfiles: Vec::new(),
352            directories: Vec::new(),
353        }
354    }
355
356    #[test]
357    fn audit_cache_key_builder_preserves_typed_fields() {
358        let coverage = AuditCoverageFingerprint {
359            path: "coverage".to_string(),
360            files: vec![AuditCoverageFileFingerprint {
361                path: "coverage/coverage-final.json".to_string(),
362                source: Some(SourceFingerprint::new(12, 34)),
363                content_hash: Some("hash".to_string()),
364                len: Some(34),
365                error: None,
366            }],
367            error: None,
368        };
369
370        let builder = AuditCacheKeyBuilder::new(
371            3,
372            "1.2.3",
373            "abc123",
374            config(),
375            vec!["src/a.ts".to_string()],
376            context(),
377        )
378        .production(true, Some(false), Some(true), None)
379        .scope(
380            Some(vec!["web".to_string()]),
381            Some("main".to_string()),
382            Some("Package".to_string()),
383            true,
384        )
385        .health(Some(42.0), Some(coverage), Some("/workspace".to_string()))
386        .styling(true, true);
387
388        let payload = builder.payload();
389        assert_eq!(payload.cache_version, 3);
390        assert_eq!(payload.base_sha, "abc123");
391        assert_eq!(payload.workspace.as_deref(), Some(&["web".to_string()][..]));
392        assert!(payload.include_entry_exports);
393        assert!(payload.css);
394        assert!(payload.css_deep);
395        assert_eq!(payload.coverage.as_ref().map(|c| c.files.len()), Some(1));
396        assert_eq!(
397            payload
398                .coverage
399                .as_ref()
400                .and_then(|c| c.files.first())
401                .and_then(|f| f.source),
402            Some(SourceFingerprint::new(12, 34))
403        );
404    }
405
406    #[test]
407    fn audit_cache_key_bytes_reflect_changed_file_order() {
408        let first = AuditCacheKeyBuilder::new(
409            1,
410            "1.0.0",
411            "base",
412            config(),
413            vec!["src/a.ts".to_string(), "src/b.ts".to_string()],
414            context(),
415        )
416        .to_json_bytes()
417        .expect("payload should serialize");
418        let second = AuditCacheKeyBuilder::new(
419            1,
420            "1.0.0",
421            "base",
422            config(),
423            vec!["src/b.ts".to_string(), "src/a.ts".to_string()],
424            context(),
425        )
426        .to_json_bytes()
427        .expect("payload should serialize");
428
429        assert_ne!(first, second);
430    }
431
432    #[test]
433    fn audit_cache_key_bytes_include_the_analysis_selection() {
434        let build = |dead_code, health, dupes, architecture: &str| {
435            AuditCacheKeyBuilder::new(
436                1,
437                "1.0.0",
438                "base",
439                config(),
440                vec!["src/a.ts".to_string()],
441                context(),
442            )
443            .analyses(dead_code, health, dupes, architecture)
444            .to_json_bytes()
445            .expect("payload should serialize")
446        };
447
448        let all = build(true, true, true, "all");
449        assert_ne!(all, build(false, true, true, "all"));
450        assert_ne!(all, build(true, false, true, "all"));
451        assert_ne!(all, build(true, true, false, "all"));
452        assert_ne!(all, build(true, true, true, "exclude"));
453    }
454
455    #[test]
456    fn audit_cache_key_bytes_include_only_a_selected_type_aware_backend() {
457        let build = |backend: Option<&str>| {
458            AuditCacheKeyBuilder::new(1, "1.0.0", "base", config(), Vec::new(), context())
459                .type_aware_backend(backend.map(str::to_string))
460                .to_json_bytes()
461                .expect("payload should serialize")
462        };
463
464        let default = build(None);
465        assert!(!String::from_utf8_lossy(&default).contains("type_aware_backend"));
466        assert_ne!(default, build(Some("tsrs")));
467    }
468
469    #[test]
470    fn audit_cache_key_bytes_include_only_an_enabled_type_aware_selection() {
471        let build = |selection: Option<AuditTypeAwareFingerprint>| {
472            AuditCacheKeyBuilder::new(1, "1.0.0", "base", config(), Vec::new(), context())
473                .type_aware(selection)
474                .to_json_bytes()
475                .expect("payload should serialize")
476        };
477        let selection = |projects: &[&str]| AuditTypeAwareFingerprint {
478            projects: projects.iter().map(|p| (*p).to_string()).collect(),
479            require: "BestEffort".to_string(),
480        };
481
482        let syntactic = build(None);
483        assert!(!String::from_utf8_lossy(&syntactic).contains("\"type_aware\""));
484        let default_projects = build(Some(selection(&[])));
485        assert_ne!(syntactic, default_projects);
486        assert_ne!(
487            default_projects,
488            build(Some(selection(&["tsconfig.app.json"])))
489        );
490    }
491
492    #[test]
493    fn audit_cache_key_bytes_include_materialized_context() {
494        let missing = context();
495        let present = AuditMaterializedContextFingerprint {
496            lockfiles: vec![AuditContextFileFingerprint {
497                path: "pnpm-lock.yaml".to_string(),
498                state: AuditContextPathState::Present,
499                source: Some(SourceFingerprint::new(1, 10)),
500                content_hash: Some("lock-hash".to_string()),
501            }],
502            directories: Vec::new(),
503        };
504        let build = |materialized_context| {
505            AuditCacheKeyBuilder::new(
506                5,
507                "1.0.0",
508                "base",
509                config(),
510                vec!["src/a.ts".to_string()],
511                materialized_context,
512            )
513            .to_json_bytes()
514            .expect("payload should serialize")
515        };
516
517        let missing_json = build(missing);
518        let present_json = build(present);
519
520        assert_ne!(missing_json, present_json);
521        assert!(
522            String::from_utf8(present_json)
523                .expect("utf8 json")
524                .contains("pnpm-lock.yaml")
525        );
526    }
527}