From 3282b05fade1de1f724121ff6859ca9b8848b7d0 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Mon, 5 Oct 2026 15:38:28 +0200 Subject: [PATCH] feat(classify): Android modules at any depth, Unity, React Native, Flutter, .NET split The classifier looked two levels deep, so an Android Studio project (app/src/main/AndroidManifest.xml) was not recognised, and a repository with an Android app, a Unity project and their generated .csproj files became a desktop app. Managed Git sets the type of its new targets from this classification, so that mattered. - Markers are collected to depth 6, skipping build output, dependencies and caches (build, .gradle, node_modules, Pods, Unity Library/Temp/Obj). - Android: a module's src/main/AndroidManifest.xml or a Gradle file applying com.android.application/library; every module is a fact (phone and tablet apps in one repository are both named). - React Native (package.json names react-native) and Flutter (sdk: flutter) are mobile apps, no longer web apps. - Unity (ProjectSettings/ProjectVersion.txt): an Android app when it has Android plugins or sits beside Android modules, otherwise a desktop app; its generated .sln/.csproj no longer count. - .NET projects are split: WPF/Windows Forms (UseWPF, UseWindowsForms, PresentationFramework, System.Windows.Forms, the WPF project type GUID) -> desktop; ASP.NET (Microsoft.NET.Sdk.Web, AspNetCore, System.Web, Web.config beside the project, the web project type GUID) and WCF (System.ServiceModel, .svc) -> backend. The kind with more projects ranks higher, and no .NET verdict outranks a clear mobile one. Refs #436. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/src/classify/language.rs | 531 ++++++++++++++++++++-- 1 file changed, 489 insertions(+), 42 deletions(-) diff --git a/compliance-agent/src/classify/language.rs b/compliance-agent/src/classify/language.rs index 9c55783..13c6541 100644 --- a/compliance-agent/src/classify/language.rs +++ b/compliance-agent/src/classify/language.rs @@ -13,8 +13,40 @@ use compliance_core::error::CoreError; use compliance_core::models::{ArtifactKind, DetectedFact, TargetType}; use compliance_core::traits::{ClassificationInput, ClassifierVerdict, TargetClassifier}; -/// Max directory depth scanned for marker files. -const SCAN_DEPTH: usize = 2; +/// Max directory depth scanned for marker files: deep enough for an Android +/// module's `app/src/main/AndroidManifest.xml` inside a monorepo folder. +const SCAN_DEPTH: usize = 6; + +/// Directories not searched: build output, installed dependencies and tool +/// caches (Unity's `Library`, `Temp`, `Obj`), which hold other projects' +/// markers. +const SKIPPED_DIRS: &[&str] = &[ + ".git", + ".gradle", + "build", + "node_modules", + "pods", + "deriveddata", + "library", + "temp", + "obj", + "logs", +]; + +/// Files whose location (relative path) is kept, for checks that need more +/// than the name: an Android module's manifest, Gradle build files, a Unity +/// project's settings. +const LOCATED_FILES: &[&str] = &[ + "androidmanifest.xml", + "build.gradle", + "build.gradle.kts", + "projectversion.txt", + "pubspec.yaml", + "web.config", +]; + +/// Extensions of files whose location is kept: .NET project files. +const LOCATED_EXTENSIONS: &[&str] = &["csproj", "vbproj"]; /// Markers collected from a code tree. #[derive(Default)] @@ -22,6 +54,9 @@ struct Markers { files: HashSet, dirs: HashSet, exts: HashSet, + /// Relative paths (`/`-separated, as on disk) of the [`LOCATED_FILES`] + /// and [`LOCATED_EXTENSIONS`]. + located: Vec, } impl Markers { @@ -34,45 +69,196 @@ impl Markers { fn any_dir_ends_with(&self, suffix: &str) -> bool { self.dirs.iter().any(|d| d.ends_with(suffix)) } -} - -/// Recursively collect marker file/dir/extension names up to [`SCAN_DEPTH`]. -fn collect_markers(root: &Path) -> Markers { - let mut m = Markers::default(); - scan_dir(root, 0, &mut m); - m -} - -fn scan_dir(dir: &Path, depth: usize, m: &mut Markers) { - let Ok(entries) = fs::read_dir(dir) else { - return; - }; - for entry in entries.flatten() { - let path = entry.path(); - let name = entry.file_name().to_string_lossy().to_lowercase(); - if path.is_dir() { - m.dirs.insert(name); - if depth < SCAN_DEPTH { - scan_dir(&path, depth + 1, m); - } - } else { - if let Some(ext) = path.extension() { - m.exts.insert(ext.to_string_lossy().to_lowercase()); - } - m.files.insert(name); - } + /// The located files whose path ends with `suffix`. + fn located_ending<'a>(&'a self, suffix: &'a str) -> impl Iterator + 'a { + self.located + .iter() + .filter(move |p| p.to_lowercase().ends_with(suffix)) } } -/// Whether a `package.json` at `root` looks like a front-end app. +/// Collect marker file/dir/extension names up to [`SCAN_DEPTH`], skipping +/// [`SKIPPED_DIRS`]. +fn collect_markers(root: &Path) -> Markers { + let mut m = Markers::default(); + let entries = walkdir::WalkDir::new(root) + .min_depth(1) + .max_depth(SCAN_DEPTH) + .into_iter() + .filter_entry(|e| { + !(e.file_type().is_dir() + && SKIPPED_DIRS.contains(&e.file_name().to_string_lossy().to_lowercase().as_str())) + }) + .filter_map(Result::ok); + for entry in entries { + let name = entry.file_name().to_string_lossy().to_lowercase(); + if entry.file_type().is_dir() { + m.dirs.insert(name); + continue; + } + if let Some(ext) = entry.path().extension() { + m.exts.insert(ext.to_string_lossy().to_lowercase()); + } + let ext = entry + .path() + .extension() + .map(|e| e.to_string_lossy().to_lowercase()) + .unwrap_or_default(); + if LOCATED_FILES.contains(&name.as_str()) || LOCATED_EXTENSIONS.contains(&ext.as_str()) { + if let Ok(rel) = entry.path().strip_prefix(root) { + m.located.push(rel.to_string_lossy().replace('\\', "/")); + } + } + m.files.insert(name); + } + m.located.sort(); + m +} + +/// The text of `rel` under `root`, if it is small enough to be a manifest. +fn read_small(root: &Path, rel: &str) -> Option { + const MAX_MANIFEST_BYTES: u64 = 256 * 1024; + let path = root.join(rel); + let size = fs::metadata(&path).ok()?.len(); + (size <= MAX_MANIFEST_BYTES) + .then(|| fs::read_to_string(&path).ok()) + .flatten() +} + +/// The mobile frameworks and app modules in a tree, beyond plain markers. +#[derive(Default)] +struct MobileShape { + /// Android application or library modules: their manifests, or Gradle + /// files applying the Android plugin. + android_modules: Vec, + react_native: bool, + flutter: bool, + /// A Unity project (`ProjectSettings/ProjectVersion.txt`). + unity: bool, + /// A Unity project with Android plugins (`Assets/Plugins/Android`). + unity_android: bool, +} + +/// How many .NET projects of each kind a tree holds. +#[derive(Default, Debug, PartialEq)] +struct DotnetShape { + /// WPF or Windows Forms applications. + desktop: usize, + /// ASP.NET (classic or Core) and WCF services. + service: usize, + /// Every project file, including libraries and tools. + projects: usize, +} + +/// Markers of a WPF or Windows Forms project, in its project file. +const DESKTOP_PROJECT_MARKERS: &[&str] = &[ + "true", + "true", + "presentationframework", + "system.windows.forms", + // The WPF project type GUID of old-style project files. + "60dc8134-eba5-43b8-bcc9-bb4bc16c2548", +]; + +/// Markers of an ASP.NET or WCF project, in its project file. +const SERVICE_PROJECT_MARKERS: &[&str] = &[ + "microsoft.net.sdk.web", + "microsoft.aspnetcore", + "system.web.mvc", + "system.web.http", + "system.servicemodel", + // The ASP.NET web application project type GUID. + "349c5851-65df-11da-9384-00065b846f21", +]; + +/// The kinds of the .NET projects under `root`. A project is a service when +/// its file names ASP.NET or WCF or a `Web.config` sits beside it, a desktop +/// app when it names WPF or Windows Forms. +fn dotnet_shape(root: &Path, m: &Markers) -> DotnetShape { + let mut shape = DotnetShape::default(); + let web_configs: Vec<&str> = m + .located_ending("web.config") + .map(|p| p.rsplit_once('/').map_or("", |(dir, _)| dir)) + .collect(); + for project in m + .located_ending(".csproj") + .chain(m.located_ending(".vbproj")) + { + shape.projects += 1; + let text = read_small(root, project).unwrap_or_default().to_lowercase(); + let dir = project.rsplit_once('/').map_or("", |(dir, _)| dir); + if SERVICE_PROJECT_MARKERS.iter().any(|k| text.contains(k)) || web_configs.contains(&dir) { + shape.service += 1; + } else if DESKTOP_PROJECT_MARKERS.iter().any(|k| text.contains(k)) { + shape.desktop += 1; + } + } + shape +} + +/// The confidence for a .NET kind found in `count` of `projects` project +/// files: the dominant kind ranks highest, and none outranks a clear mobile +/// or PLC signal (0.8). +fn dotnet_confidence(count: usize, projects: usize) -> f32 { + // Counts of project files are small; the share needs no more precision. + #[allow(clippy::cast_precision_loss)] + let share = count as f32 / projects.max(1) as f32; + 0.55 + 0.2 * share +} + +/// What kind of mobile project the tree at `root` is. +fn mobile_shape(root: &Path, m: &Markers) -> MobileShape { + let mut shape = MobileShape::default(); + for manifest in m.located_ending("androidmanifest.xml") { + // Only an app or library module's main manifest, not one under a + // test or Unity plugin folder. + let lower = manifest.to_lowercase(); + if lower.ends_with("src/main/androidmanifest.xml") || lower == "androidmanifest.xml" { + shape.android_modules.push(manifest.clone()); + } + } + for build in m + .located_ending("build.gradle") + .chain(m.located_ending("build.gradle.kts")) + { + let applies_android = read_small(root, build).is_some_and(|text| { + text.contains("com.android.application") || text.contains("com.android.library") + }); + let module = build.rsplit_once('/').map_or("", |(dir, _)| dir); + let known = shape.android_modules.iter().any(|m| m.starts_with(module)); + if applies_android && !known { + shape.android_modules.push(build.clone()); + } + } + shape.react_native = + read_small(root, "package.json").is_some_and(|text| text.contains("\"react-native\"")); + shape.flutter = m + .located_ending("pubspec.yaml") + .any(|p| read_small(root, p).is_some_and(|text| text.contains("sdk: flutter"))); + // A Unity project's root holds `ProjectSettings/ProjectVersion.txt`. + let unity_roots: Vec<&str> = m + .located_ending("projectsettings/projectversion.txt") + .map(|p| p.rsplit_once('/').map_or("", |(dir, _)| dir)) + .map(|settings| settings.rsplit_once('/').map_or("", |(dir, _)| dir)) + .collect(); + shape.unity = !unity_roots.is_empty(); + shape.unity_android = unity_roots + .iter() + .any(|unity| root.join(unity).join("Assets/Plugins/Android").is_dir()); + shape +} + +/// Whether a `package.json` at `root` looks like a front-end app. A React +/// Native app also names `react`, but it is a mobile app. fn package_json_is_frontend(root: &Path) -> bool { let Ok(content) = fs::read_to_string(root.join("package.json")) else { return false; }; let c = content.to_lowercase(); - ["react", "next", "vue", "@angular", "svelte", "vite"] - .iter() - .any(|f| c.contains(f)) + !c.contains("\"react-native\"") + && ["react", "next", "vue", "@angular", "svelte", "vite"] + .iter() + .any(|f| c.contains(f)) } /// The heuristic classifier: artifact-kind priors + source-tree markers. @@ -131,16 +317,63 @@ impl HeuristicClassifier { continue; }; let m = collect_markers(path); + let shape = mobile_shape(path, &m); // Mobile (checked first — strongest signal). - if m.has_file("androidmanifest.xml") || m.has_ext("apk") || m.has_ext("aab") { + if !shape.android_modules.is_empty() || m.has_ext("apk") || m.has_ext("aab") { + let mut facts = facts_lang("kotlin/java"); + // A repository with several apps (phone and tablet) names each. + facts.extend( + shape + .android_modules + .iter() + .take(10) + .map(|module| DetectedFact::new("android_module", module, "heuristic")), + ); out.push(verdict( TargetType::AndroidApp, 0.8, "Android manifest / gradle", - facts_lang("kotlin/java"), + facts, )); } + for (present, framework) in [ + (shape.react_native, "react-native"), + (shape.flutter, "flutter"), + ] { + if present { + let mut facts = facts_lang(if shape.flutter { "dart" } else { "javascript" }); + facts.push(DetectedFact::new("framework", framework, "heuristic")); + out.push(verdict( + TargetType::AndroidApp, + 0.75, + "cross-platform mobile app", + facts, + )); + } + } + if shape.unity { + let mut facts = facts_lang("csharp"); + facts.push(DetectedFact::new("framework", "unity", "heuristic")); + // Unity keeps the build target out of the repository; Android + // plugins in its Assets, or Android app modules beside it, are + // the sign it ships to Android. + let (target_type, confidence, why) = + if shape.unity_android || !shape.android_modules.is_empty() { + ( + TargetType::AndroidApp, + 0.8, + "Unity project with Android plugins", + ) + } else { + ( + TargetType::DesktopApp, + 0.6, + "Unity project (build target unknown)", + ) + }; + out.push(verdict(target_type, confidence, why, facts)); + } if m.any_dir_ends_with(".xcodeproj") || m.has_file("info.plist") || m.has_file("podfile") @@ -153,15 +386,39 @@ impl HeuristicClassifier { facts_lang("swift/objc"), )); } - // Desktop. - if m.has_ext("sln") - || m.has_ext("csproj") - || m.has_ext("vcxproj") - || m.has_ext("desktop") - { + // .NET, split by what each project builds. A Unity project's + // solution and C# projects are generated by the editor and say + // nothing about the product. + let dotnet = if shape.unity { + DotnetShape::default() + } else { + dotnet_shape(path, &m) + }; + if dotnet.desktop > 0 { out.push(verdict( TargetType::DesktopApp, - 0.7, + dotnet_confidence(dotnet.desktop, dotnet.projects), + "WPF / Windows Forms projects", + facts_lang("csharp"), + )); + } + if dotnet.service > 0 || m.has_ext("svc") { + out.push(verdict( + TargetType::BackendService, + dotnet_confidence(dotnet.service.max(1), dotnet.projects), + "ASP.NET / WCF projects", + facts_lang("csharp"), + )); + } + // Native desktop projects, and .NET projects of no clear kind + // (libraries, console tools). + let unclear_dotnet = dotnet.desktop == 0 + && dotnet.service == 0 + && (dotnet.projects > 0 || (!shape.unity && m.has_ext("sln"))); + if unclear_dotnet || m.has_ext("vcxproj") || m.has_ext("desktop") { + out.push(verdict( + TargetType::DesktopApp, + 0.55, "desktop project files", facts_lang("dotnet/native"), )); @@ -330,6 +587,196 @@ mod tests { assert!(v.iter().any(|x| x.target_type == TargetType::AndroidApp)); } + /// Write `files` (relative path, content) under `root`. + fn write_all(root: &Path, files: &[(&str, &str)]) { + for (rel, content) in files { + let path = root.join(rel); + fs::create_dir_all(path.parent().expect("parent")).expect("mkdir"); + fs::write(path, content).expect("write"); + } + } + + /// The verdict with the highest confidence. + fn top(verdicts: &[ClassifierVerdict]) -> TargetType { + verdicts + .iter() + .max_by(|a, b| a.confidence.total_cmp(&b.confidence)) + .map(|v| v.target_type) + .expect("a verdict") + } + + #[tokio::test] + async fn an_android_app_with_two_modules_and_a_unity_part_is_an_android_app() { + let v = classify_tree(|root| { + write_all( + root, + &[ + ("settings.gradle", "include ':phone', ':tablet'"), + ( + "phone/build.gradle", + "apply plugin: 'com.android.application'", + ), + ("phone/src/main/AndroidManifest.xml", ""), + ( + "tablet/build.gradle", + "apply plugin: 'com.android.application'", + ), + ("tablet/src/main/AndroidManifest.xml", ""), + ( + "unity/ProjectSettings/ProjectVersion.txt", + "m_EditorVersion: 2021.3.1f1", + ), + ("unity/Assets/Scripts/Pump.cs", "class Pump {}"), + ("unity/Assembly-CSharp.csproj", ""), + ( + "unity/Library/PackageCache/x/AndroidManifest.xml", + "", + ), + ], + ); + }) + .await; + assert_eq!(top(&v), TargetType::AndroidApp); + let android = v + .iter() + .find(|x| x.target_type == TargetType::AndroidApp && x.rationale.contains("manifest")) + .expect("android verdict"); + let modules: Vec<&str> = android + .facts + .iter() + .filter(|f| f.key == "android_module") + .map(|f| f.value.as_str()) + .collect(); + assert_eq!( + modules, + [ + "phone/src/main/AndroidManifest.xml", + "tablet/src/main/AndroidManifest.xml" + ] + ); + // The generated Unity C# project is not read as a desktop app. + assert!(!v.iter().any(|x| x.target_type == TargetType::DesktopApp)); + } + + #[tokio::test] + async fn a_unity_project_with_android_plugins_is_an_android_app() { + let v = classify_tree(|root| { + write_all( + root, + &[ + ( + "ProjectSettings/ProjectVersion.txt", + "m_EditorVersion: 2021.3.1f1", + ), + ("Assets/Plugins/Android/libpump.aar", ""), + ], + ); + }) + .await; + assert_eq!(top(&v), TargetType::AndroidApp); + assert!(v.iter().any(|x| x + .facts + .iter() + .any(|f| f.key == "framework" && f.value == "unity"))); + } + + #[tokio::test] + async fn a_react_native_app_is_mobile_not_a_web_app() { + let v = classify_tree(|root| { + write_all( + root, + &[ + ( + "package.json", + r#"{"dependencies":{"react":"18.2.0","react-native":"0.72.0"}}"#, + ), + ("android/app/src/main/AndroidManifest.xml", ""), + ], + ); + }) + .await; + assert_eq!(top(&v), TargetType::AndroidApp); + assert!(!v.iter().any(|x| x.target_type == TargetType::WebApp)); + } + + #[tokio::test] + async fn a_flutter_app_is_mobile() { + let v = classify_tree(|root| { + write_all( + root, + &[( + "pubspec.yaml", + "dependencies:\n flutter:\n sdk: flutter\n", + )], + ); + }) + .await; + assert!(v.iter().any(|x| x + .facts + .iter() + .any(|f| f.key == "framework" && f.value == "flutter"))); + } + + #[tokio::test] + async fn dotnet_projects_split_into_desktop_and_services_by_majority() { + let wpf = r#"{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"#; + let web = r#""#; + let wcf = r#""#; + let services = classify_tree(|root| { + write_all( + root, + &[ + ("Plant.sln", ""), + ("Plant.Client/Plant.Client.csproj", wpf), + ("Plant.Web/Plant.Web.csproj", web), + ("Plant.Web/Web.config", ""), + ("Plant.Service/Plant.Service.csproj", wcf), + ("Plant.Service/Pump.svc", ""), + ("Plant.Core/Plant.Core.csproj", ""), + ], + ); + }) + .await; + assert_eq!(top(&services), TargetType::BackendService); + assert!(services + .iter() + .any(|x| x.target_type == TargetType::DesktopApp)); + + let desktop = classify_tree(|root| { + write_all( + root, + &[ + ("Plant.Client/Plant.Client.csproj", wpf), + ( + "Plant.Tool/Plant.Tool.csproj", + "true", + ), + ], + ); + }) + .await; + assert_eq!(top(&desktop), TargetType::DesktopApp); + } + + #[tokio::test] + async fn markers_inside_build_output_and_dependencies_are_ignored() { + let v = classify_tree(|root| { + write_all( + root, + &[ + ( + "node_modules/x/android/src/main/AndroidManifest.xml", + "", + ), + ("app/build/intermediates/AndroidManifest.xml", ""), + ("Cargo.toml", "[package]\nname='x'"), + ], + ); + }) + .await; + assert!(!v.iter().any(|x| x.target_type == TargetType::AndroidApp)); + } + #[tokio::test] async fn structured_text_is_plc() { let v = classify_tree(|root| {