diff --git a/crates/pons-cli/src/main.rs b/crates/pons-cli/src/main.rs index c7e0c6a..09bd58e 100644 --- a/crates/pons-cli/src/main.rs +++ b/crates/pons-cli/src/main.rs @@ -326,6 +326,8 @@ fn run_scan( fail_on_skips: bool, required_languages: &[String], ) -> Result { + let absolute_path = std::path::absolute(path)?; + let path = absolute_path.as_path(); if !path.exists() { bail!("no such path: {}", path.display()); } diff --git a/crates/pons-cli/tests/contracts.rs b/crates/pons-cli/tests/contracts.rs index 85f0150..9f96d25 100644 --- a/crates/pons-cli/tests/contracts.rs +++ b/crates/pons-cli/tests/contracts.rs @@ -269,3 +269,112 @@ fn a_finding_outside_the_scan_root_is_rejected() { String::from_utf8_lossy(&rejected.stderr) ); } + +#[test] +fn a_relative_windows_report_validates_on_every_reader_host() { + fn rebase(value: &mut Value, root: &str) { + match value { + Value::String(text) => { + if let Some(suffix) = text.strip_prefix(root) { + *text = format!("repo{suffix}").replace('/', "\\"); + } + } + Value::Array(values) => values.iter_mut().for_each(|value| rebase(value, root)), + Value::Object(values) => values.values_mut().for_each(|value| rebase(value, root)), + _ => (), + } + } + let fixture = Fixture::new(); + let mut report = fixture.scan(); + let root = report["scanned"]["root"].as_str().unwrap().to_owned(); + rebase(&mut report, &root); + assert_eq!(report["scanned"]["root"], "repo"); + let result = fixture.validate(&report); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); +} + +#[test] +fn ambiguous_legacy_paths_require_one_consistent_record_and_fingerprint() { + use pons_core::{corroborate::fingerprint_of, finding::EvidenceClass}; + fn replace_path(value: &mut Value, original: &str, replacement: &str) { + match value { + Value::String(text) if text == original => *text = replacement.into(), + Value::Array(values) => values + .iter_mut() + .for_each(|v| replace_path(v, original, replacement)), + Value::Object(values) => values + .values_mut() + .for_each(|v| replace_path(v, original, replacement)), + _ => (), + } + } + let fixture = Fixture::new(); + let original = fixture.scan(); + let original_file = original["findings"][0]["location"]["file"] + .as_str() + .unwrap(); + for (root, file, key, conflicting_key) in [ + ( + "//server/share", + r"//server/share\sample.php", + "sample.php", + "server/share/sample.php", + ), + ( + "repo", + r"repo\sub/sample.php", + "repo/sub/sample.php", + "sub/sample.php", + ), + ( + r"src\sample.php", + r"src\sample.php", + "sample.php", + "src/sample.php", + ), + ( + r"src\sample.php", + r"src\sample.php", + "src/sample.php", + "sample.php", + ), + ] { + let mut report = original.clone(); + replace_path(&mut report, original_file, file); + report["scanned"]["root"] = json!(root); + for finding in report["findings"].as_array_mut().unwrap() { + let evidence: EvidenceClass = + serde_json::from_value(finding["evidence"].clone()).unwrap(); + let line = finding["location"]["line_start"].as_u64().unwrap() as usize; + finding["semantic_fingerprint"] = json!(fingerprint_of(key, line, evidence)); + } + for record in report["evidence_contract"]["records"] + .as_array_mut() + .unwrap() + { + record["path"] = json!(key); + } + let result = fixture.validate(&report); + assert!( + result.status.success(), + "{key}: {}", + String::from_utf8_lossy(&result.stderr) + ); + let frozen_result = fixture.validate(&as_0_4_0(&report)); + assert!( + frozen_result.status.success(), + "frozen {key}: {}", + String::from_utf8_lossy(&frozen_result.stderr) + ); + report["evidence_contract"]["records"][0]["path"] = json!(conflicting_key); + assert_eq!( + fixture.validate(&report).status.code(), + Some(2), + "mixed interpretations accepted" + ); + } +} diff --git a/crates/pons-cli/tests/coverage.rs b/crates/pons-cli/tests/coverage.rs index 04972fb..44d3099 100644 --- a/crates/pons-cli/tests/coverage.rs +++ b/crates/pons-cli/tests/coverage.rs @@ -166,6 +166,70 @@ fn jsx_keyword_attributes_reach_analysis_and_validate() { assert!(report["scanned"]["skipped"].as_array().unwrap().is_empty()); assert!(pons_core::report::validate::validate(&report.to_string()).is_ok()); } + +#[test] +fn relative_cli_inputs_emit_absolute_roots() { + let t = Temp::new(); + fs::write(t.0.join("input.js"), "const value = 1;").unwrap(); + for extra in [&[][..], &["--lang", "javascript"][..]] { + let out = Command::new(env!("CARGO_BIN_EXE_pons")) + .current_dir(&t.0) + .args(["scan", "input.js", "--format", "json"]) + .args(extra) + .output() + .unwrap(); + assert_eq!(out.status.code(), Some(0)); + let report: Value = serde_json::from_slice(&out.stdout).unwrap(); + let expected = if extra.is_empty() { + t.0.join("input.js") + } else { + t.0.clone() + }; + assert_eq!( + PathBuf::from(report["scanned"]["root"].as_str().unwrap()), + expected + ); + assert!(pons_core::report::validate::validate(&report.to_string()).is_ok()); + } + let out = Command::new(env!("CARGO_BIN_EXE_pons")) + .current_dir(&t.0) + .args(["scan", ".", "--format", "json"]) + .output() + .unwrap(); + assert_eq!(out.status.code(), Some(0)); + let report: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!( + PathBuf::from(report["scanned"]["root"].as_str().unwrap()), + t.0 + ); +} + +#[cfg(unix)] +#[test] +fn relative_posix_colon_and_backslash_filename_keeps_its_evidence_boundary() { + let t = Temp::new(); + let file = r"a:b\c.php"; + fs::write( + t.0.join(file), + ", pub anchors: std::collections::BTreeMap, pub coverage_failures: Vec, - /// The root exactly as the caller gave it — never canonicalised, so - /// relative invocations stay relative in the output. + /// Normal scans use an absolute root without resolving symbolic links. + /// Explicit `scan_files` callers retain their supplied label. Absolute + /// roots may contain checkout details; exchange keys are root-relative. pub root: String, pub findings: Vec, pub files_scanned: usize, @@ -197,6 +198,10 @@ impl Engine { /// splitting them by which layer noticed would only invite a consumer to /// handle one and miss the others. pub fn scan(&self, root: &Path) -> anyhow::Result { + // Absolute roots disambiguate POSIX filenames that resemble Windows + // drive paths without requiring access to the producer's filesystem. + let absolute_root = std::path::absolute(root)?; + let root = absolute_root.as_path(); let discovery = source::discover(root)?; let mut report = self.scan_files(root, &discovery.files); report.inventory.extend(discovery.inventory); diff --git a/crates/pons-core/src/evidence.rs b/crates/pons-core/src/evidence.rs index ff1186b..355981d 100644 --- a/crates/pons-core/src/evidence.rs +++ b/crates/pons-core/src/evidence.rs @@ -8,14 +8,22 @@ use crate::{ use serde::{Deserialize, Serialize}; pub(crate) const ASSUMPTION: &str = "Only registered rule semantics and declared parser/model coverage; no runtime safety certification"; +// Writers retain the native path semantics of the historical format. pub(crate) fn relative_path(file: &str, root: &str) -> String { - relative_path_details(file, root).0 + let path = std::path::Path::new(file); + let root = std::path::Path::new(root); + let base = if path == root { + root.parent().unwrap_or(root) + } else { + root + }; + path.strip_prefix(base) + .unwrap_or(path) + .to_string_lossy() + .replace('\\', "/") } -pub(crate) fn relative_path_details(file: &str, root: &str) -> (String, bool) { - let windows = root.as_bytes().get(1) == Some(&b':') - || root.starts_with("\\\\") - || (cfg!(windows) && !root.starts_with('/')); +fn path_for_style(file: &str, root: &str, windows: bool) -> (String, bool) { let file = if windows { file.replace('\\', "/") } else { @@ -26,8 +34,6 @@ pub(crate) fn relative_path_details(file: &str, root: &str) -> (String, bool) { } else { root.into() }; - // A file scan has root == file. Do not consult the validator's filesystem: - // the original checkout may no longer exist where evidence is consumed. let base = if file == root { root.rsplit_once('/').map_or("", |(parent, _)| parent) } else { @@ -45,36 +51,73 @@ pub(crate) fn relative_path_details(file: &str, root: &str) -> (String, bool) { ) } +// Historical relative roots do not identify the producer's platform. Readers +// enumerate both lexical interpretations and require the record and fingerprint +// to agree on ONE of them; they never consult their own filesystem or host OS. +pub(crate) fn path_candidates(file: &str, root: &str) -> Vec<(String, bool)> { + let drive_absolute = root.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) + && root.as_bytes().get(1) == Some(&b':') + && root + .as_bytes() + .get(2) + .is_some_and(|c| matches!(c, b'/' | b'\\')); + if drive_absolute || root.starts_with("\\\\") { + return vec![path_for_style(file, root, true)]; + } + let posix = path_for_style(file, root, false); + if root.starts_with('/') && !root.starts_with("//") { + return vec![posix]; + } + let windows = path_for_style(file, root, true); + if windows == posix { + vec![posix] + } else { + vec![posix, windows] + } +} + #[cfg(test)] mod portable_paths { + use super::path_candidates; #[test] fn windows_reports_have_the_same_keys_on_every_reader_host() { assert_eq!( - super::relative_path(r"C:\repo\sample.php", r"C:\repo"), - "sample.php" + path_candidates(r"C:\repo\sample.php", r"C:\repo"), + vec![("sample.php".into(), true)] ); assert_eq!( - super::relative_path(r"C:\repo\sample.php", r"C:\repo\sample.php"), - "sample.php" + path_candidates(r"C:\repo\sample.php", r"C:\repo\sample.php"), + vec![("sample.php".into(), true)] ); assert_eq!( - super::relative_path(r"C:\outside\sample.php", r"C:\repo"), - "C:/outside/sample.php" + path_candidates(r"C:\outside\sample.php", r"C:\repo"), + vec![("C:/outside/sample.php".into(), false)] + ); + assert!(path_candidates(r"repo\a.py", "repo").contains(&("a.py".into(), true))); + assert!(path_candidates(r".\a.py", ".").contains(&("a.py".into(), true))); + assert!( + path_candidates(r"//server/share\sample.php", "//server/share") + .contains(&("sample.php".into(), true)) ); } #[test] - fn posix_filename_boundaries_survive_single_file_scans() { - for file in [r"/tmp/a\b.py", "/tmp/a:b.py"] { - assert_eq!( - super::relative_path(file, file), - super::relative_path(file, "/tmp") - ); - assert!(super::relative_path_details(file, "/tmp").1); - } + fn posix_boundaries_and_ambiguous_historical_keys_are_preserved() { assert_eq!( - super::relative_path(r"/tmp/a\b.py", r"/tmp/a\b.py"), - "a/b.py" + path_candidates(r"/tmp/a\b.py", r"/tmp/a\b.py"), + vec![("a/b.py".into(), true)] ); + assert!(!path_candidates(r"/tmp/repo\outside/a.py", "/tmp/repo")[0].1); + for (file, root, expected) in [ + (r"repo\sub/a.py", "repo", "repo/sub/a.py"), + (r"repo\sub/a.py", "repo", "sub/a.py"), + (r"src\a.py", r"src\a.py", "a.py"), + (r"src\a.py", r"src\a.py", "src/a.py"), + (r"a:b\c.py", r"a:b\c.py", "a:b/c.py"), + ] { + assert!(path_candidates(file, root) + .iter() + .any(|(path, _)| path == expected)); + } } } #[derive(Debug, Clone, Default, Serialize, Deserialize)] diff --git a/crates/pons-core/src/report/validate.rs b/crates/pons-core/src/report/validate.rs index 8055676..966ab0e 100644 --- a/crates/pons-core/src/report/validate.rs +++ b/crates/pons-core/src/report/validate.rs @@ -240,9 +240,11 @@ fn validate_value(v: Value) -> Result { // is right for rendering and wrong for a join key, so it is refused. if has_corroboration { let file = location["file"].as_str().context("missing finding file")?; - let (relative, stripped) = crate::evidence::relative_path_details(file, root); + let candidates = crate::evidence::path_candidates(file, root); ensure!( - is_root_relative(&relative, stripped), + candidates + .iter() + .any(|(path, stripped)| is_root_relative(path, *stripped)), "finding path is not inside the scan root" ); } @@ -255,13 +257,12 @@ fn validate_value(v: Value) -> Result { let line = location["line_start"] .as_u64() .context("missing finding line")? as usize; - let expected = crate::corroborate::fingerprint_of( - &crate::evidence::relative_path(file, root), - line, - evidence, - ); ensure!( - f["semantic_fingerprint"] == expected.as_str(), + crate::evidence::path_candidates(file, root) + .iter() + .any(|(path, stripped)| is_root_relative(path, *stripped) + && f["semantic_fingerprint"] + == crate::corroborate::fingerprint_of(path, line, evidence)), "semantic fingerprint mismatch" ); } @@ -316,7 +317,15 @@ fn validate_value(v: Value) -> Result { r.rule == f["rule_id"] && serde_json::to_value(r.tier)? == f["tier"] && serde_json::to_value(r.evidence)? == f["evidence"] - && r.path == crate::evidence::relative_path(file, root) + && crate::evidence::path_candidates(file, root) + .iter() + .any(|(path, stripped)| r.path == *path + && (!has_corroboration + || (is_root_relative(path, *stripped) + && f["semantic_fingerprint"] + == crate::corroborate::fingerprint_of( + path, r.line, r.evidence + )))) && Some(r.line as u64) == f["location"]["line_start"].as_u64() && r.trace == f["evidence_note"] && r.counterconditions == counterconditions diff --git a/docs/PLAN.adoc b/docs/PLAN.adoc index cd5345c..3edb68e 100644 --- a/docs/PLAN.adoc +++ b/docs/PLAN.adoc @@ -464,10 +464,15 @@ file that could not be parsed. It is an **empty array when nothing was skipped, never omitted** — a consumer must be able to tell "clean" from "the key is missing so I cannot tell". One unreadable subdirectory is a skip, not a fatal error (#29); an unopenable **root** is still an operational error and exits 2, -per ADR-0005. `scanned.root` is the root exactly as the caller spelled it and is -deliberately not canonicalised, so a relative invocation stays relative — the -absolute form would be a build-machine detail, the same one Appendix E strips -out of `artifactLocation.uri`. +per ADR-0005. Normal CLI scans, forced-language scans and `Engine::scan` now +emit an absolute `scanned.root`, without resolving symbolic links. Explicit +`scan_files` callers retain their supplied root label. Absolute roots can +contain checkout details; consumers should use the root-relative exchange +keys, not publish the whole local root as an artifact identifier. Historical +relative-root reports remain readable. When a relative spelling admits both +POSIX and Windows interpretations, validation requires the record path and +semantic fingerprint to agree on one interpretation; it cannot prove a +producer platform that the historical envelope never recorded. === Versioning this envelope diff --git a/docs/echo-362-verification.adoc b/docs/echo-362-verification.adoc index 49effb1..b244f52 100644 --- a/docs/echo-362-verification.adoc +++ b/docs/echo-362-verification.adoc @@ -90,3 +90,24 @@ The updated Windows workspace suite passed 258 test executions; all-target Clippy, eight parser regressions and the 116-parse upstream corpus passed. The generator provenance is unchanged; the external scanner revision advances with the explicit Unicode boundary repair. + +The subsequent review identified ambiguous relative source paths. Normal CLI +scans (including forced grammars) and `Engine::scan` now use absolute roots, +so POSIX filenames resembling drive paths remain recognisable as POSIX input. +The reader derives relative Windows directory paths from their separators, +independently of its own operating system. Regression reports are rebased to +Windows relative syntax and validated on both hosted operating systems. + +Historical path behaviour was checked against commits `6a20ca7` and +`84f58f9`: those implementations determined the parent before replacing +backslashes. On POSIX, a single file `/tmp/a\b.py` therefore produced +`a/b.py`, as the current regression requires. The later temporary early- +normalisation bug is not adopted as the frozen 0.4.0 format's semantics. +Old reports with intrinsically ambiguous relative roots lack explicit +producer-platform metadata. The reader preserves both POSIX and Windows +interpretations and requires the record path and semantic fingerprint to +agree on the same one. Native writers retain the original path behaviour. +This establishes internal consistency, not a unique historical filesystem +identity. Tests cover both 0.4.0 and 0.5.0 legacy forms and reject mixed +interpretations; the Windows workspace suite passed 261 test executions, +with all-target Clippy and the eight CLI contract tests passing.