From 92c5df8653af8a1111ab0316bbc4e1c72aa18cca Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Sat, 5 Dec 2026 02:33:07 +0000 Subject: [PATCH 1/9] Extractor tests check presence through testing::extract Refs #373 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- packages/extractors/sdk/README.md | 5 +++++ packages/extractors/sdk/src/testing.rs | 16 +++++++++++++++- packages/extractors/sdk/src/values.rs | 5 +++-- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/packages/extractors/sdk/README.md b/packages/extractors/sdk/README.md index 6b5845975..66d0cc77a 100644 --- a/packages/extractors/sdk/README.md +++ b/packages/extractors/sdk/README.md @@ -75,6 +75,11 @@ example with tests. (and `missing_input(glob)` one that matches nothing), which `serve` writes to the extraction's `missingInputs`, so a revision from before the input was added extracts as empty rather than failing; + - `subject_exists(path)` and `subject_matches(glob, files)`: the same for an + anchor of what the projection describes; `serve` writes `presence`, + `absent` when no anchor checked exists and `present` otherwise. Built-ins + check their subject with these, keep `input_exists` for auxiliary inputs, + and write `presence` themselves on paths that check no anchor; - `scope()`: the scope the runner enforces, if any; - `checkout()`: where the project's installed packages are for this run (absent under container isolation and for Git objects); diff --git a/packages/extractors/sdk/src/testing.rs b/packages/extractors/sdk/src/testing.rs index d85a91801..88f15763d 100644 --- a/packages/extractors/sdk/src/testing.rs +++ b/packages/extractors/sdk/src/testing.rs @@ -87,9 +87,23 @@ impl Process { } } +/// What `collect` returns for `cx` as a runner receives it, with the missing +/// inputs and `presence` [`Context::finish`] adds, as [`crate::serve`] does. +pub fn extract(cx: &Context, collect: impl FnOnce(&Context) -> anyhow::Result) -> anyhow::Result { + collect(cx).and_then(|extraction| cx.finish(extraction)) +} + /// Compares `actual` with the JSON golden file, rewriting it when -/// `PROJECTIONS_UPDATE_GOLDEN=1`. +/// `PROJECTIONS_UPDATE_GOLDEN=1`. An extraction must report its `presence`, as +/// every built-in does on every path. pub fn golden(path: &Path, actual: &Value) { + if actual.get("protocolVersion").is_some() { + assert!( + matches!(actual["presence"].as_str(), Some("present" | "absent")), + "{} doesn't report presence; built-ins write it on every path (see testing::extract)", + path.display() + ); + } let rendered = format!("{}\n", serde_json::to_string_pretty(actual).unwrap()); if std::env::var("PROJECTIONS_UPDATE_GOLDEN").as_deref() == Ok("1") { fs::write(path, &rendered).unwrap(); diff --git a/packages/extractors/sdk/src/values.rs b/packages/extractors/sdk/src/values.rs index dcba00196..b390dbae3 100644 --- a/packages/extractors/sdk/src/values.rs +++ b/packages/extractors/sdk/src/values.rs @@ -159,10 +159,11 @@ pub fn database_extraction(value: Value) -> Result { /// Reads `inputs.snapshot` as a pre-exported `database/v0` extraction. A /// revision without the snapshot (before it was added) has an empty schema, and -/// the snapshot is recorded as a missing input. +/// the snapshot is recorded as a missing input that makes the subject absent +/// ([`crate::Context::subject_exists`]). pub fn pre_exported_schema(cx: &crate::Context, definition: &Value) -> Result { let filename = input(definition, "snapshot", None)?; - let mut value = if cx.input_exists(filename)? { + let mut value = if cx.subject_exists(filename)? { database_extraction(cx.read_json(filename)?)? } else { extraction("database/v0", vec![], vec![], None) From 76e5fcfd9e89bb1806c7f04d84d61eee58eb6820 Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Sat, 5 Dec 2026 02:33:16 +0000 Subject: [PATCH 2/9] Built-in extractors report their subject's presence Refs #373 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- Cargo.lock | 2 + packages/extractors/azure-what-if/src/lib.rs | 2 +- .../extractors/azure-what-if/src/native.rs | 2 +- .../tests/fixtures/base/expected.json | 1 + .../tests/fixtures/head/expected.json | 1 + .../extractors/azure-what-if/tests/what_if.rs | 7 ++- .../extractors/cargo-dependencies/src/lib.rs | 2 +- .../extractors/code-statistics/src/lib.rs | 5 +- .../tests/fixtures/options/expected.json | 1 + .../tests/fixtures/polyglot/expected.json | 1 + .../code-statistics/tests/golden.rs | 2 +- packages/extractors/command-output/src/lib.rs | 7 ++- packages/extractors/django-schema/Cargo.toml | 4 ++ packages/extractors/django-schema/src/lib.rs | 54 ++++++++++++++++++- packages/extractors/dotnet-support/src/lib.rs | 6 +-- .../extractors/github-actions-jobs/src/lib.rs | 2 +- .../github-actions-jobs/tests/extractions.rs | 16 +++++- .../fixtures/delivery/absent.expected.json | 17 ++++++ .../fixtures/delivery/after.expected.json | 1 + .../fixtures/delivery/before.expected.json | 1 + .../tests/fixtures/many/after.expected.json | 1 + .../tests/fixtures/many/before.expected.json | 1 + .../tests/fixtures/matrix/after.expected.json | 1 + .../fixtures/matrix/before.expected.json | 1 + .../fixtures/pipeline/after.expected.json | 1 + .../fixtures/pipeline/before.expected.json | 1 + .../fixtures/release/after.expected.json | 1 + .../fixtures/release/before.expected.json | 1 + .../tests/fixtures/wide/after.expected.json | 1 + .../tests/fixtures/wide/before.expected.json | 1 + .../github-agentic-workflows/src/lib.rs | 28 +++++++--- .../tests/extractions.rs | 19 ++++++- .../fixtures/docs-bot/after.expected.json | 1 + .../fixtures/docs-bot/before.expected.json | 1 + .../tests/fixtures/public/expected.json | 1 + .../fixtures/repo-ask/after.expected.json | 1 + .../fixtures/repo-ask/before.expected.json | 1 + packages/extractors/go-public-api/src/lib.rs | 28 +++++++--- packages/extractors/nestjs-di/src/lib.rs | 15 ++++-- .../extractors/nuget-dependencies/src/lib.rs | 25 ++++++--- .../openrewrite-data-tables/src/lib.rs | 7 ++- .../junit5-migration/after.expected.json | 1 + .../junit5-migration/before.expected.json | 1 + .../tests/migration.rs | 2 +- packages/extractors/prisma-schema/src/lib.rs | 13 +++-- .../extractors/prisma-schema/tests/prisma.rs | 14 ++++- packages/extractors/rails-routes/src/lib.rs | 12 +++-- packages/extractors/rails-schema/src/lib.rs | 15 +++++- .../extractors/renderer-scenarios/src/lib.rs | 2 + packages/extractors/repository-map/src/lib.rs | 5 +- .../extractors/rust-public-api/src/lib.rs | 26 ++++++--- .../scip-file-references/src/lib.rs | 9 ++-- packages/extractors/spring-di/src/lib.rs | 4 +- .../swift-package-dependencies/src/lib.rs | 2 +- .../tests/fixtures/harbor.expected.json | 1 + .../tests/package.rs | 2 +- .../extractors/swift-public-api/src/lib.rs | 2 +- .../extractors/swift-public-api/src/tests.rs | 2 +- .../compatibility/after.expected.json | 1 + .../package.expected.json | 1 + .../terraform-infrastructure/src/lib.rs | 2 +- .../terraform-infrastructure/src/native.rs | 4 +- .../tests/fixtures/aws/base.expected.json | 1 + .../tests/fixtures/aws/head.expected.json | 1 + .../tests/terraform.rs | 8 ++- .../extractors/terraform-modules/src/lib.rs | 2 + .../fixtures/network/after.expected.json | 1 + .../fixtures/network/before.expected.json | 1 + .../terraform-modules/tests/modules.rs | 4 +- .../extractors/tetragon-policies/src/lib.rs | 2 +- .../tetragon-policies/src/sources.rs | 42 +++++++++++---- .../tetragon-policies/tests/extractions.rs | 32 ++++++++++- .../fixtures/credentials/after.expected.json | 1 + .../fixtures/credentials/before.expected.json | 1 + .../credentials/monitor.expected.json | 1 + .../fixtures/deployment/after.expected.json | 1 + .../fixtures/deployment/before.expected.json | 1 + .../tests/fixtures/library/expected.json | 1 + .../tests/fixtures/skipped/expected.json | 1 + .../typescript-public-api/src/lib.rs | 7 ++- .../extractors/typescript-support/src/lib.rs | 5 +- .../workspace-dependencies/src/lib.rs | 2 +- .../tests/fixtures/bun.expected.json | 1 + .../tests/fixtures/npm.expected.json | 1 + .../tests/fixtures/pnpm-catalog.expected.json | 1 + .../tests/fixtures/pnpm.expected.json | 1 + .../tests/fixtures/yarn-berry.expected.json | 1 + .../tests/fixtures/yarn-classic.expected.json | 1 + .../workspace-dependencies/tests/managers.rs | 2 +- packages/extractors/xcode-modules/src/lib.rs | 8 +-- .../tests/fixtures/harbor-app.expected.json | 1 + .../extractors/xcode-modules/tests/project.rs | 2 +- .../renderers/graph/fixtures/azure-after.json | 1 + .../graph/fixtures/azure-before.json | 1 + .../graph/fixtures/terraform-after.json | 1 + .../graph/fixtures/terraform-before.json | 1 + .../fixtures/terraform-modules-after.json | 1 + .../fixtures/terraform-modules-before.json | 1 + 98 files changed, 429 insertions(+), 103 deletions(-) create mode 100644 packages/extractors/github-actions-jobs/tests/fixtures/delivery/absent.expected.json diff --git a/Cargo.lock b/Cargo.lock index b69a7377a..cc35168e0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1582,6 +1582,7 @@ dependencies = [ "projections-extractor-workspace-dependencies", "projections-extractor-xcode-modules", "serde_json", + "tempfile", ] [[package]] @@ -1612,6 +1613,7 @@ dependencies = [ "anyhow", "projections-extractor-sdk", "serde_json", + "tempfile", ] [[package]] diff --git a/packages/extractors/azure-what-if/src/lib.rs b/packages/extractors/azure-what-if/src/lib.rs index f89ef4fba..442b60d83 100644 --- a/packages/extractors/azure-what-if/src/lib.rs +++ b/packages/extractors/azure-what-if/src/lib.rs @@ -74,7 +74,7 @@ fn extract(cx: &Context) -> Result { let absent = json!({"status": "Succeeded", "changes": []}); let (result, template) = if inputs.get("whatIfJsonPath").is_some() { let file = input(definition, "whatIfJsonPath", None)?; - if !cx.input_exists(file)? { + if !cx.subject_exists(file)? { return infrastructure(&absent, None); } let template = match inputs.get("templateJsonPath") { diff --git a/packages/extractors/azure-what-if/src/native.rs b/packages/extractors/azure-what-if/src/native.rs index 6d138d92d..fed258f38 100644 --- a/packages/extractors/azure-what-if/src/native.rs +++ b/packages/extractors/azure-what-if/src/native.rs @@ -12,7 +12,7 @@ pub(crate) fn native(root: &Path, d: &Value, cx: &Context) -> Result String { fn extract(inputs: Value) -> anyhow::Result { let root = fixtures(); let definition = json!({"id":"azure","extractor":"azure-what-if","inputs":inputs}); - let extraction = collect(&Process::new(&root).context(&root, Value::clone(&definition)).with_files(vec![]))?; + let extraction = testing::extract( + &Process::new(&root).context(&root, Value::clone(&definition)).with_files(vec![]), + collect, + )?; projections_engine::normalize(&extraction, "").unwrap(); Ok(extraction) } diff --git a/packages/extractors/cargo-dependencies/src/lib.rs b/packages/extractors/cargo-dependencies/src/lib.rs index 26e5b7b81..5cbb44999 100644 --- a/packages/extractors/cargo-dependencies/src/lib.rs +++ b/packages/extractors/cargo-dependencies/src/lib.rs @@ -43,7 +43,7 @@ fn cargo(root: &Path, d: &Value, cx: &Context) -> Result { None => input(d, "manifestPath", Some("Cargo.toml"))?, }; // A revision without the declared metadata or manifest (before it was added) has no packages. - if !cx.input_exists(declared)? { + if !cx.subject_exists(declared)? { return Ok(extraction( "graph/v0", vec![], diff --git a/packages/extractors/code-statistics/src/lib.rs b/packages/extractors/code-statistics/src/lib.rs index cfe1570b2..65d119d3c 100644 --- a/packages/extractors/code-statistics/src/lib.rs +++ b/packages/extractors/code-statistics/src/lib.rs @@ -75,7 +75,10 @@ pub fn requires_trust(_inputs: &Value) -> bool { } pub fn collect(cx: &Context) -> Result { - statistics(cx, cx.files()?, cx.definition()) + let mut extraction = statistics(cx, cx.files()?, cx.definition())?; + // The repository is what it describes, so it is always present. + extraction["presence"] = json!("present"); + Ok(extraction) } /// The language tokei assigns a path by filename or extension. diff --git a/packages/extractors/code-statistics/tests/fixtures/options/expected.json b/packages/extractors/code-statistics/tests/fixtures/options/expected.json index 1c7e3a5e5..2824ffa17 100644 --- a/packages/extractors/code-statistics/tests/fixtures/options/expected.json +++ b/packages/extractors/code-statistics/tests/fixtures/options/expected.json @@ -103,6 +103,7 @@ "unrecognized": 0 } }, + "presence": "present", "protocolVersion": 0, "relationships": [], "schema": "metrics/v0" diff --git a/packages/extractors/code-statistics/tests/fixtures/polyglot/expected.json b/packages/extractors/code-statistics/tests/fixtures/polyglot/expected.json index b16009f92..76c469d49 100644 --- a/packages/extractors/code-statistics/tests/fixtures/polyglot/expected.json +++ b/packages/extractors/code-statistics/tests/fixtures/polyglot/expected.json @@ -339,6 +339,7 @@ "unrecognized": 2 } }, + "presence": "present", "protocolVersion": 0, "relationships": [], "schema": "metrics/v0" diff --git a/packages/extractors/code-statistics/tests/golden.rs b/packages/extractors/code-statistics/tests/golden.rs index 8e93d6ceb..466220af0 100644 --- a/packages/extractors/code-statistics/tests/golden.rs +++ b/packages/extractors/code-statistics/tests/golden.rs @@ -14,7 +14,7 @@ fn case(name: &str) -> Value { .map(|text| serde_json::from_str(&text).unwrap()) .unwrap_or_else(|_| json!({})); let definition = json!({"id":"statistics","extractor":"code-statistics","inputs":inputs}); - let extraction = collect(&testing::context(&root, definition)).unwrap(); + let extraction = testing::extract(&testing::context(&root, definition), collect).unwrap(); golden(&directory.join("expected.json"), &extraction); extraction } diff --git a/packages/extractors/command-output/src/lib.rs b/packages/extractors/command-output/src/lib.rs index 60f2717b6..1cf417e5e 100644 --- a/packages/extractors/command-output/src/lib.rs +++ b/packages/extractors/command-output/src/lib.rs @@ -87,11 +87,14 @@ pub fn collect(cx: &Context) -> Result { nodes.push(json!({"id":format!("output:{id}"),"kind":"output","label":label, "data":{"text":output,"presentation":presentation},"confidence":"authoritative"})); } - Ok(extraction( + let mut extraction = extraction( "graph/v0", nodes, vec![], Some(json!({"source":"CLI stdout", "limitations":["Command output may depend on external state or tool versions; run in a pinned, trusted environment."]})), - )) + ); + // What the commands print is what it describes: always present, even when empty. + extraction["presence"] = json!("present"); + Ok(extraction) } diff --git a/packages/extractors/django-schema/Cargo.toml b/packages/extractors/django-schema/Cargo.toml index 3b3a9ae02..e1c60714b 100644 --- a/packages/extractors/django-schema/Cargo.toml +++ b/packages/extractors/django-schema/Cargo.toml @@ -10,3 +10,7 @@ rust-version.workspace = true anyhow = "1" projections-extractor-sdk = { path = "../sdk" } serde_json = { version = "1", features = ["float_roundtrip"] } + +[dev-dependencies] +projections-extractor-sdk = { path = "../sdk", features = ["testing"] } +tempfile = "3" diff --git a/packages/extractors/django-schema/src/lib.rs b/packages/extractors/django-schema/src/lib.rs index 8e4b9f451..764fa3092 100644 --- a/packages/extractors/django-schema/src/lib.rs +++ b/packages/extractors/django-schema/src/lib.rs @@ -4,7 +4,7 @@ use anyhow::{Result, ensure}; use projections_extractor_sdk::{ - Context, Descriptor, Trust, database_extraction, execute, input, parse_json, pre_exported_schema, strings, + Context, Descriptor, Trust, database_extraction, execute, extraction, input, parse_json, pre_exported_schema, strings, }; use serde_json::{Value, json}; use std::path::Path; @@ -56,6 +56,12 @@ pub fn collect(cx: &Context) -> Result { env.get("DJANGO_SETTINGS_MODULE").is_some_and(|s| !s.trim().is_empty()), "Django requires inputs.settings or an explicitly supplied DJANGO_SETTINGS_MODULE environment variable" ); + // A revision without the settings module (before the project was added) has no + // schema. Its file may be anywhere Python could import it from (a `src/` + // layout, beside `manage.py`), so only a revision with none anywhere lacks it. + if !settings_exist(cx, env["DJANGO_SETTINGS_MODULE"].trim())? { + return Ok(extraction("database/v0", vec![], vec![], None)); + } let helper = cx.helper( "helpers/python/django_schema.py", Path::new(env!("CARGO_MANIFEST_DIR")).join("helper").join("django_schema.py"), @@ -72,3 +78,49 @@ pub fn collect(cx: &Context) -> Result { )?; database_extraction(parse_json(&output)?) } + +/// Whether the revision has a file that could be the settings `module`: a +/// `.py` or `/__init__.py` at any depth. Those that +/// match are the anchors; with neither, both are missing. +fn settings_exist(cx: &Context, module: &str) -> Result { + let path = module.replace('.', "/"); + let patterns = [format!("**/{path}.py"), format!("**/{path}/__init__.py")]; + let files = cx.files()?; + let matching: Vec<&String> = patterns + .iter() + .filter(|pattern| projections_extractor_sdk::glob(pattern).is_ok_and(|glob| files.iter().any(|file| glob.is_match(file)))) + .collect(); + let mut found = false; + for pattern in if matching.is_empty() { patterns.iter().collect() } else { matching } { + found |= cx.subject_matches(pattern, files)?; + } + Ok(found) +} + +#[cfg(test)] +mod tests { + use super::*; + use projections_extractor_sdk::testing; + use std::fs; + + #[test] + fn a_revision_without_the_settings_module_is_absent_and_runs_nothing() { + let root = tempfile::tempdir().unwrap(); + let root = root.path().canonicalize().unwrap(); + let definition = json!({"id": "schema", "extractor": ID, "inputs": {"settings": "shop.settings"}}); + // The context's tools are missing, so reaching Python would fail. + let extraction = testing::extract(&testing::trusted(&root, definition.clone()), collect).unwrap(); + assert_eq!(extraction["presence"], "absent"); + assert_eq!( + extraction["missingInputs"], + json!(["**/shop/settings.py", "**/shop/settings/__init__.py"]) + ); + projections_extractor_sdk::normalize_extraction(&extraction).unwrap(); + // A package of settings in a `src/` layout is there: Python runs. + fs::create_dir_all(root.join("src/shop/settings")).unwrap(); + fs::write(root.join("src/shop/settings/__init__.py"), "").unwrap(); + let cx = testing::trusted(&root, definition); + assert!(settings_exist(&cx, "shop.settings").unwrap()); + assert!(cx.missing_inputs().is_empty()); + } +} diff --git a/packages/extractors/dotnet-support/src/lib.rs b/packages/extractors/dotnet-support/src/lib.rs index 12e4fc375..12b35bcc0 100644 --- a/packages/extractors/dotnet-support/src/lib.rs +++ b/packages/extractors/dotnet-support/src/lib.rs @@ -80,7 +80,7 @@ pub fn collect(cx: &Context, contract: &Contract) -> Result { let absent = || parse(extraction(contract.schema, vec![], vec![], None)); if d["inputs"].get("snapshot").is_some() { let snapshot = input(d, "snapshot", None)?; - if !cx.input_exists(snapshot)? { + if !cx.subject_exists(snapshot)? { return absent(); } return parse(read_json(root, snapshot)?); @@ -89,7 +89,7 @@ pub fn collect(cx: &Context, contract: &Contract) -> Result { // Validates inputs.dotnet before anything else runs. Dotnet::executable(cx)?; let configuration = input(d, "configuration", Some("Release"))?; - if d["inputs"].get("project").is_some() && !cx.input_exists(input(d, "project", None)?)? { + if d["inputs"].get("project").is_some() && !cx.subject_exists(input(d, "project", None)?)? { return absent(); } let project = d["inputs"] @@ -104,7 +104,7 @@ pub fn collect(cx: &Context, contract: &Contract) -> Result { if project.is_some() { relative_path(assembly)?; } else { - if !cx.input_exists(assembly)? { + if !cx.subject_exists(assembly)? { return absent(); } path(root, assembly, false, false)?; diff --git a/packages/extractors/github-actions-jobs/src/lib.rs b/packages/extractors/github-actions-jobs/src/lib.rs index 0d9f761e8..127fe90b7 100644 --- a/packages/extractors/github-actions-jobs/src/lib.rs +++ b/packages/extractors/github-actions-jobs/src/lib.rs @@ -41,7 +41,7 @@ pub fn collect(cx: &Context) -> Result { "limitations":["Declaration graph only: a matrix expands and its values fill names and runners, but other expressions, reusable workflows' own jobs, conditions and runtime scheduling are not evaluated."] }); // A revision without the workflow (before it was added) has no jobs. - if !cx.input_exists(path)? { + if !cx.subject_exists(path)? { return Ok(extraction("dag/v0", vec![], vec![], Some(metadata))); } let yaml = cx.read_source(path)?; diff --git a/packages/extractors/github-actions-jobs/tests/extractions.rs b/packages/extractors/github-actions-jobs/tests/extractions.rs index db0113dd2..5eac0a3de 100644 --- a/packages/extractors/github-actions-jobs/tests/extractions.rs +++ b/packages/extractors/github-actions-jobs/tests/extractions.rs @@ -17,7 +17,7 @@ fn case(name: &str, side: &str) -> Value { let inputs: Value = serde_json::from_str(&fs::read_to_string(directory.join("inputs.json")).unwrap()).unwrap(); let root = directory.join(side).canonicalize().unwrap(); let definition = json!({"id": "jobs", "extractor": "github-actions-jobs", "inputs": inputs}); - let extraction = collect(&testing::context(&root, definition)).unwrap(); + let extraction = testing::extract(&testing::context(&root, definition), collect).unwrap(); golden(&directory.join(format!("{side}.expected.json")), &extraction); let request = json!({"version": 0, "operation": "normalize", "extraction": extraction}); let response = projections_engine::handle(request.to_string().as_bytes()); @@ -168,3 +168,17 @@ fn a_workflow_of_many_jobs_gains_one() { }; assert_eq!((jobs("before"), jobs("after")), (21, 22)); } + +#[test] +fn a_revision_without_the_workflow_has_no_jobs_and_names_it_missing() { + // The fixtures directory has no `.github`: a revision from before the workflow was added. + let inputs = json!({"workflowPath": ".github/workflows/delivery.yml"}); + let definition = json!({"id": "jobs", "extractor": "github-actions-jobs", "inputs": inputs}); + let extraction = testing::extract(&testing::context(&fixtures().canonicalize().unwrap(), definition), collect).unwrap(); + golden(&fixtures().join("delivery/absent.expected.json"), &extraction); + assert_eq!(extraction["presence"], "absent"); + assert_eq!(extraction["entities"], json!([])); + assert_eq!(extraction["missingInputs"], json!([".github/workflows/delivery.yml"])); + let request = json!({"version": 0, "operation": "normalize", "extraction": extraction}); + assert_eq!(projections_engine::handle(request.to_string().as_bytes())["ok"], true); +} diff --git a/packages/extractors/github-actions-jobs/tests/fixtures/delivery/absent.expected.json b/packages/extractors/github-actions-jobs/tests/fixtures/delivery/absent.expected.json new file mode 100644 index 000000000..84c0c98b7 --- /dev/null +++ b/packages/extractors/github-actions-jobs/tests/fixtures/delivery/absent.expected.json @@ -0,0 +1,17 @@ +{ + "entities": [], + "metadata": { + "limitations": [ + "Declaration graph only: a matrix expands and its values fill names and runners, but other expressions, reusable workflows' own jobs, conditions and runtime scheduling are not evaluated." + ], + "source": "GitHub Actions workflow declaration", + "workflow": ".github/workflows/delivery.yml" + }, + "missingInputs": [ + ".github/workflows/delivery.yml" + ], + "presence": "absent", + "protocolVersion": 0, + "relationships": [], + "schema": "dag/v0" +} diff --git a/packages/extractors/github-actions-jobs/tests/fixtures/delivery/after.expected.json b/packages/extractors/github-actions-jobs/tests/fixtures/delivery/after.expected.json index 5658bf2b4..98144165f 100644 --- a/packages/extractors/github-actions-jobs/tests/fixtures/delivery/after.expected.json +++ b/packages/extractors/github-actions-jobs/tests/fixtures/delivery/after.expected.json @@ -148,6 +148,7 @@ "source": "GitHub Actions workflow declaration", "workflow": ".github/workflows/delivery.yml" }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/github-actions-jobs/tests/fixtures/delivery/before.expected.json b/packages/extractors/github-actions-jobs/tests/fixtures/delivery/before.expected.json index 41def8042..2d50a3393 100644 --- a/packages/extractors/github-actions-jobs/tests/fixtures/delivery/before.expected.json +++ b/packages/extractors/github-actions-jobs/tests/fixtures/delivery/before.expected.json @@ -120,6 +120,7 @@ "source": "GitHub Actions workflow declaration", "workflow": ".github/workflows/delivery.yml" }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/github-actions-jobs/tests/fixtures/many/after.expected.json b/packages/extractors/github-actions-jobs/tests/fixtures/many/after.expected.json index 0ca8a1f36..5e5290158 100644 --- a/packages/extractors/github-actions-jobs/tests/fixtures/many/after.expected.json +++ b/packages/extractors/github-actions-jobs/tests/fixtures/many/after.expected.json @@ -883,6 +883,7 @@ "source": "GitHub Actions workflow declaration", "workflow": ".github/workflows/ci.yml" }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/github-actions-jobs/tests/fixtures/many/before.expected.json b/packages/extractors/github-actions-jobs/tests/fixtures/many/before.expected.json index ed9910eb9..7c82ac4dd 100644 --- a/packages/extractors/github-actions-jobs/tests/fixtures/many/before.expected.json +++ b/packages/extractors/github-actions-jobs/tests/fixtures/many/before.expected.json @@ -855,6 +855,7 @@ "source": "GitHub Actions workflow declaration", "workflow": ".github/workflows/ci.yml" }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/github-actions-jobs/tests/fixtures/matrix/after.expected.json b/packages/extractors/github-actions-jobs/tests/fixtures/matrix/after.expected.json index 1db53c8cd..f9c5a9fa5 100644 --- a/packages/extractors/github-actions-jobs/tests/fixtures/matrix/after.expected.json +++ b/packages/extractors/github-actions-jobs/tests/fixtures/matrix/after.expected.json @@ -235,6 +235,7 @@ "source": "GitHub Actions workflow declaration", "workflow": ".github/workflows/build.yml" }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/github-actions-jobs/tests/fixtures/matrix/before.expected.json b/packages/extractors/github-actions-jobs/tests/fixtures/matrix/before.expected.json index 641089a0f..439773238 100644 --- a/packages/extractors/github-actions-jobs/tests/fixtures/matrix/before.expected.json +++ b/packages/extractors/github-actions-jobs/tests/fixtures/matrix/before.expected.json @@ -388,6 +388,7 @@ "source": "GitHub Actions workflow declaration", "workflow": ".github/workflows/build.yml" }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/github-actions-jobs/tests/fixtures/pipeline/after.expected.json b/packages/extractors/github-actions-jobs/tests/fixtures/pipeline/after.expected.json index d38bc1611..0858c81f0 100644 --- a/packages/extractors/github-actions-jobs/tests/fixtures/pipeline/after.expected.json +++ b/packages/extractors/github-actions-jobs/tests/fixtures/pipeline/after.expected.json @@ -402,6 +402,7 @@ "source": "GitHub Actions workflow declaration", "workflow": ".github/workflows/release.yml" }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/github-actions-jobs/tests/fixtures/pipeline/before.expected.json b/packages/extractors/github-actions-jobs/tests/fixtures/pipeline/before.expected.json index 50411d90b..1beddb2af 100644 --- a/packages/extractors/github-actions-jobs/tests/fixtures/pipeline/before.expected.json +++ b/packages/extractors/github-actions-jobs/tests/fixtures/pipeline/before.expected.json @@ -306,6 +306,7 @@ "source": "GitHub Actions workflow declaration", "workflow": ".github/workflows/release.yml" }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/github-actions-jobs/tests/fixtures/release/after.expected.json b/packages/extractors/github-actions-jobs/tests/fixtures/release/after.expected.json index ae054f674..4c5b9e2d9 100644 --- a/packages/extractors/github-actions-jobs/tests/fixtures/release/after.expected.json +++ b/packages/extractors/github-actions-jobs/tests/fixtures/release/after.expected.json @@ -402,6 +402,7 @@ "source": "GitHub Actions workflow declaration", "workflow": ".github/workflows/release.yml" }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/github-actions-jobs/tests/fixtures/release/before.expected.json b/packages/extractors/github-actions-jobs/tests/fixtures/release/before.expected.json index 3589dce90..f4af74080 100644 --- a/packages/extractors/github-actions-jobs/tests/fixtures/release/before.expected.json +++ b/packages/extractors/github-actions-jobs/tests/fixtures/release/before.expected.json @@ -368,6 +368,7 @@ "source": "GitHub Actions workflow declaration", "workflow": ".github/workflows/release.yml" }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/github-actions-jobs/tests/fixtures/wide/after.expected.json b/packages/extractors/github-actions-jobs/tests/fixtures/wide/after.expected.json index c70dbc453..7418f191b 100644 --- a/packages/extractors/github-actions-jobs/tests/fixtures/wide/after.expected.json +++ b/packages/extractors/github-actions-jobs/tests/fixtures/wide/after.expected.json @@ -434,6 +434,7 @@ "source": "GitHub Actions workflow declaration", "workflow": ".github/workflows/ci.yml" }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/github-actions-jobs/tests/fixtures/wide/before.expected.json b/packages/extractors/github-actions-jobs/tests/fixtures/wide/before.expected.json index 3877235ff..952159ec7 100644 --- a/packages/extractors/github-actions-jobs/tests/fixtures/wide/before.expected.json +++ b/packages/extractors/github-actions-jobs/tests/fixtures/wide/before.expected.json @@ -500,6 +500,7 @@ "source": "GitHub Actions workflow declaration", "workflow": ".github/workflows/ci.yml" }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/github-agentic-workflows/src/lib.rs b/packages/extractors/github-agentic-workflows/src/lib.rs index dbe7de979..d9d7358e0 100644 --- a/packages/extractors/github-agentic-workflows/src/lib.rs +++ b/packages/extractors/github-agentic-workflows/src/lib.rs @@ -21,7 +21,9 @@ mod triggers; mod workflow; use anyhow::{Context as _, Result}; -use projections_extractor_sdk::{Access, Context, Descriptor, Determinism, Trust, extraction, globs, relationship, unique_relationships}; +use projections_extractor_sdk::{ + Access, Context, Descriptor, Determinism, Trust, extraction, globs, relationship, strings, unique_relationships, +}; use serde_json::{Value, json}; use std::collections::BTreeMap; use workflow::{Kind, classify, stem}; @@ -64,19 +66,31 @@ pub fn collect(cx: &Context) -> Result { Ok(extraction) } -/// The workflow files the inputs select, in path order. +/// The workflow files the inputs select, in path order. Its globs are the +/// anchors of the extraction's subject: one that selects none of them is +/// missing, and with every one missing (before the first workflow was added) +/// the workflows are absent. fn workflow_files(cx: &Context, inputs: &Value) -> Result> { - let paths = match inputs.get("paths").filter(|paths| !paths.is_null()) { - Some(paths) => globs(Some(paths), "inputs.paths")?, - None => globs(Some(&json!(DEFAULT_PATHS)), "paths")?, + let patterns = match inputs.get("paths").filter(|paths| !paths.is_null()) { + Some(paths) => strings(paths, "inputs.paths")?, + None => DEFAULT_PATHS.iter().map(|pattern| (*pattern).to_owned()).collect(), }; + anyhow::ensure!(!patterns.is_empty(), "inputs.paths must name at least one glob"); let exclude = globs(inputs.get("exclude").filter(|exclude| !exclude.is_null()), "inputs.exclude")?; - Ok(cx + let candidates: Vec = cx .files()? .iter() .filter(|file| file.ends_with(".md") && !stem(file).eq_ignore_ascii_case("readme")) - .filter(|file| paths.iter().any(|glob| glob.is_match(file)) && !exclude.iter().any(|glob| glob.is_match(file))) + .filter(|file| !exclude.iter().any(|glob| glob.is_match(file))) .cloned() + .collect(); + for pattern in &patterns { + cx.subject_matches(pattern, &candidates)?; + } + let paths = globs(Some(&json!(patterns)), "inputs.paths")?; + Ok(candidates + .into_iter() + .filter(|file| paths.iter().any(|glob| glob.is_match(file))) .collect()) } diff --git a/packages/extractors/github-agentic-workflows/tests/extractions.rs b/packages/extractors/github-agentic-workflows/tests/extractions.rs index a21011a02..0bfecc92f 100644 --- a/packages/extractors/github-agentic-workflows/tests/extractions.rs +++ b/packages/extractors/github-agentic-workflows/tests/extractions.rs @@ -15,7 +15,7 @@ fn fixtures() -> PathBuf { fn extract(root: &Path, inputs: Value) -> anyhow::Result { let root = root.canonicalize().unwrap(); let definition = json!({"id": "agentic-workflows", "extractor": "github-agentic-workflows", "inputs": inputs}); - collect(&testing::context(&root, definition)) + testing::extract(&testing::context(&root, definition), collect) } /// The Engine accepts the extraction: identities, endpoints, vocabulary and domain rules. @@ -199,3 +199,20 @@ fn unknown_and_renamed_fields_are_reported_and_extraction_is_deterministic() { json!({"field": "hologram", "value": {"limit": 2}}) ); } + +#[test] +fn a_revision_without_workflows_is_absent_and_names_the_globs_that_select_none() { + // The fixtures directory has no `.github/workflows`: a revision before the first workflow was added. + let absent = extract(&fixtures(), json!({})).unwrap(); + assert_eq!(absent["presence"], "absent"); + assert_eq!(absent["entities"], json!([])); + assert_eq!(absent["missingInputs"], json!([".github/workflows/*.md"])); + normalize(&absent); + // With some workflows, a glob that selects none is named but the workflows are present. + let root = fixtures().join("docs-bot/after"); + let partial = extract(&root, json!({"paths": [".github/workflows/*.md", "agents/*.md"]})).unwrap(); + assert_eq!(partial["presence"], "present"); + assert_eq!(partial["missingInputs"], json!(["agents/*.md"])); + assert!(!partial["entities"].as_array().unwrap().is_empty()); + assert!(extract(&root, json!({"paths": []})).is_err()); +} diff --git a/packages/extractors/github-agentic-workflows/tests/fixtures/docs-bot/after.expected.json b/packages/extractors/github-agentic-workflows/tests/fixtures/docs-bot/after.expected.json index 83c9d62d5..6d412fd6f 100644 --- a/packages/extractors/github-agentic-workflows/tests/fixtures/docs-bot/after.expected.json +++ b/packages/extractors/github-agentic-workflows/tests/fixtures/docs-bot/after.expected.json @@ -732,6 +732,7 @@ ], "workflows": 5 }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/github-agentic-workflows/tests/fixtures/docs-bot/before.expected.json b/packages/extractors/github-agentic-workflows/tests/fixtures/docs-bot/before.expected.json index 8fe082d7e..c6556aa0f 100644 --- a/packages/extractors/github-agentic-workflows/tests/fixtures/docs-bot/before.expected.json +++ b/packages/extractors/github-agentic-workflows/tests/fixtures/docs-bot/before.expected.json @@ -603,6 +603,7 @@ ], "workflows": 4 }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/github-agentic-workflows/tests/fixtures/public/expected.json b/packages/extractors/github-agentic-workflows/tests/fixtures/public/expected.json index 8674bacda..06db46908 100644 --- a/packages/extractors/github-agentic-workflows/tests/fixtures/public/expected.json +++ b/packages/extractors/github-agentic-workflows/tests/fixtures/public/expected.json @@ -430,6 +430,7 @@ ], "workflows": 3 }, + "presence": "present", "protocolVersion": 0, "relationships": [], "schema": "architecture/v0", diff --git a/packages/extractors/github-agentic-workflows/tests/fixtures/repo-ask/after.expected.json b/packages/extractors/github-agentic-workflows/tests/fixtures/repo-ask/after.expected.json index a643170ff..6affdc93a 100644 --- a/packages/extractors/github-agentic-workflows/tests/fixtures/repo-ask/after.expected.json +++ b/packages/extractors/github-agentic-workflows/tests/fixtures/repo-ask/after.expected.json @@ -140,6 +140,7 @@ ], "workflows": 1 }, + "presence": "present", "protocolVersion": 0, "relationships": [], "schema": "architecture/v0", diff --git a/packages/extractors/github-agentic-workflows/tests/fixtures/repo-ask/before.expected.json b/packages/extractors/github-agentic-workflows/tests/fixtures/repo-ask/before.expected.json index 0cde59ad5..c4f448a96 100644 --- a/packages/extractors/github-agentic-workflows/tests/fixtures/repo-ask/before.expected.json +++ b/packages/extractors/github-agentic-workflows/tests/fixtures/repo-ask/before.expected.json @@ -133,6 +133,7 @@ ], "workflows": 1 }, + "presence": "present", "protocolVersion": 0, "relationships": [], "schema": "architecture/v0", diff --git a/packages/extractors/go-public-api/src/lib.rs b/packages/extractors/go-public-api/src/lib.rs index 535580811..c8ad38369 100644 --- a/packages/extractors/go-public-api/src/lib.rs +++ b/packages/extractors/go-public-api/src/lib.rs @@ -48,7 +48,7 @@ pub fn collect(cx: &Context) -> Result { let empty = || Ok(extraction("api/v0", vec![], vec![], Some(json!({"ecosystem": "go"})))); // A revision without the module (before it was added) has no API. if let Some(module) = &module - && !cx.input_exists(&format!("{module}/go.mod"))? + && !cx.subject_exists(&format!("{module}/go.mod"))? { return empty(); } @@ -64,12 +64,15 @@ pub fn collect(cx: &Context) -> Result { // was added) has no packages there. Import paths aren't checked. let directory = pattern.strip_suffix("/...").unwrap_or(&pattern); let local = directory == "." || directory.starts_with("./"); - if !local || cx.input_exists(&in_repository(directory))? { + if !local || cx.subject_exists(&in_repository(directory))? { present.push(pattern); } } + // None of the selected packages is there: the API is absent, even in a module that is. if present.is_empty() { - return empty(); + let mut absent = empty()?; + absent["presence"] = json!("absent"); + return Ok(absent); } let model = exported(run_helper(cx, "api", present)?, "api/v0")?; let mut entities = array(&model["entities"], "entities")?.clone(); @@ -95,12 +98,15 @@ pub fn collect(cx: &Context) -> Result { metadata.get("ecosystem") == Some(&json!("go")), "The Go helper's `api` mode must declare the `go` ecosystem" ); - Ok(extraction( + // Present, though import-path patterns aren't checked and some local ones may be missing. + let mut extraction = extraction( "api/v0", entities, array(&model["relationships"], "relationships")?.clone(), Some(Value::Object(metadata)), - )) + ); + extraction["presence"] = json!("present"); + Ok(extraction) } #[cfg(test)] @@ -162,6 +168,7 @@ mod tests { assert_eq!(extraction["entities"][0]["evidence"][0]["source"], "samples/golang-api/ledger.go"); // A declaration without evidence gains none. assert!(extraction["entities"][1].get("evidence").is_none()); + assert_eq!(extraction["presence"], "present"); // Patterns are relative to the module; one naming a directory it lacks matches nothing. let (extraction, directory) = collect_with(&root, json!({"module": "samples/golang-api", "patterns": ["./api/..."]})); @@ -169,6 +176,7 @@ mod tests { assert_eq!(directory, None); assert_eq!(extraction["entities"], json!([])); assert_eq!(extraction["missingInputs"], json!(["samples/golang-api/api"])); + assert_eq!(extraction["presence"], "absent"); // A revision without the module has no API. let (extraction, directory) = collect_with(&root, json!({"module": "services/ledger"})); @@ -176,6 +184,7 @@ mod tests { assert_eq!(directory, None); assert_eq!(extraction["entities"], json!([])); assert_eq!(extraction["missingInputs"], json!(["services/ledger/go.mod"])); + assert_eq!(extraction["presence"], "absent"); // The module must stay inside the repository. for outside in ["..", "../other", "/tmp"] { @@ -191,7 +200,14 @@ mod tests { let root = scratch(); let (extraction, directory) = collect_with(&root, json!({})); assert_eq!(directory.as_deref(), root.to_str()); - assert_eq!(extraction.unwrap()["entities"][0]["evidence"][0]["source"], "ledger.go"); + let extraction = extraction.unwrap(); + assert_eq!(extraction["entities"][0]["evidence"][0]["source"], "ledger.go"); + assert_eq!(extraction["presence"], "present"); + // An import path isn't checked, so a pattern of one is taken as present. + let (extraction, _) = collect_with(&root, json!({"patterns": ["example.com/ledger", "./missing"]})); + let extraction = extraction.unwrap(); + assert_eq!(extraction["presence"], "present"); + assert_eq!(extraction["missingInputs"], json!(["missing"])); fs::remove_dir_all(&root).unwrap(); } } diff --git a/packages/extractors/nestjs-di/src/lib.rs b/packages/extractors/nestjs-di/src/lib.rs index 1fab2cff8..8357e3d7a 100644 --- a/packages/extractors/nestjs-di/src/lib.rs +++ b/packages/extractors/nestjs-di/src/lib.rs @@ -47,7 +47,7 @@ fn extract(cx: &Context) -> Result { if definition["inputs"].get("snapshot").is_some() { let snapshot = input(definition, "snapshot", None)?; // A revision without the snapshot (before it was added) has no services. - if !cx.input_exists(snapshot)? { + if !cx.subject_exists(snapshot)? { return Ok(projections_extractor_sdk::extraction(SCHEMA, vec![], vec![], None)); } return exported(read_json(root, snapshot)?, SCHEMA); @@ -56,7 +56,8 @@ fn extract(cx: &Context) -> Result { // and import-time code. cx.require_trust()?; // A revision without the declared bootstrap file, root module or configuration - // (before the application was added) has no services. + // (before the application was added) has no services: it is absent, whichever + // of them is missing. let inputs = &definition["inputs"]; let module = inputs["module"] .as_str() @@ -65,11 +66,15 @@ fn extract(cx: &Context) -> Result { .into_iter() .flatten() { - if !cx.input_exists(declared)? { - return Ok(projections_extractor_sdk::extraction(SCHEMA, vec![], vec![], None)); + if !cx.subject_exists(declared)? { + let mut absent = projections_extractor_sdk::extraction(SCHEMA, vec![], vec![], None); + absent["presence"] = json!("absent"); + return Ok(absent); } } - projections_extractor_typescript_support::node_helper(cx) + let mut extraction = projections_extractor_typescript_support::node_helper(cx)?; + extraction["presence"] = json!("present"); + Ok(extraction) } #[cfg(test)] diff --git a/packages/extractors/nuget-dependencies/src/lib.rs b/packages/extractors/nuget-dependencies/src/lib.rs index dd7ee5e65..a13d48e47 100644 --- a/packages/extractors/nuget-dependencies/src/lib.rs +++ b/packages/extractors/nuget-dependencies/src/lib.rs @@ -57,7 +57,7 @@ fn imported(cx: &Context, d: &Value) -> Result> { let mut assets = vec![]; for filename in strings(&d["inputs"]["assetsPaths"], "inputs.assetsPaths")? { // A revision without a declared assets file (before its project was added) has no packages there. - if cx.input_exists(&filename)? { + if cx.subject_exists(&filename)? { assets.push((filename.clone(), cx.read_json(&filename)?)); } else if ignored(cx, &filename) { bail!( @@ -87,18 +87,27 @@ fn restored(cx: &Context, d: &Value) -> Result> { Some(value) => { let mut present = vec![]; for project in strings(value, "inputs.projects")? { - if cx.input_exists(&project)? { + if cx.subject_exists(&project)? { present.push(project); } } present } - None => cx - .files()? - .iter() - .filter(|file| PROJECT_EXTENSIONS.iter().any(|extension| file.ends_with(extension))) - .cloned() - .collect(), + None => { + let found: Vec = cx + .files()? + .iter() + .filter(|file| PROJECT_EXTENSIONS.iter().any(|extension| file.ends_with(extension))) + .cloned() + .collect(); + // The languages it has are the anchors, or, with none, every one is missing. + for extension in PROJECT_EXTENSIONS { + if found.is_empty() || found.iter().any(|file| file.ends_with(extension)) { + cx.subject_matches(&format!("**/*{extension}"), &found)?; + } + } + found + } }; // A revision without projects (before the first was added) has no packages. if projects.is_empty() { diff --git a/packages/extractors/openrewrite-data-tables/src/lib.rs b/packages/extractors/openrewrite-data-tables/src/lib.rs index 2b57578c1..f52043d73 100644 --- a/packages/extractors/openrewrite-data-tables/src/lib.rs +++ b/packages/extractors/openrewrite-data-tables/src/lib.rs @@ -102,7 +102,7 @@ fn table_paths(cx: &Context, inputs: &Value) -> Result>> { let mut any = false; for path in declared { let path = path.trim_start_matches("./").trim_end_matches('/').to_owned(); - if !cx.input_exists(&path)? { + if !cx.subject_exists(&path)? { continue; } any = true; @@ -214,7 +214,10 @@ pub fn collect(cx: &Context) -> Result { "Some build projects matched no module directory, so they are drawn outside the modules: map their names to directories in inputs.projects." ]); } - Ok(extraction(SCHEMA, graph.entities, graph.relationships, Some(metadata))) + // Present, also when the tables were found rather than declared. + let mut extraction = extraction(SCHEMA, graph.entities, graph.relationships, Some(metadata)); + extraction["presence"] = json!("present"); + Ok(extraction) } #[cfg(test)] diff --git a/packages/extractors/openrewrite-data-tables/tests/fixtures/junit5-migration/after.expected.json b/packages/extractors/openrewrite-data-tables/tests/fixtures/junit5-migration/after.expected.json index 8efd57b3d..aa4acf116 100644 --- a/packages/extractors/openrewrite-data-tables/tests/fixtures/junit5-migration/after.expected.json +++ b/packages/extractors/openrewrite-data-tables/tests/fixtures/junit5-migration/after.expected.json @@ -193,6 +193,7 @@ } ] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/openrewrite-data-tables/tests/fixtures/junit5-migration/before.expected.json b/packages/extractors/openrewrite-data-tables/tests/fixtures/junit5-migration/before.expected.json index 9475f8530..ce359c6e5 100644 --- a/packages/extractors/openrewrite-data-tables/tests/fixtures/junit5-migration/before.expected.json +++ b/packages/extractors/openrewrite-data-tables/tests/fixtures/junit5-migration/before.expected.json @@ -153,6 +153,7 @@ } ] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/openrewrite-data-tables/tests/migration.rs b/packages/extractors/openrewrite-data-tables/tests/migration.rs index d104c46af..18f99d3e3 100644 --- a/packages/extractors/openrewrite-data-tables/tests/migration.rs +++ b/packages/extractors/openrewrite-data-tables/tests/migration.rs @@ -23,7 +23,7 @@ fn fixture(side: &str) -> PathBuf { fn extract_at(root: &Path, inputs: Value) -> anyhow::Result { let files = repository_files(root).unwrap(); let definition = json!({"id": "openrewrite", "extractor": "openrewrite-data-tables", "inputs": inputs}); - collect(&testing::context(root, definition).with_files(files)) + testing::extract(&testing::context(root, definition).with_files(files), collect) } fn extract(side: &str, inputs: Value) -> Value { diff --git a/packages/extractors/prisma-schema/src/lib.rs b/packages/extractors/prisma-schema/src/lib.rs index 2d1b24abe..832a2cf59 100644 --- a/packages/extractors/prisma-schema/src/lib.rs +++ b/packages/extractors/prisma-schema/src/lib.rs @@ -47,6 +47,9 @@ const LIMITATIONS: [&str; 5] = [ "Connector-specific capability checks (supported native types, index types and arguments per database) are left to Prisma.", ]; +/// The schema files discovered without `inputs.schema` or `inputs.schemas`. +const DISCOVERED: &str = "**/*.prisma"; + /// Repository-relative schema files: each selected path is a file or a schema /// folder, whose `.prisma` files (including nested folders) form one schema. fn schema_files(cx: &Context, files: &[String], definition: &Value) -> Result> { @@ -55,12 +58,12 @@ fn schema_files(cx: &Context, files: &[String], definition: &Value) -> Result vec![s.clone()], Some(v) => strings(v, "Prisma schemas")?, None => { + // A revision without any (before Prisma was adopted) has no schema. + if !cx.subject_matches(DISCOVERED, files)? { + return Ok(vec![]); + } let mut discovered: Vec = files.iter().filter(|s| s.ends_with(".prisma")).cloned().collect(); discovered.sort(); - ensure!( - !discovered.is_empty(), - "Prisma requires inputs.schema, inputs.schemas, or repository .prisma files" - ); return Ok(discovered); } }; @@ -72,7 +75,7 @@ fn schema_files(cx: &Context, files: &[String], definition: &Value) -> Result Option<&str> { let root = path.strip_suffix("config/routes.rb")?; (root.is_empty() || root.ends_with('/')).then_some(root) @@ -161,17 +164,20 @@ fn routes_files(cx: &Context, files: &[String], definition: &Value) -> Result vec![path.clone()], Some(value) => strings(value, "inputs.routes")?, None => { - return Ok(files + let found: Vec = files .iter() .filter(|f| !ignored(f) && application_root(f).is_some()) .cloned() - .collect()); + .collect(); + // A revision without any (before the application was added) has no routes. + cx.subject_matches(DISCOVERED, &found)?; + return Ok(found); } }; let mut present = Vec::new(); for path in selected { // A revision before the routes file existed has no routes. - if cx.input_exists(&path)? { + if cx.subject_exists(&path)? { present.push(path); } } diff --git a/packages/extractors/rails-schema/src/lib.rs b/packages/extractors/rails-schema/src/lib.rs index f99625d1e..9e01758d8 100644 --- a/packages/extractors/rails-schema/src/lib.rs +++ b/packages/extractors/rails-schema/src/lib.rs @@ -82,6 +82,10 @@ fn is_sql(path: &str) -> bool { /// The application root of a schema file (`web/` for `web/db/schema.rb` or /// `web/db/structure.sql`) and its database name. +/// The schema files discovered without `inputs.schema` or `inputs.schemas`, in +/// either format, outside ignored folders. +const DISCOVERED: [&str; 2] = ["**/db/*schema.rb", "**/db/*structure.sql"]; + fn schema_file(path: &str) -> Option<(&str, &str)> { let (root, name) = match path.rsplit_once("db/") { Some((root, name)) if root.is_empty() || root.ends_with('/') => (root, name), @@ -174,6 +178,15 @@ fn schema_files(cx: &Context, files: &[String], definition: &Value) -> Result strings(v, "Rails schemas")?, None => { let found: Vec<&String> = files.iter().filter(|f| !ignored(f) && schema_file(f).is_some()).collect(); + // A revision without any (before the application was added) has no tables: + // the formats it has are the anchors, or, with neither, both are missing. + let listed: Vec = found.iter().map(|f| (*f).clone()).collect(); + for pattern in DISCOVERED { + let glob = projections_extractor_sdk::glob(pattern)?; + if listed.is_empty() || listed.iter().any(|f| glob.is_match(f)) { + cx.subject_matches(pattern, &listed)?; + } + } let mut roots: Vec<&str> = found.iter().filter_map(|f| schema_file(f).map(|(root, _)| root)).collect(); roots.sort(); roots.dedup(); @@ -200,7 +213,7 @@ fn schema_files(cx: &Context, files: &[String], definition: &Value) -> Result Result { }); let mut result = extraction("graph/v0", entities, relationships, Some(metadata)); result["vocabularies"] = json!([VOCABULARY]); + // The repository is what it describes, so it is always present. + result["presence"] = json!("present"); Ok(result) } diff --git a/packages/extractors/repository-map/src/lib.rs b/packages/extractors/repository-map/src/lib.rs index 8c17dfc69..3da5ef90c 100644 --- a/packages/extractors/repository-map/src/lib.rs +++ b/packages/extractors/repository-map/src/lib.rs @@ -81,7 +81,10 @@ pub fn collect(cx: &Context) -> Result { "repository-map exceeds the 10,000-node state limit; narrow it with inputs.include or inputs.exclude globs" ); } - Ok(extraction("graph/v0", nodes, edges, None)) + let mut extraction = extraction("graph/v0", nodes, edges, None); + // The repository is what it describes, so it is always present. + extraction["presence"] = json!("present"); + Ok(extraction) } /// Lines in a text file: newline-terminated lines plus a final unterminated one. diff --git a/packages/extractors/rust-public-api/src/lib.rs b/packages/extractors/rust-public-api/src/lib.rs index 3bcbe7932..4e05d4cd4 100644 --- a/packages/extractors/rust-public-api/src/lib.rs +++ b/packages/extractors/rust-public-api/src/lib.rs @@ -65,7 +65,7 @@ pub fn collect(cx: &Context) -> Result { None => input(definition, "manifestPath", Some("Cargo.toml"))?, }; // A revision without the declared rustdoc JSON or manifest (before it was added) has no API. - if !cx.input_exists(declared)? { + if !cx.subject_exists(declared)? { return Ok(projections_extractor_sdk::extraction( "api/v0", vec![], @@ -78,12 +78,10 @@ pub fn collect(cx: &Context) -> Result { && definition["inputs"].get("package").is_some() && !declares_package(cx, input(definition, "package", None)?)? { - return Ok(projections_extractor_sdk::extraction( - "api/v0", - vec![], - vec![], - Some(serde_json::json!({"ecosystem": "rust"})), - )); + cx.missing_input(input(definition, "package", None)?); + let mut absent = projections_extractor_sdk::extraction("api/v0", vec![], vec![], Some(serde_json::json!({"ecosystem": "rust"}))); + absent["presence"] = "absent".into(); + return Ok(absent); } let (document, base) = if definition["inputs"].get("rustdocJson").is_some() { (read_json(root, declared)?, ".".to_owned()) @@ -280,9 +278,21 @@ mod tests { let runs: Arc>> = Arc::default(); // A crate a change adds: the workspace is there, the package isn't yet. let definition = json!({"id": "api", "extractor": ID, "inputs": {"toolchain": "nightly", "package": "acme-new"}}); - let extraction = collect(&context(&root, definition, false, Arc::clone(&runs))).unwrap(); + let cx = context(&root, definition, false, Arc::clone(&runs)); + let extraction = cx.finish(collect(&cx).unwrap()).unwrap(); assert_eq!(extraction["entities"], json!([])); + assert_eq!(extraction["presence"], "absent"); + assert_eq!(extraction["missingInputs"], json!(["acme-new"])); + projections_extractor_sdk::normalize_extraction(&extraction).unwrap(); assert!(runs.lock().unwrap().is_empty()); + // Without the manifest, the whole crate is absent. + let definition = json!({"id": "api", "extractor": ID, "inputs": {"manifestPath": "missing/Cargo.toml"}}); + let cx = context(&root, definition, false, Arc::clone(&runs)); + let extraction = cx.finish(collect(&cx).unwrap()).unwrap(); + assert_eq!( + (extraction["presence"].as_str(), extraction["missingInputs"].clone()), + (Some("absent"), json!(["missing/Cargo.toml"])) + ); // The package is declared, in either quotes: cargo runs for it. fs::create_dir_all(root.join("crates/new")).unwrap(); fs::write(root.join("crates/new/Cargo.toml"), "[package]\nname = 'acme-new' # added\n").unwrap(); diff --git a/packages/extractors/scip-file-references/src/lib.rs b/packages/extractors/scip-file-references/src/lib.rs index 9ea8c96c7..71449106d 100644 --- a/packages/extractors/scip-file-references/src/lib.rs +++ b/packages/extractors/scip-file-references/src/lib.rs @@ -62,19 +62,22 @@ pub fn collect(cx: &Context) -> Result { (false, true) => { let index = input(definition, "index", None)?; // A revision without the declared index (before it was added) references nothing. - if !cx.input_exists(index)? { + if !cx.subject_exists(index)? { return references(Index::default(), files, &prefix, index, false); } let file = path(root, index, false, false)?; (read_file(&file, MAX_INDEX_BYTES)?, index.to_owned(), false) } - (true, false) if !prefix.is_empty() && !cx.input_exists(&prefix)? => { + (true, false) if !prefix.is_empty() && !cx.subject_exists(&prefix)? => { return references(Index::default(), files, &prefix, "indexer", true); } (true, false) => (index(root, files, &prefix, definition, cx)?, "indexer".into(), true), }; let index = Index::parse_from_bytes(&bytes).context("Invalid SCIP index")?; - references(index, files, &prefix, &source, generated) + // Present: an indexer run at the repository's root checks no anchor. + let mut extraction = references(index, files, &prefix, &source, generated)?; + extraction["presence"] = json!("present"); + Ok(extraction) } /// Runs the configured indexer in the revision and returns the index it wrote. diff --git a/packages/extractors/spring-di/src/lib.rs b/packages/extractors/spring-di/src/lib.rs index 2d5450ee9..524956d3b 100644 --- a/packages/extractors/spring-di/src/lib.rs +++ b/packages/extractors/spring-di/src/lib.rs @@ -242,7 +242,7 @@ fn extract(cx: &Context) -> Result { let absent = || Ok(projections_extractor_sdk::extraction(SCHEMA, vec![], vec![], None)); if d["inputs"].get("snapshot").is_some() { let snapshot = input(d, "snapshot", None)?; - if !cx.input_exists(snapshot)? { + if !cx.subject_exists(snapshot)? { return absent(); } return exported(read_json(root, snapshot)?, SCHEMA); @@ -250,7 +250,7 @@ fn extract(cx: &Context) -> Result { // The main method, the build and every bean's construction are repository code. cx.require_trust()?; let relative = input(d, "project", Some("."))?; - if !cx.input_exists(relative)? { + if !cx.subject_exists(relative)? { return absent(); } let project = path(root, relative, false, false)?; diff --git a/packages/extractors/swift-package-dependencies/src/lib.rs b/packages/extractors/swift-package-dependencies/src/lib.rs index 9e5cb0a83..37dc00891 100644 --- a/packages/extractors/swift-package-dependencies/src/lib.rs +++ b/packages/extractors/swift-package-dependencies/src/lib.rs @@ -50,7 +50,7 @@ pub fn collect(cx: &Context) -> Result { _ => manifest, }; // A revision without the package (before it was added) has no graph. - if !cx.input_exists(&declared)? { + if !cx.subject_exists(&declared)? { return Ok(extraction( "graph/v0", vec![], diff --git a/packages/extractors/swift-package-dependencies/tests/fixtures/harbor.expected.json b/packages/extractors/swift-package-dependencies/tests/fixtures/harbor.expected.json index ce1aea5ae..fb012c3fe 100644 --- a/packages/extractors/swift-package-dependencies/tests/fixtures/harbor.expected.json +++ b/packages/extractors/swift-package-dependencies/tests/fixtures/harbor.expected.json @@ -162,6 +162,7 @@ "resolved": "harbor/Package.resolved", "unresolved": [] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/swift-package-dependencies/tests/package.rs b/packages/extractors/swift-package-dependencies/tests/package.rs index 3a5dd7587..2f7a19eb4 100644 --- a/packages/extractors/swift-package-dependencies/tests/package.rs +++ b/packages/extractors/swift-package-dependencies/tests/package.rs @@ -24,7 +24,7 @@ fn extract(inputs: Value) -> anyhow::Result { .filter(|f| !f.ends_with(".expected.json")) .collect(); let definition = json!({"id": "swift", "extractor": "swift-package-dependencies", "inputs": inputs}); - collect(&testing::context(&root, definition).with_files(files)) + testing::extract(&testing::context(&root, definition).with_files(files), collect) } fn dumped(name: &str) -> Value { diff --git a/packages/extractors/swift-public-api/src/lib.rs b/packages/extractors/swift-public-api/src/lib.rs index b69596249..12b62a415 100644 --- a/packages/extractors/swift-public-api/src/lib.rs +++ b/packages/extractors/swift-public-api/src/lib.rs @@ -68,7 +68,7 @@ pub fn collect(cx: &Context) -> Result { format!("{}/Package.swift", package.trim_end_matches('/')) }; // A revision without the package or the graphs (before they were added) has no API. - if !cx.input_exists(if imported { declared } else { manifest.as_str() })? { + if !cx.subject_exists(if imported { declared } else { manifest.as_str() })? { return Ok(projections_extractor_sdk::extraction( "api/v0", vec![], diff --git a/packages/extractors/swift-public-api/src/tests.rs b/packages/extractors/swift-public-api/src/tests.rs index b7001e65c..e13a8d2d6 100644 --- a/packages/extractors/swift-public-api/src/tests.rs +++ b/packages/extractors/swift-public-api/src/tests.rs @@ -17,7 +17,7 @@ fn fixtures() -> PathBuf { /// The extraction of `{graphs}.symbols` in a fixture, which the Engine must accept. fn import(fixture: &Path, graphs: &str, module: &str) -> Value { let definition = json!({"id": "api", "extractor": ID, "inputs": {"symbolGraphPath": format!("{graphs}.symbols"), "modules": [module]}}); - let extraction = collect(&testing::context(fixture, definition)).unwrap(); + let extraction = testing::extract(&testing::context(fixture, definition), collect).unwrap(); if let Err(error) = normalize_extraction(&extraction) { panic!("{}/{graphs}.symbols: {error:#}", fixture.display()); } diff --git a/packages/extractors/swift-public-api/tests/fixtures/compatibility/after.expected.json b/packages/extractors/swift-public-api/tests/fixtures/compatibility/after.expected.json index b43e0f498..c1cd8574c 100644 --- a/packages/extractors/swift-public-api/tests/fixtures/compatibility/after.expected.json +++ b/packages/extractors/swift-public-api/tests/fixtures/compatibility/after.expected.json @@ -799,6 +799,7 @@ "metadata": { "ecosystem": "swift" }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/swift-public-api/tests/fixtures/constrained-extensions/package.expected.json b/packages/extractors/swift-public-api/tests/fixtures/constrained-extensions/package.expected.json index 4b6ee295c..7201b288b 100644 --- a/packages/extractors/swift-public-api/tests/fixtures/constrained-extensions/package.expected.json +++ b/packages/extractors/swift-public-api/tests/fixtures/constrained-extensions/package.expected.json @@ -960,6 +960,7 @@ "metadata": { "ecosystem": "swift" }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/terraform-infrastructure/src/lib.rs b/packages/extractors/terraform-infrastructure/src/lib.rs index 99da925a8..61c7b4300 100644 --- a/packages/extractors/terraform-infrastructure/src/lib.rs +++ b/packages/extractors/terraform-infrastructure/src/lib.rs @@ -69,7 +69,7 @@ fn extract(cx: &Context) -> Result { let (root, definition) = (cx.root(), cx.definition()); let document = if definition["inputs"].get("planJsonPath").is_some() { let file = input(definition, "planJsonPath", None)?; - if !cx.input_exists(file)? { + if !cx.subject_exists(file)? { return infrastructure(&ABSENT); } read_json(root, file)? diff --git a/packages/extractors/terraform-infrastructure/src/native.rs b/packages/extractors/terraform-infrastructure/src/native.rs index 5d9515c48..18008d1c4 100644 --- a/packages/extractors/terraform-infrastructure/src/native.rs +++ b/packages/extractors/terraform-infrastructure/src/native.rs @@ -12,7 +12,7 @@ pub(crate) fn native(root: &Path, d: &Value, cx: &Context) -> Result Result PathBuf { fn extract(file: &str) -> Value { let root = fixtures(); let definition = json!({"id":"infrastructure","extractor":"terraform-infrastructure","inputs":{"planJsonPath":file}}); - let extraction = collect(&Process::new(&root).context(&root, Value::clone(&definition)).with_files(vec![])).unwrap(); + let extraction = testing::extract( + &Process::new(&root).context(&root, Value::clone(&definition)).with_files(vec![]), + collect, + ) + .unwrap(); projections_engine::normalize(&extraction, "").unwrap(); extraction } diff --git a/packages/extractors/terraform-modules/src/lib.rs b/packages/extractors/terraform-modules/src/lib.rs index ecf181967..d1712a2cc 100644 --- a/packages/extractors/terraform-modules/src/lib.rs +++ b/packages/extractors/terraform-modules/src/lib.rs @@ -69,6 +69,8 @@ pub fn collect(cx: &Context) -> Result { let configuration = configuration::read(&files, |file| cx.read_source(file))?; let mut extraction = graph::graph(&configuration); extraction["vocabularies"] = json!([VOCABULARY]); + // The repository is what it describes, so it is always present. + extraction["presence"] = json!("present"); Ok(extraction) } diff --git a/packages/extractors/terraform-modules/tests/fixtures/network/after.expected.json b/packages/extractors/terraform-modules/tests/fixtures/network/after.expected.json index 0c804bd81..196a1ec39 100644 --- a/packages/extractors/terraform-modules/tests/fixtures/network/after.expected.json +++ b/packages/extractors/terraform-modules/tests/fixtures/network/after.expected.json @@ -1113,6 +1113,7 @@ "source": "Terraform configuration (.tf files)", "unresolvedReferences": 0 }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/terraform-modules/tests/fixtures/network/before.expected.json b/packages/extractors/terraform-modules/tests/fixtures/network/before.expected.json index 1c2a6c0c3..41cfd0baf 100644 --- a/packages/extractors/terraform-modules/tests/fixtures/network/before.expected.json +++ b/packages/extractors/terraform-modules/tests/fixtures/network/before.expected.json @@ -1037,6 +1037,7 @@ "source": "Terraform configuration (.tf files)", "unresolvedReferences": 0 }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/terraform-modules/tests/modules.rs b/packages/extractors/terraform-modules/tests/modules.rs index 054b0367f..66b43e77e 100644 --- a/packages/extractors/terraform-modules/tests/modules.rs +++ b/packages/extractors/terraform-modules/tests/modules.rs @@ -7,7 +7,7 @@ //! extractions are goldens (`PROJECTIONS_UPDATE_GOLDEN=1` rewrites them) and //! the graph renderer's Terraform modules scenario. -use projections_extractor_sdk::testing::{Process, golden}; +use projections_extractor_sdk::testing::{self, Process, golden}; use projections_extractor_terraform_modules::collect; use serde_json::{Value, json}; use std::collections::BTreeSet; @@ -34,7 +34,7 @@ fn try_extract(revision: &str, inputs: Value) -> anyhow::Result { listed(&root, &root, &mut files); files.sort(); let definition = json!({"id":"modules","extractor":"terraform-modules","inputs":inputs}); - let extraction = collect(&Process::new(&root).context(&root, definition).with_files(files))?; + let extraction = testing::extract(&Process::new(&root).context(&root, definition).with_files(files), collect)?; projections_engine::normalize(&extraction, "").unwrap(); Ok(extraction) } diff --git a/packages/extractors/tetragon-policies/src/lib.rs b/packages/extractors/tetragon-policies/src/lib.rs index e1f75e9a5..6b7899120 100644 --- a/packages/extractors/tetragon-policies/src/lib.rs +++ b/packages/extractors/tetragon-policies/src/lib.rs @@ -103,7 +103,7 @@ fn extract(cx: &Context) -> Result { } } if let Some(patterns) = inputs.get("workloadPaths").filter(|v| !v.is_null()) { - let patterns = matching(cx, files, patterns, "inputs.workloadPaths")?; + let patterns = matching(cx, files, patterns, "inputs.workloadPaths", false)?; if patterns != json!([]) { enrich::workloads(&mut model, root, files, &patterns, namespace)?; } diff --git a/packages/extractors/tetragon-policies/src/sources.rs b/packages/extractors/tetragon-policies/src/sources.rs index 770c80c90..821ca40a4 100644 --- a/packages/extractors/tetragon-policies/src/sources.rs +++ b/packages/extractors/tetragon-policies/src/sources.rs @@ -36,14 +36,14 @@ fn rendered(root: &Path, definition: &Value, cx: &Context) -> Result cx.require_trust()?; let chart = field(helm, "chart", "inputs.helm")?.context("inputs.helm.chart is required")?; // A revision without the chart (before it was added) renders nothing from it. - if cx.input_exists(&chart)? { + if cx.subject_exists(&chart)? { sources.push(helm_template(cx, root, helm, &chart, &field, &inside)?); } } if let Some(kustomize) = inputs.get("kustomize").filter(|v| !v.is_null()) { cx.require_trust()?; let directory = field(kustomize, "path", "inputs.kustomize")?.context("inputs.kustomize.path is required")?; - if cx.input_exists(&directory)? { + if cx.subject_exists(&directory)? { let directory = inside(&directory)?; let argv = vec![ field(kustomize, "kustomizePath", "inputs.kustomize")?.unwrap_or_else(|| "kustomize".into()), @@ -93,15 +93,24 @@ fn helm_template(cx: &Context, root: &Path, helm: &Value, chart: &str, field: &F } /// The declared globs that match some file of the revision. One that matches -/// none (the revision predates what it selects) is recorded as missing. -pub(crate) fn matching(cx: &Context, files: &[String], patterns: &Value, label: &str) -> Result { +/// none (the revision predates what it selects) is recorded as missing; when +/// they select the policies themselves (`subject`), they are the anchors of the +/// extraction's subject ([`Context::subject_matches`]). +pub(crate) fn matching(cx: &Context, files: &[String], patterns: &Value, label: &str, subject: bool) -> Result { let mut present = vec![]; for pattern in strings(patterns, label)? { - let glob = projections_extractor_sdk::glob(&pattern)?; - if files.iter().any(|file| glob.is_match(file)) { - present.push(pattern); + let matches = if subject { + cx.subject_matches(&pattern, files)? } else { - cx.missing_input(&pattern); + let glob = projections_extractor_sdk::glob(&pattern)?; + let matches = files.iter().any(|file| glob.is_match(file)); + if !matches { + cx.missing_input(&pattern); + } + matches + }; + if matches { + present.push(pattern); } } Ok(json!(present)) @@ -111,7 +120,7 @@ pub(crate) fn sources(root: &Path, files: &[String], definition: &Value, cx: &Co let inputs = &definition["inputs"]; if let Some(path) = inputs.get("renderedManifestsPath").filter(|v| !v.is_null()) { let path = text(path, "inputs.renderedManifestsPath")?; - if !cx.input_exists(path)? { + if !cx.subject_exists(path)? { return Ok(vec![]); } return Ok(vec![Source { @@ -124,7 +133,7 @@ pub(crate) fn sources(root: &Path, files: &[String], definition: &Value, cx: &Co let explicit = inputs .get("paths") .filter(|v| !v.is_null()) - .map(|paths| matching(cx, files, paths, "inputs.paths")) + .map(|paths| matching(cx, files, paths, "inputs.paths", true)) .transpose()?; if !sources.is_empty() && explicit.is_none() { return Ok(sources); @@ -136,7 +145,18 @@ pub(crate) fn sources(root: &Path, files: &[String], definition: &Value, cx: &Co let explicit = explicit.as_ref(); let include = match explicit { Some(paths) => globs(Some(paths), "inputs.paths")?, - None => globs(Some(&json!(DEFAULT_PATHS)), "paths")?, + None => { + // The default globs that match are the anchors, or, with none matching, both are missing. + let matched: Vec<&str> = DEFAULT_PATHS + .iter() + .copied() + .filter(|pattern| projections_extractor_sdk::glob(pattern).is_ok_and(|glob| files.iter().any(|file| glob.is_match(file)))) + .collect(); + for pattern in if matched.is_empty() { DEFAULT_PATHS } else { &matched[..] } { + cx.subject_matches(pattern, files)?; + } + globs(Some(&json!(DEFAULT_PATHS)), "paths")? + } }; let exclude = globs(inputs.get("exclude").filter(|v| !v.is_null()), "inputs.exclude")?; let mut matched: Vec<&String> = files diff --git a/packages/extractors/tetragon-policies/tests/extractions.rs b/packages/extractors/tetragon-policies/tests/extractions.rs index ace48b0a9..b34d6e0bf 100644 --- a/packages/extractors/tetragon-policies/tests/extractions.rs +++ b/packages/extractors/tetragon-policies/tests/extractions.rs @@ -15,7 +15,7 @@ fn fixtures() -> PathBuf { fn extract(root: &Path, inputs: Value) -> anyhow::Result { let root = root.canonicalize().unwrap(); let definition = json!({"id":"runtime-policies","extractor":"tetragon-policies","inputs":inputs}); - collect(&testing::context(&root, definition)) + testing::extract(&testing::context(&root, definition), collect) } fn inputs(case: &str) -> Value { @@ -343,14 +343,44 @@ fn declared_inputs_the_revision_lacks_are_missing_not_errors() { "deploy/tetragon/*.yaml" ]) ); + assert_eq!(absent["presence"], "absent"); normalize(&absent); // Some present: they are extracted, the missing ones are named. let partial = run(json!({"paths": ["*.yaml", "deploy/tetragon/*.yaml"]})); find(&partial, "policy", "p"); assert_eq!(partial["missingInputs"], json!(["deploy/tetragon/*.yaml"])); + assert_eq!(partial["presence"], "present"); let rendered = run(json!({"renderedManifestsPath": "rendered.yaml"})); assert_eq!(rendered["entities"], json!([])); assert_eq!(rendered["missingInputs"], json!(["rendered.yaml"])); + assert_eq!(rendered["presence"], "absent"); + // The default globs: the one that matches is the anchor, and the other isn't named missing. + let defaults = run(json!({})); + assert_eq!( + (defaults["presence"].as_str(), defaults.get("missingInputs")), + (Some("present"), None) + ); +} + +#[test] +fn a_missing_auxiliary_input_leaves_an_empty_policy_set_present() { + let scratch = Scratch::new("auxiliary"); + fs::create_dir_all(scratch.0.join("deploy/tetragon")).unwrap(); + fs::write(scratch.0.join("deploy/tetragon/README.yaml"), "notes: no policies yet\n").unwrap(); + let root = scratch.0.canonicalize().unwrap(); + let cx = testing::context( + &root, + json!({"id":"runtime-policies","extractor":"tetragon-policies","inputs":{ + "paths": ["deploy/tetragon/*.yaml"], + "agentValuesPath": "deploy/tetragon-values.yaml", + }}), + ); + // No policies and a missing input, but the policy set is there: present and empty, not absent. + let extraction = testing::extract(&cx, collect).unwrap(); + assert_eq!(extraction["entities"], json!([])); + assert_eq!(extraction["missingInputs"], json!(["deploy/tetragon-values.yaml"])); + assert_eq!(extraction["presence"], "present"); + normalize(&extraction); } #[test] diff --git a/packages/extractors/tetragon-policies/tests/fixtures/credentials/after.expected.json b/packages/extractors/tetragon-policies/tests/fixtures/credentials/after.expected.json index 8ffa29f25..77bdd2f3a 100644 --- a/packages/extractors/tetragon-policies/tests/fixtures/credentials/after.expected.json +++ b/packages/extractors/tetragon-policies/tests/fixtures/credentials/after.expected.json @@ -360,6 +360,7 @@ "deploy/tetragon/protect-credentials.yaml" ] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/tetragon-policies/tests/fixtures/credentials/before.expected.json b/packages/extractors/tetragon-policies/tests/fixtures/credentials/before.expected.json index b935b2a84..4415c9e5d 100644 --- a/packages/extractors/tetragon-policies/tests/fixtures/credentials/before.expected.json +++ b/packages/extractors/tetragon-policies/tests/fixtures/credentials/before.expected.json @@ -364,6 +364,7 @@ "deploy/tetragon/protect-credentials.yaml" ] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/tetragon-policies/tests/fixtures/credentials/monitor.expected.json b/packages/extractors/tetragon-policies/tests/fixtures/credentials/monitor.expected.json index 4b2cbd994..afef7eef6 100644 --- a/packages/extractors/tetragon-policies/tests/fixtures/credentials/monitor.expected.json +++ b/packages/extractors/tetragon-policies/tests/fixtures/credentials/monitor.expected.json @@ -360,6 +360,7 @@ "deploy/tetragon/protect-credentials.yaml" ] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/tetragon-policies/tests/fixtures/deployment/after.expected.json b/packages/extractors/tetragon-policies/tests/fixtures/deployment/after.expected.json index 31be48bbc..c43c13f69 100644 --- a/packages/extractors/tetragon-policies/tests/fixtures/deployment/after.expected.json +++ b/packages/extractors/tetragon-policies/tests/fixtures/deployment/after.expected.json @@ -949,6 +949,7 @@ "deploy/tetragon/protect-credentials.yaml" ] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/tetragon-policies/tests/fixtures/deployment/before.expected.json b/packages/extractors/tetragon-policies/tests/fixtures/deployment/before.expected.json index 4a92f8f26..43db1a30a 100644 --- a/packages/extractors/tetragon-policies/tests/fixtures/deployment/before.expected.json +++ b/packages/extractors/tetragon-policies/tests/fixtures/deployment/before.expected.json @@ -800,6 +800,7 @@ "deploy/tetragon/protect-credentials.yaml" ] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/tetragon-policies/tests/fixtures/library/expected.json b/packages/extractors/tetragon-policies/tests/fixtures/library/expected.json index 3ddd6d965..502ce7fcf 100644 --- a/packages/extractors/tetragon-policies/tests/fixtures/library/expected.json +++ b/packages/extractors/tetragon-policies/tests/fixtures/library/expected.json @@ -926,6 +926,7 @@ "policies/listed.yaml" ] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/tetragon-policies/tests/fixtures/skipped/expected.json b/packages/extractors/tetragon-policies/tests/fixtures/skipped/expected.json index aa09453c0..8175eb827 100644 --- a/packages/extractors/tetragon-policies/tests/fixtures/skipped/expected.json +++ b/packages/extractors/tetragon-policies/tests/fixtures/skipped/expected.json @@ -221,6 +221,7 @@ "examples/library.yaml" ] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/typescript-public-api/src/lib.rs b/packages/extractors/typescript-public-api/src/lib.rs index fa679cb53..c3825d178 100644 --- a/packages/extractors/typescript-public-api/src/lib.rs +++ b/packages/extractors/typescript-public-api/src/lib.rs @@ -33,7 +33,12 @@ pub fn requires_trust(_inputs: &Value) -> bool { pub fn collect(cx: &Context) -> Result { match projections_extractor_typescript_support::present_inputs(cx)? { - Some(request) => projections_extractor_typescript_support::node_helper_with(cx, &request), + // Present, also when the definition declares no paths and the helper finds the project. + Some(request) => { + let mut extraction = projections_extractor_typescript_support::node_helper_with(cx, &request)?; + extraction["presence"] = json!("present"); + Ok(extraction) + } // A revision without the declared configuration or entrypoints (before they were added) has no API. None => Ok(projections_extractor_sdk::extraction( "api/v0", diff --git a/packages/extractors/typescript-support/src/lib.rs b/packages/extractors/typescript-support/src/lib.rs index d8e845166..71eba1892 100644 --- a/packages/extractors/typescript-support/src/lib.rs +++ b/packages/extractors/typescript-support/src/lib.rs @@ -69,7 +69,8 @@ fn out_of_memory(error: anyhow::Error) -> anyhow::Error { /// The request with only the declared `tsconfig`, `tsconfigs` and `entrypoints` /// the examined revision has, or `None` when it has none of them (the project -/// predates them). Each one it lacks is recorded as a missing input. +/// predates them). They are the anchors of its subject +/// ([`Context::subject_exists`]); each one it lacks is recorded as a missing input. pub fn present_inputs(cx: &Context) -> Result> { let mut request = cx.request().clone(); // A definition without inputs (one `explore` proposes) has none to leave out; indexing would add `inputs: null`. @@ -85,7 +86,7 @@ pub fn present_inputs(cx: &Context) -> Result> { return Ok(true); }; declared += 1; - let exists = cx.input_exists(path)?; + let exists = cx.subject_exists(path)?; present += usize::from(exists); Ok(exists) }; diff --git a/packages/extractors/workspace-dependencies/src/lib.rs b/packages/extractors/workspace-dependencies/src/lib.rs index 9c462b412..9325d64e9 100644 --- a/packages/extractors/workspace-dependencies/src/lib.rs +++ b/packages/extractors/workspace-dependencies/src/lib.rs @@ -56,7 +56,7 @@ pub fn collect(cx: &Context) -> Result { let present: BTreeSet<&str> = files.iter().map(String::as_str).collect(); let root_file = format!("{base}package.json"); // A revision without the workspace (before it was added) has no packages. - if !cx.input_exists(&root_file)? { + if !cx.subject_exists(&root_file)? { return Ok(extraction("graph/v0", vec![], vec![], None)); } let root_manifest = cx.read_json(&root_file)?; diff --git a/packages/extractors/workspace-dependencies/tests/fixtures/bun.expected.json b/packages/extractors/workspace-dependencies/tests/fixtures/bun.expected.json index ad11c5fb5..0d3d5f5d7 100644 --- a/packages/extractors/workspace-dependencies/tests/fixtures/bun.expected.json +++ b/packages/extractors/workspace-dependencies/tests/fixtures/bun.expected.json @@ -194,6 +194,7 @@ "packageManager": "bun", "unresolved": [] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/workspace-dependencies/tests/fixtures/npm.expected.json b/packages/extractors/workspace-dependencies/tests/fixtures/npm.expected.json index fb22a343d..3820f36a3 100644 --- a/packages/extractors/workspace-dependencies/tests/fixtures/npm.expected.json +++ b/packages/extractors/workspace-dependencies/tests/fixtures/npm.expected.json @@ -194,6 +194,7 @@ "packageManager": "npm", "unresolved": [] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/workspace-dependencies/tests/fixtures/pnpm-catalog.expected.json b/packages/extractors/workspace-dependencies/tests/fixtures/pnpm-catalog.expected.json index 12da4fe3a..0f09d107b 100644 --- a/packages/extractors/workspace-dependencies/tests/fixtures/pnpm-catalog.expected.json +++ b/packages/extractors/workspace-dependencies/tests/fixtures/pnpm-catalog.expected.json @@ -102,6 +102,7 @@ "packageManager": "pnpm", "unresolved": [] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/workspace-dependencies/tests/fixtures/pnpm.expected.json b/packages/extractors/workspace-dependencies/tests/fixtures/pnpm.expected.json index 6386a8d61..d6eb90515 100644 --- a/packages/extractors/workspace-dependencies/tests/fixtures/pnpm.expected.json +++ b/packages/extractors/workspace-dependencies/tests/fixtures/pnpm.expected.json @@ -194,6 +194,7 @@ "packageManager": "pnpm", "unresolved": [] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/workspace-dependencies/tests/fixtures/yarn-berry.expected.json b/packages/extractors/workspace-dependencies/tests/fixtures/yarn-berry.expected.json index bb7a35f0c..5bef71158 100644 --- a/packages/extractors/workspace-dependencies/tests/fixtures/yarn-berry.expected.json +++ b/packages/extractors/workspace-dependencies/tests/fixtures/yarn-berry.expected.json @@ -194,6 +194,7 @@ "packageManager": "yarn-berry", "unresolved": [] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/workspace-dependencies/tests/fixtures/yarn-classic.expected.json b/packages/extractors/workspace-dependencies/tests/fixtures/yarn-classic.expected.json index 13fda47f5..918fcdca2 100644 --- a/packages/extractors/workspace-dependencies/tests/fixtures/yarn-classic.expected.json +++ b/packages/extractors/workspace-dependencies/tests/fixtures/yarn-classic.expected.json @@ -232,6 +232,7 @@ "packageManager": "yarn-classic", "unresolved": [] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/workspace-dependencies/tests/managers.rs b/packages/extractors/workspace-dependencies/tests/managers.rs index 00de770a5..e66c69e09 100644 --- a/packages/extractors/workspace-dependencies/tests/managers.rs +++ b/packages/extractors/workspace-dependencies/tests/managers.rs @@ -26,7 +26,7 @@ fn extract(root: &Path, inputs: Value) -> anyhow::Result { .filter(|f| !f.ends_with(".expected.json")) .collect(); let definition = json!({"id":"dependencies","extractor":"workspace-dependencies","inputs":inputs}); - collect(&testing::context(root, definition).with_files(files)) + testing::extract(&testing::context(root, definition).with_files(files), collect) } fn manager(name: &str) -> Value { diff --git a/packages/extractors/xcode-modules/src/lib.rs b/packages/extractors/xcode-modules/src/lib.rs index 77991ef7f..b84a0dc75 100644 --- a/packages/extractors/xcode-modules/src/lib.rs +++ b/packages/extractors/xcode-modules/src/lib.rs @@ -115,14 +115,16 @@ fn paths(cx: &Context, inputs: &Value) -> Result> { path.ends_with(".xcodeproj"), "`inputs.projects` names .xcodeproj directories, not {path}" ); - if cx.input_exists(&join(&path, "project.pbxproj"))? { + if cx.subject_exists(&join(&path, "project.pbxproj"))? { found.push(path); } } return Ok(found); } - Ok(cx - .files()? + let files = cx.files()?; + // A revision without any (before the app was added) has no modules. + cx.subject_matches("**/*.xcodeproj/project.pbxproj", files)?; + Ok(files .iter() .filter_map(|file| file.strip_suffix("/project.pbxproj")) .filter(|dir| dir.ends_with(".xcodeproj")) diff --git a/packages/extractors/xcode-modules/tests/fixtures/harbor-app.expected.json b/packages/extractors/xcode-modules/tests/fixtures/harbor-app.expected.json index 39291835f..46b06712b 100644 --- a/packages/extractors/xcode-modules/tests/fixtures/harbor-app.expected.json +++ b/packages/extractors/xcode-modules/tests/fixtures/harbor-app.expected.json @@ -117,6 +117,7 @@ "unresolved": [], "unresolvedModules": [] }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/extractors/xcode-modules/tests/project.rs b/packages/extractors/xcode-modules/tests/project.rs index 4f6f5dbd5..9c0b83f6d 100644 --- a/packages/extractors/xcode-modules/tests/project.rs +++ b/packages/extractors/xcode-modules/tests/project.rs @@ -22,7 +22,7 @@ fn extract(inputs: Value) -> Value { let root = fixture(); let files = repository_files(&root).unwrap(); let definition = json!({"id": "xcode", "extractor": "xcode-modules", "inputs": inputs}); - collect(&testing::context(&root, definition).with_files(files)).unwrap() + testing::extract(&testing::context(&root, definition).with_files(files), collect).unwrap() } fn find<'a>(items: &'a Value, predicate: impl Fn(&Value) -> bool, what: &str) -> &'a Value { diff --git a/packages/renderers/graph/fixtures/azure-after.json b/packages/renderers/graph/fixtures/azure-after.json index 67f69547e..c3d4199e8 100644 --- a/packages/renderers/graph/fixtures/azure-after.json +++ b/packages/renderers/graph/fixtures/azure-after.json @@ -376,6 +376,7 @@ "sourceConfidence": "authoritative", "unmatchedTemplateDependencies": 0 }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/renderers/graph/fixtures/azure-before.json b/packages/renderers/graph/fixtures/azure-before.json index 692b81e01..f06eb2b20 100644 --- a/packages/renderers/graph/fixtures/azure-before.json +++ b/packages/renderers/graph/fixtures/azure-before.json @@ -300,6 +300,7 @@ "sourceConfidence": "authoritative", "unmatchedTemplateDependencies": 0 }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/renderers/graph/fixtures/terraform-after.json b/packages/renderers/graph/fixtures/terraform-after.json index f8c44dcac..c79a8b4f5 100644 --- a/packages/renderers/graph/fixtures/terraform-after.json +++ b/packages/renderers/graph/fixtures/terraform-after.json @@ -427,6 +427,7 @@ "terraformVersion": "1.9.8", "unresolvedReferences": 0 }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/renderers/graph/fixtures/terraform-before.json b/packages/renderers/graph/fixtures/terraform-before.json index 2d5e44f26..26158450b 100644 --- a/packages/renderers/graph/fixtures/terraform-before.json +++ b/packages/renderers/graph/fixtures/terraform-before.json @@ -397,6 +397,7 @@ "terraformVersion": "1.9.8", "unresolvedReferences": 0 }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/renderers/graph/fixtures/terraform-modules-after.json b/packages/renderers/graph/fixtures/terraform-modules-after.json index 0c804bd81..196a1ec39 100644 --- a/packages/renderers/graph/fixtures/terraform-modules-after.json +++ b/packages/renderers/graph/fixtures/terraform-modules-after.json @@ -1113,6 +1113,7 @@ "source": "Terraform configuration (.tf files)", "unresolvedReferences": 0 }, + "presence": "present", "protocolVersion": 0, "relationships": [ { diff --git a/packages/renderers/graph/fixtures/terraform-modules-before.json b/packages/renderers/graph/fixtures/terraform-modules-before.json index 1c2a6c0c3..41cfd0baf 100644 --- a/packages/renderers/graph/fixtures/terraform-modules-before.json +++ b/packages/renderers/graph/fixtures/terraform-modules-before.json @@ -1037,6 +1037,7 @@ "source": "Terraform configuration (.tf files)", "unresolvedReferences": 0 }, + "presence": "present", "protocolVersion": 0, "relationships": [ { From 4083ea5a0e04e6b452ade47f365abfc5d2c29bcf Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Sat, 5 Dec 2026 02:33:17 +0000 Subject: [PATCH 3/9] Test that every built-in reports presence Refs #373 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- packages/extractors/catalog/Cargo.toml | 4 + packages/extractors/catalog/tests/presence.rs | 121 ++++++++++++++++++ 2 files changed, 125 insertions(+) create mode 100644 packages/extractors/catalog/tests/presence.rs diff --git a/packages/extractors/catalog/Cargo.toml b/packages/extractors/catalog/Cargo.toml index 0c716dee4..9829177dd 100644 --- a/packages/extractors/catalog/Cargo.toml +++ b/packages/extractors/catalog/Cargo.toml @@ -40,3 +40,7 @@ projections-extractor-xcode-modules = { path = "../xcode-modules" } projections-extractor-typescript-public-api = { path = "../typescript-public-api" } projections-extractor-workspace-dependencies = { path = "../workspace-dependencies" } serde_json = { version = "1", features = ["float_roundtrip"] } + +[dev-dependencies] +projections-extractor-sdk = { path = "../sdk", features = ["testing"] } +tempfile = "3" diff --git a/packages/extractors/catalog/tests/presence.rs b/packages/extractors/catalog/tests/presence.rs new file mode 100644 index 000000000..d86c9688f --- /dev/null +++ b/packages/extractors/catalog/tests/presence.rs @@ -0,0 +1,121 @@ +//! Every built-in extractor reports its subject's `presence` on every path: absent +//! at a revision without what its inputs name, present for the repository-wide +//! ones, and in every golden extraction its own tests keep. + +use projections_extractor_catalog::{IDS, collect}; +use projections_extractor_sdk::testing::{Process, Runner}; +use projections_extractor_sdk::{Output, normalize_extraction}; +use serde_json::{Value, json}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +/// Inputs naming what an empty revision lacks, and the presence expected there. +fn cases() -> Vec<(&'static str, Value, &'static str)> { + vec![ + ("workspace-dependencies", json!({}), "absent"), + ("repository-map", json!({}), "present"), + ("typescript-public-api", json!({"tsconfig": "tsconfig.json"}), "absent"), + ("rust-public-api", json!({"rustdocJson": "target/doc/api.json"}), "absent"), + ("go-public-api", json!({"module": "services/ledger"}), "absent"), + ("swift-public-api", json!({"symbolGraphPath": "graphs"}), "absent"), + ("cargo-dependencies", json!({}), "absent"), + ("swift-package-dependencies", json!({}), "absent"), + ("xcode-modules", json!({}), "absent"), + ("nuget-dependencies", json!({}), "absent"), + ("terraform-infrastructure", json!({"planJsonPath": "plan.json"}), "absent"), + ("terraform-modules", json!({}), "present"), + ("azure-what-if", json!({"whatIfJsonPath": "what-if.json"}), "absent"), + ("github-actions-jobs", json!({"workflowPath": ".github/workflows/ci.yml"}), "absent"), + ("github-agentic-workflows", json!({}), "absent"), + ("tetragon-policies", json!({}), "absent"), + ("dotnet-public-api", json!({"snapshot": "api.json"}), "absent"), + ("dotnet-di", json!({"snapshot": "di.json"}), "absent"), + ("nestjs-di", json!({"entry": "src/main.ts"}), "absent"), + ("spring-di", json!({"project": "services/api"}), "absent"), + ("openrewrite-data-tables", json!({"tables": "rewrite"}), "absent"), + ("efcore-schema", json!({"snapshot": "model.json"}), "absent"), + ("django-schema", json!({"settings": "shop.settings"}), "absent"), + ("code-statistics", json!({}), "present"), + ("prisma-schema", json!({}), "absent"), + ("rails-schema", json!({}), "absent"), + ("rails-routes", json!({}), "absent"), + ("renderer-scenarios", json!({}), "present"), + ("scip-file-references", json!({"index": "index.scip"}), "absent"), + ( + "command-output", + json!({"commands": [{"id": "version", "label": "Version", "command": ["tool", "--version"]}]}), + "present", + ), + ] +} + +#[test] +fn every_built_in_reports_presence_at_a_revision_without_its_subject() { + let cases = cases(); + let covered: Vec<&str> = cases.iter().map(|(id, _, _)| *id).collect(); + for id in IDS { + assert!(covered.contains(id), "add a case for built-in {id}"); + } + let scratch = tempfile::tempdir().unwrap(); + let root = scratch.path().canonicalize().unwrap(); + // A revision with only an unrelated file; a tool that runs prints a line. + fs::write(root.join("NOTES.txt"), "nothing to describe\n").unwrap(); + let runner: Arc = Arc::new(|_, _| { + Ok(Output { + stdout: "1.0\n".into(), + stderr: String::new(), + }) + }); + let process = Process { + trusted: true, + checkout: root.clone(), + runner: Some(runner), + }; + for (id, inputs, expected) in cases { + let cx = process.context(&root, json!({"id": "subject", "extractor": id, "inputs": inputs})); + let extraction = collect(id, &cx) + .and_then(|extraction| cx.finish(extraction)) + .unwrap_or_else(|error| panic!("{id}: {error:#}")); + assert_eq!(extraction["presence"], expected, "{id}: {extraction}"); + normalize_extraction(&extraction).unwrap_or_else(|error| panic!("{id}: {error:#}")); + } +} + +fn goldens(directory: &Path, found: &mut Vec) { + for entry in fs::read_dir(directory).unwrap() { + let path = entry.unwrap().path(); + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + if path.is_dir() { + goldens(&path, found); + } else if name == "expected.json" || name.ends_with(".expected.json") { + found.push(path); + } + } +} + +#[test] +fn every_golden_extraction_of_a_built_in_reports_presence() { + let extractors = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap(); + let mut files = vec![]; + for id in IDS { + let tests = extractors.join(id).join("tests"); + if tests.is_dir() { + goldens(&tests, &mut files); + } + } + let mut extractions = 0; + for file in &files { + let value: Value = serde_json::from_str(&fs::read_to_string(file).unwrap()).unwrap(); + if value.get("protocolVersion").is_none() { + continue; + } + extractions += 1; + assert!( + matches!(value["presence"].as_str(), Some("present" | "absent")), + "{} doesn't report presence", + file.display() + ); + } + assert!(extractions >= 30, "found only {extractions} golden extractions"); +} From f0457282350237ec335bc983a23ede511b5bd3fe Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Sat, 5 Dec 2026 02:33:19 +0000 Subject: [PATCH 4/9] Document built-in presence Refs #373 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- docs/builtins/extractors/go-public-api.md | 2 +- docs/contracts/extractions.md | 13 ++++++++++--- docs/design/proposals/subject-presence.md | 10 +++++++--- packages/extractors/go-public-api/README.md | 4 +++- 4 files changed, 21 insertions(+), 8 deletions(-) diff --git a/docs/builtins/extractors/go-public-api.md b/docs/builtins/extractors/go-public-api.md index b477a6921..a150f5668 100644 --- a/docs/builtins/extractors/go-public-api.md +++ b/docs/builtins/extractors/go-public-api.md @@ -65,7 +65,7 @@ repository. `projections explore` proposes the root module when there is a root Source locations are always relative to the repository root, including for a module below it. A revision without the module's `go.mod` (before it was added) -yields an empty API rather than failing. +yields an absent, empty API rather than failing. Each importable package becomes a `package` entity, and each exported symbol becomes a `constant`, `variable`, `function`, or `type`, with `method` entities diff --git a/docs/contracts/extractions.md b/docs/contracts/extractions.md index 07a5c3b4f..afb44b427 100644 --- a/docs/contracts/extractions.md +++ b/docs/contracts/extractions.md @@ -171,9 +171,16 @@ both sides), `present` (present on both sides), or `unknown` when either side is. `inferred` is true when either side's presence was inferred. Comparisons stay item-level: a subject that's added still shows every item as added. -Built-in extractors will write `presence` on every extraction, so their digests -change once when they start. In `extraction/v1`, `presence` will be required, -and the inference will go away. +Built-in extractors write `presence` on every extraction, both values, so +their digests changed once when they started. A built-in that describes the +whole repository (`code-statistics`, `repository-map`, `terraform-modules`, +`renderer-scenarios`) or a command's output (`command-output`) is always +`present`. One that discovers its files when its inputs don't name them +(`prisma-schema`, `rails-routes`, `rails-schema`, `nuget-dependencies`, +`xcode-modules`, `tetragon-policies`, `github-agentic-workflows`) is `absent` +when it discovers none, and names the globs it looked for in `missingInputs`. +In `extraction/v1`, `presence` will be required, and the inference will go +away. ## Volatile data diff --git a/docs/design/proposals/subject-presence.md b/docs/design/proposals/subject-presence.md index 131e83f38..5e6da2595 100644 --- a/docs/design/proposals/subject-presence.md +++ b/docs/design/proposals/subject-presence.md @@ -1,7 +1,8 @@ # Proposal: subject presence Status: **in progress**. Phase 1 (the contract: schema, Engine and SDK helpers) -is implemented; the other phases are proposals. Trigger: +and Phase 2 (built-in extractors write `presence`) are implemented; the other +phases are proposals. Trigger: [#373](https://github.com/githubnext/projections/issues/373). A projection describes something: a workflow, a package manifest, a set of @@ -184,14 +185,17 @@ shows every item as added. - **Phase 0**: fix #373 without a schema change. The kit and viewer use the heuristic. -- **Phase 1** (this change): the contract. Add the schema field, Engine parsing, +- **Phase 1**: the contract. Add the schema field, Engine parsing, validation, encoding, the rerun check, and the pair-state function (native, Wasm, and the TypeScript mirror). Add the SDK helpers in Rust, Node, and Python, plus documentation. Existing extractions keep their digests. - **Phase 2**: built-in extractors write `presence` on every extraction, both values. Anchors switch from `input_exists` to `subject_exists`; auxiliary inputs keep `input_exists`. Repository-wide extractors write `present`. - Built-in digests change once. + Built-in digests change once. Discovery that finds nothing (Prisma, Rails, + NuGet, Xcode, Tetragon and agentic-workflow globs) is absent rather than an + error or a silent empty extraction, and a Django settings module with no file + anywhere in the revision is absent. - **Phase 3**: consumers prefer `presence`: CLI notices and `check`, the kit and hosts, sweeps, the CI summary, and PNG snapshots. They fall back to the inferred state only when `presence` is omitted. diff --git a/packages/extractors/go-public-api/README.md b/packages/extractors/go-public-api/README.md index ed385a73e..b0e60ba56 100644 --- a/packages/extractors/go-public-api/README.md +++ b/packages/extractors/go-public-api/README.md @@ -36,7 +36,9 @@ or newer, `--trust`) and cache handling are those of `"samples/golang-api"` in a repository with no root `go.mod`: the helper loads it there, `patterns` are relative to it, and evidence still names source files from the repository root. A revision without `/go.mod` (before the -module was added) has no API, and lists it in `missingInputs`. Without `module`, +module was added) has no API: the extraction is `absent` and lists it in +`missingInputs`. So is one whose `patterns` name only directories the module +doesn't have; import-path patterns aren't checked. Without `module`, the root module is loaded. `projections explore` proposes the extractor once for a root `go.mod`, and otherwise once per module below the root (`go-public-api-`) with `module` set. From 7eadd30c2430ca9bb4b8d2ac16fc5d7bed895fff Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Sat, 5 Dec 2026 02:33:59 +0000 Subject: [PATCH 5/9] Format presence docs Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- docs/contracts/extractions.md | 11 +++++------ docs/design/proposals/subject-presence.md | 8 ++++---- packages/extractors/go-public-api/README.md | 6 +++--- packages/extractors/sdk/README.md | 8 ++++---- 4 files changed, 16 insertions(+), 17 deletions(-) diff --git a/docs/contracts/extractions.md b/docs/contracts/extractions.md index afb44b427..aeca5a5f0 100644 --- a/docs/contracts/extractions.md +++ b/docs/contracts/extractions.md @@ -171,16 +171,15 @@ both sides), `present` (present on both sides), or `unknown` when either side is. `inferred` is true when either side's presence was inferred. Comparisons stay item-level: a subject that's added still shows every item as added. -Built-in extractors write `presence` on every extraction, both values, so -their digests changed once when they started. A built-in that describes the -whole repository (`code-statistics`, `repository-map`, `terraform-modules`, +Built-in extractors write `presence` on every extraction, both values, so their +digests changed once when they started. A built-in that describes the whole +repository (`code-statistics`, `repository-map`, `terraform-modules`, `renderer-scenarios`) or a command's output (`command-output`) is always `present`. One that discovers its files when its inputs don't name them (`prisma-schema`, `rails-routes`, `rails-schema`, `nuget-dependencies`, `xcode-modules`, `tetragon-policies`, `github-agentic-workflows`) is `absent` -when it discovers none, and names the globs it looked for in `missingInputs`. -In `extraction/v1`, `presence` will be required, and the inference will go -away. +when it discovers none, and names the globs it looked for in `missingInputs`. In +`extraction/v1`, `presence` will be required, and the inference will go away. ## Volatile data diff --git a/docs/design/proposals/subject-presence.md b/docs/design/proposals/subject-presence.md index 5e6da2595..899d03fdc 100644 --- a/docs/design/proposals/subject-presence.md +++ b/docs/design/proposals/subject-presence.md @@ -185,10 +185,10 @@ shows every item as added. - **Phase 0**: fix #373 without a schema change. The kit and viewer use the heuristic. -- **Phase 1**: the contract. Add the schema field, Engine parsing, - validation, encoding, the rerun check, and the pair-state function (native, - Wasm, and the TypeScript mirror). Add the SDK helpers in Rust, Node, and - Python, plus documentation. Existing extractions keep their digests. +- **Phase 1**: the contract. Add the schema field, Engine parsing, validation, + encoding, the rerun check, and the pair-state function (native, Wasm, and the + TypeScript mirror). Add the SDK helpers in Rust, Node, and Python, plus + documentation. Existing extractions keep their digests. - **Phase 2**: built-in extractors write `presence` on every extraction, both values. Anchors switch from `input_exists` to `subject_exists`; auxiliary inputs keep `input_exists`. Repository-wide extractors write `present`. diff --git a/packages/extractors/go-public-api/README.md b/packages/extractors/go-public-api/README.md index b0e60ba56..109694959 100644 --- a/packages/extractors/go-public-api/README.md +++ b/packages/extractors/go-public-api/README.md @@ -38,9 +38,9 @@ it there, `patterns` are relative to it, and evidence still names source files from the repository root. A revision without `/go.mod` (before the module was added) has no API: the extraction is `absent` and lists it in `missingInputs`. So is one whose `patterns` name only directories the module -doesn't have; import-path patterns aren't checked. Without `module`, -the root module is loaded. `projections explore` proposes the extractor once for -a root `go.mod`, and otherwise once per module below the root +doesn't have; import-path patterns aren't checked. Without `module`, the root +module is loaded. `projections explore` proposes the extractor once for a root +`go.mod`, and otherwise once per module below the root (`go-public-api-`) with `module` set. ## Model diff --git a/packages/extractors/sdk/README.md b/packages/extractors/sdk/README.md index 66d0cc77a..87a99b62d 100644 --- a/packages/extractors/sdk/README.md +++ b/packages/extractors/sdk/README.md @@ -76,10 +76,10 @@ example with tests. to the extraction's `missingInputs`, so a revision from before the input was added extracts as empty rather than failing; - `subject_exists(path)` and `subject_matches(glob, files)`: the same for an - anchor of what the projection describes; `serve` writes `presence`, - `absent` when no anchor checked exists and `present` otherwise. Built-ins - check their subject with these, keep `input_exists` for auxiliary inputs, - and write `presence` themselves on paths that check no anchor; + anchor of what the projection describes; `serve` writes `presence`, `absent` + when no anchor checked exists and `present` otherwise. Built-ins check their + subject with these, keep `input_exists` for auxiliary inputs, and write + `presence` themselves on paths that check no anchor; - `scope()`: the scope the runner enforces, if any; - `checkout()`: where the project's installed packages are for this run (absent under container isolation and for Git objects); From d4a137b542fdd01e14baaf4d771e20bcebc45f07 Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Sat, 5 Dec 2026 02:45:20 +0000 Subject: [PATCH 6/9] Share discovery anchoring through subject_matches_any Refs #373 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- packages/extractors/django-schema/src/lib.rs | 14 ++--------- .../extractors/nuget-dependencies/src/lib.rs | 9 +++---- .../extractors/rails-routes/tests/routes.rs | 24 +++++++++++++++++++ packages/extractors/rails-schema/src/lib.rs | 10 ++------ .../extractors/rails-schema/tests/schema.rs | 6 ++++- packages/extractors/sdk/README.md | 9 ++++--- packages/extractors/sdk/src/context.rs | 20 ++++++++++++++++ packages/extractors/sdk/tests/source.rs | 16 +++++++++++++ .../tetragon-policies/src/sources.rs | 10 +------- 9 files changed, 79 insertions(+), 39 deletions(-) diff --git a/packages/extractors/django-schema/src/lib.rs b/packages/extractors/django-schema/src/lib.rs index 764fa3092..e13dc73ef 100644 --- a/packages/extractors/django-schema/src/lib.rs +++ b/packages/extractors/django-schema/src/lib.rs @@ -80,21 +80,11 @@ pub fn collect(cx: &Context) -> Result { } /// Whether the revision has a file that could be the settings `module`: a -/// `.py` or `/__init__.py` at any depth. Those that -/// match are the anchors; with neither, both are missing. +/// `.py` or `/__init__.py` at any depth. fn settings_exist(cx: &Context, module: &str) -> Result { let path = module.replace('.', "/"); let patterns = [format!("**/{path}.py"), format!("**/{path}/__init__.py")]; - let files = cx.files()?; - let matching: Vec<&String> = patterns - .iter() - .filter(|pattern| projections_extractor_sdk::glob(pattern).is_ok_and(|glob| files.iter().any(|file| glob.is_match(file)))) - .collect(); - let mut found = false; - for pattern in if matching.is_empty() { patterns.iter().collect() } else { matching } { - found |= cx.subject_matches(pattern, files)?; - } - Ok(found) + cx.subject_matches_any(&patterns.each_ref().map(String::as_str), cx.files()?) } #[cfg(test)] diff --git a/packages/extractors/nuget-dependencies/src/lib.rs b/packages/extractors/nuget-dependencies/src/lib.rs index a13d48e47..a2b91a9a5 100644 --- a/packages/extractors/nuget-dependencies/src/lib.rs +++ b/packages/extractors/nuget-dependencies/src/lib.rs @@ -100,12 +100,9 @@ fn restored(cx: &Context, d: &Value) -> Result> { .filter(|file| PROJECT_EXTENSIONS.iter().any(|extension| file.ends_with(extension))) .cloned() .collect(); - // The languages it has are the anchors, or, with none, every one is missing. - for extension in PROJECT_EXTENSIONS { - if found.is_empty() || found.iter().any(|file| file.ends_with(extension)) { - cx.subject_matches(&format!("**/*{extension}"), &found)?; - } - } + // A revision without any (before the first was added) has no packages. + let patterns = PROJECT_EXTENSIONS.map(|extension| format!("**/*{extension}")); + cx.subject_matches_any(&patterns.each_ref().map(String::as_str), &found)?; found } }; diff --git a/packages/extractors/rails-routes/tests/routes.rs b/packages/extractors/rails-routes/tests/routes.rs index c7f83d90e..8400f1091 100644 --- a/packages/extractors/rails-routes/tests/routes.rs +++ b/packages/extractors/rails-routes/tests/routes.rs @@ -265,3 +265,27 @@ end ); assert!(routes[2].endpoint.as_deref().unwrap().starts_with("redirect { |params, _|")); } + +#[test] +fn discovered_or_declared_routes_files_are_the_subject_and_a_revision_without_them_is_absent() { + use projections_extractor_sdk::testing; + let root = tempfile::tempdir().unwrap(); + fs::create_dir_all(root.path().join("web/config")).unwrap(); + fs::write(root.path().join("web/config/routes.rb"), "Rails.application.routes.draw do\nend\n").unwrap(); + let run = |inputs: Value| { + let definition = serde_json::json!({"id": "routes", "extractor": "rails-routes", "inputs": inputs}); + testing::extract( + &testing::context(root.path(), definition), + projections_extractor_rails_routes::collect, + ) + .unwrap() + }; + let discovered = run(serde_json::json!({})); + assert_eq!(discovered["presence"], "present"); + assert!(discovered.get("missingInputs").is_none()); + let declared = run(serde_json::json!({"routes": ["web/config/routes.rb", "api/config/routes.rb"]})); + assert_eq!(declared["presence"], "present"); + assert_eq!(declared["missingInputs"], serde_json::json!(["api/config/routes.rb"])); + let absent = run(serde_json::json!({"routes": "api/config/routes.rb"})); + assert_eq!(absent["presence"], "absent"); +} diff --git a/packages/extractors/rails-schema/src/lib.rs b/packages/extractors/rails-schema/src/lib.rs index 9e01758d8..06693185b 100644 --- a/packages/extractors/rails-schema/src/lib.rs +++ b/packages/extractors/rails-schema/src/lib.rs @@ -178,15 +178,9 @@ fn schema_files(cx: &Context, files: &[String], definition: &Value) -> Result strings(v, "Rails schemas")?, None => { let found: Vec<&String> = files.iter().filter(|f| !ignored(f) && schema_file(f).is_some()).collect(); - // A revision without any (before the application was added) has no tables: - // the formats it has are the anchors, or, with neither, both are missing. + // A revision without any (before the application was added) has no tables. let listed: Vec = found.iter().map(|f| (*f).clone()).collect(); - for pattern in DISCOVERED { - let glob = projections_extractor_sdk::glob(pattern)?; - if listed.is_empty() || listed.iter().any(|f| glob.is_match(f)) { - cx.subject_matches(pattern, &listed)?; - } - } + cx.subject_matches_any(&DISCOVERED, &listed)?; let mut roots: Vec<&str> = found.iter().filter_map(|f| schema_file(f).map(|(root, _)| root)).collect(); roots.sort(); roots.dedup(); diff --git a/packages/extractors/rails-schema/tests/schema.rs b/packages/extractors/rails-schema/tests/schema.rs index c263b955e..454f571a8 100644 --- a/packages/extractors/rails-schema/tests/schema.rs +++ b/packages/extractors/rails-schema/tests/schema.rs @@ -633,7 +633,11 @@ fn follows_the_applications_schema_format_when_it_keeps_both_files() { let sources = |files: &[&str]| { let definition = json!({"id": "schema", "extractor": "rails-schema", "inputs": {}}); let cx = testing::context(root.path(), definition).with_files(files.iter().map(|f| f.to_string()).collect()); - collect(&cx).unwrap()["metadata"]["sources"].clone() + // Discovered schema files are the subject; the format the application doesn't use isn't missing. + let extraction = testing::extract(&cx, collect).unwrap(); + assert_eq!(extraction["presence"], "present"); + assert!(extraction.get("missingInputs").is_none(), "{extraction}"); + extraction["metadata"]["sources"].clone() }; let both = ["config/application.rb", "db/schema.rb", "db/structure.sql"]; // Without a format it can read, schema.rb. diff --git a/packages/extractors/sdk/README.md b/packages/extractors/sdk/README.md index 87a99b62d..43a2935ee 100644 --- a/packages/extractors/sdk/README.md +++ b/packages/extractors/sdk/README.md @@ -77,9 +77,12 @@ example with tests. added extracts as empty rather than failing; - `subject_exists(path)` and `subject_matches(glob, files)`: the same for an anchor of what the projection describes; `serve` writes `presence`, `absent` - when no anchor checked exists and `present` otherwise. Built-ins check their - subject with these, keep `input_exists` for auxiliary inputs, and write - `presence` themselves on paths that check no anchor; + when no anchor checked exists and `present` otherwise. + `subject_matches_any(globs, files)` checks alternative discovery globs + (`**/*.csproj`, `**/*.fsproj`), anchoring those that match, or every one + when none does. Built-ins check their subject with these, keep + `input_exists` for auxiliary inputs, and write `presence` themselves on + paths that check no anchor; - `scope()`: the scope the runner enforces, if any; - `checkout()`: where the project's installed packages are for this run (absent under container isolation and for Git objects); diff --git a/packages/extractors/sdk/src/context.rs b/packages/extractors/sdk/src/context.rs index 43aaf14fc..63a4a4f7d 100644 --- a/packages/extractors/sdk/src/context.rs +++ b/packages/extractors/sdk/src/context.rs @@ -403,6 +403,26 @@ impl Context { Ok(matches) } + /// [`Context::subject_matches`] for alternative globs an extractor discovers + /// its subject with when its inputs don't name it, such as `**/*.csproj` and + /// `**/*.fsproj`: whether any matches one of `files`. Those that match are the + /// anchors, so an alternative the revision doesn't use isn't recorded as + /// missing; when none matches, every one is. + pub fn subject_matches_any(&self, patterns: &[&str], files: &[String]) -> Result { + let mut matching = vec![]; + for pattern in patterns { + let glob = crate::glob(pattern)?; + if files.iter().any(|file| glob.is_match(file)) { + matching.push(*pattern); + } + } + let anchors = if matching.is_empty() { patterns } else { &matching[..] }; + for pattern in anchors { + self.subject_matches(pattern, files)?; + } + Ok(!matching.is_empty()) + } + fn anchor(&self, input: &str, exists: bool) { let mut subject = self.subject.lock().expect("subject lock"); subject.checked = true; diff --git a/packages/extractors/sdk/tests/source.rs b/packages/extractors/sdk/tests/source.rs index 16bd931e1..a94aa7309 100644 --- a/packages/extractors/sdk/tests/source.rs +++ b/packages/extractors/sdk/tests/source.rs @@ -214,6 +214,22 @@ fn a_subject_none_of_whose_anchors_exists_is_absent() { ); } +#[test] +fn alternative_discovery_globs_anchor_those_the_revision_uses_or_every_one_when_it_uses_none() { + let (root, _) = repository(); + let cx = checkout(root.path()); + let files = cx.files().unwrap().to_vec(); + assert!(cx.subject_matches_any(&["**/*.json", "**/*.yaml"], &files).unwrap()); + let present = cx.finish(empty()).unwrap(); + assert_eq!(present["presence"], "present"); + assert!(present.get("missingInputs").is_none()); + let cx = checkout(root.path()); + assert!(!cx.subject_matches_any(&["**/*.prisma", "**/*.yaml"], &files).unwrap()); + let absent = cx.finish(empty()).unwrap(); + assert_eq!(absent["presence"], "absent"); + assert_eq!(absent["missingInputs"], json!(["**/*.prisma", "**/*.yaml"])); +} + #[test] fn a_subject_some_of_whose_anchors_exist_is_present_and_names_the_rest() { let (root, _) = repository(); diff --git a/packages/extractors/tetragon-policies/src/sources.rs b/packages/extractors/tetragon-policies/src/sources.rs index 821ca40a4..badbd2412 100644 --- a/packages/extractors/tetragon-policies/src/sources.rs +++ b/packages/extractors/tetragon-policies/src/sources.rs @@ -146,15 +146,7 @@ pub(crate) fn sources(root: &Path, files: &[String], definition: &Value, cx: &Co let include = match explicit { Some(paths) => globs(Some(paths), "inputs.paths")?, None => { - // The default globs that match are the anchors, or, with none matching, both are missing. - let matched: Vec<&str> = DEFAULT_PATHS - .iter() - .copied() - .filter(|pattern| projections_extractor_sdk::glob(pattern).is_ok_and(|glob| files.iter().any(|file| glob.is_match(file)))) - .collect(); - for pattern in if matched.is_empty() { DEFAULT_PATHS } else { &matched[..] } { - cx.subject_matches(pattern, files)?; - } + cx.subject_matches_any(DEFAULT_PATHS, files)?; globs(Some(&json!(DEFAULT_PATHS)), "paths")? } }; From fadf650e27b8115e78b887805d8a7f97f44ed119 Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Sat, 5 Dec 2026 02:46:18 +0000 Subject: [PATCH 7/9] Changelog: built-in extractors report their subject's presence Refs #373 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- changelog.d/414.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 changelog.d/414.md diff --git a/changelog.d/414.md b/changelog.d/414.md new file mode 100644 index 000000000..7fff4380e --- /dev/null +++ b/changelog.d/414.md @@ -0,0 +1,8 @@ +--- +section: behaviour-changes +--- + +- **Built-in extractors report whether their subject is present, and their digests change once** (#414). Every built-in extraction now carries `presence`, `present` or `absent` ([presence](docs/contracts/extractions.md#presence)), so every built-in extraction digest changes once. Saved documents, caches and digests recorded by earlier versions won't match new ones for the same revision. An extraction whose subject doesn't exist at the revision, such as a workflow the revision predates, is `absent`, and a pull request that adds it shows it as added rather than as an empty extraction. Built-ins that describe the whole repository (`code-statistics`, `repository-map`, `terraform-modules`, `renderer-scenarios`) and `command-output` are always `present`. + - When a built-in discovers its files itself and finds none, its extraction is now absent instead of an error or a silent empty extraction. This covers `prisma-schema` with no `.prisma` files (previously an error), `rails-routes`, `rails-schema`, `nuget-dependencies`, `xcode-modules`, `tetragon-policies` with its default globs, and `github-agentic-workflows`. The extraction names the globs it looked for in `missingInputs`. + - `django-schema` is absent when the revision has no file that could be its settings module. `rust-public-api` is absent when no `Cargo.toml` declares the requested `package`. `go-public-api` is absent when none of the local package directories its `patterns` name exist. + - A `github-agentic-workflows` `paths` glob that matches no workflow is now listed in `missingInputs`, as `tetragon-policies` already does, so `projections check` reports it. `paths: []` is now an error. From 7c30feff1f5c0fce1a6ab86a0cbe7c12b377bb3c Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Sat, 5 Dec 2026 02:47:36 +0000 Subject: [PATCH 8/9] Changelog: say how to fix agentic-workflows paths: [] Refs #373 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- changelog.d/414.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/changelog.d/414.md b/changelog.d/414.md index 7fff4380e..3d2c182a8 100644 --- a/changelog.d/414.md +++ b/changelog.d/414.md @@ -5,4 +5,5 @@ section: behaviour-changes - **Built-in extractors report whether their subject is present, and their digests change once** (#414). Every built-in extraction now carries `presence`, `present` or `absent` ([presence](docs/contracts/extractions.md#presence)), so every built-in extraction digest changes once. Saved documents, caches and digests recorded by earlier versions won't match new ones for the same revision. An extraction whose subject doesn't exist at the revision, such as a workflow the revision predates, is `absent`, and a pull request that adds it shows it as added rather than as an empty extraction. Built-ins that describe the whole repository (`code-statistics`, `repository-map`, `terraform-modules`, `renderer-scenarios`) and `command-output` are always `present`. - When a built-in discovers its files itself and finds none, its extraction is now absent instead of an error or a silent empty extraction. This covers `prisma-schema` with no `.prisma` files (previously an error), `rails-routes`, `rails-schema`, `nuget-dependencies`, `xcode-modules`, `tetragon-policies` with its default globs, and `github-agentic-workflows`. The extraction names the globs it looked for in `missingInputs`. - `django-schema` is absent when the revision has no file that could be its settings module. `rust-public-api` is absent when no `Cargo.toml` declares the requested `package`. `go-public-api` is absent when none of the local package directories its `patterns` name exist. - - A `github-agentic-workflows` `paths` glob that matches no workflow is now listed in `missingInputs`, as `tetragon-policies` already does, so `projections check` reports it. `paths: []` is now an error. + - A `github-agentic-workflows` `paths` glob that matches no workflow is now listed in `missingInputs`, as `tetragon-policies` already does, so `projections check` reports it. + - **`github-agentic-workflows` rejects `paths: []`**, which can break an existing definition that sets it: extraction fails with "inputs.paths must name at least one glob" where it used to return an empty extraction. Remove `paths` to read the default `.github/workflows/*.md`, or list the globs that select your workflows. From 9cb564cd4c47b9212155254dd762857f27bd557e Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Sat, 5 Dec 2026 03:31:15 +0000 Subject: [PATCH 9/9] Reject empty selections and keep absent tetragon policy sets bare - subject_matches_any normalizes alternatives as subject_matches anchors them. - nuget, rails-routes, xcode and tetragon reject an empty selection, which checked no anchor. - tetragon carries presence out of its sources: an absent policy set gains no agent, kernel or workload enrichment, and a missing chart or kustomization no longer falls through to the default globs. Refs #373 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- changelog.d/414.md | 2 + packages/extractors/catalog/tests/presence.rs | 24 ++++++++++ .../extractors/nuget-dependencies/src/lib.rs | 8 +++- packages/extractors/rails-routes/src/lib.rs | 3 +- packages/extractors/sdk/src/context.rs | 9 +++- packages/extractors/sdk/tests/source.rs | 2 +- .../extractors/tetragon-policies/README.md | 2 +- .../extractors/tetragon-policies/src/lib.rs | 9 ++-- .../tetragon-policies/src/sources.rs | 46 +++++++++++++------ .../tetragon-policies/tests/extractions.rs | 24 ++++++++++ packages/extractors/xcode-modules/src/lib.rs | 7 ++- 11 files changed, 109 insertions(+), 27 deletions(-) diff --git a/changelog.d/414.md b/changelog.d/414.md index 3d2c182a8..19615dd9e 100644 --- a/changelog.d/414.md +++ b/changelog.d/414.md @@ -6,4 +6,6 @@ section: behaviour-changes - When a built-in discovers its files itself and finds none, its extraction is now absent instead of an error or a silent empty extraction. This covers `prisma-schema` with no `.prisma` files (previously an error), `rails-routes`, `rails-schema`, `nuget-dependencies`, `xcode-modules`, `tetragon-policies` with its default globs, and `github-agentic-workflows`. The extraction names the globs it looked for in `missingInputs`. - `django-schema` is absent when the revision has no file that could be its settings module. `rust-public-api` is absent when no `Cargo.toml` declares the requested `package`. `go-public-api` is absent when none of the local package directories its `patterns` name exist. - A `github-agentic-workflows` `paths` glob that matches no workflow is now listed in `missingInputs`, as `tetragon-policies` already does, so `projections check` reports it. + - **An empty selection is now an error**: `paths: []` in `tetragon-policies`, `routes: []` in `rails-routes`, `assetsPaths: []` or `projects: []` in `nuget-dependencies` and `projects: []` in `xcode-modules` fail with a message saying the input must name at least one file, where they used to return an empty extraction. Remove the input to discover the files, or list them. + - With `helm` or `kustomize` set and no `paths`, `tetragon-policies` no longer reads the default YAML globs when the chart or kustomization is missing, as its documentation says; the policy set is absent instead. - **`github-agentic-workflows` rejects `paths: []`**, which can break an existing definition that sets it: extraction fails with "inputs.paths must name at least one glob" where it used to return an empty extraction. Remove `paths` to read the default `.github/workflows/*.md`, or list the globs that select your workflows. diff --git a/packages/extractors/catalog/tests/presence.rs b/packages/extractors/catalog/tests/presence.rs index d86c9688f..037333b66 100644 --- a/packages/extractors/catalog/tests/presence.rs +++ b/packages/extractors/catalog/tests/presence.rs @@ -119,3 +119,27 @@ fn every_golden_extraction_of_a_built_in_reports_presence() { } assert!(extractions >= 30, "found only {extractions} golden extractions"); } + +#[test] +fn an_empty_selection_is_an_error_rather_than_an_unreported_presence() { + let scratch = tempfile::tempdir().unwrap(); + let root = scratch.path().canonicalize().unwrap(); + fs::write(root.join("policy.yaml"), "kind: ConfigMap\n").unwrap(); + let process = Process { + trusted: true, + checkout: root.clone(), + runner: None, + }; + for (id, inputs) in [ + ("nuget-dependencies", json!({"assetsPaths": []})), + ("nuget-dependencies", json!({"projects": []})), + ("rails-routes", json!({"routes": []})), + ("xcode-modules", json!({"projects": []})), + ("tetragon-policies", json!({"paths": []})), + ("github-agentic-workflows", json!({"paths": []})), + ] { + let cx = process.context(&root, json!({"id": "subject", "extractor": id, "inputs": inputs})); + let error = collect(id, &cx).map_err(|error| format!("{error:#}")).unwrap_err(); + assert!(error.contains("at least one"), "{id} {inputs}: {error}"); + } +} diff --git a/packages/extractors/nuget-dependencies/src/lib.rs b/packages/extractors/nuget-dependencies/src/lib.rs index a2b91a9a5..e80dd7e33 100644 --- a/packages/extractors/nuget-dependencies/src/lib.rs +++ b/packages/extractors/nuget-dependencies/src/lib.rs @@ -55,7 +55,9 @@ pub fn collect(cx: &Context) -> Result { /// ignores isn't part of the revision, so it is named rather than treated as missing. fn imported(cx: &Context, d: &Value) -> Result> { let mut assets = vec![]; - for filename in strings(&d["inputs"]["assetsPaths"], "inputs.assetsPaths")? { + let declared = strings(&d["inputs"]["assetsPaths"], "inputs.assetsPaths")?; + ensure!(!declared.is_empty(), "inputs.assetsPaths must name at least one assets file"); + for filename in declared { // A revision without a declared assets file (before its project was added) has no packages there. if cx.subject_exists(&filename)? { assets.push((filename.clone(), cx.read_json(&filename)?)); @@ -86,7 +88,9 @@ fn restored(cx: &Context, d: &Value) -> Result> { let projects = match d["inputs"].get("projects") { Some(value) => { let mut present = vec![]; - for project in strings(value, "inputs.projects")? { + let declared = strings(value, "inputs.projects")?; + ensure!(!declared.is_empty(), "inputs.projects must name at least one project file"); + for project in declared { if cx.subject_exists(&project)? { present.push(project); } diff --git a/packages/extractors/rails-routes/src/lib.rs b/packages/extractors/rails-routes/src/lib.rs index aea7aaf2b..20dfdd9ac 100644 --- a/packages/extractors/rails-routes/src/lib.rs +++ b/packages/extractors/rails-routes/src/lib.rs @@ -15,7 +15,7 @@ mod scope; pub use build::signature; pub use mapper::{Route, Unresolved}; -use anyhow::{Result, bail}; +use anyhow::{Result, bail, ensure}; use projections_extractor_ruby_support::{Stmt, inflect::Inflections, parse}; use projections_extractor_sdk::{Context, Descriptor, Trust, strings}; use serde_json::{Value, json}; @@ -174,6 +174,7 @@ fn routes_files(cx: &Context, files: &[String], definition: &Value) -> Result Result { + // As subject_matches normalizes them, so an alternative is matched as it is anchored. + let patterns: Vec<&str> = patterns + .iter() + .map(|pattern| pattern.trim_start_matches("./").trim_end_matches('/')) + .collect(); let mut matching = vec![]; - for pattern in patterns { + for pattern in &patterns { let glob = crate::glob(pattern)?; if files.iter().any(|file| glob.is_match(file)) { matching.push(*pattern); } } - let anchors = if matching.is_empty() { patterns } else { &matching[..] }; + let anchors = if matching.is_empty() { &patterns[..] } else { &matching[..] }; for pattern in anchors { self.subject_matches(pattern, files)?; } diff --git a/packages/extractors/sdk/tests/source.rs b/packages/extractors/sdk/tests/source.rs index a94aa7309..9ad14be6e 100644 --- a/packages/extractors/sdk/tests/source.rs +++ b/packages/extractors/sdk/tests/source.rs @@ -219,7 +219,7 @@ fn alternative_discovery_globs_anchor_those_the_revision_uses_or_every_one_when_ let (root, _) = repository(); let cx = checkout(root.path()); let files = cx.files().unwrap().to_vec(); - assert!(cx.subject_matches_any(&["**/*.json", "**/*.yaml"], &files).unwrap()); + assert!(cx.subject_matches_any(&["./src/*.json", "**/*.yaml"], &files).unwrap()); let present = cx.finish(empty()).unwrap(); assert_eq!(present["presence"], "present"); assert!(present.get("missingInputs").is_none()); diff --git a/packages/extractors/tetragon-policies/README.md b/packages/extractors/tetragon-policies/README.md index 67d6b1e0f..009cbe183 100644 --- a/packages/extractors/tetragon-policies/README.md +++ b/packages/extractors/tetragon-policies/README.md @@ -27,7 +27,7 @@ to have changes interpreted (newly enforced, scope broadened, coverage lost). | Input | Meaning | | --- | --- | -| `paths` | Globs selecting YAML files. Default: every `.yaml` and `.yml` file (none when `helm` or `kustomize` is set). A file is parsed only if it mentions `TracingPolicy`; other documents in it (a `ConfigMap`, say) are ignored. Explicit `paths` that match no file fail | +| `paths` | Globs selecting YAML files. Default: every `.yaml` and `.yml` file (none when `helm` or `kustomize` is set). A file is parsed only if it mentions `TracingPolicy`; other documents in it (a `ConfigMap`, say) are ignored. An explicit glob that matches no file is listed in `missingInputs`; when none matches, the policy set is absent. `paths: []` is an error | | `exclude` | Globs to skip | | `namespace` | The namespace of `TracingPolicyNamespaced` resources and workloads that name none; otherwise namespaced policies apply to "the namespace the policy is applied to" and workloads to `default` | | `renderedManifestsPath` | One file of already rendered manifests (for example `helm template` output that CI wrote) to read instead of everything else | diff --git a/packages/extractors/tetragon-policies/src/lib.rs b/packages/extractors/tetragon-policies/src/lib.rs index 6b7899120..bbed1a17d 100644 --- a/packages/extractors/tetragon-policies/src/lib.rs +++ b/packages/extractors/tetragon-policies/src/lib.rs @@ -76,7 +76,7 @@ fn extract(cx: &Context) -> Result { .filter(|v| !v.is_null()) .map(|v| text(v, "inputs.namespace")) .transpose()?; - let sources = sources(root, files, definition, cx)?; + let (sources, present) = sources(root, files, definition, cx)?; let crds = crds(cx, root, inputs)?; let mut model = policy::Model::default(); let read = documents::read(cx, &mut model, &sources, crds.as_ref(), namespace)?; @@ -92,19 +92,20 @@ fn extract(cx: &Context) -> Result { } if let Some(path) = inputs.get("agentValuesPath").filter(|v| !v.is_null()) { let path = text(path, "inputs.agentValuesPath")?; - if cx.input_exists(path)? { + // An absent policy set gains nothing from what describes where it would run. + if cx.input_exists(path)? && present { enrich::agent(&mut model, root, path)?; } } if let Some(path) = inputs.get("kernelProfilesPath").filter(|v| !v.is_null()) { let path = text(path, "inputs.kernelProfilesPath")?; - if cx.input_exists(path)? { + if cx.input_exists(path)? && present { enrich::kernels(&mut model, root, path)?; } } if let Some(patterns) = inputs.get("workloadPaths").filter(|v| !v.is_null()) { let patterns = matching(cx, files, patterns, "inputs.workloadPaths", false)?; - if patterns != json!([]) { + if patterns != json!([]) && present { enrich::workloads(&mut model, root, files, &patterns, namespace)?; } } diff --git a/packages/extractors/tetragon-policies/src/sources.rs b/packages/extractors/tetragon-policies/src/sources.rs index badbd2412..723514596 100644 --- a/packages/extractors/tetragon-policies/src/sources.rs +++ b/packages/extractors/tetragon-policies/src/sources.rs @@ -116,39 +116,55 @@ pub(crate) fn matching(cx: &Context, files: &[String], patterns: &Value, label: Ok(json!(present)) } -pub(crate) fn sources(root: &Path, files: &[String], definition: &Value, cx: &Context) -> Result> { +/// The manifests to read, and whether the policy set is present: whether any of +/// what selects it (rendered manifests, a chart, a kustomization, `paths` or the +/// default globs) exists at the revision. +pub(crate) fn sources(root: &Path, files: &[String], definition: &Value, cx: &Context) -> Result<(Vec, bool)> { let inputs = &definition["inputs"]; if let Some(path) = inputs.get("renderedManifestsPath").filter(|v| !v.is_null()) { let path = text(path, "inputs.renderedManifestsPath")?; if !cx.subject_exists(path)? { - return Ok(vec![]); + return Ok((vec![], false)); } - return Ok(vec![Source { + let source = Source { label: path.to_owned(), text: read_source(root, path)?, globbed: false, - }]); + }; + return Ok((vec![source], true)); } + let renders = ["helm", "kustomize"] + .iter() + .any(|tool| inputs.get(*tool).is_some_and(|value| !value.is_null())); let mut sources = rendered(root, definition, cx)?; + // A source is rendered only from a chart or kustomization the revision has. + let rendered = !sources.is_empty(); let explicit = inputs .get("paths") .filter(|v| !v.is_null()) - .map(|paths| matching(cx, files, paths, "inputs.paths", true)) + .map(|paths| { + anyhow::ensure!( + paths.as_array().is_none_or(|paths| !paths.is_empty()), + "inputs.paths must name at least one glob" + ); + matching(cx, files, paths, "inputs.paths", true) + }) .transpose()?; - if !sources.is_empty() && explicit.is_none() { - return Ok(sources); + // With a chart or kustomization, files are read only when `paths` selects them. + if renders && explicit.is_none() { + return Ok((sources, rendered)); } // Every declared glob matches nothing: the revision has none of the policies yet. if explicit.as_ref().is_some_and(|paths| paths == &json!([])) { - return Ok(sources); + return Ok((sources, rendered)); } let explicit = explicit.as_ref(); - let include = match explicit { - Some(paths) => globs(Some(paths), "inputs.paths")?, - None => { - cx.subject_matches_any(DEFAULT_PATHS, files)?; - globs(Some(&json!(DEFAULT_PATHS)), "paths")? - } + let (include, globbed) = match explicit { + Some(paths) => (globs(Some(paths), "inputs.paths")?, true), + None => ( + globs(Some(&json!(DEFAULT_PATHS)), "paths")?, + cx.subject_matches_any(DEFAULT_PATHS, files)?, + ), }; let exclude = globs(inputs.get("exclude").filter(|v| !v.is_null()), "inputs.exclude")?; let mut matched: Vec<&String> = files @@ -167,5 +183,5 @@ pub(crate) fn sources(root: &Path, files: &[String], definition: &Value, cx: &Co }); } } - Ok(sources) + Ok((sources, rendered || globbed)) } diff --git a/packages/extractors/tetragon-policies/tests/extractions.rs b/packages/extractors/tetragon-policies/tests/extractions.rs index b34d6e0bf..45c895e42 100644 --- a/packages/extractors/tetragon-policies/tests/extractions.rs +++ b/packages/extractors/tetragon-policies/tests/extractions.rs @@ -745,3 +745,27 @@ fn fixtures_validate_against_tetragons_published_crds() { )] ); } + +#[test] +fn an_absent_policy_set_is_not_enriched_by_auxiliary_inputs_the_revision_has() { + let scratch = Scratch::new("absent-enriched"); + fs::create_dir_all(scratch.0.join("deploy")).unwrap(); + fs::write(scratch.0.join("deploy/tetragon-values.yaml"), "tetragon:\n enabled: true\n").unwrap(); + let root = scratch.0.canonicalize().unwrap(); + let run = |cx: projections_extractor_sdk::Context| testing::extract(&cx, collect).unwrap(); + let definition = |inputs: Value| json!({"id":"runtime-policies","extractor":"tetragon-policies","inputs":inputs}); + // The agent's values exist, but none of the policies do: absent, with nothing added. + let absent = run(testing::context( + &root, + definition(json!({"paths": ["deploy/tetragon/*.yaml"], "agentValuesPath": "deploy/tetragon-values.yaml"})), + )); + assert_eq!( + (absent["presence"].as_str(), absent["entities"].clone()), + (Some("absent"), json!([])) + ); + normalize(&absent); + // A chart the revision lacks is absent too, without reading unrelated YAML by the default globs. + let chart = run(testing::trusted(&root, definition(json!({"helm": {"chart": "charts/policies"}})))); + assert_eq!(chart["presence"], "absent"); + assert_eq!(chart["missingInputs"], json!(["charts/policies"])); +} diff --git a/packages/extractors/xcode-modules/src/lib.rs b/packages/extractors/xcode-modules/src/lib.rs index b84a0dc75..4666a0b96 100644 --- a/packages/extractors/xcode-modules/src/lib.rs +++ b/packages/extractors/xcode-modules/src/lib.rs @@ -109,7 +109,12 @@ pub fn collect(cx: &Context) -> Result { fn paths(cx: &Context, inputs: &Value) -> Result> { if let Some(declared) = inputs.get("projects") { let mut found = Vec::new(); - for path in strings(declared, "inputs.projects")? { + let declared = strings(declared, "inputs.projects")?; + ensure!( + !declared.is_empty(), + "`inputs.projects` must name at least one .xcodeproj directory" + ); + for path in declared { let path = path.trim_end_matches('/').to_owned(); ensure!( path.ends_with(".xcodeproj"),