From 20dc5f311ee2197e77387630947f12ad3e237d62 Mon Sep 17 00:00:00 2001 From: Lee Faus Date: Wed, 25 Nov 2026 12:42:31 -0500 Subject: [PATCH 1/4] new review --- Cargo.lock | 13 + Cargo.toml | 2 + .../src/turn/orchestrator/attestation.rs | 122 +- atomic-audit/AUDITS.md | 84 + atomic-audit/CONVENTIONS.md | 109 + atomic-audit/Cargo.toml | 21 + atomic-audit/IMPACT.md | 74 + atomic-audit/README.md | 182 + atomic-audit/RISK.md | 123 + atomic-audit/src/catalog.rs | 257 ++ atomic-audit/src/extract/languages.rs | 1181 ++++++ atomic-audit/src/extract/mod.rs | 634 ++++ atomic-audit/src/extract/tests.rs | 558 +++ atomic-audit/src/extract/tokens.rs | 174 + atomic-audit/src/impact/analysis.rs | 305 ++ atomic-audit/src/impact/mod.rs | 94 + atomic-audit/src/impact/tests.rs | 463 +++ atomic-audit/src/lib.rs | 27 + atomic-audit/src/metrics.rs | 346 ++ atomic-audit/src/risk.rs | 310 ++ atomic-audit/src/risk/fqn_facts.json | 79 + atomic-audit/src/risk/tests.rs | 227 ++ atomic-audit/src/structural.rs | 309 ++ atomic-audit/src/substantive/branching.rs | 154 + atomic-audit/src/substantive/mod.rs | 192 + atomic-audit/src/substantive/rust.rs | 542 +++ atomic-audit/src/substantive/tests.rs | 258 ++ atomic-canonical/Cargo.toml | 1 + atomic-canonical/src/lib.rs | 2 + atomic-canonical/src/review_finding.rs | 279 ++ atomic-canonical/src/review_graph.rs | 202 ++ atomic-cli/Cargo.toml | 2 + atomic-cli/README.md | 74 + atomic-cli/skills/review/SKILL.md | 289 ++ .../review/references/review-contract.md | 522 +++ atomic-cli/src/commands/agent/mod.rs | 2 + atomic-cli/src/commands/agent/publication.rs | 184 + atomic-cli/src/commands/intent/graph.rs | 37 +- atomic-cli/src/commands/mod.rs | 2 + atomic-cli/src/commands/review/analysis.rs | 725 ++++ .../src/commands/review/assets/README.md | 21 + .../commands/review/assets/atomic-logo.png | Bin 0 -> 37621 bytes atomic-cli/src/commands/review/graph.rs | 979 +++++ atomic-cli/src/commands/review/html.rs | 475 +++ atomic-cli/src/commands/review/impact.rs | 273 ++ atomic-cli/src/commands/review/incremental.rs | 3188 +++++++++++++++++ .../src/commands/review/metric_output.rs | 559 +++ atomic-cli/src/commands/review/mod.rs | 121 + .../src/commands/review/presentation.rs | 302 ++ atomic-cli/src/commands/review/progress.rs | 68 + atomic-cli/src/commands/review/publish.rs | 1329 +++++++ atomic-cli/src/commands/review/risk.rs | 480 +++ atomic-cli/src/commands/review/risk_facts.rs | 463 +++ atomic-cli/src/commands/review/scope.rs | 564 +++ atomic-cli/src/commands/review/terminal.rs | 434 +++ .../src/commands/review/view_comparison.rs | 501 +++ .../review/view_comparison/conformance.rs | 726 ++++ .../review/view_comparison/findings.rs | 187 + .../commands/review/view_comparison/impact.rs | 87 + .../review/view_comparison/metrics.rs | 274 ++ .../src/commands/review/view_snapshot.rs | 313 ++ atomic-cli/src/commands/review/viewer.css | 59 + atomic-cli/src/commands/review/viewer.html | 38 + atomic-cli/src/commands/review/viewer.js | 702 ++++ atomic-cli/src/commands/triage/mod.rs | 2 +- .../src/commands/triage/publication_review.rs | 8 +- atomic-cli/src/main.rs | 5 + atomic-cli/src/output/html.rs | 38 + atomic-cli/src/output/mod.rs | 1 + atomic-cli/tests/review_audits.rs | 370 ++ atomic-cli/tests/review_comparison.rs | 393 ++ atomic-cli/tests/review_comparison_passes.rs | 620 ++++ atomic-cli/tests/review_impact.rs | 93 + atomic-cli/tests/review_view.rs | 353 ++ atomic-cli/tests/review_viewer_browser.mjs | 301 ++ .../examples/compact_semantic_codec.rs | 213 ++ .../examples/compact_semantic_codec/codec.rs | 499 +++ .../examples/compact_semantic_codec/tests.rs | 336 ++ atomic-identity/src/store.rs | 207 ++ atomic-repository/src/analysis_scope.rs | 39 + atomic-repository/src/content_search.rs | 86 + atomic-repository/src/lib.rs | 2 + atomic-repository/src/repository/content.rs | 162 +- atomic-repository/src/repository/mod.rs | 3 + .../repository/publication_review/graph.rs | 19 +- .../src/repository/publication_review/mod.rs | 36 +- .../repository/publication_review/tests.rs | 103 + .../src/repository/review_authorization.rs | 956 +++++ atomic-repository/src/repository/sandbox.rs | 396 +- .../src/repository/semantic_review.rs | 360 ++ .../src/repository/syntax_index.rs | 228 +- .../src/repository/tests/query_view_tests.rs | 4 +- atomic-repository/src/repository/vault.rs | 13 +- atomic-repository/src/triage/report.rs | 7 +- atomic-semantic/src/entity.rs | 11 + atomic-semantic/src/lib.rs | 10 +- atomic-semantic/src/parser.rs | 28 + atomic-semantic/src/parsers/cpp.rs | 23 + atomic-semantic/src/parsers/go.rs | 23 + atomic-semantic/src/parsers/java.rs | 23 + atomic-semantic/src/parsers/mod.rs | 201 +- atomic-semantic/src/parsers/python.rs | 23 + atomic-semantic/src/parsers/rust.rs | 23 + atomic-semantic/src/parsers/swift.rs | 23 + atomic-semantic/src/parsers/typescript.rs | 21 + atomic-semantic/src/relationships.rs | 679 ++++ atomic-semantic/src/source.rs | 919 +++++ atomic-semantic/src/source/tests.rs | 157 + docs/COMPACT-SEMANTIC-CODEC-EXPERIMENT.md | 152 + 109 files changed, 29275 insertions(+), 198 deletions(-) create mode 100644 atomic-audit/AUDITS.md create mode 100644 atomic-audit/CONVENTIONS.md create mode 100644 atomic-audit/Cargo.toml create mode 100644 atomic-audit/IMPACT.md create mode 100644 atomic-audit/README.md create mode 100644 atomic-audit/RISK.md create mode 100644 atomic-audit/src/catalog.rs create mode 100644 atomic-audit/src/extract/languages.rs create mode 100644 atomic-audit/src/extract/mod.rs create mode 100644 atomic-audit/src/extract/tests.rs create mode 100644 atomic-audit/src/extract/tokens.rs create mode 100644 atomic-audit/src/impact/analysis.rs create mode 100644 atomic-audit/src/impact/mod.rs create mode 100644 atomic-audit/src/impact/tests.rs create mode 100644 atomic-audit/src/lib.rs create mode 100644 atomic-audit/src/metrics.rs create mode 100644 atomic-audit/src/risk.rs create mode 100644 atomic-audit/src/risk/fqn_facts.json create mode 100644 atomic-audit/src/risk/tests.rs create mode 100644 atomic-audit/src/structural.rs create mode 100644 atomic-audit/src/substantive/branching.rs create mode 100644 atomic-audit/src/substantive/mod.rs create mode 100644 atomic-audit/src/substantive/rust.rs create mode 100644 atomic-audit/src/substantive/tests.rs create mode 100644 atomic-canonical/src/review_finding.rs create mode 100644 atomic-canonical/src/review_graph.rs create mode 100644 atomic-cli/skills/review/SKILL.md create mode 100644 atomic-cli/skills/review/references/review-contract.md create mode 100644 atomic-cli/src/commands/agent/publication.rs create mode 100644 atomic-cli/src/commands/review/analysis.rs create mode 100644 atomic-cli/src/commands/review/assets/README.md create mode 100644 atomic-cli/src/commands/review/assets/atomic-logo.png create mode 100644 atomic-cli/src/commands/review/graph.rs create mode 100644 atomic-cli/src/commands/review/html.rs create mode 100644 atomic-cli/src/commands/review/impact.rs create mode 100644 atomic-cli/src/commands/review/incremental.rs create mode 100644 atomic-cli/src/commands/review/metric_output.rs create mode 100644 atomic-cli/src/commands/review/mod.rs create mode 100644 atomic-cli/src/commands/review/presentation.rs create mode 100644 atomic-cli/src/commands/review/progress.rs create mode 100644 atomic-cli/src/commands/review/publish.rs create mode 100644 atomic-cli/src/commands/review/risk.rs create mode 100644 atomic-cli/src/commands/review/risk_facts.rs create mode 100644 atomic-cli/src/commands/review/scope.rs create mode 100644 atomic-cli/src/commands/review/terminal.rs create mode 100644 atomic-cli/src/commands/review/view_comparison.rs create mode 100644 atomic-cli/src/commands/review/view_comparison/conformance.rs create mode 100644 atomic-cli/src/commands/review/view_comparison/findings.rs create mode 100644 atomic-cli/src/commands/review/view_comparison/impact.rs create mode 100644 atomic-cli/src/commands/review/view_comparison/metrics.rs create mode 100644 atomic-cli/src/commands/review/view_snapshot.rs create mode 100644 atomic-cli/src/commands/review/viewer.css create mode 100644 atomic-cli/src/commands/review/viewer.html create mode 100644 atomic-cli/src/commands/review/viewer.js create mode 100644 atomic-cli/src/output/html.rs create mode 100644 atomic-cli/tests/review_audits.rs create mode 100644 atomic-cli/tests/review_comparison.rs create mode 100644 atomic-cli/tests/review_comparison_passes.rs create mode 100644 atomic-cli/tests/review_impact.rs create mode 100644 atomic-cli/tests/review_view.rs create mode 100644 atomic-cli/tests/review_viewer_browser.mjs create mode 100644 atomic-core/examples/compact_semantic_codec.rs create mode 100644 atomic-core/examples/compact_semantic_codec/codec.rs create mode 100644 atomic-core/examples/compact_semantic_codec/tests.rs create mode 100644 atomic-repository/src/analysis_scope.rs create mode 100644 atomic-repository/src/repository/review_authorization.rs create mode 100644 atomic-repository/src/repository/semantic_review.rs create mode 100644 atomic-semantic/src/relationships.rs create mode 100644 atomic-semantic/src/source.rs create mode 100644 atomic-semantic/src/source/tests.rs create mode 100644 docs/COMPACT-SEMANTIC-CODEC-EXPERIMENT.md diff --git a/Cargo.lock b/Cargo.lock index de5645aa..d3788d8e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -240,10 +240,21 @@ dependencies = [ "zstd", ] +[[package]] +name = "atomic-audit" +version = "0.22.1" +dependencies = [ + "atomic-semantic", + "serde", + "serde_json", + "similar", +] + [[package]] name = "atomic-canonical" version = "0.22.1" dependencies = [ + "atomic-audit", "atomic-identity", "blake3", "bs58", @@ -264,6 +275,7 @@ version = "0.22.1" dependencies = [ "anyhow", "atomic-agent", + "atomic-audit", "atomic-canonical", "atomic-client", "atomic-config", @@ -285,6 +297,7 @@ dependencies = [ "data-encoding", "dialoguer", "dirs", + "flate2", "fs2", "futures-core", "git2", diff --git a/Cargo.toml b/Cargo.toml index 4e24a517..7adb0fbb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,7 @@ resolver = "2" members = [ "atomic-agent", + "atomic-audit", "atomic-canonical", "atomic-cli", "atomic-client", @@ -30,6 +31,7 @@ rust-version = "1.90" [workspace.dependencies] # Core atomic-agent = { path = "atomic-agent" } +atomic-audit = { path = "atomic-audit" } atomic-canonical = { path = "atomic-canonical" } atomic-client = { path = "atomic-client" } atomic-core = { path = "atomic-core" } diff --git a/atomic-agent/src/turn/orchestrator/attestation.rs b/atomic-agent/src/turn/orchestrator/attestation.rs index da6a92d2..acd68e48 100644 --- a/atomic-agent/src/turn/orchestrator/attestation.rs +++ b/atomic-agent/src/turn/orchestrator/attestation.rs @@ -59,27 +59,38 @@ pub(crate) fn capture_root( Ok(atomic_core::types::Hash::of(&buf)) } +fn did_signing_identity_from_store( + store: &atomic_identity::IdentityStore, + selected_name: Option<&str>, +) -> Option<(String, atomic_identity::KeyPair)> { + let identity = match selected_name { + Some(name) => store.load_by_name(name).ok()?, + None => store.get_default().ok()??, + }; + // Verify the secret matches this identity's public key. An unavailable + // explicit signer must never fall back to a different identity. + let keypair = store.load_keypair(&identity.id, None).ok()?; + Some(( + atomic_canonical::did::did_for_public_key(&identity.public_key), + keypair, + )) +} + impl TurnOrchestrator { /// Load the configured agent DID identity for attestation signing /// (CB-12A AC3). /// /// Returns the signer DID (`did:atomic:` from /// `atomic_canonical::did`) plus the store-verified keypair when a - /// default identity with a loadable secret key exists. Any failure — no - /// store, no default identity, encrypted/locked key, secret/public + /// selected agent identity (or the default when none is selected) has a + /// loadable secret key. Any failure — no store, missing identity, + /// encrypted/locked key, secret/public /// mismatch — yields `None` and the attestation falls back to the /// session MAC, which [`atomic_core::change::attestation::TrustPolicy`] /// then refuses as trusted evidence. pub(crate) fn load_did_signing_identity(&self) -> Option<(String, atomic_identity::KeyPair)> { let store = atomic_identity::IdentityStore::open_default().ok()?; - // get_default resolves the configured default identity directly. - let identity = store.get_default().ok()??; - // load_keypair verifies the secret matches the identity's public key. - let keypair = store.load_keypair(&identity.id, None).ok()?; - Some(( - atomic_canonical::did::did_for_public_key(&identity.public_key), - keypair, - )) + did_signing_identity_from_store(&store, self.agent_identity.as_deref()) } // ========================================================================= @@ -496,3 +507,94 @@ impl TurnOrchestrator { } } } + +#[cfg(test)] +mod signing_identity_tests { + use super::did_signing_identity_from_store; + use atomic_identity::{Identity, IdentityStore, KeyPair}; + + fn store_with_default() -> (tempfile::TempDir, IdentityStore, Identity) { + let temp = tempfile::tempdir().unwrap(); + let mut store = IdentityStore::open(temp.path()).unwrap(); + let keypair = KeyPair::generate(); + let human = Identity::new("human", &keypair); + store.save_with_keypair(&human, &keypair, None).unwrap(); + store.set_default(&human.id).unwrap(); + (temp, store, human) + } + + #[test] + fn selected_reviewer_uses_its_own_did_and_key() { + let (_temp, store, human) = store_with_default(); + let reviewer_key = KeyPair::generate(); + let reviewer = Identity::new("reviewer", &reviewer_key); + store + .save_with_keypair(&reviewer, &reviewer_key, None) + .unwrap(); + + let (did, keypair) = did_signing_identity_from_store(&store, Some("reviewer")).unwrap(); + assert_eq!( + did, + atomic_canonical::did::did_for_public_key(&reviewer.public_key) + ); + assert_eq!(keypair.public, reviewer_key.public); + assert_ne!(keypair.public, human.public_key); + } + + #[test] + fn no_selection_retains_default_signer() { + let (_temp, store, human) = store_with_default(); + + let (did, keypair) = did_signing_identity_from_store(&store, None).unwrap(); + assert_eq!( + did, + atomic_canonical::did::did_for_public_key(&human.public_key) + ); + assert_eq!(keypair.public, human.public_key); + } + + #[test] + fn missing_selected_reviewer_does_not_use_default() { + let (_temp, store, _human) = store_with_default(); + assert!(did_signing_identity_from_store(&store, Some("missing-reviewer")).is_none()); + } + + #[test] + fn keyless_selected_reviewer_does_not_use_default() { + let (_temp, store, _human) = store_with_default(); + store.save(&Identity::generate("reviewer")).unwrap(); + assert!(did_signing_identity_from_store(&store, Some("reviewer")).is_none()); + } + + #[test] + fn mismatched_selected_reviewer_key_does_not_use_default() { + let (_temp, store, _human) = store_with_default(); + let reviewer = Identity::generate("reviewer"); + store + .save_with_keypair(&reviewer, &KeyPair::generate(), None) + .unwrap(); + assert!(did_signing_identity_from_store(&store, Some("reviewer")).is_none()); + } + + #[test] + fn locked_selected_reviewer_key_does_not_use_default() { + let (_temp, store, _human) = store_with_default(); + let reviewer_key = KeyPair::generate(); + let reviewer = Identity::new("reviewer", &reviewer_key); + store + .save_with_keypair(&reviewer, &reviewer_key, None) + .unwrap(); + let secret_path = store + .root() + .join(format!("reviewer-{}", reviewer.id.short())) + .join("secret.key"); + let secret = std::fs::read_to_string(&secret_path).unwrap(); + std::fs::write( + secret_path, + secret.replace("encryption = \"none\"", "encryption = \"locked\""), + ) + .unwrap(); + + assert!(did_signing_identity_from_store(&store, Some("reviewer")).is_none()); + } +} diff --git a/atomic-audit/AUDITS.md b/atomic-audit/AUDITS.md new file mode 100644 index 00000000..245174a9 --- /dev/null +++ b/atomic-audit/AUDITS.md @@ -0,0 +1,84 @@ +# Executable anti-slop audits — ruleset 2 + +All ten audit cards have executable checks. The seven substantive families are +no longer guidance-only: matches flow through the same recorded before/after +adapter into numbered findings, with source locations, concrete observations, +introduction attribution and proposed corrections. Nothing here runs tests, +fixes code, rewrites acceptance criteria or grants approval. + +These checks inspect specific source constructs. Completing a check means its +documented patterns were inspected, not that the entire behavioral concern was +proved absent. Unsupported languages, syntax recovery and budget exhaustion +remain explicit. The parser registry and its trees are reused; there is no new +parser, whole-project scan, global-name caller join or compiler/type resolver. + +## Implemented checks + +| Audit | Executable evidence | Languages | Important exclusions | +|---|---|---|---| +| Syntax | Error/missing syntax nodes | All nine registered syntax modes | Parser evidence, not compiler proof | +| Unfinished behavior | Actual `todo!`/`unimplemented!` invocations | Rust | Comments/strings are not invocations; macro shadowing and deliberate scaffolds need judgment | +| Undocumented empty catch | Empty catch AST body without comments | TS/TSX | An explanatory comment or executable handler is not an empty-catch match | +| Failure masking | `Err` match/if-let branch constructs `Ok`; catch ends with `return true` | Rust, TS/TSX | Error propagation, ordinary successful branches and explicit `std::io::ErrorKind::NotFound`-guarded `Ok(None)` absence contracts are excluded; other intentional fallbacks may be justified by their contract | +| Duplicated behavior | Nonempty if/else bodies have identical syntax tokens, with literal content preserved | Rust, TS/TSX | Comments/formatting do not change comparison; Rust let/let-chain name bindings are excluded; condition effects must be preserved | +| Unnecessary machinery | At least two same-module private forwarding layers, unchanged arguments and identical first-layer parameter/return contracts | Rust | Excludes single naming wrappers, public/attributed/generic/receiver boundaries, transformed arguments and direct cycles; architectural naming intent still needs judgment | +| Manageability | Joint long-body/control-flow concentration, new or worsened relative to the recorded baseline | All nine modes | Unique named functions only; standalone large length/parameter/complexity values do not produce a finding | +| Async/resource safety | Known synchronous std/parking_lot guard remains live across same-block await; async executor passed to unshadowed standard Promise | Rust, TS/TSX | Explicit drop/completed inner scopes and Tokio mutexes are excluded. Rust binding recognition is limited to qualified constructors/simple parameter types; indirect aliases, complex paths, possible ownership transfers and type inference are not guessed. Shadowing does not incorrectly count as releasing the old guard | +| Weak verification | Empty test without should_panic; test asserts literal true or compares an identical simple expression with itself | Rust | Does not classify every assertion-free test as weak. Result-returning tests and framework behavior can verify real contracts; side-effecting self-calls are excluded | +| Unsafe shortcuts | Selected qualified unsafe memory operation without local SAFETY argument; blanket warnings/clippy::all suppression without local reason | Rust | Narrow lint exceptions and locally explained operations are excluded; absence of a safety argument is not proof of undefined behavior | + +Unnecessary-machinery, duplication and manageability matches are Low-severity +review concerns, not declarations that an abstraction is forbidden or a bug +exists. Other source-pattern matches are Medium review findings. Every result +states the observed construct and its potential contract consequence so a +reviewer can accept/reject the concern with relevant context. No finding invents +a governing criterion or marks an acceptance criterion unmet. + +The Rust constructors/macros in these patterns are source-syntax observations; +unusual local shadowing or generated code can require contextual rejection of a +match. In particular, this is not proof of a compiled `Result` type, runtime +reachability, external API compatibility, executed tests or complete cleanup. + +## Joint manageability policy + +`atomic.manageability.v1` is explicit Atomic review policy, not a universal +scientific cutoff or a metric-quality pass/fail gate. It requires: + +- at least **100 code-bearing function-body lines**, **and** +- cyclomatic complexity at least **15** or control-flow nesting at least **4**. + +Both use the existing `atomic.metrics.syntax.v1` counting implementation, with +comments and nested-function bodies excluded according to that convention. +Long straight-line tables alone and small branch-heavy dispatchers alone do not +trigger it. For an already-triggering named function, a new finding requires at +least **three additional decision points or a new nesting level**, not merely +one more line, formatting, straight-line growth or an unchanged count. This is +also Atomic policy, not a calibrated defect predictor. New/worsened joint burden +reports the actual after factors and, when present, before factors. An unavailable +baseline yields Unknown introduction, never an invented zero baseline. + +An isolated metric value, metric count or risk-rule trigger still does not create +a defect finding. This audit's finding is the specific combination of long body +and branching/nesting in an identified recorded function, qualified as increased +review/maintenance burden rather than proof of missing tests or runtime failure. + +## Scope, attribution and bounds + +The adapter inspects selected recorded content and its actual before snapshot. +Later/dirty source is not used. Ordinary matches use exact rule/source-text +multisets: line shifts alone are preexisting; additional identical occurrences +can be new; an edited existing same-rule match has Unknown introduction rather +than a fabricated regression. Manageability additionally compares the named +subject's joint evidence as described above. + +The existing 1 MiB source limit and 100-issue limit remain. AST inventory is capped +at 300,000 nodes / nesting depth 256 and substantive subtree work is capped at 32 MiB of inspected +source spans per file. Budget exhaustion produces an explicit incomplete check, +not a truncated clean result. A syntax-recovered tree runs syntax diagnostics +only, never substantive checks on unreliable nodes. + +Tests include positive evidence for every substantive family, nearby negative +cases, attribution of new/preexisting/unknown concerns, scope-pinned recorded +inspection and a real CLI invocation producing all seven families without a +supplied findings file. Those fixtures validate detector execution; they do not +claim exhaustive detection of every problem in each audit category. diff --git a/atomic-audit/CONVENTIONS.md b/atomic-audit/CONVENTIONS.md new file mode 100644 index 00000000..3ecfed81 --- /dev/null +++ b/atomic-audit/CONVENTIONS.md @@ -0,0 +1,109 @@ +# Automatic metric conventions: atomic.metrics.syntax.v1 + +All counting is over recorded source supplied by the adapter. The existing +`atomic-semantic` parser registry supplies the nine syntax modes; no code is +executed and no compiler/type checker is run. A module boundary here is one +supplied source file, not an inferred whole package or runtime application. + +## Subjects and availability + +- Functions/methods/closures with known syntax are measured separately. Class + metrics apply to TypeScript/TSX, Python, Java class/record/enum, C++ class/struct + and Swift `class` declarations. Rust structs, Go/C structs and Swift value types + are not silently relabeled classes. +- Qualified lexical names identify subjects. Renames are separate subjects; + anonymous or overloaded matches have no inferred before-value, location or + delta. Unavailable baseline is never replaced by zero. +- Known additions/deletions use `not_applicable` on the absent side. Invalid, + binary, non-UTF-8, unreadable or unsupported source produces unavailable facts. +- A valid file without applicable declarations has not-applicable function or + class observations, while an empty class genuinely has zero methods and zero + implemented source complexity. +- Locations are one-based inclusive declaration ranges on each recorded side. + Method length counts code-bearing body lines; a signature-only line is excluded, + but an opening delimiter on a signature line is body code and counts. + +## Length and parameters + +Length is based on AST token ranges, skipping comment nodes and blank lines. +Strings count as source code (including Python docstrings), not comment text. +Nested function/type bodies do not inflate a containing function's length; +nested type bodies do not inflate the containing class. A nested declaration's +header can still contribute a code-bearing line. Class length includes methods. + +Declared parameter slots are counted, not identifier tokens: Go `a, b int` has +two slots, while a destructured/rest parameter has one. Rust `self`, Go receiver +lists, TypeScript `this` pseudo-parameters and the first Python instance/class +receiver are excluded. Canonical `@staticmethod` leaves all declared slots. +Return slots and inferred/compiler-generated parameters are not reconstructed. +Unsupported/inferred parameter syntax is unavailable, not an assumed zero. + +Method count includes directly declared constructors and syntactic methods; +overload/abstract signatures count as declarations. Function-valued fields are +not method declarations. Inherited and nested-type methods are excluded. +Aggregate class complexity sums concrete source bodies. Abstract/signature-only +and compiler-generated bodies do not contribute source complexity; an unresolved +C/C++ out-of-line or Java native implementation makes the aggregate unavailable. +C++ default arguments are not mistaken for pure-virtual method bodies. + +## Branching and nesting + +Function-body complexity starts at one. Explicit `if`/`elif`, loops, catch/except, +guard and conditional expressions add decisions. Logical `&&`/`||` and Python +`and`/`or` operators add short-circuit decisions. Non-default switch/match cases +add decisions; wildcard default arms without guards do not. Assertions, compiler +expansions, implicit failure propagation and parameter-default execution are not +reconstructed. Nested functions/types are separate subjects. + +Nesting tracks control constructs, not ordinary lexical braces. An `else if` or +Python `elif` remains at the chain's depth. Nested functions/types do not inflate +the enclosing function's control metrics. These are syntactic proxies, not a +compiler CFG path count or a universal measure of readability. + +## Declared dependencies and visibility + +Dependency fan-out de-duplicates explicit declarations rather than counting +import statements. Units are Python module paths, TS/TSX import/re-export paths, +Rust imported crate/root namespaces, Java qualified import targets, Go import +paths, literal C/C++ headers and Swift imported module roots. Aliases/repeated +declarations do not inflate counts. Nonliteral header/import paths are unavailable. +Dynamic loads, implicit/prelude dependencies, macro expansion and type-resolved +coupling are not claimed by this metric. + +Public surface counts unique named bindings under source visibility, including +visible class members. Overload sets count once. Private/local declarations and +hidden enclosing types are excluded where declared visibility is known. Python +uses naming conventions or a static literal `__all__`; dynamic export lists are +unavailable. Wildcard re-exports, dynamic CommonJS exports, unresolved public Rust +impl targets and preprocessing-dependent visibility are not guessed. It is not +a compiled ABI/export-table measurement or a proof of compatibility. + +## Changed-token duplication + +The comparison scope is the exact supplied paths, separated by language/syntax +mode. The default token window is 32, preserving names and literal values while +discarding comments and whitespace. This is a detector setting, not a universal +quality threshold. Hash matches are verified against actual tokens. Matches +inside the same file must not be overlapping copies; matched token positions are +unioned so overlapping windows do not multiply the count. + +A bounded Myers token diff selects changed positions on each side. Only those +positions that also belong to a clone count toward the metric. Formatting-only +changes do not invent duplicated tokens. Unavailable baseline, incomplete +same-language comparison inputs, exhausted diff work or clone-comparison caps +produce unavailable counts rather than partial lower bounds disguised as totals. +Zero means zero within the declared supplied comparison scope, not the repository. + +## Default work limits + +Per request: 128 supplied file pairs, 8 MiB source across both sides, 80,000 +tokens, 1,024 function/class subjects, 16 million token-diff work units and 100,000 +clone candidate comparisons. Per source: 1 MiB, 20,000 tokens, 256 subjects, +300,000 AST nodes and 256 AST nesting levels. `ExtractionConfig` exposes the +request limits; exceeding them is disclosed, never interpreted as a clean zero. +Review's default clone scope is changed files only; no exhaustive source scan is +started to fill a missing measurement. + +Token-index or clone/diff work exhaustion affects duplication availability, not +otherwise valid local AST counts. A long method does not lose its length or +complexity measurement just because a clone index cannot be completed. diff --git a/atomic-audit/Cargo.toml b/atomic-audit/Cargo.toml new file mode 100644 index 00000000..94fed0f4 --- /dev/null +++ b/atomic-audit/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "atomic-audit" +description = "Tool-neutral audit cards, manageability metrics and structural review checks" +version.workspace = true +edition.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[features] +default = [] +structural = ["dep:atomic-semantic", "dep:similar"] + +[dependencies] +serde = { workspace = true } +atomic-semantic = { workspace = true, optional = true } +similar = { workspace = true, optional = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/atomic-audit/IMPACT.md b/atomic-audit/IMPACT.md new file mode 100644 index 00000000..1b81cad6 --- /dev/null +++ b/atomic-audit/IMPACT.md @@ -0,0 +1,74 @@ +# Change-rooted semantic impact + +Review consumes the existing semantic and recorded-content search layers. It +does not maintain its own AST parser or scan the first 256 repository files. + +## Ownership + +- `atomic-semantic::ParserRegistry::analyze_source` invokes the registered grammar + once, reuses its existing entity visitor, and retains qualified call spelling, + receiver, lexical owner, imports, visibility and declaration context. +- Existing `Reference` results retain the backward-compatible simple `symbol` + and optionally include structured `call` context. A syntactic reference's high + confidence is not proof that its target has been resolved. +- `atomic-semantic::relationships::SourceGraph` binds supported relationships from + those shared facts. Same-name methods/functions do not establish relationships. + It borrows declaration facts per call rather than cloning function bodies. +- Existing repository caller queries use the same source graph. The former global + simple-name join and duplicate relative-import resolver have been removed. +- `atomic-repository::RecordedSemanticView` pins before/after recorded view + projections and uses the existing `RecordedContentSearch` syntext path/regex + machinery to select source **before** AST budgets. No ambient working-copy + index is treated as authoritative for a historical snapshot. +- `atomic-audit::impact::analyze_semantic` applies review policy to semantic facts: + changed declarations, incoming/outgoing relationships, availability/access/arity + checks, introduction evidence and scoped limitations. It does not traverse ASTs. +- CLI code translates established contract issues into numbered findings and + preserves evidence in the graph/JSON. It does not infer criterion failures. + +## Selection and performance + +1. Load and parse changed supported source first; retain it for later stages. +2. Compare semantic entities and source tokens to derive changed functions/methods. +3. Search for those targets. Private lexical regions constrain eligible paths; + owned methods include owner context instead of globally searching `value`/`id`. +4. Parse matching files plus explicit declaration/import context using the same + registry. Unrelated nonmatching syntax, macros and cfg declarations never + consume the candidate AST budget or produce per-file review warnings. + +Search results are candidates, not confirmed callers. Recorded search may verify +source bytes; reduced AST work is not a promise of zero content I/O or a new +persistent semantic index. `searched_files_before/after` and +`inspected_files_before/after` expose the distinction. A regression fixture with +300 unrelated files parses only the two affected/caller files in each snapshot. + +The bounded adapter accepts up to four selected source changes, 256 changed plus +matching source files and 64 additional declaration/import context files. Roots, +matches and context each have an 8 MiB source allowance; individual parsing is +limited to 1 MiB, 100,000 AST nodes and 256 nesting levels. Truncation is a scoped +selection gap, not a guessed zero or a reason to replace the selected change. + +## Evidence and limits + +Incoming/outgoing references retain call sites, declaration identity, qualified +spelling and binding reason. Before callers survive declaration removal. Removed +and inaccessible references are not counted as legal current callers. Full path +inventory is preserved even when only relevant files are parsed, so an omitted +alternative cannot silently become a unique import target. + +Ordinary attributes, cfg/test declarations and macros are retained as source +context, not blanket file exclusions. Configuration/expansion-dependent evidence +is labeled; it is not authenticated active-build configuration. Ambiguous scopes, +custom visibility and unresolved receiver/import context are not guessed. + +The source-level contract assessment covers supported availability/access/argument +counts (currently Rust and TypeScript/TSX conventions), not arbitrary type checking +or runtime behavior. Known lexical/declared receivers and explicit module/import +paths can establish bindings; dynamic/inferred/cross-crate cases may remain +unresolved. Public APIs may have external consumers. Absence of findings does not +prove low implementation risk. Reviewers still inspect relevant types, behavior, +persistence, security and tests where needed. + +The terminal-only Thinking guard is retained. It clears on success/error and never +animates in JSON, pipes or dumb terminals. No compiler, build script, language +server, model invocation or application-code remediation is launched by this pass. diff --git a/atomic-audit/README.md b/atomic-audit/README.md new file mode 100644 index 00000000..7cb4ff19 --- /dev/null +++ b/atomic-audit/README.md @@ -0,0 +1,182 @@ +# atomic-audit + +Tool-neutral engineering audit cards and manageability metrics for Atomic review. +This crate reports evidence and review signals. It never fixes code, edits an +acceptance criterion, opens a repository, launches tests/tools, or grants approval. + +## Ownership + +```text +atomic-audit +├── catalog readable audit and metric cards +├── metrics explicit measurements, profiles, advisory bands and deltas +├── extract automatic multilingual source-syntax metric collection +├── impact compatibility policy over shared semantic source facts +├── risk versioned, explainable change-review risk rules +└── structural executable AST audit adapter (substantive rules included) + └── atomic-semantic: grammar registry and parsing + +atomic-cli / atomic-repository: recorded scope, source retrieval and adapters +atomic-canonical: common findings, criterion assessments and review graph +``` + +The default build needs only Serde. Enable `structural` to run all ten audit +families using `atomic-semantic`'s existing grammar instances and syntax trees. +Ruleset 2 adds executable substantive checks; the original three rule identities +remain stable. See [implemented patterns, languages and limits](AUDITS.md). +`atomic review` runs these checks against recorded before/after content and +projects evidence-backed matches into numbered findings. No second parser is introduced. + +## Readable cards + +`catalog::AUDIT_CARDS` describes each audit's question, required evidence, +exceptions and actual automation coverage. The initial families cover syntax, +unfinished behavior, empty catches, failure masking, duplication, unnecessary +machinery, manageability, async/resource safety, weak verification and safety +bypasses. Each family has executable checks with documented language/pattern +coverage; completing a pattern check is not exhaustive behavioral proof. + +`catalog::METRIC_CARDS` includes: + +| Metric | Subject | Measurement | +| --- | --- | --- | +| Method/function length | Function | Code-containing body lines | +| Class length | Class | Code-containing class-body lines, including methods | +| Methods per class | Class | Directly declared methods | +| Parameter count | Function | Declared input slots | +| Nesting depth | Function | Maximum control-flow nesting | +| Cyclomatic complexity | Function | Decisions under a declared language convention | +| Aggregate class complexity | Class | Sum of directly declared method complexity | +| Dependency fan-out | Module | Distinct direct dependencies | +| Public surface | Module | Externally visible declarations | +| Duplicated tokens | Change | Unique changed token positions in clone matches | + +Cards contain the precise counting boundaries, interpretation and exceptions. +Class metrics are not applicable to constructs without class semantics. Do not +turn every Rust struct or data record into an object-oriented design warning. + +## Automatic extraction + +With `structural` enabled, `extract::extract_changes` automatically collects all +ten metrics using the existing registered Rust, TypeScript/TSX, Python, Java, Go, +C/C++ and Swift parsers. Supply recorded before/after `FileChange` inputs; the +extractor does no filesystem I/O, builds, tests or external tool invocation. + +```rust +# #[cfg(feature = "structural")] +# { +use atomic_audit::extract::{extract_changes, ExtractionConfig, FileChange, Source}; +use atomic_semantic::ParserRegistry; + +let inputs = vec![FileChange { + path: "example.ts".into(), + before: Source::Text("export function work(x: number) { return x; }".into()), + after: Source::Text("export function work(x: number, y: number) { return x + y; }".into()), +}]; +let result = extract_changes(&inputs, &mut ParserRegistry::new(), &ExtractionConfig::default()).unwrap(); +assert!(result.metrics.iter().any(|record| record.observation.metric == atomic_audit::Metric::ParameterCount && record.delta == Some(1))); +# } +``` + +Results include convention `atomic.metrics.syntax.v1`, recorded-side line +locations, before/after values and safe deltas. Named subjects are paired within +their qualified scope. Ambiguous overloads/anonymous subjects do not acquire an +invented baseline. No applicable class/function is `not_applicable`; parse/read +failures, unresolved facts and budgets are `unavailable`, not zero. + +See [counting conventions and coverage](CONVENTIONS.md). These are source-syntax +metrics, not compiler-resolved runtime facts or measurements of human cognition. +Public surface means declared visibility; fan-out means explicit dependency +units. Wildcard/dynamic export expansion and unresolved implementation bodies +are not guessed. + +`atomic review` collects metrics from exact selected recorded before/after +source under `changes[].analysis.metrics`, with `metric_diagnostics` and +`metric_comparison_scope`. Graph metric nodes link cards and source anchors. +The terminal shows every family, comparable numeric changes and selected actual +values/locations; --details and JSON retain every collected observation. +Metrics are observations, not automatic F-number findings or unmet criteria. +The separate manageability audit requires joint source/control-flow evidence and +recorded new/worsened burden under [explicit Atomic review policy](AUDITS.md). + +Clone comparison is exact-token, same-language and restricted to supplied paths +(changed files by default in review). It counts only changed token positions and +unions overlapping matches. It is **not** a repository-wide duplication score. +Callers may include unchanged comparison files with identical before/after text. + +## Direct-call impact and contract evidence + +With `structural` enabled, `impact::analyze_semantic` consumes already-parsed +`atomic-semantic` source sets. The existing parser registry owns entity extraction, +qualified calls, receivers, scopes and relationships; this crate owns compatibility +policy, not another AST parser. `impact::analyze` remains a convenience adapter for +in-memory source pairs, delegating to that same registry. Review uses recorded +syntext-backed candidate selection before parsing callers, not a whole-project +AST pass. It measures incoming/outgoing supported relationships and checks +declaration availability, access and declared fixed/optional/rest argument counts. + +```rust +# #[cfg(feature = "structural")] +# { +use atomic_audit::impact::analyze; +use atomic_semantic::ParserRegistry; +let before = vec![("lib.rs".into(), "fn work(x:i32) {} fn consumer() { work(1); }".into())]; +let after = vec![("lib.rs".into(), "fn work(x:i32,y:i32) {} fn consumer() { work(1); }".into())]; +let report = analyze(&before, &after, &["lib.rs".into()], &mut ParserRegistry::new()); +assert_eq!(report.callers_after.len(), 1); +assert_eq!(report.issues.len(), 1); +assert!(report.issues[0].introduced); +# } +``` + +The CLI turns concrete contract issues into numbered findings with source evidence. +Separately, [change-review risk rules](RISK.md) use measured breadth, consumer +exposure and contract churn to prioritize review, even with zero confirmed defects. +These are Atomic policy bands, not calibrated defect probabilities. Incomplete +evidence limits confidence without erasing measured exposure. Neither a risk +estimate nor metric growth creates a defect finding or criterion failure. +See [impact coverage and safety boundaries](IMPACT.md). + +## Advisory policy + +`Measurement` distinguishes a measured value (including real zero), unavailable +with a reason, and not applicable with a reason. Missing baselines have no delta. +There are no universal limits or default pass/fail gates. A project selects a +named `MetricProfile` with explicit inclusive review/high-review thresholds. + +```rust +use std::collections::BTreeMap; +use atomic_audit::{evaluate, Measurement, Metric, MetricObservation, + MetricProfile, ReviewBand, Threshold}; + +let observation = MetricObservation { + metric: Metric::MethodLength, + subject: "src/report.ts#ReportBuilder.build".into(), + before: Measurement::Measured { value: 34 }, + after: Measurement::Measured { value: 112 }, +}; +// Illustrative project policy, not a universal good-code standard. +let profile = MetricProfile { + name: "example-typescript-service".into(), + limits: BTreeMap::from([( + Metric::MethodLength, + Threshold { review_at: 50, high_review_at: Some(100) }, + )]), +}; +let assessment = evaluate(&observation, &profile).unwrap(); +assert_eq!(assessment.delta, Some(78)); +assert_eq!(assessment.band, ReviewBand::HighReview); +``` + +The next question is whether that growth obscures responsibilities or failure +paths. A high band does not prove slop, a regression, missing tests, or an unmet +acceptance criterion. Adapters/reviewers make an evidenced finding when justified; +the existing review layer assigns finding numbers and validates criterion links. + +## Focused validation + +```sh +cargo test -p atomic-audit +cargo test -p atomic-audit --features structural +cargo test -p atomic-cli commands::review --bin atomic +``` diff --git a/atomic-audit/RISK.md b/atomic-audit/RISK.md new file mode 100644 index 00000000..8037ca27 --- /dev/null +++ b/atomic-audit/RISK.md @@ -0,0 +1,123 @@ +# Atomic change-review risk, v1 + +`atomic.change-risk.v1` is an explainable **review-priority estimate**, not a +defect probability, confirmed-bug count, outage prediction or approval. A change +can deserve High risk review while all observed call contracts remain compatible. + +## Research and what it supports + +The literature supports using change characteristics and dependencies to focus +review effort. It does **not** provide universal caller-count or size cutoffs: + +1. Kamei et al., *A Large-Scale Empirical Study of Just-in-Time Quality Assurance*, + IEEE TSE 39(6), 2013, DOI [10.1109/TSE.2012.70](https://doi.org/10.1109/TSE.2012.70). + [Author institution abstract](https://kyushu-u.elsevierpure.com/en/publications/a-large-scale-empirical-study-of-just-in-time-quality-assurance). + Change-level features can prioritize quality assurance. Atomic does not import + that trained model, its accuracy, developer-experience judgments or coefficients. +2. Zimmermann and Nagappan, *Predicting Defects using Network Analysis on Dependency + Graphs*, ICSE 2008, DOI [10.1145/1368088.1368161](https://doi.org/10.1145/1368088.1368161). + [Microsoft Research publication](https://www.microsoft.com/en-us/research/publication/predicting-defects-using-network-analysis-on-dependency-graphs/). + Dependency structure can reveal important program units. Simple observed caller + counts are not equivalent to the paper's network model or validated predictions. +3. Google's [Small CLs](https://google.github.io/eng-practices/review/developer/small-cls.html) + and [What to look for](https://google.github.io/eng-practices/review/reviewer/looking-for.html) + explain why broad changes are harder to review/test and emphasize functionality, + concurrency, complexity, integration and useful tests. Google explicitly rejects + a universal line-count definition of a small change. +4. [NIST SP 800-30 Rev. 1](https://csrc.nist.gov/pubs/sp/800/30/r1/final) + separates risk factors, impact, likelihood and uncertainty. Atomic borrows the + principle of exposing uncertainty separately; this is not a NIST security-risk + assessment, calibrated likelihood estimate or claim of standards conformance. +5. Shahini et al., [*On the calibration of Just-in-time Defect Prediction*](https://arxiv.org/abs/2504.12051), + 2025 preprint, reports calibration limitations even for learned models. Atomic + therefore reports no invented percentage probability or numeric certainty. + +**The following thresholds are Atomic-owned starter policy**, not scientifically +established constants. Teams should calibrate them against their changes and +observed outcomes. Changing the counting/role conventions requires a model-version +change; an explicit profile records numeric threshold choices. + +## Default `balanced` rules + +Rules take the maximum triggered band; correlated signals are not added into an +opaque score. Each result retains the full profile, measured facts, stable rule ID, +reason and bounded recorded references in JSON/graph. + +| Rule | Band | Default trigger | +|---|---|---| +| `risk.broad-production-change` | High | At least 50 production functions, 5 changed source files, 2 component groups | +| `risk.cross-component-api-churn` | High | At least 20 production functions, 3 component groups, 10 declared public units added/removed | +| `risk.existing-consumer-exposure` | High | At least 25 observed production consumers in 5 files of modified/removed existing declarations | +| `risk.change-diffusion` | Medium | At least 10 production functions, 5 changed source files, or 2 component groups | +| `risk.public-contract-churn` | Medium | Declared public units added/removed, or an existing production signature changed | +| `risk.consumer-review` | Medium | At least 5 observed production consumers of existing declarations, or an observed consumer outside selected source files | +| `risk.dependency-growth` | Medium | Existing-file declared dependency fan-out increases alongside production-function changes | +| `risk.module-contract-change` | Medium | Production imports/types/module-level source changes beyond function-body checks | +| `risk.structural-alerts` | Medium | Introduced/uncertain automated syntax, placeholder or empty-catch alerts requiring judgment | +| `risk.localized-change` | Low | No elevated trigger and sufficient source-selection, reference and surface evidence for localized/test-support scope | + +Unknown is reserved for insufficient facts to apply an elevated rule or support a +localized estimate. Missing evidence is not zero. **Partial coverage does not erase +positive High/Medium triggers.** Conversely, a large number of unresolved names is +not measured fan-out and never raises severity by itself. + +Confirmed/reported risk findings impose a severity floor independently of the +estimate. Profiles or reviewer input cannot downgrade that floor. Rule triggers +do not create F-number findings or acceptance-criterion failures. A reviewer can +override an estimate with scoped evidence; the automatic estimate remains visible. + +## Counting conventions and confidence + +- Functions and consumers are deduplicated by semantic identity, not call-site + count. New-helper consumers are distinguished from consumers of changed existing + declarations. File scope includes selected paths even when their functions did + not change, preventing a false “outside change” classification. +- Test/support classification uses conventional test/fixture/example/bench paths, + test filenames and inline `tests::`/`test::` scopes. It is not proof of runtime + deployment, executed tests, behavioral coverage or test adequacy. Such functions + and consumers are reported separately rather than inflating production exposure. +- Component groups use conventional repository roots (`crates/`, + `packages/`, `services/`, `apps/`; otherwise a top-level project + directory, with a single `src`/`lib` root grouped together). They are not inferred + compiler/runtime service boundaries. +- Public units and fan-out use the existing versioned metric convention. Additions + of a new file are not numeric before=0 deltas. Unknown baselines/conventions stay + unavailable. Public units are source declarations, not a compiled ABI; dependency + roots are not necessarily new third-party packages or vulnerabilities. + Aggregate growth counters tally only comparable observations and are lower + bounds when measurements are incomplete; a zero tally is not a fabricated + before-value or a claim that unmeasured API growth is zero. The separate + completeness/unknown fields prevent such a tally from establishing Low risk. +- Confidence describes input sufficiency for the rule estimate, not a calibrated + probability of defects. Unresolved references, missing metric facts or incomplete + source selection reduce it. Static estimates retain Partial overall coverage; + complete structural inputs do not establish runtime/security/test correctness. + +For captured change `FQNWHCPNXXO5`, the measured summary contains 76 changed functions +(53 production, 23 test/support), 53 current bound consumers (31 production, 22 +test/support), four affected component groups, +19 declared public units in existing +files and 24 in added files. The default broad-change/API-integration rules yield +**High review risk**, even with zero detected contract violations. Unresolved +expressions remain outside those caller counts and lower confidence. + +## Profiles and reproduction + +```sh +atomic review --change --risk-profile review-risk.json +``` + +```json +{ + "name": "team-calibration", + "broad_functions": 80, + "api_growth": 20, + "propagation_callers": 40 +} +``` + +Omitted settings use `balanced` defaults. Profiles reject unknown fields, empty +names, zero thresholds and contradictory high/moderate bands. Their expanded +values and model version are retained in `graph.risk.model`. They affect local +inspection only, not insertion/push, signed publication policy or authorization. +No online research, model training, build scripts, runtime tests or fixes run as +part of this deterministic assessment. diff --git a/atomic-audit/src/catalog.rs b/atomic-audit/src/catalog.rs new file mode 100644 index 00000000..2af6d6ec --- /dev/null +++ b/atomic-audit/src/catalog.rs @@ -0,0 +1,257 @@ +//! Original, readable audit and metric cards, independent of a vendor rule set. + +use crate::metrics::Metric; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Automation { + /// Implemented by this crate's optional structural adapter, for its explicitly + /// supported languages. Matches still require contextual judgment. + Structural, + /// A readable review audit, not a claim of implemented automatic detection. + Substantive, +} + +#[derive(Clone, Copy, Debug, Serialize)] +pub struct AuditCard { + pub id: &'static str, + pub title: &'static str, + pub question: &'static str, + pub evidence: &'static str, + pub exceptions: &'static str, + pub automation: Automation, +} + +pub const AUDIT_CARDS: &[AuditCard] = &[ + AuditCard { + id: "structural.syntax", title: "Invalid or missing syntax", + question: "Does recorded source parse with the declared language grammar?", + evidence: "Error/missing AST node, recorded location and grammar version; verify with the language toolchain when needed.", + exceptions: "An incomplete grammar can reject valid language features. Parser evidence alone is not a compiler verdict.", + automation: Automation::Structural, + }, + AuditCard { + id: "anti-slop.rust-placeholder", title: "Unfinished required behavior", + question: "Does a Rust todo!/unimplemented! invocation stand in for required behavior?", + evidence: "Actual macro invocation, reachable requirement context and recorded baseline; strings/comments are not invocations.", + exceptions: "Intentional scaffolding, test fixtures and shadowed macros need contextual inspection.", + automation: Automation::Structural, + }, + AuditCard { + id: "anti-slop.empty-catch", title: "Undocumented empty catch", + question: "Does a TypeScript/TSX handler discard a failure without behavior or explanation?", + evidence: "Catch AST node, affected operation/caller and its failure contract.", + exceptions: "Explicitly optional operations can legitimately ignore failures. Comments require judgment, not automatic approval.", + automation: Automation::Structural, + }, + AuditCard { + id: "anti-slop.failure-masking", title: "Failure reported as success", + question: "Can an operation fail while its caller receives apparent success or an unexplained default?", + evidence: "Failure path, handler, returned value and caller expectations across the relevant language's error model.", + exceptions: "Documented optional behavior and deliberate degraded operation may be correct.", + automation: Automation::Structural, + }, + AuditCard { + id: "anti-slop.duplicated-behavior", title: "Copy/paste logic and repeated behavior", + question: "Did the change introduce inconsistent copies, identical conditional branches or repeated conditions?", + evidence: "Both source ranges, structural similarity, behavioral differences and the recorded baseline.", + exceptions: "Independent contracts, generated code and intentionally parallel fixtures can justify duplication. Do not create an abstraction solely to reduce a count.", + automation: Automation::Structural, + }, + AuditCard { + id: "anti-slop.unnecessary-machinery", title: "Machinery without a demonstrated purpose", + question: "Do wrappers, extension points, configuration or generic parameters solve a current requirement?", + evidence: "Added abstraction, actual consumers, stated requirement and existing simpler alternatives.", + exceptions: "A single implementation can still justify an interface for a real boundary. Data records are not inherently poor design.", + automation: Automation::Structural, + }, + AuditCard { + id: "anti-slop.manageability", title: "Growing responsibility or reasoning burden", + question: "Did method/class growth, nesting, complexity or coupling make a component harder to change safely?", + evidence: "Before/after metric observations, chosen profile, affected responsibilities and concrete maintenance consequences.", + exceptions: "Long declarative tables, generated code and straightforward parsers/dispatchers may be appropriate. A threshold is a review trigger, not a defect.", + automation: Automation::Structural, + }, + AuditCard { + id: "anti-slop.async-resource-safety", title: "Async work and resource lifetime", + question: "Are failures, pending work, cleanup and synchronization handled according to the language's ownership/concurrency model?", + evidence: "Relevant call/lifetime/control-flow path; type or data-flow evidence where syntax cannot establish behavior.", + exceptions: "Ownership-based cleanup, framework-managed resources and explicitly supervised background work can be correct.", + automation: Automation::Structural, + }, + AuditCard { + id: "anti-slop.weak-verification", title: "Tests or completion claims without behavioral evidence", + question: "Do tests and documented completion claims establish the requested observable behavior, including relevant failure cases?", + evidence: "Actual assertions, exercised behavior, matching test/coverage artifacts and criterion text.", + exceptions: "Framework assertions, snapshot checks and expected-exception tests may not contain ordinary assert calls. Missing coverage is unknown, not zero.", + automation: Automation::Structural, + }, + AuditCard { + id: "anti-slop.unsafe-shortcuts", title: "Safety bypasses and unexplained suppressions", + question: "Does new code bypass validation, verification, authorization or meaningful diagnostics?", + evidence: "Changed trust boundary, validation/suppression point and relevant data/caller path; redact secret values.", + exceptions: "Narrow documented exceptions may be justified. A suspicious API alone does not prove an exploitable vulnerability.", + automation: Automation::Structural, + }, +]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum MetricScope { + Function, + Class, + Module, + Change, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum MetricUnit { + CodeLines, + Count, + Tokens, +} + +#[derive(Clone, Copy, Debug, Serialize)] +pub struct MetricCard { + pub metric: Metric, + pub title: &'static str, + pub scope: MetricScope, + pub unit: MetricUnit, + pub definition: &'static str, + pub interpretation: &'static str, + pub exceptions: &'static str, +} + +pub const METRIC_CARDS: &[MetricCard] = &[ + MetricCard { + metric: Metric::MethodLength, title: "Method/function length", scope: MetricScope::Function, unit: MetricUnit::CodeLines, + definition: "Count physical lines containing code in the function body, excluding signature-only lines, blank/comment-only lines and nested function/type bodies; include body delimiters where present.", + interpretation: "Review growth together with responsibility, nesting and branching. Use the same language/counting convention for the baseline.", + exceptions: "Generated code, tables, parsers and simple dispatchers can legitimately be long.", + }, + MetricCard { + metric: Metric::ClassLength, title: "Class length", scope: MetricScope::Class, unit: MetricUnit::CodeLines, + definition: "Count physical code-containing lines in the class body, including its methods but excluding nested type bodies, blank lines and comment-only lines.", + interpretation: "Review concentration of responsibilities and dependencies; compare within a suitable language and code-role profile.", + exceptions: "Not applicable to constructs without class semantics. Do not substitute zero for unsupported extraction or treat all records/structs as classes.", + }, + MetricCard { + metric: Metric::MethodCount, title: "Methods per class", scope: MetricScope::Class, unit: MetricUnit::Count, + definition: "Count directly declared syntactic methods and constructors, including abstract/overload signatures but excluding inherited methods, nested-type methods and function-valued fields; follow the versioned language convention.", + interpretation: "Inspect interface size and responsibility accumulation alongside method complexity.", + exceptions: "Generated bindings and framework-required methods may justify large counts.", + }, + MetricCard { + metric: Metric::ParameterCount, title: "Function parameter count", scope: MetricScope::Function, unit: MetricUnit::Count, + definition: "Count declared input parameter slots, excluding implicit receivers and return slots; a destructured or variadic parameter occupies one slot.", + interpretation: "Inspect calling conventions and related data; parameter count alone does not justify adding builders or parameter objects.", + exceptions: "Foreign-function interfaces, callbacks and framework signatures can constrain the parameter list.", + }, + MetricCard { + metric: Metric::NestingDepth, title: "Control-flow nesting depth", scope: MetricScope::Function, unit: MetricUnit::Count, + definition: "Measure maximum nested control-flow constructs within a function, excluding plain lexical blocks and separate nested function bodies; declare language-specific else-if handling.", + interpretation: "Review how much branch context a reader must retain and which error paths become obscured.", + exceptions: "Pattern matching and declarative/generated structures need language-aware interpretation.", + }, + MetricCard { + metric: Metric::CyclomaticComplexity, title: "Function cyclomatic complexity", scope: MetricScope::Function, unit: MetricUnit::Count, + definition: "Use one plus decision points under a declared, versioned language counting convention; do not combine results from different conventions.", + interpretation: "A structural proxy for path/testing burden, not a measurement of human understanding or proof of missing tests.", + exceptions: "Generated state machines and decision tables can be intentionally branch-heavy.", + }, + MetricCard { + metric: Metric::ClassComplexity, title: "Aggregate class complexity", scope: MetricScope::Class, unit: MetricUnit::Count, + definition: "Sum directly declared executable source-method complexity under one convention, excluding inherited/nested-type methods and abstract/compiler-generated bodies. Missing out-of-line/native implementations make the aggregate unavailable, not zero.", + interpretation: "Find cumulative complexity that is hidden when each method is considered separately.", + exceptions: "Not applicable without class semantics. Incomplete method measurements make the aggregate unavailable, not smaller.", + }, + MetricCard { + metric: Metric::DependencyFanOut, title: "Declared dependency fan-out", scope: MetricScope::Module, unit: MetricUnit::Count, + definition: "Count distinct explicit dependency units under a versioned language granularity: import source paths, Rust crate roots, Java import targets or C/C++ headers. De-duplicate aliases and repeated declarations; unresolved explicit paths are unavailable. This is not whole-program/runtime coupling.", + interpretation: "Inspect coupling growth and change responsibilities, not simply import statement counts.", + exceptions: "Composition roots and public facade modules may intentionally coordinate many dependencies.", + }, + MetricCard { + metric: Metric::PublicSurface, title: "Declared public surface", scope: MetricScope::Module, unit: MetricUnit::Count, + definition: "Count unique named source-visible bindings and visible members under the versioned language convention; overload sets count once. Exclude private/local and compiler-generated bindings. Unresolved wildcard/dynamic exports are unavailable; this is not a compiled ABI measurement.", + interpretation: "Review growth of the supported compatibility and testing contract.", + exceptions: "Public bindings and intentionally broad compatibility facades need context.", + }, + MetricCard { + metric: Metric::DuplicatedTokens, title: "Duplicated tokens in changed code", scope: MetricScope::Change, unit: MetricUnit::Tokens, + definition: "Count unique token positions in changed source that participate in clone matches under declared normalization and minimum-match settings; count overlapping positions once.", + interpretation: "Inspect repeated behavior and synchronization burden against the baseline. State the searched comparison scope.", + exceptions: "Independent contracts, generated code, tables and fixtures can justify repeated source. No comparison index means unavailable, not zero.", + }, +]; + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeSet; + + #[test] + fn cards_have_unique_identities_definitions_and_interpretation_limits() { + assert_eq!(METRIC_CARDS.len(), Metric::ALL.len()); + assert_eq!( + AUDIT_CARDS + .iter() + .map(|card| card.id) + .collect::>() + .len(), + AUDIT_CARDS.len() + ); + assert_eq!( + METRIC_CARDS + .iter() + .map(|card| card.metric) + .collect::>(), + Metric::ALL.into_iter().collect() + ); + for card in AUDIT_CARDS { + assert!([ + card.id, + card.title, + card.question, + card.evidence, + card.exceptions + ] + .iter() + .all(|text| !text.trim().is_empty())); + } + for card in METRIC_CARDS { + assert!([ + card.title, + card.definition, + card.interpretation, + card.exceptions + ] + .iter() + .all(|text| !text.trim().is_empty())); + } + assert!(METRIC_CARDS + .iter() + .any(|card| card.metric == Metric::MethodLength)); + assert!(METRIC_CARDS + .iter() + .any(|card| card.metric == Metric::ClassLength)); + serde_json::to_value(METRIC_CARDS).unwrap(); + } + + #[cfg(feature = "structural")] + #[test] + fn every_automated_rule_has_a_readable_card_and_vice_versa() { + let rules: BTreeSet<_> = crate::structural::Rule::ALL + .into_iter() + .map(|rule| rule.id()) + .collect(); + let cards = AUDIT_CARDS + .iter() + .filter(|card| card.automation == Automation::Structural) + .map(|card| card.id) + .collect(); + assert_eq!(rules, cards); + } +} diff --git a/atomic-audit/src/extract/languages.rs b/atomic-audit/src/extract/languages.rs new file mode 100644 index 00000000..a24a541b --- /dev/null +++ b/atomic-audit/src/extract/languages.rs @@ -0,0 +1,1181 @@ +//! Explicit source-syntax conventions. No compiler/type/runtime claims. + +use super::tokens::{children, named, text}; +use crate::metrics::Measurement; +use atomic_semantic::{Language, SyntaxNode as Node}; +use std::collections::BTreeSet; + +pub(super) fn literal(node: Node<'_>) -> bool { + let kind = node.kind(); + (kind.contains("string") || kind.contains("char_literal") || kind == "template_string") + && !named(node).iter().any(|child| { + child.kind().contains("interpolation") || child.kind().contains("substitution") + }) +} + +pub(super) fn class_like(node: Node<'_>, language: Language) -> bool { + match language { + Language::TypeScript | Language::Tsx => matches!( + node.kind(), + "class_declaration" | "abstract_class_declaration" | "class" + ), + Language::Python => node.kind() == "class_definition", + Language::Java => matches!( + node.kind(), + "class_declaration" | "record_declaration" | "enum_declaration" + ), + Language::Cpp => matches!(node.kind(), "class_specifier" | "struct_specifier"), + Language::Swift => { + node.kind() == "class_declaration" + && node + .child_by_field_name("declaration_kind") + .is_some_and(|kind| kind.kind() == "class") + } + Language::Rust | Language::Go | Language::C => false, + } +} + +pub(super) fn type_boundary(node: Node<'_>, language: Language) -> bool { + class_like(node, language) + || matches!( + node.kind(), + "struct_item" + | "enum_item" + | "trait_item" + | "interface_declaration" + | "protocol_declaration" + | "struct_specifier" + | "enum_specifier" + ) + || (language == Language::Swift && node.kind() == "class_declaration") +} + +pub(crate) fn callable(node: Node<'_>, language: Language) -> bool { + match language { + Language::Rust => matches!( + node.kind(), + "function_item" | "function_signature_item" | "closure_expression" + ), + Language::TypeScript | Language::Tsx => matches!( + node.kind(), + "function_declaration" + | "generator_function_declaration" + | "function_expression" + | "function" + | "generator_function" + | "arrow_function" + | "method_definition" + | "abstract_method_signature" + | "method_signature" + ), + Language::Python => matches!(node.kind(), "function_definition" | "lambda"), + Language::Java => matches!( + node.kind(), + "method_declaration" + | "constructor_declaration" + | "compact_constructor_declaration" + | "lambda_expression" + ), + Language::Go => matches!( + node.kind(), + "function_declaration" | "method_declaration" | "func_literal" | "method_elem" + ), + Language::C | Language::Cpp => { + matches!(node.kind(), "function_definition" | "lambda_expression") + || (matches!(node.kind(), "field_declaration" | "declaration") + && declarator(node) + .and_then(|declaration| declaration.child_by_field_name("declarator")) + .is_some_and(|name| { + matches!( + name.kind(), + "identifier" + | "field_identifier" + | "qualified_identifier" + | "operator_name" + | "destructor_name" + ) + })) + } + Language::Swift => matches!( + node.kind(), + "function_declaration" + | "protocol_function_declaration" + | "init_declaration" + | "deinit_declaration" + | "lambda_literal" + ), + } +} + +fn declarator(mut node: Node<'_>) -> Option> { + for _ in 0..16 { + if matches!( + node.kind(), + "function_declarator" | "abstract_function_declarator" | "lambda_declarator" + ) { + return Some(node); + } + node = node.child_by_field_name("declarator")?; + } + None +} + +pub(crate) fn body(node: Node<'_>, language: Language) -> Option> { + node.child_by_field_name("body").or_else(|| { + if language == Language::Swift && node.kind() == "lambda_literal" { + named(node) + .into_iter() + .find(|child| child.kind() == "statements") + } else { + None + } + }) +} + +pub(super) fn body_is_missing(node: Node<'_>, source: &str, language: Language) -> bool { + if body(node, language).is_some() { + return false; + } + match language { + Language::C => true, + Language::Cpp => { + let implicit = named(node).iter().any(|child| { + matches!( + child.kind(), + "pure_virtual_clause" | "default_method_clause" | "delete_method_clause" + ) + }) || node + .child_by_field_name("default_value") + .is_some_and(|value| text(value, source).trim() == "0"); + !implicit + } + Language::Java => modifier(node, source, "native"), + _ => false, + } +} + +pub(super) fn owner_class(mut node: Node<'_>, language: Language) -> Option> { + while let Some(parent) = node.parent() { + if callable(parent, language) { + return None; + } + if class_like(parent, language) { + return Some(parent); + } + node = parent; + } + None +} + +pub(super) fn method(node: Node<'_>, language: Language) -> bool { + owner_class(node, language).is_some() + && !matches!( + node.kind(), + "arrow_function" + | "lambda" + | "lambda_expression" + | "lambda_literal" + | "closure_expression" + | "function_expression" + | "func_literal" + ) +} + +pub(super) fn node_name(node: Node<'_>, source: &str) -> Option { + if let Some(name) = node.child_by_field_name("name") { + return Some(text(name, source).into()); + } + if let Some(function) = declarator(node) { + if let Some(name) = function.child_by_field_name("declarator") { + return Some(text(name, source).into()); + } + } + if let Some(parent) = node.parent() { + if matches!( + parent.kind(), + "variable_declarator" | "public_field_definition" | "assignment" | "let_declaration" + ) { + return parent + .child_by_field_name("name") + .or_else(|| parent.child_by_field_name("left")) + .or_else(|| parent.child_by_field_name("pattern")) + .map(|name| text(name, source).into()); + } + } + None +} + +pub(crate) fn qualified(node: Node<'_>, source: &str, language: Language) -> (String, bool) { + let mut reliable = true; + let mut parts = Vec::new(); + let mut next = Some(node); + while let Some(item) = next { + if callable(item, language) + || type_boundary(item, language) + || matches!( + item.kind(), + "namespace_definition" | "mod_item" | "impl_item" + ) + { + match node_name(item, source).or_else(|| { + item.child_by_field_name("type") + .map(|kind| text(kind, source).into()) + }) { + Some(name) if !name.is_empty() => parts.push(name), + _ => { + parts.push(format!("", item.start_byte())); + reliable = false; + } + } + } + if parts.iter().map(String::len).sum::() > 2048 { + reliable = false; + break; + } + next = item.parent(); + } + parts.reverse(); + (parts.join("::"), reliable) +} + +pub(super) fn parameters(node: Node<'_>, source: &str, language: Language) -> Measurement { + let container = node + .child_by_field_name("parameters") + .or_else(|| declarator(node).and_then(|decl| decl.child_by_field_name("parameters"))); + let mut params = if let Some(container) = container { + if matches!(container.kind(), "identifier" | "inferred_parameter") { + vec![container] + } else { + named(container) + } + } else if let Some(parameter) = node.child_by_field_name("parameter") { + vec![parameter] + } else if language == Language::Swift && node.kind() != "lambda_literal" { + named(node) + .into_iter() + .filter(|child| child.kind() == "parameter") + .collect() + } else if (language == Language::Cpp && node.kind() == "lambda_expression") + || node.kind() == "compact_constructor_declaration" + || node.kind() == "deinit_declaration" + { + vec![] + } else { + return Measurement::Unavailable { + reason: "Parameter syntax is inferred or not supported by this convention".into(), + }; + }; + params.retain(|parameter| { + !matches!( + parameter.kind(), + "comment" + | "line_comment" + | "block_comment" + | "attribute_item" + | "self_parameter" + | "positional_separator" + | "keyword_separator" + | "receiver_parameter" + ) && !(language == Language::Rust + && parameter + .child_by_field_name("pattern") + .is_some_and(|pattern| text(pattern, source) == "self")) + && !(matches!(language, Language::TypeScript | Language::Tsx) + && parameter + .child_by_field_name("pattern") + .is_some_and(|pattern| text(pattern, source) == "this")) + }); + if language == Language::Python && method(node, language) { + let is_static = node + .parent() + .filter(|parent| parent.kind() == "decorated_definition") + .is_some_and(|parent| { + named(parent).iter().any(|child| { + child.kind() == "decorator" + && matches!( + text(*child, source).trim(), + "@staticmethod" | "@builtins.staticmethod" + ) + }) + }); + if !is_static && !params.is_empty() { + params.remove(0); + } + } + let count: usize = params + .iter() + .map(|parameter| { + if language == Language::Go { + let mut cursor = parameter.walk(); + parameter + .children_by_field_name("name", &mut cursor) + .count() + .max(1) + } else if matches!(language, Language::C | Language::Cpp) + && text(*parameter, source) == "void" + { + 0 + } else { + 1 + } + }) + .sum(); + Measurement::Measured { + value: count as u32, + } +} + +fn is_else_if(node: Node<'_>) -> bool { + let mut previous = node.prev_named_sibling(); + while previous.is_some_and(super::tokens::comment) { + previous = previous.and_then(|item| item.prev_named_sibling()); + } + node.kind() == "elif_clause" + || (matches!(node.kind(), "if_statement" | "if_expression") + && node.parent().is_some_and(|parent| { + parent.kind() == "else_clause" + || (matches!(parent.kind(), "if_statement" | "if_expression") + && previous.is_some_and(|item| item.kind() == "else")) + || parent + .child_by_field_name("alternative") + .is_some_and(|alternative| alternative.id() == node.id()) + })) +} + +pub(crate) fn control_flow(root: Node<'_>, source: &str, language: Language) -> (u32, u32) { + let mut complexity = 1; + let mut maximum = 0; + let mut stack = vec![(root, 0)]; + while let Some((node, depth)) = stack.pop() { + if node.id() != root.id() && (callable(node, language) || type_boundary(node, language)) { + continue; + } + if super::tokens::comment(node) || literal(node) { + continue; + } + let go_switch = matches!( + node.kind(), + "expression_switch_statement" | "type_switch_statement" + ); + let control = go_switch + || matches!( + node.kind(), + "if_statement" + | "if_expression" + | "elif_clause" + | "for_statement" + | "for_expression" + | "for_in_statement" + | "while_statement" + | "while_expression" + | "do_statement" + | "do_while_statement" + | "loop_expression" + | "catch_clause" + | "except_clause" + | "guard_statement" + | "switch_statement" + | "switch_expression" + | "match_expression" + | "match_statement" + | "select_statement" + | "conditional_expression" + | "ternary_expression" + ); + let next_depth = depth + u32::from(control && !is_else_if(node)); + maximum = maximum.max(next_depth); + if control + && !go_switch + && !matches!( + node.kind(), + "switch_statement" + | "switch_expression" + | "match_expression" + | "match_statement" + | "select_statement" + ) + { + complexity += 1; + } + if matches!( + node.kind(), + "conjunction_expression" | "disjunction_expression" + ) { + complexity += 1; + } + if matches!(node.kind(), "binary_expression" | "boolean_operator") + && node + .child_by_field_name("operator") + .is_some_and(|operator| { + matches!(text(operator, source), "&&" | "||" | "and" | "or") + }) + { + complexity += 1; + } + if matches!( + node.kind(), + "match_arm" + | "switch_case" + | "switch_label" + | "expression_case" + | "type_case" + | "communication_case" + | "case_clause" + | "case_statement" + | "switch_entry" + ) { + let pattern = node + .child_by_field_name("pattern") + .or_else(|| node.child_by_field_name("value")) + .or_else(|| { + named(node) + .into_iter() + .find(|child| child.kind().contains("pattern")) + }); + let guarded = node.child_by_field_name("guard").is_some() + || named(node).iter().any(|child| { + matches!( + child.kind(), + "if_clause" | "match_condition_clause" | "guard" + ) + }); + if !text(node, source).trim_start().starts_with("default") + && !(pattern.is_some_and(|pattern| text(pattern, source).trim() == "_") && !guarded) + { + complexity += 1; + } + } + stack.extend( + children(node) + .into_iter() + .rev() + .map(|child| (child, next_depth)), + ); + } + (complexity, maximum) +} + +fn unquote(value: &str) -> Option { + let value = value.trim(); + let stripped = if (value.starts_with('\"') && value.ends_with('\"')) + || (value.starts_with('\'') && value.ends_with('\'')) + || (value.starts_with('`') && value.ends_with('`')) + || (value.starts_with('<') && value.ends_with('>')) + { + &value[1..value.len().checked_sub(1)?] + } else { + value + }; + if stripped.is_empty() || stripped.contains(['\\', '$', '\n']) { + None + } else { + Some(stripped.into()) + } +} + +/// Distinct explicit dependency units, not a type-resolved coupling metric. +fn rust_roots(node: Node<'_>, source: &str, result: &mut BTreeSet) { + if node.kind() == "use_list" { + for child in named(node) { + rust_roots(child, source, result); + } + } else if node.kind() == "use_as_clause" { + if let Some(path) = node.child_by_field_name("path") { + rust_roots(path, source, result); + } + } else { + let path = node.child_by_field_name("path").unwrap_or(node); + let root = text(path, source) + .trim_start_matches("::") + .split("::") + .next() + .unwrap_or_default() + .trim(); + if !root.is_empty() { + result.insert(root.into()); + } + } +} + +fn rust_bindings(node: Node<'_>, source: &str, prefix: Option<&str>, result: &mut Vec) { + match node.kind() { + "use_list" => { + for child in named(node) { + rust_bindings(child, source, prefix, result); + } + } + "scoped_use_list" => { + let parent = node + .child_by_field_name("path") + .map(|path| text(path, source)); + for list in named(node) + .into_iter() + .filter(|child| child.kind() == "use_list") + { + rust_bindings(list, source, parent, result); + } + } + "use_as_clause" => { + if let Some(alias) = node.child_by_field_name("alias") { + result.push(text(alias, source).into()); + } + } + "self" => result.push( + prefix + .unwrap_or("self") + .rsplit("::") + .next() + .unwrap_or("self") + .into(), + ), + _ => result.push( + text(node, source) + .rsplit("::") + .next() + .unwrap_or_default() + .trim() + .into(), + ), + } +} + +pub(super) fn dependencies(nodes: &[Node<'_>], source: &str, language: Language) -> Measurement { + let mut units = BTreeSet::new(); + let mut incomplete = false; + for &node in nodes { + let path = match (language, node.kind()) { + (Language::TypeScript | Language::Tsx, "import_statement" | "export_statement") => node + .child_by_field_name("source") + .map(|path| text(path, source).to_owned()), + (Language::Python, "import_from_statement") => node + .child_by_field_name("module_name") + .map(|path| text(path, source).into()), + (Language::Python, "import_statement") => { + for child in named(node) { + let child = child.child_by_field_name("name").unwrap_or(child); + units.insert(text(child, source).to_owned()); + } + None + } + (Language::Rust, "use_declaration") => { + if let Some(path) = node.child_by_field_name("argument") { + rust_roots(path, source, &mut units); + } + None + } + (Language::Rust, "extern_crate_declaration") => node + .child_by_field_name("name") + .map(|path| text(path, source).into()), + (Language::Go, "import_spec") => node + .child_by_field_name("path") + .map(|path| text(path, source).into()), + (Language::Java, "import_declaration") => { + let raw = text(node, source) + .trim_start_matches("import") + .trim() + .trim_end_matches(';') + .trim(); + Some( + raw.trim_start_matches("static ") + .trim_end_matches(".*") + .into(), + ) + } + (Language::C | Language::Cpp, "preproc_include") => { + let path = node.child_by_field_name("path"); + if path.is_none_or(|path| { + !matches!(path.kind(), "string_literal" | "system_lib_string") + }) { + incomplete = true; + None + } else { + path.map(|path| text(path, source).into()) + } + } + (Language::Swift, "import_declaration") => named(node) + .into_iter() + .find(|child| child.kind() == "identifier") + .map(|path| { + text(path, source) + .split('.') + .next() + .unwrap_or_default() + .into() + }), + _ => None, + }; + if let Some(path) = path { + if let Some(path) = unquote(&path) { + units.insert(path); + } else { + incomplete = true; + } + } + if matches!(language, Language::TypeScript | Language::Tsx) + && node.kind() == "import_require_clause" + { + if let Some(path) = named(node) + .into_iter() + .find(|child| child.kind() == "string") + .and_then(|path| unquote(text(path, source))) + { + units.insert(path); + } else { + incomplete = true; + } + } + } + if incomplete { + Measurement::Unavailable { + reason: "One or more explicit dependency paths cannot be statically identified".into(), + } + } else { + Measurement::Measured { + value: units.len() as u32, + } + } +} + +fn modifier(node: Node<'_>, source: &str, expected: &str) -> bool { + let mut stack: Vec<_> = named(node) + .into_iter() + .filter(|child| { + matches!( + child.kind(), + "modifiers" + | "visibility_modifier" + | "accessibility_modifier" + | "storage_class_specifier" + ) + }) + .collect(); + while let Some(item) = stack.pop() { + if item.kind() == "visibility_modifier" && expected == "pub" { + if text(item, source).trim() == "pub" { + return true; + } + continue; + } + if matches!( + item.kind(), + "annotation" | "marker_annotation" | "attribute" | "decorator" + ) || literal(item) + { + continue; + } + if text(item, source).trim() == expected { + return true; + } + stack.extend(children(item)); + } + false +} + +fn in_function(mut node: Node<'_>, language: Language) -> bool { + while let Some(parent) = node.parent() { + if callable(parent, language) { + return true; + } + node = parent; + } + false +} + +fn cpp_access(node: Node<'_>, source: &str) -> bool { + let mut current = node; + while let Some(parent) = current.parent() { + if parent.kind() == "field_declaration_list" { + let mut public = parent + .parent() + .is_some_and(|owner| owner.kind() == "struct_specifier"); + for child in named(parent) { + if child.id() == current.id() { + break; + } + if child.kind() == "access_specifier" { + public = matches!(text(child, source), "public" | "protected"); + } + } + if !public { + return false; + } + } + if parent.kind() == "namespace_definition" && parent.child_by_field_name("name").is_none() { + return false; + } + current = parent; + } + true +} + +fn exported_ts(mut node: Node<'_>, source: &str) -> bool { + loop { + if modifier(node, source, "private") + || node + .child_by_field_name("name") + .is_some_and(|name| text(name, source).starts_with('#')) + { + return false; + } + if node.kind() == "export_statement" { + return true; + } + let Some(parent) = node.parent() else { + return false; + }; + node = parent; + } +} + +fn names(node: Node<'_>, source: &str) -> Vec { + if matches!(node.kind(), "import_statement" | "import_from_statement") { + let mut cursor = node.walk(); + return node + .children_by_field_name("name", &mut cursor) + .map(|name| { + name.child_by_field_name("alias") + .map(|alias| text(alias, source).to_owned()) + .unwrap_or_else(|| { + text(name, source) + .split('.') + .next() + .unwrap_or_default() + .into() + }) + }) + .collect(); + } + let mut cursor = node.walk(); + let mut bindings: Vec<_> = node.children_by_field_name("name", &mut cursor).collect(); + if bindings.is_empty() { + bindings.extend( + node.child_by_field_name("left") + .or_else(|| node.child_by_field_name("pattern")), + ); + } + if !bindings.is_empty() { + let mut result = Vec::new(); + while let Some(binding) = bindings.pop() { + match binding.kind() { + "tuple_pattern" | "list_pattern" | "pattern_list" | "tuple" | "list" + | "array_pattern" | "object_pattern" => bindings.extend(named(binding)), + "pair_pattern" => bindings.extend(binding.child_by_field_name("value")), + "assignment_pattern" | "object_assignment_pattern" => { + bindings.extend(binding.child_by_field_name("left")) + } + "rest_pattern" => bindings.extend(named(binding)), + _ => result.push(text(binding, source).into()), + } + } + return result; + } + if let Some(function) = + declarator(node).and_then(|function| function.child_by_field_name("declarator")) + { + return vec![text(function, source).into()]; + } + if matches!(node.kind(), "declaration" | "field_declaration") { + let mut cursor = node.walk(); + return node + .children_by_field_name("declarator", &mut cursor) + .map(|declaration| { + let declaration = declaration + .child_by_field_name("declarator") + .unwrap_or(declaration); + text(declaration, source).to_owned() + }) + .collect(); + } + Vec::new() +} + +/// Count source-declared visibility, not a compiled ABI or dynamic export set. +pub(super) fn public_surface(nodes: &[Node<'_>], source: &str, language: Language) -> Measurement { + let unavailable = |reason: &str| Measurement::Unavailable { + reason: reason.into(), + }; + let mut explicit_python = None; + if language == Language::Python { + for &node in nodes { + if in_function(node, language) || owner_class(node, language).is_some() { + continue; + } + if node.kind() == "call" + && node + .child_by_field_name("function") + .is_some_and(|function| text(function, source).starts_with("__all__.")) + { + return unavailable("Python __all__ is used through a potentially mutating call"); + } + if matches!(node.kind(), "assignment" | "augmented_assignment") + && node + .child_by_field_name("left") + .is_some_and(|left| text(left, source).starts_with("__all__[")) + { + return unavailable("Python __all__ is mutated through indexing"); + } + if matches!(node.kind(), "assignment" | "augmented_assignment") + && node + .child_by_field_name("left") + .is_some_and(|left| text(left, source) == "__all__") + { + if explicit_python.is_some() || node.kind() == "augmented_assignment" { + return unavailable("Dynamic or multiply assigned Python __all__"); + } + let Some(value) = node + .child_by_field_name("right") + .filter(|value| matches!(value.kind(), "list" | "tuple")) + else { + return unavailable("Python __all__ is not a static literal sequence"); + }; + let mut exports = BTreeSet::new(); + for item in named(value) { + if item.kind() != "string" { + return unavailable("Python __all__ contains nonliteral names"); + } + let raw = text(item, source); + if !raw.starts_with(['\'', '"']) + || raw.starts_with("\"\"\"") + || raw.starts_with("'''") + { + return unavailable("Prefixed/triple-quoted export names are not decoded by this convention"); + } + let Some(name) = unquote(raw) else { + return unavailable("Python __all__ contains encoded or dynamic names"); + }; + exports.insert(name); + } + explicit_python = Some(exports); + } + } + } + let mut result = BTreeSet::new(); + for &node in nodes { + if matches!(language, Language::TypeScript | Language::Tsx) + && matches!(node.kind(), "required_parameter" | "optional_parameter") + && (named(node) + .iter() + .any(|child| child.kind() == "accessibility_modifier") + || children(node) + .iter() + .any(|child| child.kind() == "readonly")) + && !modifier(node, source, "private") + { + let mut parent = node.parent(); + while let Some(owner) = parent { + if callable(owner, language) { + if owner.kind() == "method_definition" + && node_name(owner, source).as_deref() == Some("constructor") + { + if let Some(class) = + owner_class(owner, language).filter(|class| exported_ts(*class, source)) + { + for name in names(node, source) { + result.insert(format!( + "{}::{name}", + qualified(class, source, language).0 + )); + } + } + } + break; + } + parent = owner.parent(); + } + } + if in_function(node, language) { + continue; + } + if matches!(language, Language::TypeScript | Language::Tsx) { + if matches!(node.kind(), "internal_module" | "module") { + return unavailable( + "Namespace/module export expansion is not resolved by this convention", + ); + } + if node.kind() == "export_statement" + && node.child_by_field_name("declaration").is_none() + { + if children(node).iter().any(|child| child.kind() == "*") { + return unavailable("Wildcard re-exports require an external export index"); + } + if children(node).iter().any(|child| child.kind() == "default") { + result.insert("default".to_owned()); + } + } + if node.kind() == "export_specifier" { + if let Some(name) = node + .child_by_field_name("alias") + .or_else(|| node.child_by_field_name("name")) + { + result.insert(text(name, source).into()); + } + } + if matches!(node.kind(), "assignment_expression" | "call_expression") + && (text(node, source).starts_with("module.exports") + || text(node, source).starts_with("exports[") + || text(node, source).starts_with("exports.")) + { + return unavailable("CommonJS dynamic export assignments are not resolved"); + } + } + if matches!(language, Language::C | Language::Cpp) + && matches!( + node.kind(), + "preproc_if" | "preproc_ifdef" | "preproc_function_def" + ) + { + return unavailable("Preprocessing can change the public declarations"); + } + if language == Language::Rust + && node.kind() == "use_declaration" + && modifier(node, source, "pub") + && text(node, source).contains('*') + { + return unavailable("Wildcard Rust public re-exports require a resolved export index"); + } + if language == Language::Rust + && node.kind() == "use_declaration" + && modifier(node, source, "pub") + { + if let Some(argument) = node.child_by_field_name("argument") { + let mut exported = Vec::new(); + rust_bindings(argument, source, None, &mut exported); + result.extend(exported); + } + } + if language == Language::Rust + && node.kind() == "macro_invocation" + && node.parent().is_some_and(|parent| { + matches!(parent.kind(), "source_file" | "declaration_list") + || (parent.kind() == "expression_statement" + && parent.parent().is_some_and(|owner| { + matches!(owner.kind(), "source_file" | "declaration_list") + })) + }) + { + return unavailable("Module-level macro expansion can alter public declarations"); + } + if language == Language::Python + && node.kind() == "wildcard_import" + && explicit_python.is_none() + { + return unavailable("Python wildcard imports require a resolved export index"); + } + + let declaration = match language { + Language::Rust => matches!( + node.kind(), + "function_item" + | "function_signature_item" + | "struct_item" + | "enum_item" + | "trait_item" + | "const_item" + | "static_item" + | "type_item" + | "mod_item" + | "field_declaration" + | "enum_variant" + ), + Language::TypeScript | Language::Tsx => matches!( + node.kind(), + "function_declaration" + | "generator_function_declaration" + | "class_declaration" + | "abstract_class_declaration" + | "interface_declaration" + | "type_alias_declaration" + | "enum_declaration" + | "variable_declarator" + | "method_definition" + | "abstract_method_signature" + | "public_field_definition" + | "method_signature" + | "property_signature" + ), + Language::Python => matches!( + node.kind(), + "function_definition" + | "class_definition" + | "assignment" + | "import_statement" + | "import_from_statement" + ), + Language::Java => matches!( + node.kind(), + "class_declaration" + | "record_declaration" + | "enum_declaration" + | "interface_declaration" + | "method_declaration" + | "constructor_declaration" + | "field_declaration" + ), + Language::Go => matches!( + node.kind(), + "function_declaration" + | "method_declaration" + | "type_spec" + | "var_spec" + | "const_spec" + | "field_declaration" + | "method_elem" + ), + Language::C | Language::Cpp => matches!( + node.kind(), + "function_definition" + | "declaration" + | "field_declaration" + | "class_specifier" + | "struct_specifier" + | "enum_specifier" + ), + Language::Swift => matches!( + node.kind(), + "function_declaration" + | "class_declaration" + | "protocol_declaration" + | "init_declaration" + | "property_declaration" + | "typealias_declaration" + ), + }; + if !declaration { + continue; + } + let mut declared_names = names(node, source); + if language == Language::Python { + if explicit_python.is_some() && owner_class(node, language).is_none() { + continue; + } + declared_names.retain(|name| { + !name.starts_with('_') + || (owner_class(node, language).is_some() + && name.starts_with("__") + && name.ends_with("__")) + }); + } + if language == Language::Go { + declared_names.retain(|name| name.chars().next().is_some_and(char::is_uppercase)); + } + let visible = match language { + Language::Rust => { + let mut parent = node.parent(); + let mut implicit = false; + while let Some(owner) = parent { + if matches!(owner.kind(), "trait_item" | "enum_item") { + implicit = modifier(owner, source, "pub") + && matches!( + node.kind(), + "function_signature_item" | "function_item" | "enum_variant" + ); + break; + } + parent = owner.parent(); + } + modifier(node, source, "pub") || implicit + } + Language::TypeScript | Language::Tsx => exported_ts(node, source), + Language::Python => declared_names.iter().any(|name| { + if owner_class(node, language).is_none() { + explicit_python + .as_ref() + .map(|exports| exports.contains(name)) + .unwrap_or(!name.starts_with('_')) + } else { + !name.starts_with('_') || (name.starts_with("__") && name.ends_with("__")) + } + }), + Language::Java => { + modifier(node, source, "public") + || modifier(node, source, "protected") + || node + .parent() + .is_some_and(|parent| parent.kind() == "interface_body") + } + Language::Go => declared_names + .iter() + .any(|name| name.chars().next().is_some_and(char::is_uppercase)), + Language::C | Language::Cpp => { + (!modifier(node, source, "static") || owner_class(node, language).is_some()) + && cpp_access(node, source) + } + Language::Swift => modifier(node, source, "public") || modifier(node, source, "open"), + }; + if !visible { + continue; + } + if declared_names.is_empty() { + return unavailable("A visible declaration has unsupported binding syntax"); + } + // Visibility of enclosing classes/types matters as well as member flags. + let mut ancestor = node.parent(); + let mut hidden = false; + while let Some(parent) = ancestor { + if language == Language::Rust && parent.kind() == "impl_item" { + if let Some(target) = parent.child_by_field_name("type") { + let target = text(target, source).split('<').next().unwrap_or_default(); + let types: Vec<_> = nodes + .iter() + .filter(|candidate| { + matches!(candidate.kind(), "struct_item" | "enum_item" | "type_item") + && node_name(**candidate, source).as_deref() == Some(target) + }) + .collect(); + if types.len() != 1 { + return unavailable("Public inherent impl target is not uniquely resolved in this source file"); + } + hidden |= !modifier(*types[0], source, "pub"); + } + } + if language == Language::Rust && parent.kind() == "mod_item" { + hidden |= !modifier(parent, source, "pub"); + } + if type_boundary(parent, language) { + hidden |= match language { + Language::Rust => !modifier(parent, source, "pub"), + Language::Java => { + !modifier(parent, source, "public") + && !modifier(parent, source, "protected") + } + Language::Python => node_name(parent, source).is_some_and(|name| { + if owner_class(parent, language).is_none() { + explicit_python + .as_ref() + .map(|exports| !exports.contains(&name)) + .unwrap_or(name.starts_with('_')) + } else { + name.starts_with('_') + } + }), + Language::Swift => { + !modifier(parent, source, "public") && !modifier(parent, source, "open") + } + _ => false, + }; + } + ancestor = parent.parent(); + } + if hidden { + continue; + } + let prefix = qualified(node, source, language).0; + for name in declared_names { + result.insert( + if callable(node, language) || type_boundary(node, language) { + prefix.clone() + } else if prefix.is_empty() { + name + } else { + format!("{prefix}::{name}") + }, + ); + } + } + if let Some(exports) = explicit_python { + result.extend(exports); + } + Measurement::Measured { + value: result.len() as u32, + } +} diff --git a/atomic-audit/src/extract/mod.rs b/atomic-audit/src/extract/mod.rs new file mode 100644 index 00000000..195d252c --- /dev/null +++ b/atomic-audit/src/extract/mod.rs @@ -0,0 +1,634 @@ +//! Automatic, bounded source-syntax measurements over before/after snapshots. +//! Inputs are supplied recorded source; this module performs no filesystem I/O. + +pub(crate) mod languages; +pub(crate) mod tokens; + +use crate::catalog::{MetricScope, METRIC_CARDS}; +use crate::metrics::{ + ExtractedMetric, Measurement, Metric, MetricLocation, MetricObservation, EXTRACTION_CONVENTION, +}; +use atomic_semantic::{Language, ParserRegistry, SyntaxNode as Node}; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Clone, Debug)] +pub enum Source { + Text(String), + /// Proven absence, not a failed read or an unavailable historical baseline. + Absent, + Unavailable(String), +} + +impl Source { + pub fn from_bytes(bytes: Vec) -> Self { + if bytes.contains(&0) { + return Self::Unavailable("Binary source".into()); + } + String::from_utf8(bytes) + .map(Self::Text) + .unwrap_or_else(|_| Self::Unavailable("Non-UTF-8 source".into())) + } +} + +#[derive(Clone, Debug)] +pub struct FileChange { + pub path: String, + pub before: Source, + pub after: Source, +} + +#[derive(Clone, Debug)] +pub struct ExtractionConfig { + pub max_files: usize, + pub max_total_bytes: usize, + pub max_tokens_per_file: usize, + pub max_total_tokens: usize, + pub max_subjects_per_file: usize, + pub max_total_subjects: usize, + pub minimum_clone_tokens: usize, + pub max_diff_work: usize, + pub max_clone_pairs: usize, +} + +impl Default for ExtractionConfig { + fn default() -> Self { + Self { + max_files: 128, + max_total_bytes: 8 * 1024 * 1024, + max_tokens_per_file: 20_000, + max_total_tokens: 80_000, + max_subjects_per_file: 256, + max_total_subjects: 1024, + minimum_clone_tokens: 32, + max_diff_work: 16_000_000, + max_clone_pairs: 100_000, + } + } +} + +#[derive(Clone, Debug)] +pub struct Extraction { + pub metrics: Vec, + pub diagnostics: Vec, + /// Exact supplied comparison paths, not an assertion of repository coverage. + pub comparison_paths: Vec, +} + +#[derive(Clone, Debug)] +struct Entry { + value: Measurement, + location: MetricLocation, + reliable_identity: bool, +} + +#[derive(Clone, Debug)] +enum State { + Ready, + Absent, + Unavailable(String), +} + +struct Parsed { + language: Option, + state: State, + entries: BTreeMap<(Metric, String), Entry>, + tokens: Vec, + token_error: Option, + location: Option, +} + +impl Parsed { + fn unavailable(language: Option, reason: impl Into) -> Self { + Self { + language, + state: State::Unavailable(reason.into()), + entries: BTreeMap::new(), + tokens: vec![], + token_error: None, + location: None, + } + } + + fn value(&self, key: &(Metric, String), known_other: bool) -> Measurement { + if let Some(entry) = self.entries.get(key) { + return entry.value.clone(); + } + match &self.state { + State::Absent => not_applicable("File is absent in this revision"), + State::Unavailable(reason) => unavailable(reason), + State::Ready if known_other => { + not_applicable("Subject is not present in this revision") + } + State::Ready => not_applicable("No applicable declarations in this file"), + } + } +} + +fn measured(value: u32) -> Measurement { + Measurement::Measured { value } +} +fn unavailable(reason: &str) -> Measurement { + Measurement::Unavailable { + reason: reason.into(), + } +} +fn not_applicable(reason: &str) -> Measurement { + Measurement::NotApplicable { + reason: reason.into(), + } +} + +fn location(node: Node<'_>) -> MetricLocation { + MetricLocation { + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + + u32::from( + node.end_position().column > 0 + || node.end_position().row == node.start_position().row, + ), + } +} + +fn metric_scope(metric: Metric) -> MetricScope { + METRIC_CARDS + .iter() + .find(|card| card.metric == metric) + .expect("catalog covers every metric") + .scope +} + +fn inventory(root: Node<'_>) -> Result>, String> { + let mut result = Vec::new(); + let mut stack = vec![(root, 0)]; + while let Some((node, depth)) = stack.pop() { + if depth > 256 { + return Err("AST nesting budget exceeded".into()); + } + if tokens::comment(node) { + continue; + } + result.push(node); + if result.len() > 300_000 { + return Err("AST node budget exceeded".into()); + } + stack.extend( + tokens::named(node) + .into_iter() + .rev() + .map(|child| (child, depth + 1)), + ); + } + Ok(result) +} + +fn parse( + source: &Source, + path: &str, + registry: &mut ParserRegistry, + config: &ExtractionConfig, + bytes_left: &mut usize, + tokens_left: &mut usize, + subjects_left: &mut usize, +) -> Parsed { + let language = Language::detect(path); + let source = match source { + Source::Absent => { + return Parsed { + language, + state: State::Absent, + entries: BTreeMap::new(), + tokens: vec![], + token_error: None, + location: None, + } + } + Source::Unavailable(reason) => return Parsed::unavailable(language, reason), + Source::Text(source) => source, + }; + let Some(language) = language else { + return Parsed::unavailable(None, "Unsupported language"); + }; + if source.len() > atomic_semantic::MAX_SOURCE_BYTES || source.len() > *bytes_left { + return Parsed::unavailable(Some(language), "Source byte budget exceeded"); + } + *bytes_left -= source.len(); + if source.contains('\0') { + return Parsed::unavailable(Some(language), "Binary source"); + } + let Some(tree) = registry.parse_tree(path, source) else { + return Parsed::unavailable(Some(language), "No syntax tree"); + }; + if tree.root_node().has_error() { + return Parsed::unavailable( + Some(language), + "Syntax recovery prevents reliable metric extraction", + ); + } + let nodes = match inventory(tree.root_node()) { + Ok(nodes) => nodes, + Err(reason) => return Parsed::unavailable(Some(language), reason), + }; + let token_limit = config.max_tokens_per_file.min(*tokens_left); + let (token_stream, token_error) = + match tokens::leaf_tokens(tree.root_node(), source, token_limit) { + Ok(tokens) => (tokens, None), + Err(reason) => { + *tokens_left -= token_limit; + (Vec::new(), Some(reason)) + } + }; + *tokens_left -= token_stream.len(); + let functions: Vec<_> = nodes + .iter() + .copied() + .filter(|node| languages::callable(*node, language)) + .collect(); + let classes: Vec<_> = nodes + .iter() + .copied() + .filter(|node| languages::class_like(*node, language)) + .collect(); + if functions.len() + classes.len() > config.max_subjects_per_file + || functions.len() + classes.len() > *subjects_left + { + return Parsed::unavailable(Some(language), "Subject inventory budget exceeded"); + } + *subjects_left -= functions.len() + classes.len(); + let mut entries = BTreeMap::new(); + let mut names = BTreeMap::::new(); + for &node in functions.iter().chain(classes.iter()) { + *names + .entry(languages::qualified(node, source, language).0) + .or_default() += 1; + } + let mut ordinals = BTreeMap::::new(); + for &node in &functions { + let (name, stable) = languages::qualified(node, source, language); + let ordinal = ordinals.entry(name.clone()).or_default(); + *ordinal += 1; + let subject = format!("{path}#function:{name}:{}", *ordinal); + let reliable = stable && names[&name] == 1; + let body = languages::body(node, language); + let body_missing = if languages::body_is_missing(node, source, language) { + unavailable("Implementation body is outside this source; not an abstract-body zero") + } else { + not_applicable("Declaration has no executable source body") + }; + let (complexity, depth) = body + .map(|body| languages::control_flow(body, source, language)) + .unwrap_or((0, 0)); + for (metric, value) in [ + ( + Metric::MethodLength, + body.map(|body| measured(tokens::code_lines(body, source, language, true))) + .unwrap_or_else(|| body_missing.clone()), + ), + ( + Metric::ParameterCount, + languages::parameters(node, source, language), + ), + ( + Metric::NestingDepth, + body.map(|_| measured(depth)) + .unwrap_or_else(|| body_missing.clone()), + ), + ( + Metric::CyclomaticComplexity, + body.map(|_| measured(complexity)) + .unwrap_or_else(|| body_missing.clone()), + ), + ] { + entries.insert( + (metric, subject.clone()), + Entry { + value, + location: location(node), + reliable_identity: reliable, + }, + ); + } + } + for &class in &classes { + let (name, stable) = languages::qualified(class, source, language); + let ordinal = ordinals.entry(name.clone()).or_default(); + *ordinal += 1; + let subject = format!("{path}#class:{name}:{}", *ordinal); + let Some(body) = languages::body(class, language) else { + for metric in [ + Metric::ClassLength, + Metric::MethodCount, + Metric::ClassComplexity, + ] { + entries.insert( + (metric, subject.clone()), + Entry { + value: unavailable("Class body is only forward-declared in this source"), + location: location(class), + reliable_identity: stable && names[&name] == 1, + }, + ); + } + continue; + }; + let methods: Vec<_> = functions + .iter() + .copied() + .filter(|node| { + languages::method(*node, language) + && languages::owner_class(*node, language) + .is_some_and(|owner| owner.id() == class.id()) + }) + .collect(); + let unresolved = methods + .iter() + .any(|method| languages::body_is_missing(*method, source, language)); + let complexity = if unresolved { + unavailable("One or more method implementations are outside this source; aggregate is incomplete") + } else { + measured( + methods + .iter() + .filter_map(|method| languages::body(*method, language)) + .map(|body| languages::control_flow(body, source, language).0) + .sum(), + ) + }; + for (metric, value) in [ + ( + Metric::ClassLength, + measured(tokens::code_lines(body, source, language, false)), + ), + (Metric::MethodCount, measured(methods.len() as u32)), + (Metric::ClassComplexity, complexity), + ] { + entries.insert( + (metric, subject.clone()), + Entry { + value, + location: location(class), + reliable_identity: stable && names[&name] == 1, + }, + ); + } + } + for (metric, value) in [ + ( + Metric::DependencyFanOut, + languages::dependencies(&nodes, source, language), + ), + ( + Metric::PublicSurface, + languages::public_surface(&nodes, source, language), + ), + ] { + entries.insert( + (metric, path.into()), + Entry { + value, + location: location(tree.root_node()), + reliable_identity: true, + }, + ); + } + Parsed { + language: Some(language), + state: State::Ready, + entries, + tokens: token_stream, + token_error, + location: Some(location(tree.root_node())), + } +} + +fn clone_measurements( + parsed: &mut [Parsed], + masks: &[Result, String>], + paths: &[String], + config: &ExtractionConfig, + pairs_left: &mut usize, +) { + let languages: BTreeSet<_> = parsed + .iter() + .filter_map(|file| file.language.map(|language| language.name())) + .collect(); + for language in languages { + let indices: Vec<_> = parsed + .iter() + .enumerate() + .filter(|(_, file)| { + file.language.is_some_and(|item| item.name() == language) + && matches!(file.state, State::Ready) + }) + .map(|(index, _)| index) + .collect(); + let incomplete = parsed.iter().any(|file| { + file.language.is_some_and(|item| item.name() == language) + && (matches!(file.state, State::Unavailable(_)) || file.token_error.is_some()) + }); + let matches = if incomplete { + Err("Same-language comparison corpus is incomplete".into()) + } else { + let corpus: Vec<_> = indices + .iter() + .map(|index| (language, parsed[*index].tokens.as_slice())) + .collect(); + tokens::duplicated(&corpus, config.minimum_clone_tokens, pairs_left) + }; + for (position, index) in indices.into_iter().enumerate() { + let value = match (&matches, &masks[index]) { + (Ok(matches), Ok(changed)) => measured( + matches[position] + .iter() + .zip(changed) + .filter(|(duplicate, changed)| **duplicate && **changed) + .count() as u32, + ), + (Err(reason), _) | (_, Err(reason)) => unavailable(reason), + }; + parsed[index].entries.insert( + (Metric::DuplicatedTokens, paths[index].clone()), + Entry { + value, + location: parsed[index].location.clone().unwrap(), + reliable_identity: true, + }, + ); + } + } +} + +/// Extract every catalog metric. Function/class facts are per declared subject; +/// absent constructs are not applicable. Clone scope is exactly the supplied +/// same-language files, with exact tokens and an explicit minimum window size. +/// Unchanged comparison files may be supplied with identical before/after text. +pub fn extract_changes( + changes: &[FileChange], + registry: &mut ParserRegistry, + config: &ExtractionConfig, +) -> Result { + if config.minimum_clone_tokens < 4 || config.minimum_clone_tokens > config.max_tokens_per_file { + return Err("clone token minimum must be between 4 and the per-file token budget"); + } + let mut ordered: Vec<_> = changes.iter().collect(); + ordered.sort_by(|a, b| a.path.cmp(&b.path)); + if ordered.windows(2).any(|pair| pair[0].path == pair[1].path) + || ordered.iter().any(|change| change.path.is_empty()) + { + return Err("metric extraction requires unique nonempty source paths"); + } + let paths: Vec<_> = ordered.iter().map(|change| change.path.clone()).collect(); + let mut bytes_left = config.max_total_bytes; + let mut tokens_left = config.max_total_tokens; + let mut subjects_left = config.max_total_subjects; + let mut before = Vec::new(); + let mut after = Vec::new(); + for (index, change) in ordered.iter().enumerate() { + if index >= config.max_files { + before.push(Parsed::unavailable( + Language::detect(&change.path), + "File count budget exceeded", + )); + after.push(Parsed::unavailable( + Language::detect(&change.path), + "File count budget exceeded", + )); + } else { + before.push(parse( + &change.before, + &change.path, + registry, + config, + &mut bytes_left, + &mut tokens_left, + &mut subjects_left, + )); + after.push(parse( + &change.after, + &change.path, + registry, + config, + &mut bytes_left, + &mut tokens_left, + &mut subjects_left, + )); + } + } + let mut diff_left = config.max_diff_work; + let mut old_masks = Vec::new(); + let mut new_masks = Vec::new(); + for (old, new) in before.iter().zip(&after) { + let masks = if old.token_error.is_some() || new.token_error.is_some() { + Err("Changed-token comparison lacks a complete token stream".into()) + } else { + match (&old.state, &new.state) { + (State::Ready, State::Ready) => { + tokens::changed(&old.tokens, &new.tokens, &mut diff_left) + } + (State::Ready, State::Absent) + | (State::Absent, State::Ready) + | (State::Absent, State::Absent) => { + Ok((vec![true; old.tokens.len()], vec![true; new.tokens.len()])) + } + _ => Err("Changed-token baseline is unavailable".into()), + } + }; + match masks { + Ok((old, new)) => { + old_masks.push(Ok(old)); + new_masks.push(Ok(new)); + } + Err(reason) => { + old_masks.push(Err(reason.clone())); + new_masks.push(Err(reason)); + } + } + } + let mut pairs_left = config.max_clone_pairs; + clone_measurements(&mut before, &old_masks, &paths, config, &mut pairs_left); + clone_measurements(&mut after, &new_masks, &paths, config, &mut pairs_left); + let mut result = Extraction { + metrics: Vec::new(), + diagnostics: Vec::new(), + comparison_paths: paths.clone(), + }; + for (index, (old, new)) in before.iter().zip(&after).enumerate() { + for (side, file) in [("before", old), ("after", new)] { + if let State::Unavailable(reason) = &file.state { + result + .diagnostics + .push(format!("{} ({side}): {reason}", paths[index])); + } + if let Some(reason) = &file.token_error { + result + .diagnostics + .push(format!("{} ({side} tokens): {reason}", paths[index])); + } + } + for metric in Metric::ALL { + let mut subjects: BTreeSet<_> = old + .entries + .keys() + .chain(new.entries.keys()) + .filter(|(item, _)| *item == metric) + .map(|(_, subject)| subject.clone()) + .collect(); + if subjects.is_empty() { + subjects.insert(format!("{}#<{:?}>", paths[index], metric_scope(metric))); + } + for subject in subjects { + let key = (metric, subject.clone()); + let old_entry = old.entries.get(&key); + let new_entry = new.entries.get(&key); + let mut old_value = old.value(&key, new_entry.is_some()); + let mut new_value = new.value(&key, old_entry.is_some()); + let ambiguous = matches!((&old.state, &new.state), (State::Ready, State::Ready)) + && old_entry + .into_iter() + .chain(new_entry) + .any(|entry| !entry.reliable_identity); + if ambiguous { + old_value = unavailable( + "Anonymous/overloaded subject matching is ambiguous; no delta inferred", + ); + if new_entry.is_none() { + new_value = + unavailable("Anonymous/overloaded subject matching is ambiguous"); + } + } + let detail = if metric == Metric::DuplicatedTokens { + format!("Exact same-language tokens in {} supplied comparison files; minimum {} tokens; counts only changed token positions, without overlapping-position double counts", paths.len(), config.minimum_clone_tokens) + } else { + "Source-syntax convention v1; not compiler-resolved runtime behavior. Compare only matching named subjects and counting conventions".into() + }; + let observation = MetricObservation { + metric, + subject, + before: old_value, + after: new_value, + }; + result.metrics.push(ExtractedMetric { + delta: observation.delta(), + observation, + path: paths[index].clone(), + scope: metric_scope(metric), + subject_identity_ambiguous: old_entry + .into_iter() + .chain(new_entry) + .any(|entry| !entry.reliable_identity), + before_location: if ambiguous { + None + } else { + old_entry.map(|entry| entry.location.clone()) + }, + after_location: new_entry.map(|entry| entry.location.clone()), + convention: EXTRACTION_CONVENTION.into(), + detail, + }); + } + } + } + Ok(result) +} + +#[cfg(test)] +mod tests; diff --git a/atomic-audit/src/extract/tests.rs b/atomic-audit/src/extract/tests.rs new file mode 100644 index 00000000..d8152689 --- /dev/null +++ b/atomic-audit/src/extract/tests.rs @@ -0,0 +1,558 @@ +use super::*; + +fn run(changes: Vec) -> Extraction { + extract_changes( + &changes, + &mut ParserRegistry::new(), + &ExtractionConfig::default(), + ) + .unwrap() +} + +fn added(path: &str, source: &str) -> FileChange { + FileChange { + path: path.into(), + before: Source::Absent, + after: Source::Text(source.into()), + } +} + +fn value(result: &Extraction, metric: Metric, name: &str) -> Measurement { + result + .metrics + .iter() + .find(|record| { + record.observation.metric == metric && record.observation.subject.contains(name) + }) + .unwrap_or_else(|| panic!("missing {metric:?}/{name}: {:#?}", result.metrics)) + .observation + .after + .clone() +} + +#[test] +fn all_ten_metrics_have_automatic_results_across_registered_languages() { + for (path, source, classes) in [ + ("lib.rs", "use std::fs;\npub fn work(x: i32) -> i32 { if x > 0 { x } else { 0 } }", false), + ("app.ts", "import { x } from './dep';\nexport class C { run(x: number) { if (x > 0) { return x; } return 0; } }", true), + ("app.tsx", "import { x } from './dep';\nexport class C { run(x: number) { if (x > 0) { return
; } return null; } }", true), + ("app.py", "from pathlib import Path\nclass C:\n def run(self, x):\n if x > 0:\n return x\n return 0\n", true), + ("C.java", "import java.util.List;\npublic class C { public int run(int x) { if (x > 0) { return x; } return 0; } }", true), + ("app.go", "package p\nimport \"fmt\"\nfunc Work(x int) int { if x > 0 { return x }; return 0 }", false), + ("app.c", "#include \nint work(int x) { if (x > 0) { return x; } return 0; }", false), + ("app.cpp", "#include \nclass C { public: int run(int x) { if (x > 0) { return x; } return 0; } };", true), + ("app.swift", "import Foundation\npublic class C { public func run(_ x: Int) -> Int { if x > 0 { return x }; return 0 } }", true), + ] { + let result = run(vec![added(path, source)]); + assert!(result.diagnostics.is_empty(), "{path}: {:?}", result.diagnostics); + assert_eq!(result.metrics.iter().map(|record| record.observation.metric).collect::>(), Metric::ALL.into_iter().collect(), "{path}"); + for metric in [Metric::MethodLength, Metric::ParameterCount, Metric::NestingDepth, Metric::CyclomaticComplexity, Metric::DependencyFanOut, Metric::PublicSurface, Metric::DuplicatedTokens] { + assert!(result.metrics.iter().any(|record| record.observation.metric == metric && matches!(record.observation.after, Measurement::Measured { .. })), "{path}: {metric:?}: {:#?}", result.metrics); + } + assert!(result.metrics.iter().filter(|record| record.observation.metric == Metric::ParameterCount).all(|record| record.observation.after == measured(1)), "{path}"); + assert!(result.metrics.iter().filter(|record| record.observation.metric == Metric::CyclomaticComplexity).all(|record| record.observation.after == measured(2)), "{path}"); + if classes { + assert!(result.metrics.iter().filter(|record| record.observation.metric == Metric::MethodCount).all(|record| record.observation.after == measured(1)), "{path}"); + assert!(result.metrics.iter().filter(|record| record.observation.metric == Metric::ClassComplexity).all(|record| record.observation.after == measured(2)), "{path}"); + } + assert!(result.metrics.iter().filter(|record| [Metric::ClassLength, Metric::MethodCount, Metric::ClassComplexity].contains(&record.observation.metric)).all(|record| { + if classes { matches!(record.observation.after, Measurement::Measured { .. }) } else { matches!(record.observation.after, Measurement::NotApplicable { .. }) } + }), "{path}: {:#?}", result.metrics); + } +} + +#[test] +fn method_and_class_lengths_exclude_comments_and_nested_bodies() { + let source = "class Outer:\n # comment\n class Inner:\n def nested(self):\n return 1\n def run(self, x):\n # if x and bogus\n text = 'if x and bogus'\n def local(y):\n if y:\n return 1\n return 0\n if x:\n return x\n return 0\n"; + let result = run(vec![added("app.py", source)]); + assert_eq!( + value(&result, Metric::MethodCount, "class:Outer:1"), + measured(1) + ); + assert_eq!( + value(&result, Metric::MethodCount, "class:Outer::Inner:1"), + measured(1) + ); + assert_eq!( + value( + &result, + Metric::CyclomaticComplexity, + "function:Outer::run:1" + ), + measured(2) + ); + assert_eq!( + value(&result, Metric::ParameterCount, "function:Outer::run:1"), + measured(1) + ); + assert_eq!( + value(&result, Metric::NestingDepth, "function:Outer::run:1"), + measured(1) + ); + assert_eq!( + value(&result, Metric::MethodLength, "function:Outer::run:1"), + measured(5) + ); + assert_eq!( + value(&result, Metric::ClassLength, "class:Outer:1"), + measured(10) + ); + assert_eq!( + value(&result, Metric::ClassComplexity, "class:Outer:1"), + measured(2) + ); +} + +#[test] +fn parameter_conventions_cover_receivers_grouping_destructuring_and_defaults() { + let typed_self = run(vec![added( + "lib.rs", + "struct S; impl S { fn work(self: Box, x: i32) {} }", + )]); + assert_eq!( + value(&typed_self, Metric::ParameterCount, "work"), + measured(1) + ); + for (path, source, expected) in [ + ( + "app.go", + "package p\nfunc work(a, b int, rest ...string) {}", + 3, + ), + ( + "lib.rs", + "struct S; impl S { fn work(&self, x: i32, y: i32) {} }", + 2, + ), + ( + "app.ts", + "export const work = (thisValue: number, { a, b }: any, rest = 1) => rest;", + 3, + ), + ( + "app.py", + "class C:\n @staticmethod\n def work(self, x):\n pass\n", + 2, + ), + ( + "app.py", + "class C:\n @classmethod\n def work(cls, x, *, y=1):\n pass\n", + 2, + ), + ("app.c", "int work(void) { return 0; }", 0), + ] { + let result = run(vec![added(path, source)]); + assert_eq!( + value(&result, Metric::ParameterCount, "work"), + measured(expected), + "{path}: {source}" + ); + } +} + +#[test] +fn named_subjects_pair_across_line_shifts_and_changed_signatures() { + let result = run(vec![FileChange { + path: "app.ts".into(), + before: Source::Text("export function work(a: number) { return a; }".into()), + after: Source::Text( + "// shifted\nexport function work(a: number, b: number) {\n return a + b;\n}".into(), + ), + }]); + let record = result + .metrics + .iter() + .find(|record| { + record.observation.metric == Metric::ParameterCount + && record.observation.subject.contains("work") + }) + .unwrap(); + assert_eq!(record.observation.before, measured(1)); + assert_eq!(record.observation.after, measured(2)); + assert_eq!(record.before_location.as_ref().unwrap().start_line, 1); + assert_eq!(record.after_location.as_ref().unwrap().start_line, 2); +} + +#[test] +fn additions_deletions_parse_failures_and_real_zero_are_distinct() { + let mut change = added("lib.rs", "pub fn work() {}\n"); + let added_result = run(vec![change.clone()]); + assert!(added_result + .metrics + .iter() + .filter(|record| record.observation.subject.contains("work")) + .all(|record| matches!(record.observation.before, Measurement::NotApplicable { .. }))); + change.before = change.after; + change.after = Source::Absent; + let deleted = run(vec![change.clone()]); + assert!(deleted + .metrics + .iter() + .filter(|record| record.observation.subject.contains("work")) + .all(|record| matches!(record.observation.after, Measurement::NotApplicable { .. }))); + change.after = Source::Text("fn broken( {".into()); + let broken = run(vec![change]); + assert!(broken + .metrics + .iter() + .all(|record| matches!(record.observation.after, Measurement::Unavailable { .. }))); + let empty = run(vec![added("lib.rs", "")]); + assert_eq!(value(&empty, Metric::PublicSurface, "lib.rs"), measured(0)); + assert_eq!( + value(&empty, Metric::DependencyFanOut, "lib.rs"), + measured(0) + ); + assert!(run(vec![added("readme.md", "text")]) + .metrics + .iter() + .all(|record| matches!(record.observation.after, Measurement::Unavailable { .. }))); +} + +#[test] +fn exact_token_clones_count_changed_positions_once_and_ignore_formatting() { + let source = "pub fn work(x:i32)->i32 { let total=x+1; let result=total*2; return result; }"; + let changes = vec![ + FileChange { + path: "a.rs".into(), + before: Source::Text(source.into()), + after: Source::Text(format!("// comment\n{source}")), + }, + added("b.rs", &source.replace("work", "copy")), + ]; + let config = ExtractionConfig { + minimum_clone_tokens: 8, + ..Default::default() + }; + let result = extract_changes(&changes, &mut ParserRegistry::new(), &config).unwrap(); + assert_eq!( + value(&result, Metric::DuplicatedTokens, "a.rs"), + measured(0) + ); + match value(&result, Metric::DuplicatedTokens, "b.rs") { + Measurement::Measured { value } => assert!((8..50).contains(&value)), + other => panic!("{other:?}"), + } + assert_eq!(result.comparison_paths, vec!["a.rs", "b.rs"]); +} + +#[test] +fn incomplete_comparison_and_work_caps_are_not_clean_clone_results() { + let changes = vec![added("a.rs", "fn a() {}"), added("b.rs", "fn b() {}")]; + let config = ExtractionConfig { + max_files: 1, + ..Default::default() + }; + let result = extract_changes(&changes, &mut ParserRegistry::new(), &config).unwrap(); + assert!(matches!( + value(&result, Metric::DuplicatedTokens, "a.rs"), + Measurement::Unavailable { .. } + )); + let changes = vec![FileChange { + path: "a.rs".into(), + before: Source::Text("fn a() { let x=1; }".into()), + after: Source::Text("fn a() { let x=2; }".into()), + }]; + let config = ExtractionConfig { + max_diff_work: 0, + ..Default::default() + }; + let result = extract_changes(&changes, &mut ParserRegistry::new(), &config).unwrap(); + assert!(matches!( + value(&result, Metric::DuplicatedTokens, "a.rs"), + Measurement::Unavailable { .. } + )); + assert!(matches!( + value(&result, Metric::MethodLength, "a"), + Measurement::Measured { .. } + )); +} + +#[test] +fn dynamic_exports_and_header_macros_are_explicitly_unavailable() { + for (path, source, metric) in [ + ( + "app.ts", + "export * from './unknown';", + Metric::PublicSurface, + ), + ( + "app.py", + "__all__ = build_exports()\n", + Metric::PublicSurface, + ), + ( + "app.c", + "#include HEADER\nint work(void) { return 0; }", + Metric::DependencyFanOut, + ), + ( + "app.cpp", + "class C { public: void work(); };", + Metric::ClassComplexity, + ), + ] { + let result = run(vec![added(path, source)]); + assert!( + result + .metrics + .iter() + .filter(|record| record.observation.metric == metric) + .all(|record| matches!(record.observation.after, Measurement::Unavailable { .. })), + "{path}: {:#?}", + result.metrics + ); + } +} + +#[test] +fn public_surface_uses_visibility_bindings_and_static_export_lists() { + for source in [ + "__all__ = ['C']\n__all__.append('D')\n", + "__all__ = ['C']\n__all__[0] = 'D'\n", + "__all__ = [r'C']\n", + ] { + assert!(matches!( + value( + &run(vec![added("app.py", source)]), + Metric::PublicSurface, + "app.py" + ), + Measurement::Unavailable { .. } + )); + } + for (path, source, expected) in [ + ("app.py", "__all__ = ['C']\nclass C:\n def run(self): pass\nclass Hidden:\n def secret(self): pass\n", 2), + ("app.py", "from pathlib import Path\na, b = 1, 2\ndef exported(): pass\ndef _hidden(): pass\n", 4), + ("app.ts", "export class C { public f() {} private h() {} protected p() {} }", 3), + ("app.ts", "export const {a, b: renamed} = {a: 1, b: 2}; export { a }; const hidden = 1;", 2), + ("app.ts", "export class C { constructor(public x: number, private y: number, readonly z: number) {} }", 4), + ("C.java", "public class C { public void f() {} private void h() {} private class Hidden { public void g() {} } }", 2), + ("app.cpp", "class C { public: void f() {} private: void h() {} class Hidden { public: void g() {} }; };", 2), + ("app.c", "static int hidden(void) { return 1; } int shown(void) { return 2; }", 1), + ("app.go", "package p\nvar Exported, hidden int\nfunc Shown() {}\nfunc hiddenFunc() {}", 2), + ("lib.rs", "struct Hidden; impl Hidden { pub fn h() {} } pub struct V { pub x:u32, y:u32 } impl V { pub fn f(&self) {} fn h(&self) {} } pub enum E { A, B }", 6), + ("lib.rs", "pub trait T { fn work(&self); } mod hidden { pub fn work() {} }", 2), + ("lib.rs", "pub use crate::things::{A, B};", 2), + ("lib.rs", "pub const NAME: &str = env!(\"NAME\");", 1), + ("lib.rs", "pub(crate) fn internal() {} pub(self) struct Hidden; pub fn shown() {}", 1), + ] { + let result = run(vec![added(path, source)]); + assert_eq!(value(&result, Metric::PublicSurface, path), measured(expected), "{path}: {source}"); + } +} + +#[test] +fn declared_dependency_units_are_deduplicated_not_import_statement_counts() { + for (path, source, expected) in [ + ("app.py", "import os\nimport os as renamed\nfrom pathlib import Path\nfrom pathlib import PurePath\n", 2), + ("app.ts", "import {a} from './one'; import {b} from './one'; export {c} from './two';", 2), + ("app.go", "package p\nimport (\"fmt\"; f \"fmt\"; \"io\")", 2), + ("lib.rs", "use {std::fs, serde::Serialize}; use std::{io, fmt};", 2), + ("app.c", "#include \n#include \n#include \"local.h\"\n", 2), + ] { + let result = run(vec![added(path, source)]); + assert_eq!(value(&result, Metric::DependencyFanOut, path), measured(expected), "{path}: {source}"); + } +} + +#[test] +fn overload_and_anonymous_identity_never_fabricates_a_baseline_delta() { + let result = run(vec![FileChange { + path: "C.java".into(), + before: Source::Text( + "public class C { void work(int x) {} void work(String x) {} }".into(), + ), + after: Source::Text("public class C { void work(String x) {} void work(int x) {} }".into()), + }]); + assert!(result + .metrics + .iter() + .filter(|record| record.observation.subject.contains("function:C::work")) + .all(|record| record.delta.is_none() + && matches!(record.observation.before, Measurement::Unavailable { .. }))); + let changes = vec![added("same.rs", "fn a() {}"), added("same.rs", "fn b() {}")]; + assert!(extract_changes( + &changes, + &mut ParserRegistry::new(), + &ExtractionConfig::default() + ) + .is_err()); +} + +#[test] +fn declarations_default_arguments_and_function_pointer_fields_are_not_fake_bodies() { + let result = run(vec![added("app.cpp", "class C { public: void missing(int x = 0); void (*callback)(int); virtual void abstract() = 0; };" )]); + assert_eq!( + value(&result, Metric::MethodCount, "class:C:1"), + measured(2) + ); + assert!(matches!( + value(&result, Metric::ClassComplexity, "class:C:1"), + Measurement::Unavailable { .. } + )); + assert!(matches!( + value(&result, Metric::MethodLength, "missing"), + Measurement::Unavailable { .. } + )); + assert!(matches!( + value(&result, Metric::CyclomaticComplexity, "abstract"), + Measurement::NotApplicable { .. } + )); + let result = run(vec![added("app.c", "int declared(int x);")]); + assert_eq!( + value(&result, Metric::ParameterCount, "declared"), + measured(1) + ); + assert!(matches!( + value(&result, Metric::MethodLength, "declared"), + Measurement::Unavailable { .. } + )); +} + +#[test] +fn real_zero_empty_class_and_empty_function_complexity_are_separate() { + let result = run(vec![added( + "app.ts", + "export class Empty {}\nexport function work() {\n // comment\n}\n", + )]); + assert_eq!( + value(&result, Metric::MethodCount, "class:Empty:1"), + measured(0) + ); + assert_eq!( + value(&result, Metric::ClassComplexity, "class:Empty:1"), + measured(0) + ); + assert_eq!( + value(&result, Metric::CyclomaticComplexity, "work"), + measured(1) + ); + assert_eq!(value(&result, Metric::NestingDepth, "work"), measured(0)); + assert_eq!(value(&result, Metric::MethodLength, "work"), measured(2)); +} + +#[test] +fn parser_and_subject_budgets_never_silently_produce_zero() { + for config in [ + ExtractionConfig { + max_total_bytes: 1, + ..Default::default() + }, + ExtractionConfig { + max_total_subjects: 0, + ..Default::default() + }, + ] { + let result = extract_changes( + &[added("lib.rs", "fn work() {}")], + &mut ParserRegistry::new(), + &config, + ) + .unwrap(); + assert!(result + .metrics + .iter() + .all(|record| matches!(record.observation.after, Measurement::Unavailable { .. }))); + assert!(!result.diagnostics.is_empty()); + } + let result = extract_changes( + &[added("lib.rs", "fn work() {}")], + &mut ParserRegistry::new(), + &ExtractionConfig { + max_total_tokens: 1, + ..Default::default() + }, + ) + .unwrap(); + assert!(matches!( + value(&result, Metric::DuplicatedTokens, "lib.rs"), + Measurement::Unavailable { .. } + )); + assert_eq!( + value(&result, Metric::MethodLength, "work"), + measured(1), + "a clone-index cap must not erase local AST measurements" + ); +} + +#[test] +fn changed_token_scopes_do_not_match_different_languages_or_ignore_real_literals() { + let config = ExtractionConfig { + minimum_clone_tokens: 8, + ..Default::default() + }; + let changes = vec![ + added("a.ts", "function work(x) { let y = x + 1; return y * 2; }"), + added("b.cpp", "int work(int x) { int y = x + 1; return y * 2; }"), + ]; + let result = extract_changes(&changes, &mut ParserRegistry::new(), &config).unwrap(); + assert_eq!( + value(&result, Metric::DuplicatedTokens, "a.ts"), + measured(0) + ); + assert_eq!( + value(&result, Metric::DuplicatedTokens, "b.cpp"), + measured(0) + ); + let changes = vec![ + added( + "a.rs", + "fn work() { let text = \"if a b c d e f g h i j k l m n\"; }", + ), + added( + "b.rs", + "fn other() { let text = \"different a b c d e f g h i j k l m n\"; }", + ), + ]; + let result = extract_changes( + &changes, + &mut ParserRegistry::new(), + &ExtractionConfig { + minimum_clone_tokens: 16, + ..config + }, + ) + .unwrap(); + assert_eq!( + value(&result, Metric::DuplicatedTokens, "a.rs"), + measured(0) + ); +} + +#[test] +fn branch_and_nesting_conventions_cover_chains_switches_matches_and_expressions() { + for (path, source, complexity, depth) in [ + ("app.ts", "function work(a: boolean, b: boolean) { if (a && b) { return 1; } else if (a || b) { return 2; } return 0; }", 5, 1), + ("app.ts", "function work(a: boolean, b: boolean) { return a ? (b ? 1 : 2) : 3; }", 3, 2), + ("app.c", "int work(int x) { switch(x) { case 0: return 0; case 1: return 1; default: return 2; } }", 3, 1), + ("app.go", "package p\nfunc work(x int) int { switch x { case 0: return 0; default: return 1 } }", 2, 1), + ("lib.rs", "fn work(x: i32) -> i32 { match x { 0 => 0, _ => 1 } }", 2, 1), + ("app.py", "def work(x):\n match x:\n case 0:\n return 0\n case _:\n return 1\n", 2, 1), + ("app.swift", "func work(_ x: Int) -> Int { if x > 1 { return 1 } else if x > 0 { return 2 } else { return 0 } }", 3, 1), + ] { + let result = run(vec![added(path, source)]); + assert_eq!(value(&result, Metric::CyclomaticComplexity, "work"), measured(complexity), "{path}: {source}"); + assert_eq!(value(&result, Metric::NestingDepth, "work"), measured(depth), "{path}: {source}; {}", ParserRegistry::new().parse_tree(path, source).unwrap().root_node().to_sexp()); + } +} + +#[test] +fn real_extractor_source_runs_without_repository_materialization() { + let source = include_str!("languages.rs"); + let start = std::time::Instant::now(); + let result = run(vec![FileChange { + path: "collector.rs".into(), + before: Source::Text(source.into()), + after: Source::Text(source.into()), + }]); + assert!(result + .metrics + .iter() + .any(|record| record.observation.metric == Metric::MethodLength + && matches!(record.observation.after, Measurement::Measured { value } if value > 0))); + eprintln!( + "metric extraction over real source: {} observations in {:?}", + result.metrics.len(), + start.elapsed() + ); +} diff --git a/atomic-audit/src/extract/tokens.rs b/atomic-audit/src/extract/tokens.rs new file mode 100644 index 00000000..38d26241 --- /dev/null +++ b/atomic-audit/src/extract/tokens.rs @@ -0,0 +1,174 @@ +use std::collections::{hash_map::DefaultHasher, BTreeSet, HashMap}; +use std::hash::{Hash, Hasher}; + +use atomic_semantic::SyntaxNode; + +use super::languages; + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub(crate) struct Token { + pub kind: String, + pub text: String, +} + +pub(crate) fn comment(node: SyntaxNode<'_>) -> bool { + node.kind().contains("comment") +} + +pub(crate) fn children(node: SyntaxNode<'_>) -> Vec> { + let mut cursor = node.walk(); + node.children(&mut cursor).collect() +} + +pub(crate) fn named(node: SyntaxNode<'_>) -> Vec> { + let mut cursor = node.walk(); + node.named_children(&mut cursor).collect() +} + +pub(crate) fn text<'a>(node: SyntaxNode<'_>, source: &'a str) -> &'a str { + &source[node.byte_range()] +} + +pub(crate) fn leaf_tokens( + root: SyntaxNode<'_>, + source: &str, + max: usize, +) -> Result, String> { + let mut result = Vec::new(); + let mut stack = vec![root]; + let mut visited = 0; + while let Some(node) = stack.pop() { + visited += 1; + if visited > 300_000 { + return Err("AST node budget exceeded".into()); + } + if comment(node) { + continue; + } + // Keep literals atomic. Quotes/fragments must not turn unrelated string + // contents into apparent code clones or conditional operators. + if node.child_count() == 0 || languages::literal(node) { + let value = text(node, source); + if !value.trim().is_empty() { + result.push(Token { + kind: node.kind().into(), + text: value.into(), + }); + if result.len() > max { + return Err("Token budget exceeded".into()); + } + } + } else { + stack.extend(children(node).into_iter().rev()); + } + } + Ok(result) +} + +/// Count physical code-bearing lines from AST tokens, not text/comment regexes. +pub(crate) fn code_lines( + root: SyntaxNode<'_>, + source: &str, + language: atomic_semantic::Language, + skip_functions: bool, +) -> u32 { + let mut lines = BTreeSet::new(); + let mut stack = vec![(root, true)]; + while let Some((node, first)) = stack.pop() { + if comment(node) { + continue; + } + if !first + && (languages::type_boundary(node, language) + || (skip_functions && languages::callable(node, language))) + { + let body = languages::body(node, language).map(|body| body.id()); + stack.extend( + children(node) + .into_iter() + .rev() + .filter(|child| Some(child.id()) != body) + .map(|child| (child, false)), + ); + continue; + } + if node.child_count() == 0 || languages::literal(node) { + for (offset, part) in text(node, source).split('\n').enumerate() { + if !part.trim().is_empty() { + lines.insert(node.start_position().row + offset); + } + } + } else { + stack.extend(children(node).into_iter().rev().map(|child| (child, false))); + } + } + lines.len() as u32 +} + +pub(super) fn changed( + old: &[Token], + new: &[Token], + work: &mut usize, +) -> Result<(Vec, Vec), String> { + if old == new { + return Ok((vec![false; old.len()], vec![false; new.len()])); + } + let cost = old.len().saturating_mul(new.len()); + if cost > *work { + return Err("Changed-token diff work budget exceeded".into()); + } + *work -= cost; + let mut before = vec![false; old.len()]; + let mut after = vec![false; new.len()]; + for op in similar::capture_diff_slices(similar::Algorithm::Myers, old, new) { + if op.tag() != similar::DiffTag::Equal { + for index in op.old_range() { + before[index] = true; + } + for index in op.new_range() { + after[index] = true; + } + } + } + Ok((before, after)) +} + +/// Exact same-language token windows. Verify equality after hashing; collisions +/// never become clone evidence. Overlaps are unioned and never counted twice. +pub(super) fn duplicated( + files: &[(&str, &[Token])], + minimum: usize, + pairs: &mut usize, +) -> Result>, String> { + let mut positions: HashMap> = HashMap::new(); + let mut matches: Vec> = files + .iter() + .map(|(_, tokens)| vec![false; tokens.len()]) + .collect(); + for (file, (language, tokens)) in files.iter().enumerate() { + for start in 0..tokens.len().saturating_add(1).saturating_sub(minimum) { + let window = &tokens[start..start + minimum]; + let mut hash = DefaultHasher::new(); + language.hash(&mut hash); + window.hash(&mut hash); + let previous = positions.entry(hash.finish()).or_default(); + for &(other_file, other_start) in previous.iter() { + if *pairs == 0 { + return Err("Clone comparison work budget exceeded".into()); + } + *pairs -= 1; + if other_file == file && start.abs_diff(other_start) < minimum { + continue; + } + if files[other_file].0 == *language + && files[other_file].1[other_start..other_start + minimum] == *window + { + matches[file][start..start + minimum].fill(true); + matches[other_file][other_start..other_start + minimum].fill(true); + } + } + previous.push((file, start)); + } + } + Ok(matches) +} diff --git a/atomic-audit/src/impact/analysis.rs b/atomic-audit/src/impact/analysis.rs new file mode 100644 index 00000000..2fede08f --- /dev/null +++ b/atomic-audit/src/impact/analysis.rs @@ -0,0 +1,305 @@ +//! Review policy over shared semantic facts; no AST traversal or source search. + +use std::collections::BTreeSet; + +use atomic_semantic::{ + relationships::{BoundCall, SourceGraph}, + source::{SourceSet, SourceSpan}, + ParserRegistry, +}; + +use super::{ + ChangedFunction, ContractAssessment, ContractIssue, DirectCall, ImpactReport, SourceLocation, +}; + +impl From<&SourceSpan> for SourceLocation { + fn from(span: &SourceSpan) -> Self { + Self { + path: span.path.clone(), + start_line: span.start_line, + end_line: span.end_line, + } + } +} + +fn direct(call: &BoundCall<'_>) -> DirectCall { + DirectCall { + caller: call.call.caller.clone(), + callee: call.symbol.id.clone(), + location: (&call.call.location).into(), + declaration: (&call.symbol.location).into(), + binding: call.reason.clone(), + arguments: call.call.arguments, + target_present: call.present, + visibility_compatible: call.accessible, + configuration_dependent: call.configuration_dependent, + } +} + +fn compatible(call: &BoundCall<'_>) -> Option { + let arguments = call.call.arguments?; + call.symbol.arity_known.then_some( + call.present + && call.accessible + && arguments >= call.expected_min + && call.expected_max.is_none_or(|max| arguments <= max), + ) +} + +pub fn analyze( + before: &[(String, String)], + after: &[(String, String)], + paths: &[String], + registry: &mut ParserRegistry, +) -> ImpactReport { + analyze_semantic( + registry.analyze_sources(before), + registry.analyze_sources(after), + paths, + ) +} + +pub fn analyze_with_coverage( + before: &[(String, String)], + after: &[(String, String)], + paths: &[String], + complete: bool, + registry: &mut ParserRegistry, +) -> ImpactReport { + let mut before = registry.analyze_sources(before); + let mut after = registry.analyze_sources(after); + before.complete &= complete; + after.complete &= complete; + before.paths_complete &= complete; + after.paths_complete &= complete; + analyze_semantic(before, after, paths) +} + +/// Apply compatibility policy to already-parsed shared semantic source sets. +pub fn analyze_semantic(before: SourceSet, after: SourceSet, paths: &[String]) -> ImpactReport { + let complete = before.complete && after.complete; + let mut report = ImpactReport { + source_selection_complete: Some(complete), + inspected_files_before: before.files.len(), + inspected_files_after: after.files.len(), + searched_files_before: before.searched_files, + searched_files_after: after.searched_files, + ..Default::default() + }; + report + .gaps + .extend(before.gaps.iter().map(|gap| format!("before: {gap}"))); + report + .gaps + .extend(after.gaps.iter().map(|gap| format!("after: {gap}"))); + let inventory_complete = before.paths_complete && after.paths_complete; + let old = SourceGraph::new(before.files, before.paths, inventory_complete); + let new = SourceGraph::new(after.files, after.paths, inventory_complete); + let paths: BTreeSet<_> = paths + .iter() + .filter(|path| atomic_semantic::is_supported(path)) + .map(String::as_str) + .collect(); + let mut roots = BTreeSet::new(); + for id in old + .symbols + .keys() + .chain(new.symbols.keys()) + .collect::>() + { + let before = old.symbols.get(id); + let after = new.symbols.get(id); + let symbol = after.or(before).unwrap(); + if !matches!( + symbol.entity.kind, + atomic_semantic::EntityKind::Function | atomic_semantic::EntityKind::Method + ) { + continue; + } + if after.is_none() + && new.paths.contains(&symbol.location.path) + && !new.files.contains_key(&symbol.location.path) + { + if paths.contains(symbol.location.path.as_str()) { + report.gaps.push(format!( + "{id}: after-source unavailable; deletion is not inferred" + )); + } + continue; + } + if old.ambiguous.contains(id) || new.ambiguous.contains(id) { + if paths.contains(symbol.location.path.as_str()) { + report.gaps.push(format!("{id}: ambiguous conditional/overloaded declaration; no root delta or caller verdict inferred")); + } + continue; + } + if !paths.contains(symbol.location.path.as_str()) + || before.zip(after).is_some_and(|(a, b)| { + a.tokens == b.tokens + && a.public == b.public + && a.parent_visible == b.parent_visible + && a.restricted == b.restricted + && a.conditional == b.conditional + }) + { + continue; + } + roots.insert(id.clone()); + report.changed_functions.push(ChangedFunction { + id: id.clone(), + before: before.map(|symbol| (&symbol.location).into()), + after: after.map(|symbol| (&symbol.location).into()), + change: match (before, after) { + (None, _) + if old.paths.contains(&symbol.location.path) + && !old.files.contains_key(&symbol.location.path) => + { + "baseline_unavailable" + } + (None, _) => "added", + (_, None) => "removed", + _ => "modified", + } + .into(), + signature_changed: before.zip(after).is_some_and(|(a, b)| { + a.signature != b.signature + || a.public != b.public + || a.parent_visible != b.parent_visible + || a.restricted != b.restricted + || a.conditional != b.conditional + }), + }); + if before + .zip(after) + .is_some_and(|(a, b)| a.conditional != b.conditional) + { + report.gaps.push(format!("{}: conditional configuration changed; active configuration is not established by source syntax", symbol.id)); + } + } + for path in &paths { + if old + .files + .get(*path) + .zip(new.files.get(*path)) + .is_some_and(|(a, b)| a.tokens == b.tokens) + { + continue; + } + report.code_changed = true; + let before = old + .files + .get(*path) + .map(|file| file.outside_tokens.as_slice()) + .unwrap_or(&[]); + let after = new + .files + .get(*path) + .map(|file| file.outside_tokens.as_slice()) + .unwrap_or(&[]); + if before != after { + report.non_callable_changes.push((*path).into()); + report.gaps.push(format!("{path}: changed imports/types/globals require implementation review beyond call contracts")); + } + } + let before_calls = old.bind_calls(None); + let after_calls = new.bind_calls(Some(&old)); + report.callers_before = before_calls + .iter() + .filter(|call| roots.contains(&call.symbol.id)) + .map(direct) + .collect(); + report.callers_after = after_calls + .iter() + .filter(|call| roots.contains(&call.symbol.id)) + .map(direct) + .collect(); + report.callees_after = after_calls + .iter() + .filter(|call| roots.contains(&call.call.caller)) + .map(direct) + .collect(); + let names: BTreeSet<_> = roots + .iter() + .filter_map(|id| new.symbols.get(id).or_else(|| old.symbols.get(id))) + .map(|symbol| symbol.entity.name.as_str()) + .collect(); + let bound_sites: BTreeSet<_> = after_calls + .iter() + .map(|call| (&call.call.location, &call.call.caller)) + .collect(); + let unresolved = new + .files + .values() + .flat_map(|file| &file.calls) + .filter(|call| { + (roots.contains(&call.caller) + || call + .target + .last() + .is_some_and(|name| names.contains(name.as_str()))) + && !bound_sites.contains(&(&call.location, &call.caller)) + }) + .count(); + report.unresolved_references = Some(unresolved); + if unresolved > 0 { + report.gaps.push(format!("{unresolved} relevant source reference(s) need additional receiver/import context; excluded from bound-caller counts")); + } + let mut unchecked = 0; + for call in &after_calls { + if !roots.contains(&call.symbol.id) && !roots.contains(&call.call.caller) { + continue; + } + let Some(valid) = compatible(call) else { + unchecked += 1; + continue; + }; + report.checked_call_contracts += 1; + if valid { + report.compatible_call_contracts += 1; + continue; + } + let prior: Vec<_> = before_calls + .iter() + .filter(|before| { + before.call.caller == call.call.caller + && before.symbol.id == call.symbol.id + && before.call.tokens == call.call.tokens + }) + .collect(); + if prior.iter().any(|call| compatible(call) == Some(false)) { + report.preexisting_incompatible_contracts += 1; + continue; + } + let before_symbol = old.symbols.get(&call.symbol.id); + let after_symbol = new.symbols.get(&call.symbol.id); + let introduced = prior.iter().any(|call| compatible(call) == Some(true)) + || (complete && roots.contains(&call.call.caller) && prior.is_empty()); + let (primary_location, primary_before) = if roots.contains(&call.call.caller) { + ((&call.call.location).into(), false) + } else if let Some(after) = after_symbol { + ((&after.location).into(), false) + } else { + ((&call.symbol.location).into(), true) + }; + report.issues.push(ContractIssue { function: call.symbol.id.clone(), call: direct(call), before_declaration: before_symbol.map(|symbol| (&symbol.location).into()), after_declaration: after_symbol.map(|symbol| (&symbol.location).into()), primary_location, primary_before, introduced, + summary: if !call.present { "A previously bound call still references a removed declaration" } else if !call.accessible { "A direct reference violates the declaration's visibility/export contract" } else { "A bound call does not match the declaration's argument-count contract" }.into(), + evidence: format!("AST target {} from {}; {} argument(s), expected {}..{:?}; target present={}, accessible={}; {}", call.symbol.id, call.call.caller, call.call.arguments.unwrap(), call.expected_min, call.expected_max, call.present, call.accessible, call.reason) }); + } + if unchecked > 0 { + report.gaps.push(format!("{unchecked} affected bound call(s) have unavailable argument-count conventions; no contract verdict inferred")); + } + if report.preexisting_incompatible_contracts > 0 { + report.gaps.push(format!("{} incompatible call(s) already existed before the change; not attributed as new regressions", report.preexisting_incompatible_contracts)); + } + report.contract_assessment = + if !report.issues.is_empty() || report.preexisting_incompatible_contracts > 0 { + ContractAssessment::IncompatibleResolvedCalls + } else if report.checked_call_contracts > 0 { + ContractAssessment::CompatibleResolvedCalls + } else { + ContractAssessment::NotEvaluated + }; + report.gaps.sort(); + report.gaps.dedup(); + report +} diff --git a/atomic-audit/src/impact/mod.rs b/atomic-audit/src/impact/mod.rs new file mode 100644 index 00000000..4f4116e0 --- /dev/null +++ b/atomic-audit/src/impact/mod.rs @@ -0,0 +1,94 @@ +//! Recorded-source direct-call binding and compatibility evidence. +//! No filesystem access, builds, compiler invocation or runtime execution. + +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct SourceLocation { + pub path: String, + pub start_line: u32, + pub end_line: u32, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct DirectCall { + pub caller: String, + pub callee: String, + pub location: SourceLocation, + pub declaration: SourceLocation, + pub binding: String, + pub arguments: Option, + pub target_present: bool, + pub visibility_compatible: bool, + #[serde(default)] + pub configuration_dependent: bool, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct ChangedFunction { + pub id: String, + pub before: Option, + pub after: Option, + pub change: String, + pub signature_changed: bool, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct ContractIssue { + pub function: String, + pub call: DirectCall, + pub before_declaration: Option, + pub after_declaration: Option, + pub primary_location: SourceLocation, + pub primary_before: bool, + pub introduced: bool, + pub summary: String, + pub evidence: String, +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub struct ImpactReport { + pub change: String, + pub changed_functions: Vec, + pub callers_before: Vec, + pub callers_after: Vec, + pub callees_after: Vec, + pub issues: Vec, + pub gaps: Vec, + pub inspected_files_before: usize, + pub inspected_files_after: usize, + #[serde(default)] + pub searched_files_before: usize, + #[serde(default)] + pub searched_files_after: usize, + pub checked_call_contracts: usize, + pub compatible_call_contracts: usize, + pub preexisting_incompatible_contracts: usize, + pub code_changed: bool, + pub contract_assessment: ContractAssessment, + #[serde(default)] + pub source_selection_complete: Option, + #[serde(default)] + pub unresolved_references: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub non_callable_changes: Vec, +} + +/// Applies only to resolved direct-call availability/access/argument-count checks, +/// not type compatibility or overall implementation correctness. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ContractAssessment { + #[default] + NotEvaluated, + CompatibleResolvedCalls, + IncompatibleResolvedCalls, +} + +#[cfg(feature = "structural")] +mod analysis; +#[cfg(feature = "structural")] +pub use analysis::{analyze, analyze_semantic, analyze_with_coverage}; + +#[cfg(all(test, feature = "structural"))] +mod tests; diff --git a/atomic-audit/src/impact/tests.rs b/atomic-audit/src/impact/tests.rs new file mode 100644 index 00000000..5ccb09cf --- /dev/null +++ b/atomic-audit/src/impact/tests.rs @@ -0,0 +1,463 @@ +use super::*; +use atomic_semantic::ParserRegistry; + +fn sources(files: &[(&str, &str)]) -> Vec<(String, String)> { + files + .iter() + .map(|(path, source)| ((*path).into(), (*source).into())) + .collect() +} + +fn compare(before: &[(&str, &str)], after: &[(&str, &str)], paths: &[&str]) -> ImpactReport { + analyze( + &sources(before), + &sources(after), + &paths.iter().map(|path| (*path).into()).collect::>(), + &mut ParserRegistry::new(), + ) +} + +#[test] +fn rust_direct_calls_measure_real_contract_regression_not_shared_names() { + let report = compare( + &[ + ( + "src/lib.rs", + "fn work(x: i32) {} fn consumer() { work(1); }", + ), + ("other.rs", "fn work() {} fn unrelated() { work(); }"), + ], + &[ + ( + "src/lib.rs", + "fn work(x: i32, y: i32) {} fn consumer() { work(1); }", + ), + ("other.rs", "fn work() {} fn unrelated() { work(); }"), + ], + &["src/lib.rs"], + ); + assert_eq!(report.changed_functions.len(), 1); + assert_eq!(report.callers_after.len(), 1); + assert!(report.callers_after[0].caller.ends_with("#consumer")); + assert_eq!(report.issues.len(), 1); + assert_eq!(report.checked_call_contracts, 1); + assert_eq!(report.issues[0].call.arguments, Some(1)); +} + +#[test] +fn rust_declared_modules_aliases_and_visibility_resolve_without_global_names() { + let before = [ + ("src/lib.rs", "mod api; mod user;"), + ("src/api.rs", "pub fn work(x: i32) {} fn private() {}"), + ( + "src/user.rs", + "use crate::api::work as invoke; fn consumer() { invoke(1); crate::api::private(); }", + ), + ]; + let after = [ + ("src/lib.rs", "mod api; mod user;"), + ( + "src/api.rs", + "pub fn work(x: i32, y: i32) {} fn private() {}", + ), + ( + "src/user.rs", + "use crate::api::work as invoke; fn consumer() { invoke(1); crate::api::private(); }", + ), + ]; + let report = compare(&before, &after, &["src/api.rs"]); + assert_eq!( + report.callers_after.len(), + 1, + "private sibling functions are not accessible callers" + ); + assert_eq!(report.issues.len(), 1); + assert!(report.callers_after[0] + .binding + .contains("Rust import/module")); +} + +#[test] +fn rust_inline_modules_nested_imports_and_private_module_boundaries() { + let old = "mod api { pub fn work(x:i32) {} mod hidden { pub fn secret() {} } } mod user { use crate::api::{work as invoke}; fn consumer() { invoke(1); crate::api::hidden::secret(); } }"; + let new = old.replace("work(x:i32)", "work(x:i32, y:i32)"); + let report = compare( + &[("src/lib.rs", old)], + &[("src/lib.rs", &new)], + &["src/lib.rs"], + ); + assert_eq!(report.callers_after.len(), 1); + assert_eq!(report.issues.len(), 1); +} + +#[test] +fn rust_parent_visibility_and_explicit_module_aliases_bind_to_the_declared_parent() { + let old = "mod parent { mod api { pub(super) fn work(x:i32) {} } use self::api as implementation; fn consumer() { implementation::work(1); } } mod unrelated { fn work() {} }"; + let new = old.replace("work(x:i32)", "work(x:i32,y:i32)"); + let report = compare( + &[("src/lib.rs", old)], + &[("src/lib.rs", &new)], + &["src/lib.rs"], + ); + assert_eq!(report.callers_after.len(), 1); + assert_eq!(report.issues.len(), 1); +} + +#[test] +fn typescript_explicit_relative_alias_and_namespace_calls_bind_exported_functions() { + for import in [ + "import { work as invoke } from './api'; function consumer() { invoke(1); }", + "import * as api from './api'; function consumer() { api.work(1); }", + ] { + let report = compare( + &[ + ("src/api.ts", "export function work(x: number) {}"), + ("src/user.ts", import), + ], + &[ + ( + "src/api.ts", + "export function work(x: number, y: number) {}", + ), + ("src/user.ts", import), + ], + &["src/api.ts"], + ); + assert_eq!(report.callers_after.len(), 1); + assert_eq!(report.issues.len(), 1); + } +} + +#[test] +fn removed_declarations_keep_before_callers_and_detect_surviving_broken_calls() { + let report = compare( + &[ + ("api.ts", "export function work() {}"), + ( + "user.ts", + "import {work} from './api'; function consumer() { work(); }", + ), + ], + &[( + "user.ts", + "import {work} from './api'; function consumer() { work(); }", + )], + &["api.ts"], + ); + assert_eq!(report.changed_functions[0].change, "removed"); + assert_eq!(report.callers_before.len(), 1); + assert_eq!(report.issues.len(), 1); + assert!(report.issues[0].after_declaration.is_none()); +} + +#[test] +fn shadowed_dynamic_and_overloaded_calls_are_not_guessed() { + for source in [ + "fn work(x:i32) {} fn consumer(work: fn(i32)) { work(1); }", + "fn work(x:i32) {} fn consumer() { let work = other; work(1); }", + "fn work(x:i32) {} fn consumer() { object.work(1); }", + ] { + let new = source.replace("work(x:i32)", "work(x:i32,y:i32)"); + let report = compare( + &[("src/lib.rs", source)], + &[("src/lib.rs", &new)], + &["src/lib.rs"], + ); + assert!(report.callers_after.is_empty(), "{source}"); + assert!(report.issues.is_empty(), "{source}"); + assert!(!report.gaps.is_empty(), "{source}"); + } + let old = "function work(x: number): void; function work(x: number) {} function consumer() { work(1); }"; + let new = old.replace( + "function work(x: number) {}", + "function work(x: number, y: number) {}", + ); + let report = compare(&[("api.ts", old)], &[("api.ts", &new)], &["api.ts"]); + assert!(report.issues.is_empty()); +} + +#[test] +fn comments_unchanged_functions_and_repaired_consumers_do_not_inflate_risk() { + let old = "fn work(x:i32) {} fn untouched() {} fn consumer() { work(1); }"; + let comment = format!("// comment\n{old}"); + let report = compare(&[("lib.rs", old)], &[("lib.rs", &comment)], &["lib.rs"]); + assert!(report.changed_functions.is_empty() && report.issues.is_empty()); + let new = "fn work(x:i32,y:i32) {} fn untouched() {} fn consumer() { work(1,2); }"; + let report = compare(&[("lib.rs", old)], &[("lib.rs", new)], &["lib.rs"]); + assert_eq!(report.changed_functions.len(), 2); + assert!(report.issues.is_empty()); + assert_eq!(report.callees_after.len(), 1); +} + +#[test] +fn optional_default_and_rest_parameters_do_not_create_fake_arity_breaks() { + for parameters in [ + "x: number, y?: number", + "x: number, y = 2", + "x: number, ...rest: number[]", + ] { + let new = format!("function work({parameters}) {{}} function consumer() {{ work(1); }}"); + let report = compare( + &[( + "api.ts", + "function work(x:number) {} function consumer() { work(1); }", + )], + &[("api.ts", &new)], + &["api.ts"], + ); + assert!(report.issues.is_empty(), "{parameters}"); + assert_eq!(report.compatible_call_contracts, 1, "{parameters}"); + } +} + +#[test] +fn missing_syntax_or_replaced_binding_is_not_a_proven_deletion() { + for after in [ + "fn work( {", + "#[cfg(feature=\"x\")] fn work() {} fn consumer() { work(); }", + "const work: fn() = other; fn consumer() { work(); }", + ] { + let report = compare( + &[("lib.rs", "fn work() {} fn consumer() { work(); }")], + &[("lib.rs", after)], + &["lib.rs"], + ); + assert!(report.issues.is_empty(), "{after}"); + assert!(!report.gaps.is_empty()); + } +} + +#[test] +fn changed_and_added_callers_are_checked_against_unchanged_or_new_contracts() { + let report = compare( + &[("lib.rs", "fn work(x:i32) {} fn caller() { work(1); }")], + &[("lib.rs", "fn work(x:i32) {} fn caller() { work(); }")], + &["lib.rs"], + ); + assert_eq!(report.issues.len(), 1); + assert!(report.issues[0].introduced); + assert!(!report.issues[0].primary_before); + assert_eq!( + report.contract_assessment, + ContractAssessment::IncompatibleResolvedCalls + ); + let report = compare( + &[], + &[("lib.rs", "fn work(x:i32) {} fn caller() { work(); }")], + &["lib.rs"], + ); + assert_eq!(report.issues.len(), 1); + assert!(report.issues[0].before_declaration.is_none()); + assert!(report.issues[0].introduced); +} + +#[test] +fn preexisting_incompatibility_is_not_attributed_to_an_unrelated_body_edit() { + let report = compare( + &[("lib.rs", "fn work(x:i32) {} fn caller() { work(); }")], + &[( + "lib.rs", + "fn work(x:i32) {} fn caller() { work(); let x = 1; }", + )], + &["lib.rs"], + ); + assert!(report.issues.is_empty()); + assert!(report + .gaps + .iter() + .any(|gap| gap.contains("already existed"))); + assert_eq!(report.preexisting_incompatible_contracts, 1); + assert_eq!( + report.contract_assessment, + ContractAssessment::IncompatibleResolvedCalls + ); +} + +#[test] +fn truncated_snapshots_withhold_cross_file_bindings_instead_of_inventing_uniqueness() { + let before = sources(&[ + ("api.ts", "export function work(x:number) {}"), + ( + "caller.ts", + "import {work} from './api'; function caller() { work(1); }", + ), + ]); + let after = sources(&[ + ("api.ts", "export function work(x:number,y:number) {}"), + ( + "caller.ts", + "import {work} from './api'; function caller() { work(1); }", + ), + ]); + let report = analyze_with_coverage( + &before, + &after, + &["api.ts".into()], + false, + &mut ParserRegistry::new(), + ); + assert!(report.callers_after.is_empty() && report.issues.is_empty()); + assert!(!report.gaps.is_empty()); +} + +#[test] +fn unresolved_module_alternatives_and_type_only_imports_are_not_real_callers() { + let old = [ + ("api.ts", "export function work(x:number) {}"), + ("api.tsx", "broken {{{"), + ( + "caller.ts", + "import {work} from './api'; function caller() { work(1); }", + ), + ]; + let new = [ + ("api.ts", "export function work(x:number,y:number) {}"), + ("api.tsx", "broken {{{"), + ( + "caller.ts", + "import {work} from './api'; function caller() { work(1); }", + ), + ]; + assert!(compare(&old, &new, &["api.ts"]).issues.is_empty()); + let report = compare( + &[ + ("api.ts", "export function work(x:number) {}"), + ( + "caller.ts", + "import type {work} from './api'; function caller() { work(1); }", + ), + ], + &[ + ("api.ts", "export function work(x:number,y:number) {}"), + ( + "caller.ts", + "import type {work} from './api'; function caller() { work(1); }", + ), + ], + &["api.ts"], + ); + assert!(report.callers_after.is_empty()); +} + +#[test] +fn mixed_global_and_function_edits_leave_an_explicit_implementation_gap() { + let report = compare( + &[( + "lib.rs", + "const VALUE:i32=1; fn work() -> i32 { VALUE } fn other() {}", + )], + &[( + "lib.rs", + "const VALUE:i32=2; fn work() -> i32 { VALUE } fn other() { let x = 1; }", + )], + &["lib.rs"], + ); + assert_eq!(report.changed_functions.len(), 1); + assert!(report + .gaps + .iter() + .any(|gap| gap.contains("imports/types/globals"))); +} + +#[test] +fn impact_budgets_and_duplicate_paths_are_explicit_not_clean_results() { + let large = " ".repeat(atomic_semantic::MAX_SOURCE_BYTES + 1); + let report = compare(&[], &[("lib.rs", &large)], &["lib.rs"]); + assert!(report.issues.is_empty() && report.changed_functions.is_empty()); + assert!(report.gaps.iter().any(|gap| gap.contains("byte limit"))); + let duplicate = sources(&[("lib.rs", "fn work() {}"), ("lib.rs", "fn work(x:i32) {}")]); + let report = analyze( + &[], + &duplicate, + &["lib.rs".into()], + &mut ParserRegistry::new(), + ); + assert!(report.issues.is_empty()); + assert!(report + .gaps + .iter() + .any(|gap| gap.contains("Duplicate semantic source paths"))); +} + +#[test] +fn shared_semantic_facts_keep_normal_macros_and_cfg_declarations() { + for source in [ + "fn work(x:i32) {} fn consumer() { println!(\"hello\"); work(1); }", + "#[cfg(feature=\"optional\")] fn work(x:i32) {} fn consumer() { work(1); }", + "#![cfg(feature=\"optional\")] fn work(x:i32) {} fn consumer() { work(1); }", + ] { + let new = source.replace("work(x:i32)", "work(x:i32,y:i32)"); + let report = compare( + &[("src/lib.rs", source)], + &[("src/lib.rs", &new)], + &["src/lib.rs"], + ); + assert_eq!(report.callers_after.len(), 1, "{source}"); + assert!(report.callers_after[0].configuration_dependent, "{source}"); + assert_eq!(report.issues.len(), 1); + } + let source = "fn work(#[cfg(feature=\"optional\")] x:i32) {} fn consumer() { work(1); }"; + let report = compare(&[], &[("src/lib.rs", source)], &["src/lib.rs"]); + assert_eq!(report.callers_after.len(), 1); + assert_eq!(report.checked_call_contracts, 0); + assert!(report.issues.is_empty()); +} + +#[test] +fn accessor_return_values_do_not_inherit_the_accessors_argument_count() { + let before = "class Reader { get value() { return (x:number) => x; } } function consumer(reader:Reader) { return reader.value(1); }"; + let after = "class Reader { get value() { return (x:number,y:number) => x+y; } } function consumer(reader:Reader) { return reader.value(1); }"; + let report = compare(&[("app.ts", before)], &[("app.ts", after)], &["app.ts"]); + assert!( + report.issues.is_empty(), + "getter arity is not the returned function's contract" + ); + assert!(report + .gaps + .iter() + .any(|gap| gap.contains("unavailable argument-count conventions"))); +} + +#[test] +fn lost_exports_and_private_visibility_are_concrete_contract_regressions() { + let report = compare( + &[ + ("api.ts", "export function work() {}"), + ( + "caller.ts", + "import {work} from './api'; function consumer() { work(); }", + ), + ], + &[ + ("api.ts", "function work() {}"), + ( + "caller.ts", + "import {work} from './api'; function consumer() { work(); }", + ), + ], + &["api.ts"], + ); + assert_eq!(report.issues.len(), 1); + assert!(report.issues[0].introduced); + assert!(!report.callers_after[0].visibility_compatible); + assert!(report.issues[0].summary.contains("visibility/export")); + let old = "mod api { pub fn work() {} } mod consumer { fn run() { crate::api::work(); } }"; + let new = old.replace("pub fn work", "fn work"); + let report = compare(&[("lib.rs", old)], &[("lib.rs", &new)], &["lib.rs"]); + assert_eq!(report.issues.len(), 1); + assert!(!report.callers_after[0].visibility_compatible); +} + +#[test] +fn unresolved_export_expansion_is_not_misreported_as_private_access_failure() { + let old = "function work(x:number) {} export {work};"; + let new = "function work(x:number,y:number) {} export {work};"; + let caller = "import {work} from './api'; function consumer() { work(1); }"; + let report = compare( + &[("api.ts", old), ("caller.ts", caller)], + &[("api.ts", new), ("caller.ts", caller)], + &["api.ts"], + ); + assert!(report.issues.is_empty() && report.callers_after.is_empty()); + assert!(!report.gaps.is_empty()); +} diff --git a/atomic-audit/src/lib.rs b/atomic-audit/src/lib.rs new file mode 100644 index 00000000..dc09e444 --- /dev/null +++ b/atomic-audit/src/lib.rs @@ -0,0 +1,27 @@ +//! Tool-neutral engineering audits and manageability metrics. +//! +//! Cards describe what to inspect and how to interpret evidence. Metric limits +//! are advisory, not acceptance verdicts. Parsing is an optional adapter: enable +//! `structural` to run the existing checks using `atomic-semantic` grammars. +//! Repository scope, finding numbering and publication remain outside this crate. + +#![doc = include_str!("../README.md")] + +pub mod catalog; +#[cfg(feature = "structural")] +pub mod extract; +pub mod impact; +pub mod metrics; +pub mod risk; +#[cfg(feature = "structural")] +pub mod structural; +#[cfg(feature = "structural")] +mod substantive; + +pub use catalog::{AuditCard, MetricCard, AUDIT_CARDS, METRIC_CARDS}; +pub use metrics::{ + evaluate, Measurement, Metric, MetricAssessment, MetricObservation, MetricProfile, ReviewBand, + Threshold, +}; + +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/atomic-audit/src/metrics.rs b/atomic-audit/src/metrics.rs new file mode 100644 index 00000000..200a3f2a --- /dev/null +++ b/atomic-audit/src/metrics.rs @@ -0,0 +1,346 @@ +//! Advisory evaluation of measurements supplied by language/tool adapters. +//! +//! This module does not extract metrics, infer missing values, or decide whether +//! a requirement is unmet. The caller supplies comparable before/after facts +//! using the metric card's counting convention and selects a suitable profile. + +use crate::catalog::MetricScope; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// Counting conventions are versioned independently of advisory project limits. +pub const EXTRACTION_CONVENTION: &str = "atomic.metrics.syntax.v1"; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MetricLocation { + pub start_line: u32, + pub end_line: u32, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExtractedMetric { + pub observation: MetricObservation, + pub path: String, + pub scope: MetricScope, + /// Anonymous or overloaded owners cannot be matched across independently + /// extracted snapshots by their display ordinal alone. + #[serde(default, skip_serializing_if = "is_false")] + pub subject_identity_ambiguous: bool, + pub before_location: Option, + pub after_location: Option, + pub convention: String, + pub detail: String, + pub delta: Option, +} + +fn is_false(value: &bool) -> bool { + !value +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Metric { + MethodLength, + ClassLength, + MethodCount, + ParameterCount, + NestingDepth, + CyclomaticComplexity, + ClassComplexity, + DependencyFanOut, + PublicSurface, + DuplicatedTokens, +} + +impl Metric { + pub const ALL: [Self; 10] = [ + Self::MethodLength, + Self::ClassLength, + Self::MethodCount, + Self::ParameterCount, + Self::NestingDepth, + Self::CyclomaticComplexity, + Self::ClassComplexity, + Self::DependencyFanOut, + Self::PublicSurface, + Self::DuplicatedTokens, + ]; + + pub fn id(self) -> &'static str { + match self { + Self::MethodLength => "metric.method-length", + Self::ClassLength => "metric.class-length", + Self::MethodCount => "metric.method-count", + Self::ParameterCount => "metric.parameter-count", + Self::NestingDepth => "metric.nesting-depth", + Self::CyclomaticComplexity => "metric.cyclomatic-complexity", + Self::ClassComplexity => "metric.class-complexity", + Self::DependencyFanOut => "metric.dependency-fan-out", + Self::PublicSurface => "metric.public-surface", + Self::DuplicatedTokens => "metric.duplicated-tokens", + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)] +pub enum Measurement { + Measured { value: u32 }, + Unavailable { reason: String }, + NotApplicable { reason: String }, +} + +impl Measurement { + fn value(&self) -> Option { + match self { + Self::Measured { value } => Some(*value), + _ => None, + } + } + + fn validate(&self) -> Result<(), &'static str> { + match self { + Self::Unavailable { reason } | Self::NotApplicable { reason } + if reason.trim().is_empty() => + { + Err("unavailable/not-applicable measurements require a reason") + } + _ => Ok(()), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MetricObservation { + pub metric: Metric, + /// Caller-owned recorded entity/subject identity; source anchors and analyzer + /// provenance belong to the review adapter, not this policy-only module. + pub subject: String, + pub before: Measurement, + pub after: Measurement, +} + +impl MetricObservation { + pub fn delta(&self) -> Option { + self.before + .value() + .zip(self.after.value()) + .map(|(before, after)| i64::from(after) - i64::from(before)) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Threshold { + /// Inclusive review trigger, not a defect/acceptance-failure boundary. + pub review_at: u32, + pub high_review_at: Option, +} + +impl Threshold { + fn validate(self) -> Result<(), &'static str> { + if self + .high_review_at + .is_some_and(|high| high <= self.review_at) + { + return Err("high review threshold must exceed the review threshold"); + } + Ok(()) + } +} + +/// No universal limits are installed. Callers select a named profile appropriate +/// for the language, code role and project, excluding generated code as needed. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MetricProfile { + pub name: String, + pub limits: BTreeMap, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReviewBand { + NotConfigured, + WithinLimit, + Review, + HighReview, + Unknown, + NotApplicable, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MetricAssessment { + pub observation: MetricObservation, + pub profile: String, + pub threshold: Option, + /// Available only when both samples were measured, never by substituting 0. + pub delta: Option, + pub band: ReviewBand, +} + +/// Evaluate a metric against explicit advisory limits. A review band is a +/// prioritization signal; it neither creates a finding nor fails a criterion. +/// +/// # Errors +/// Rejects empty subject/profile identities, invalid threshold ordering, and +/// unavailable/not-applicable samples without an explanation. +pub fn evaluate( + observation: &MetricObservation, + profile: &MetricProfile, +) -> Result { + if observation.subject.trim().is_empty() || profile.name.trim().is_empty() { + return Err("metric evaluation requires a subject and named profile"); + } + observation.before.validate()?; + observation.after.validate()?; + for limit in profile.limits.values() { + limit.validate()?; + } + let threshold = profile.limits.get(&observation.metric).copied(); + let delta = observation.delta(); + let band = match &observation.after { + Measurement::Unavailable { .. } => ReviewBand::Unknown, + Measurement::NotApplicable { .. } => ReviewBand::NotApplicable, + Measurement::Measured { value } => match threshold { + None => ReviewBand::NotConfigured, + Some(limit) if limit.high_review_at.is_some_and(|high| *value >= high) => { + ReviewBand::HighReview + } + Some(limit) if *value >= limit.review_at => ReviewBand::Review, + Some(_) => ReviewBand::WithinLimit, + }, + }; + Ok(MetricAssessment { + observation: observation.clone(), + profile: profile.name.clone(), + threshold, + delta, + band, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn profile() -> MetricProfile { + MetricProfile { + name: "example-project-policy".into(), + limits: BTreeMap::from([( + Metric::MethodLength, + Threshold { + review_at: 50, + high_review_at: Some(100), + }, + )]), + } + } + + fn observation(after: Measurement) -> MetricObservation { + MetricObservation { + metric: Metric::MethodLength, + subject: "src/report.ts#ReportBuilder.build".into(), + before: Measurement::Measured { value: 34 }, + after, + } + } + + #[test] + fn thresholds_are_inclusive_configurable_review_signals() { + for (value, band) in [ + (49, ReviewBand::WithinLimit), + (50, ReviewBand::Review), + (99, ReviewBand::Review), + (100, ReviewBand::HighReview), + ] { + let result = + evaluate(&observation(Measurement::Measured { value }), &profile()).unwrap(); + assert_eq!(result.band, band); + assert_eq!(result.delta, Some(i64::from(value) - 34)); + } + } + + #[test] + fn missing_or_inapplicable_is_neither_zero_nor_a_pass() { + let missing = evaluate( + &observation(Measurement::Unavailable { + reason: "No extractor for this syntax".into(), + }), + &profile(), + ) + .unwrap(); + assert_eq!(missing.band, ReviewBand::Unknown); + assert_eq!(missing.delta, None); + let mut record = observation(Measurement::NotApplicable { + reason: "No classes in this language construct".into(), + }); + record.metric = Metric::ClassLength; + assert_eq!( + evaluate(&record, &profile()).unwrap().band, + ReviewBand::NotApplicable + ); + record.before = Measurement::Unavailable { + reason: "No baseline".into(), + }; + record.after = Measurement::Measured { value: 20 }; + assert_eq!(evaluate(&record, &profile()).unwrap().delta, None); + } + + #[test] + fn zero_is_real_and_large_deltas_do_not_overflow() { + let mut record = observation(Measurement::Measured { value: 0 }); + record.before = Measurement::Measured { value: u32::MAX }; + assert_eq!( + evaluate(&record, &profile()).unwrap().delta, + Some(-i64::from(u32::MAX)) + ); + record.before = Measurement::Measured { value: 0 }; + record.after = Measurement::Measured { value: u32::MAX }; + assert_eq!( + evaluate(&record, &profile()).unwrap().delta, + Some(i64::from(u32::MAX)) + ); + } + + #[test] + fn absent_limits_are_not_an_implicit_quality_gate() { + let result = evaluate( + &observation(Measurement::Measured { value: 112 }), + &MetricProfile { + name: "observe-only".into(), + limits: BTreeMap::new(), + }, + ) + .unwrap(); + assert_eq!(result.band, ReviewBand::NotConfigured); + assert_eq!(result.delta, Some(78)); + let roundtrip: MetricAssessment = + serde_json::from_str(&serde_json::to_string(&result).unwrap()).unwrap(); + assert_eq!(roundtrip, result); + } + + #[test] + fn malformed_profiles_and_samples_are_rejected() { + let record = observation(Measurement::Measured { value: 10 }); + let mut policy = profile(); + policy + .limits + .get_mut(&Metric::MethodLength) + .unwrap() + .high_review_at = Some(50); + assert!(evaluate(&record, &policy).is_err()); + assert!(evaluate( + &observation(Measurement::Unavailable { reason: " ".into() }), + &profile() + ) + .is_err()); + let mut empty = record; + empty.subject.clear(); + assert!(evaluate(&empty, &profile()).is_err()); + } +} diff --git a/atomic-audit/src/risk.rs b/atomic-audit/src/risk.rs new file mode 100644 index 00000000..647f5aba --- /dev/null +++ b/atomic-audit/src/risk.rs @@ -0,0 +1,310 @@ +//! Explainable change-review prioritization, not a defect probability model. +//! Research motivates the dimensions; numeric defaults are Atomic policy. + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +pub const MODEL: &str = "atomic.change-risk.v1"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RiskLevel { + Unknown, + Low, + Medium, + High, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct RiskProfile { + pub name: String, + pub broad_functions: usize, + pub broad_files: usize, + pub broad_components: usize, + pub api_functions: usize, + pub api_components: usize, + pub api_growth: u64, + pub propagation_callers: usize, + pub propagation_files: usize, + pub moderate_functions: usize, + pub moderate_files: usize, + pub moderate_callers: usize, +} + +impl Default for RiskProfile { + fn default() -> Self { + Self { + name: "balanced".into(), + broad_functions: 50, + broad_files: 5, + broad_components: 2, + api_functions: 20, + api_components: 3, + api_growth: 10, + propagation_callers: 25, + propagation_files: 5, + moderate_functions: 10, + moderate_files: 5, + moderate_callers: 5, + } + } +} + +impl RiskProfile { + pub fn validate(&self) -> Result<(), &'static str> { + if self.name.trim().is_empty() + || self.api_growth == 0 + || [ + self.broad_functions, + self.broad_files, + self.broad_components, + self.api_functions, + self.api_components, + self.propagation_callers, + self.propagation_files, + self.moderate_functions, + self.moderate_files, + self.moderate_callers, + ] + .contains(&0) + { + return Err("risk profile requires a nonempty name and positive thresholds"); + } + if self.broad_functions < self.moderate_functions + || self.broad_files < self.moderate_files + || self.propagation_callers < self.moderate_callers + { + return Err("high-risk thresholds cannot be below corresponding moderate thresholds"); + } + Ok(()) + } +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub struct RiskFacts { + pub available: bool, + pub production_functions: usize, + pub existing_production_functions: usize, + pub signature_changes: usize, + pub test_support_functions: usize, + pub structural_alerts: usize, + pub production_paths: Vec, + pub components: Vec, + pub observed_production_callers: usize, + pub observed_test_support_callers: usize, + /// Consumers of modified/removed existing declarations, not only new helpers. + pub existing_production_callers: usize, + pub existing_caller_files: usize, + pub outside_change_callers: usize, + pub public_growth: Option, + pub added_file_public_units: Option, + pub public_removed: Option, + pub dependency_growth: Option, + pub non_callable_paths: Vec, + pub source_selection_complete: Option, + /// Unresolved expressions are uncertainty, never observed callers. + pub unresolved_references: Option, + pub surface_measurements_complete: bool, + pub unknowns: Vec, + /// Bounded recorded references by dimension: change, calls, surface, dependency. + pub references: BTreeMap>, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct RiskRule { + pub id: String, + pub level: RiskLevel, + pub reason: String, + pub references: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct RiskEvaluation { + pub model: String, + pub profile: RiskProfile, + pub rating: RiskLevel, + /// Confidence in applicability to observed scope, not calibrated probability. + pub evidence_complete: bool, + pub rules: Vec, + pub facts: RiskFacts, +} + +/// Apply independent rule triggers and take the highest band. Correlated size +/// signals are not summed into a spurious numeric probability or bug count. +pub fn assess(facts: RiskFacts, profile: &RiskProfile) -> Result { + profile.validate()?; + if !facts.available { + return Ok(RiskEvaluation { + model: MODEL.into(), + profile: profile.clone(), + rating: RiskLevel::Unknown, + evidence_complete: false, + rules: vec![], + facts, + }); + } + let mut rules = Vec::new(); + let mut trigger = |id: &str, level, reason: String, dimensions: &[&str]| { + let mut references: Vec<_> = dimensions + .iter() + .flat_map(|key| facts.references.get(*key).into_iter().flatten()) + .cloned() + .collect(); + references.sort(); + references.dedup(); + references.truncate(8); + rules.push(RiskRule { + id: id.into(), + level, + reason, + references, + }); + }; + let public_growth = facts + .public_growth + .unwrap_or(0) + .saturating_add(facts.added_file_public_units.unwrap_or(0)); + let public_churn = public_growth.saturating_add(facts.public_removed.unwrap_or(0)); + if facts.production_functions >= profile.broad_functions + && facts.production_paths.len() >= profile.broad_files + && facts.components.len() >= profile.broad_components + { + trigger("risk.broad-production-change", RiskLevel::High, format!("{} production functions across {} source files and {} components exceed the broad-change thresholds ({}/{}/{})", facts.production_functions, facts.production_paths.len(), facts.components.len(), profile.broad_functions, profile.broad_files, profile.broad_components), &["change"]); + } + if facts.production_functions >= profile.api_functions + && facts.components.len() >= profile.api_components + && public_churn >= profile.api_growth + { + trigger("risk.cross-component-api-churn", RiskLevel::High, format!("{} production functions across {} components with {} declared public units added/removed meet the integration thresholds ({}/{}/{})", facts.production_functions, facts.components.len(), public_churn, profile.api_functions, profile.api_components, profile.api_growth), &["change", "surface"]); + } + if facts.existing_production_callers >= profile.propagation_callers + && facts.existing_caller_files >= profile.propagation_files + && facts.existing_production_functions > 0 + { + trigger("risk.existing-consumer-exposure", RiskLevel::High, format!("Modified existing declarations have {} observed production consumers in {} files (thresholds {}/{})", facts.existing_production_callers, facts.existing_caller_files, profile.propagation_callers, profile.propagation_files), &["change", "calls"]); + } + if facts.production_functions >= profile.moderate_functions + || facts.production_paths.len() >= profile.moderate_files + || facts.components.len() >= 2 + { + trigger( + "risk.change-diffusion", + RiskLevel::Medium, + format!( + "Change spans {} production functions, {} source files and {} components", + facts.production_functions, + facts.production_paths.len(), + facts.components.len() + ), + &["change"], + ); + } + if public_churn > 0 || facts.signature_changes > 0 { + trigger("risk.public-contract-churn", RiskLevel::Medium, format!("{} declared public units added/removed and {} modified existing production signatures need compatibility review", public_churn, facts.signature_changes), &["surface", "change"]); + } + if facts.existing_production_callers >= profile.moderate_callers + || facts.outside_change_callers > 0 + { + trigger("risk.consumer-review", RiskLevel::Medium, format!("{} observed production consumers of existing declarations; {} observed consumers outside the selected source files", facts.existing_production_callers, facts.outside_change_callers), &["calls"]); + } + if facts.dependency_growth.is_some_and(|growth| growth > 0) && facts.production_functions > 0 { + trigger( + "risk.dependency-growth", + RiskLevel::Medium, + format!( + "Declared dependency fan-out increased by {} units across modified files", + facts.dependency_growth.unwrap() + ), + &["dependency"], + ); + } + if !facts.non_callable_paths.is_empty() { + trigger("risk.module-contract-change", RiskLevel::Medium, format!("{} production source files changed imports/types/module-level declarations beyond function bodies", facts.non_callable_paths.len()), &["change"]); + } + if facts.structural_alerts > 0 { + trigger( + "risk.structural-alerts", + RiskLevel::Medium, + format!( + "{} introduced/uncertain automated structural alerts require contextual review", + facts.structural_alerts + ), + &["alerts"], + ); + } + let evidence_complete = facts.source_selection_complete == Some(true) + && facts.unresolved_references == Some(0) + && facts.surface_measurements_complete + && facts.unknowns.is_empty(); + if rules.is_empty() && facts.available && evidence_complete { + let references = facts.references.get("change").cloned().unwrap_or_default(); + rules.push(RiskRule { id: "risk.localized-change".into(), level: RiskLevel::Low, reason: if facts.production_functions == 0 && facts.test_support_functions > 0 { "Only conventionally classified test/support functions changed; no measured production exposure trigger" } else { "Localized measured change with no elevated exposure trigger in the analyzed scope" }.into(), references }); + } + let rating = rules + .iter() + .map(|rule| rule.level) + .max() + .unwrap_or(RiskLevel::Unknown); + rules.sort_by(|a, b| b.level.cmp(&a.level).then_with(|| a.id.cmp(&b.id))); + Ok(RiskEvaluation { + model: MODEL.into(), + profile: profile.clone(), + rating, + evidence_complete, + rules, + facts, + }) +} + +/// Conventional test/support classification, not evidence that tests ran or +/// that these files cover production behavior. +pub fn test_support(path: &str, symbol: &str) -> bool { + let parts: Vec<_> = path.split('/').collect(); + let file = parts.last().copied().unwrap_or(""); + let stem = file.rsplit_once('.').map(|(stem, _)| stem).unwrap_or(file); + let scope = symbol + .rsplit_once('#') + .map(|(_, name)| name) + .unwrap_or(symbol) + .split("::") + .collect::>(); + parts.iter().any(|part| { + matches!( + *part, + "tests" + | "test" + | "__tests__" + | "fixtures" + | "testdata" + | "examples" + | "benches" + | "benchmarks" + ) + }) || matches!(stem, "test" | "tests") + || file.starts_with("test_") + || file.contains(".test.") + || file.contains(".spec.") + || file.contains("_test.") + || scope + .iter() + .take(scope.len().saturating_sub(1)) + .any(|part| matches!(*part, "tests" | "test")) +} + +/// Stable conventional component grouping; explicit package roots are not +/// inferred from compiler/build configuration. +pub fn component(path: &str) -> String { + let mut parts = path.split('/'); + match parts.next().unwrap_or("") { + "crates" | "packages" | "services" | "apps" => { + path.split('/').take(2).collect::>().join("/") + } + "src" | "lib" | "include" | "" => "".into(), + first if path.contains('/') => first.into(), + _ => "".into(), + } +} + +#[cfg(test)] +mod tests; diff --git a/atomic-audit/src/risk/fqn_facts.json b/atomic-audit/src/risk/fqn_facts.json new file mode 100644 index 00000000..50efb6b4 --- /dev/null +++ b/atomic-audit/src/risk/fqn_facts.json @@ -0,0 +1,79 @@ +{ + "available": true, + "production_functions": 53, + "existing_production_functions": 4, + "signature_changes": 0, + "test_support_functions": 23, + "structural_alerts": 0, + "production_paths": [ + "atomic-audit/src/catalog.rs", + "atomic-audit/src/extract/languages.rs", + "atomic-audit/src/extract/mod.rs", + "atomic-audit/src/extract/tokens.rs", + "atomic-audit/src/lib.rs", + "atomic-audit/src/metrics.rs", + "atomic-canonical/src/review_finding.rs", + "atomic-cli/src/commands/review/analysis.rs", + "atomic-cli/src/commands/review/graph.rs", + "atomic-cli/src/commands/review/incremental.rs", + "atomic-semantic/src/lib.rs" + ], + "components": ["atomic-audit", "atomic-canonical", "atomic-cli", "atomic-semantic"], + "observed_production_callers": 31, + "observed_test_support_callers": 22, + "existing_production_callers": 2, + "existing_caller_files": 2, + "outside_change_callers": 0, + "public_growth": 19, + "added_file_public_units": 24, + "public_removed": 0, + "dependency_growth": 4, + "non_callable_paths": [ + "atomic-audit/src/catalog.rs", + "atomic-audit/src/extract/languages.rs", + "atomic-audit/src/extract/mod.rs", + "atomic-audit/src/extract/tokens.rs", + "atomic-audit/src/lib.rs", + "atomic-audit/src/metrics.rs", + "atomic-canonical/src/review_finding.rs", + "atomic-cli/src/commands/review/analysis.rs", + "atomic-cli/src/commands/review/incremental.rs", + "atomic-semantic/src/lib.rs" + ], + "source_selection_complete": true, + "unresolved_references": 1328, + "surface_measurements_complete": true, + "unknowns": ["Unresolved reference expressions are excluded from observed callers"], + "references": { + "calls": [ + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:atomic-cli/src/commands/review/graph.rs:332-332:atomic-cli/src/commands/review/graph.rs#build", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:atomic-cli/src/commands/review/incremental.rs:722-730:atomic-cli/src/commands/review/incremental.rs#resolve_with_session" + ], + "change": [ + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:after:atomic-audit/src/extract/languages.rs:110-121", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:after:atomic-audit/src/extract/languages.rs:123-133", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:after:atomic-audit/src/extract/languages.rs:135-155", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:after:atomic-audit/src/extract/languages.rs:157-168", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:after:atomic-audit/src/extract/languages.rs:16-36", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:after:atomic-audit/src/extract/languages.rs:170-182", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:after:atomic-audit/src/extract/languages.rs:184-206", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:after:atomic-audit/src/extract/languages.rs:208-239" + ], + "dependency": [ + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:dependency_fan_out:atomic-audit/src/extract/languages.rs", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:dependency_fan_out:atomic-audit/src/extract/mod.rs", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:dependency_fan_out:atomic-audit/src/extract/tokens.rs", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:dependency_fan_out:atomic-audit/src/metrics.rs", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:dependency_fan_out:atomic-cli/src/commands/review/graph.rs", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:dependency_fan_out:atomic-cli/src/commands/review/incremental.rs", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:dependency_fan_out:atomic-semantic/src/lib.rs" + ], + "surface": [ + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:public_surface:atomic-audit/src/extract/mod.rs", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:public_surface:atomic-audit/src/lib.rs", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:public_surface:atomic-audit/src/metrics.rs", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:public_surface:atomic-canonical/src/review_finding.rs", + "FQNWHCPNXXO5SFTEKSJENKPC3KBGUVFM3O3KLEIZ56AEHW2MJQ5A:public_surface:atomic-semantic/src/lib.rs" + ] + } +} diff --git a/atomic-audit/src/risk/tests.rs b/atomic-audit/src/risk/tests.rs new file mode 100644 index 00000000..64abf325 --- /dev/null +++ b/atomic-audit/src/risk/tests.rs @@ -0,0 +1,227 @@ +use super::*; + +fn localized() -> RiskFacts { + RiskFacts { + available: true, + production_functions: 1, + existing_production_functions: 1, + production_paths: vec!["src/lib.rs".into()], + components: vec!["".into()], + public_growth: Some(0), + public_removed: Some(0), + added_file_public_units: Some(0), + dependency_growth: Some(0), + source_selection_complete: Some(true), + unresolved_references: Some(0), + surface_measurements_complete: true, + references: BTreeMap::from([("change".into(), vec!["selected:src/lib.rs".into()])]), + ..Default::default() + } +} + +#[test] +fn known_localized_change_can_be_low_without_a_bug_or_probability_claim() { + let result = assess(localized(), &RiskProfile::default()).unwrap(); + assert_eq!(result.rating, RiskLevel::Low); + assert!(result.evidence_complete); + assert_eq!(result.rules[0].id, "risk.localized-change"); +} + +#[test] +fn unavailable_facts_are_not_assumed_zero_risk() { + assert_eq!( + assess(RiskFacts::default(), &RiskProfile::default()) + .unwrap() + .rating, + RiskLevel::Unknown + ); + let mut facts = localized(); + facts.public_growth = None; + facts.surface_measurements_complete = false; + assert_eq!( + assess(facts, &RiskProfile::default()).unwrap().rating, + RiskLevel::Unknown + ); +} + +#[test] +fn fqn_recorded_summary_is_high_despite_no_contract_failure_and_partial_coverage() { + // Measured FQNWHCPNXXO5 summary; test/helper functions have been excluded. + let mut facts = localized(); + facts.production_functions = 53; + facts.existing_production_functions = 4; + facts.test_support_functions = 23; + facts.production_paths = [ + "atomic-audit/src/extract/languages.rs", + "atomic-audit/src/extract/mod.rs", + "atomic-audit/src/extract/tokens.rs", + "atomic-audit/src/metrics.rs", + "atomic-cli/src/commands/review/analysis.rs", + "atomic-cli/src/commands/review/graph.rs", + "atomic-canonical/src/review_finding.rs", + "atomic-semantic/src/lib.rs", + ] + .into_iter() + .map(str::to_owned) + .collect(); + facts.components = [ + "atomic-audit", + "atomic-cli", + "atomic-canonical", + "atomic-semantic", + ] + .into_iter() + .map(str::to_owned) + .collect(); + facts.observed_production_callers = 31; + facts.observed_test_support_callers = 22; + facts.public_growth = Some(19); + facts.added_file_public_units = Some(24); + facts.unresolved_references = Some(1328); + let result = assess(facts, &RiskProfile::default()).unwrap(); + assert_eq!(result.rating, RiskLevel::High); + assert!(!result.evidence_complete); + assert!(result + .rules + .iter() + .any(|rule| rule.id == "risk.cross-component-api-churn")); + assert!(result + .rules + .iter() + .any(|rule| rule.id == "risk.broad-production-change")); +} + +#[test] +fn replay_actual_optimized_fqn_capture() { + let facts: RiskFacts = serde_json::from_str(include_str!("fqn_facts.json")).unwrap(); + let result = assess(facts, &RiskProfile::default()).unwrap(); + assert_eq!(result.rating, RiskLevel::High); + assert!(!result.evidence_complete); + assert_eq!(result.facts.production_functions, 53); + assert_eq!(result.facts.observed_production_callers, 31); + assert_eq!(result.facts.unresolved_references, Some(1328)); + assert_eq!( + result + .rules + .iter() + .filter(|rule| rule.level == RiskLevel::High) + .map(|rule| rule.id.as_str()) + .collect::>(), + [ + "risk.broad-production-change", + "risk.cross-component-api-churn" + ] + ); + assert!(result.rules.iter().all(|rule| !rule.references.is_empty())); +} + +#[test] +fn unresolved_names_never_inflate_callers_or_severity() { + let mut facts = localized(); + facts.unresolved_references = Some(100_000); + let result = assess(facts, &RiskProfile::default()).unwrap(); + assert_eq!(result.rating, RiskLevel::Unknown); + assert!(!result.rules.iter().any(|rule| rule.id.contains("consumer"))); + assert_eq!(result.facts.observed_production_callers, 0); +} + +#[test] +fn broad_test_support_changes_do_not_become_production_exposure() { + let mut facts = localized(); + facts.production_functions = 0; + facts.existing_production_functions = 0; + facts.production_paths.clear(); + facts.components.clear(); + facts.test_support_functions = 500; + facts.observed_test_support_callers = 1000; + assert_eq!( + assess(facts, &RiskProfile::default()).unwrap().rating, + RiskLevel::Low + ); + for path in [ + "src/extract/tests.rs", + "test/client.mjs", + "examples/demo.rs", + "src/a.test.ts", + ] { + assert!(test_support(path, ""), "{path}"); + } + assert!(test_support("src/lib.rs", "src/lib.rs#tests::helper")); + assert!(!test_support("src/lib.rs", "src/lib.rs#test_connection")); +} + +#[test] +fn integration_threshold_is_inclusive_and_profile_is_explicit() { + let mut facts = localized(); + facts.production_functions = 20; + facts.public_growth = Some(10); + facts.components = vec!["a".into(), "b".into(), "c".into()]; + assert_eq!( + assess(facts.clone(), &RiskProfile::default()) + .unwrap() + .rating, + RiskLevel::High + ); + facts.production_functions = 19; + assert_eq!( + assess(facts.clone(), &RiskProfile::default()) + .unwrap() + .rating, + RiskLevel::Medium + ); + let profile = RiskProfile { + api_growth: 11, + ..Default::default() + }; + facts.production_functions = 20; + let result = assess(facts, &profile).unwrap(); + assert_eq!(result.rating, RiskLevel::Medium); + assert_eq!(result.profile.api_growth, 11); +} + +#[test] +fn propagation_and_api_removal_need_no_invented_defect() { + let mut facts = localized(); + facts.existing_production_callers = 25; + facts.existing_caller_files = 5; + assert_eq!( + assess(facts, &RiskProfile::default()).unwrap().rating, + RiskLevel::High + ); + let mut facts = localized(); + facts.public_removed = Some(1); + assert_eq!( + assess(facts, &RiskProfile::default()).unwrap().rating, + RiskLevel::Medium + ); + let mut facts = localized(); + facts.structural_alerts = 1; + assert_eq!( + assess(facts, &RiskProfile::default()).unwrap().rating, + RiskLevel::Medium + ); +} + +#[test] +fn invalid_profiles_fail_closed_and_defaults_deserialize() { + for profile in [ + RiskProfile { + name: "".into(), + ..Default::default() + }, + RiskProfile { + api_growth: 0, + ..Default::default() + }, + RiskProfile { + broad_functions: 1, + ..Default::default() + }, + ] { + assert!(profile.validate().is_err()); + } + assert!(serde_json::from_str::(r#"{"typo":1}"#).is_err()); + let profile: RiskProfile = serde_json::from_str(r#"{"name":"team","api_growth":30}"#).unwrap(); + assert_eq!(profile.api_growth, 30); + assert_eq!(profile.broad_functions, 50); +} diff --git a/atomic-audit/src/structural.rs b/atomic-audit/src/structural.rs new file mode 100644 index 00000000..860dfe6b --- /dev/null +++ b/atomic-audit/src/structural.rs @@ -0,0 +1,309 @@ +//! Small, explicit structural rules over the existing parser registry. +//! +//! Matches are inspection candidates. They do not establish reachability, +//! requirement satisfaction, or whether suppression/placeholders are intentional. + +use atomic_semantic::{Language, ParserRegistry}; + +pub use atomic_semantic::MAX_SOURCE_BYTES; +pub const RULESET_VERSION: &str = "2"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Rule { + Syntax, + RustPlaceholder, + EmptyCatch, + FailureMasking, + DuplicatedBehavior, + UnnecessaryMachinery, + Manageability, + AsyncResourceSafety, + WeakVerification, + UnsafeShortcuts, +} + +impl Rule { + pub const ALL: [Self; 10] = [ + Self::Syntax, + Self::RustPlaceholder, + Self::EmptyCatch, + Self::FailureMasking, + Self::DuplicatedBehavior, + Self::UnnecessaryMachinery, + Self::Manageability, + Self::AsyncResourceSafety, + Self::WeakVerification, + Self::UnsafeShortcuts, + ]; + + pub fn id(self) -> &'static str { + match self { + Self::Syntax => "structural.syntax", + Self::RustPlaceholder => "anti-slop.rust-placeholder", + Self::EmptyCatch => "anti-slop.empty-catch", + Self::FailureMasking => "anti-slop.failure-masking", + Self::DuplicatedBehavior => "anti-slop.duplicated-behavior", + Self::UnnecessaryMachinery => "anti-slop.unnecessary-machinery", + Self::Manageability => "anti-slop.manageability", + Self::AsyncResourceSafety => "anti-slop.async-resource-safety", + Self::WeakVerification => "anti-slop.weak-verification", + Self::UnsafeShortcuts => "anti-slop.unsafe-shortcuts", + } + } + + pub fn supports(self, language: Language) -> bool { + match self { + Self::Syntax => true, + Self::RustPlaceholder => language == Language::Rust, + Self::EmptyCatch => matches!(language, Language::TypeScript | Language::Tsx), + Self::FailureMasking | Self::DuplicatedBehavior | Self::AsyncResourceSafety => { + matches!( + language, + Language::Rust | Language::TypeScript | Language::Tsx + ) + } + Self::UnnecessaryMachinery | Self::WeakVerification | Self::UnsafeShortcuts => { + language == Language::Rust + } + Self::Manageability => true, + } + } + + pub fn summary(self) -> &'static str { + match self { + Self::Syntax => "Parser reports invalid or missing syntax", + Self::RustPlaceholder => "Placeholder macro requires review", + Self::EmptyCatch => "Empty catch may silently discard a failure", + Self::FailureMasking => "Failure path converts an observed error into apparent success", + Self::DuplicatedBehavior => "Conditional alternatives execute identical code", + Self::UnnecessaryMachinery => { + "Private wrapper forwards an unchanged contract without behavior" + } + Self::Manageability => { + "Function combines a long body with substantial branching or nesting" + } + Self::AsyncResourceSafety => { + "Async work violates an observed resource or completion contract" + } + Self::WeakVerification => "Test has empty or non-independent verification", + Self::UnsafeShortcuts => "Safety or verification bypass lacks a local justification", + } + } + + /// Exact implemented pattern coverage; completing these checks is not an + /// assertion that every concern in the broad audit card was proved absent. + pub fn coverage(self) -> &'static str { + match self { + Self::Syntax => "Registered-language syntax error/missing nodes", + Self::RustPlaceholder => "Rust todo!/unimplemented! AST invocations", + Self::EmptyCatch => "TypeScript/TSX catch bodies without behavior or comments", + Self::FailureMasking => "Rust Err-pattern branches returning Ok; TypeScript/TSX catch returning true", + Self::DuplicatedBehavior => "Rust/TypeScript/TSX identical nonempty if/else token bodies, excluding Rust if-let bindings", + Self::UnnecessaryMachinery => "Rust same-module private unchanged forwarding chains; excludes public/attributed/generic/adapter boundaries", + Self::Manageability => "Unique named bodies with >=100 code lines AND complexity >=15 or nesting >=4; existing concerns need >=3 additional decisions or a new nesting level", + Self::AsyncResourceSafety => "Rust same-block known synchronous guards across await; TypeScript/TSX unshadowed async Promise executors", + Self::WeakVerification => "Rust empty tests (except should_panic) and test assertions of true or pure self-comparisons", + Self::UnsafeShortcuts => "Rust selected qualified unsafe memory operations without local SAFETY argument, or unexplained blanket warnings/clippy::all suppression", + } + } + + pub fn correction(self) -> &'static str { + match self { + Self::Syntax => "Inspect the syntax error and verify with the language toolchain; grammar support may be incomplete", + Self::RustPlaceholder => "Implement the required behavior, or explicitly justify this placeholder and exercise its intended behavior", + Self::EmptyCatch => "Handle or propagate the failure, or document why ignoring it is correct for this requirement", + Self::FailureMasking => "Preserve the failure signal or make the intentional degraded-success contract explicit and test its callers", + Self::DuplicatedBehavior => "Check for a mistaken branch body; otherwise remove the redundant distinction only if condition evaluation and branch-local bindings are preserved", + Self::UnnecessaryMachinery => "Check for a real naming or architectural boundary; otherwise call the existing implementation rather than maintaining an identical private contract", + Self::Manageability => "Review the combined control-flow and responsibility growth; simplify cohesive paths where justified and verify relevant branches, rather than splitting solely to satisfy a count", + Self::AsyncResourceSafety => "Release synchronous guards before suspension, or use an appropriate async primitive; return/await failures through the owning task or promise contract", + Self::WeakVerification => "Exercise the requested behavior and compare its result with an independent expectation, including relevant failure cases", + Self::UnsafeShortcuts => "Restore validation/diagnostics or document the precise preconditions and narrow justification for the bypass, with tests of the affected boundary", + } + } +} + +#[derive(Clone, Debug)] +pub struct ManageabilityEvidence { + pub subject: String, + pub code_lines: u32, + pub complexity: u32, + pub nesting: u32, +} + +#[derive(Debug)] +pub struct StructuralIssue { + pub rule: Rule, + pub start_line: u32, + pub end_line: u32, + /// Exact AST node bytes, retained for baseline comparison before display clipping. + pub source: String, + pub detail: String, + pub manageability: Option, +} + +#[derive(Debug)] +pub struct StructuralInspection { + pub issues: Vec, + /// Anti-slop checks are not evaluated on error-recovered trees. + pub has_syntax_errors: bool, + pub ambiguous_manageability_subjects: Vec, +} + +/// Inspect full recorded UTF-8 content with the registry's configured grammar. +/// Errors are explicit coverage gaps, never empty successful inspections. +pub fn inspect( + registry: &mut ParserRegistry, + path: &str, + source: &str, +) -> Result { + let language = Language::detect(path).ok_or("Unsupported language")?; + if source.len() > MAX_SOURCE_BYTES { + return Err("Source exceeds the 1 MiB structural inspection budget"); + } + let tree = registry + .parse_tree(path, source) + .ok_or("Parser returned no syntax tree")?; + let has_syntax_errors = tree.root_node().has_error(); + let mut issues = Vec::new(); + let mut nodes = Vec::new(); + let mut stack = vec![(tree.root_node(), 0)]; + while let Some((node, depth)) = stack.pop() { + if depth > 256 { + return Err("Audit AST nesting budget exceeded; inspection is incomplete"); + } + nodes.push(node); + if nodes.len() > 300_000 { + return Err("Audit AST node budget exceeded"); + } + let rule = if has_syntax_errors { + (node.is_error() || node.is_missing()).then_some(Rule::Syntax) + } else if language == Language::Rust && node.kind() == "macro_invocation" { + node.child_by_field_name("macro") + .and_then(|name| name.utf8_text(source.as_bytes()).ok()) + .filter(|name| { + matches!( + name.rsplit("::").next().map(str::trim), + Some("todo" | "unimplemented") + ) + }) + .map(|_| Rule::RustPlaceholder) + } else if matches!(language, Language::TypeScript | Language::Tsx) + && node.kind() == "catch_clause" + { + // A comment may explain intentional suppression. Leave that case to + // substantive review rather than calling it an undocumented discard. + node.child_by_field_name("body") + .filter(|body| body.named_child_count() == 0) + .map(|_| Rule::EmptyCatch) + } else { + None + }; + if let Some(rule) = rule { + let text = node + .utf8_text(source.as_bytes()) + .map_err(|_| "Invalid AST source range")?; + issues.push(StructuralIssue { + rule, + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + + u32::from( + node.end_position().column > 0 + || node.end_position().row == node.start_position().row, + ), + source: text.into(), + detail: rule.summary().into(), + manageability: None, + }); + if has_syntax_errors { + // One syntax finding is sufficient; recovered subtrees are not + // independent anti-slop evidence. + break; + } + if issues.len() > 100 { + return Err("Structural issue budget exceeded; inspect this file manually"); + } + } + let mut cursor = node.walk(); + let children: Vec<_> = node.children(&mut cursor).collect(); + stack.extend(children.into_iter().rev().map(|child| (child, depth + 1))); + } + let ambiguous_manageability_subjects = if !has_syntax_errors { + crate::substantive::inspect(language, path, source, &nodes, &mut issues)? + } else { + Vec::new() + }; + Ok(StructuralInspection { + issues, + has_syntax_errors, + ambiguous_manageability_subjects, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rust_placeholders_are_ast_matches_not_strings_or_comments() { + let mut registry = ParserRegistry::new(); + let result = inspect( + &mut registry, + "lib.rs", + "// todo!()\nfn f() { let _ = \"unimplemented!()\"; std::todo!(); }", + ) + .unwrap(); + assert!(!result.has_syntax_errors); + assert_eq!(result.issues.len(), 1); + assert_eq!(result.issues[0].source, "std::todo!()"); + assert_eq!(result.issues[0].start_line, 2); + } + + #[test] + fn empty_catch_does_not_flag_handler_logic_or_explanatory_comments() { + let mut registry = ParserRegistry::new(); + let result = inspect(&mut registry, "app.ts", "try { work(); } catch (e) {}\ntry { work(); } catch { throw Error(); }\ntry { optional(); } catch { /* explicitly optional */ }").unwrap(); + assert_eq!(result.issues.len(), 1); + assert_eq!(result.issues[0].rule, Rule::EmptyCatch); + } + + #[test] + fn parse_errors_are_not_clean_or_anti_slop_evidence() { + let mut registry = ParserRegistry::new(); + let result = inspect(&mut registry, "lib.rs", "fn broken( { todo!();").unwrap(); + assert!(result.has_syntax_errors); + assert_eq!(result.issues.len(), 1); + assert_eq!(result.issues[0].rule, Rule::Syntax); + assert!(inspect(&mut registry, "unknown.txt", "hello").is_err()); + assert!(inspect(&mut registry, "lib.rs", &" ".repeat(MAX_SOURCE_BYTES + 1)).is_err()); + } + + #[test] + fn existing_grammar_registry_handles_every_supported_language() { + let mut registry = ParserRegistry::new(); + for (path, source) in [ + ("app.ts", "const x = 1;"), + ("app.tsx", "const x =
;"), + ("app.py", "x = 1\n"), + ("lib.rs", "fn main() {}"), + ("main.go", "package main\nfunc main() {}"), + ("App.java", "class App {}"), + ("app.cpp", "int main() {}"), + ("app.c", "int main() {}"), + ("app.swift", "let x = 1"), + ] { + let result = inspect(&mut registry, path, source).unwrap(); + assert!(!result.has_syntax_errors, "{path}"); + assert!(result.issues.is_empty(), "{path}"); + } + } + + #[test] + fn issue_budget_is_an_explicit_failure_not_a_truncated_clean_result() { + let mut registry = ParserRegistry::new(); + let source = format!("fn unfinished() {{ {} }}", "todo!();".repeat(101)); + assert!(inspect(&mut registry, "lib.rs", &source) + .unwrap_err() + .contains("budget exceeded")); + } +} diff --git a/atomic-audit/src/substantive/branching.rs b/atomic-audit/src/substantive/branching.rs new file mode 100644 index 00000000..3628f248 --- /dev/null +++ b/atomic-audit/src/substantive/branching.rs @@ -0,0 +1,154 @@ +use super::*; + +pub(super) fn inspect( + node: Node<'_>, + context: &mut Context<'_>, + issues: &mut Vec, +) -> Result<(), &'static str> { + let rust = context.language == Language::Rust; + if (rust && node.kind() == "if_expression") || (!rust && node.kind() == "if_statement") { + if let (Some(condition), Some(left), Some(right)) = ( + node.child_by_field_name("condition"), + node.child_by_field_name("consequence"), + node.child_by_field_name("alternative"), + ) { + let right = if right.kind() == "else_clause" { + code_children(right).first().copied() + } else { + Some(right) + }; + if let Some(right) = right { + // `if let` can bind a name differently from the else scope. + // Identical spelling would not establish identical references. + let binds_names = rust + && context + .normalized(condition)? + .iter() + .any(|token| token.kind == "let"); + if !binds_names + && matches!(right.kind(), "block" | "statement_block") + && !code_children(left).is_empty() + && context.normalized(left)? == context.normalized(right)? + { + issues.push(context.issue(Rule::DuplicatedBehavior, node, format!("The nonempty alternatives at lines {} and {} have identical syntax tokens (comments excluded, literal contents preserved). The conditional does not select different branch code; check for a copied or mistaken body. Condition effects still matter.", left.start_position().row + 1, right.start_position().row + 1))); + } + } + } + if rust { + if let (Some(condition), Some(left)) = ( + node.child_by_field_name("condition"), + node.child_by_field_name("consequence"), + ) { + if condition.kind() == "let_condition" { + if let Some(pattern) = condition.child_by_field_name("pattern") { + if error_pattern(pattern, context)? && success(tail(left), context)? { + issues.push(context.issue(Rule::FailureMasking, node, "An Err-pattern branch ends by constructing Ok(...). The observed error is converted into a successful result; verify that callers explicitly expect degraded success rather than failure propagation.")); + } + } + } + } + } + } + if rust && node.kind() == "match_arm" { + if let (Some(pattern), Some(value)) = ( + node.child_by_field_name("pattern"), + node.child_by_field_name("value"), + ) { + if error_pattern(pattern, context)? + && success(tail(value), context)? + && !optional_not_found(pattern, tail(value), context)? + { + issues.push(context.issue(Rule::FailureMasking, node, "A match arm selecting Err(...) returns Ok(...). Error provenance is discarded at this branch and callers receive the success variant; check the declared fallback contract and its tests.")); + } + } + } + if !rust && node.kind() == "catch_clause" { + if let Some(body) = node.child_by_field_name("body") { + let last = code_children(body).last().copied(); + if last.is_some_and(|last| last.kind() == "return_statement") + && context.compact(tail(body))? == "true" + { + issues.push(context.issue(Rule::FailureMasking, node, "The catch handler ends with `return true`, reporting success after an exception. Verify an explicit degraded-success contract rather than silently replacing failure.")); + } + } + } + if !rust && node.kind() == "new_expression" && !context.promise_shadowed { + if let (Some(constructor), Some(arguments)) = ( + node.child_by_field_name("constructor"), + node.child_by_field_name("arguments"), + ) { + if tokens::text(constructor, context.source) == "Promise" { + let executor = code_children(arguments).first().copied(); + if let Some(executor) = executor.filter(|executor| { + matches!( + executor.kind(), + "arrow_function" | "function_expression" | "function" + ) + }) { + if tokens::children(executor) + .iter() + .any(|child| child.kind() == "async") + { + issues.push(context.issue(Rule::AsyncResourceSafety, node, "An async function is used as the Promise executor. Promise ignores the executor's returned promise, so exceptions/rejections from the async executor do not automatically reject the constructed promise; it can remain pending. This check assumes the unshadowed standard Promise constructor.")); + } + } + } + } + } + Ok(()) +} + +fn error_pattern(node: Node<'_>, context: &mut Context<'_>) -> Result { + let pattern = context.compact(node)?; + Ok([ + "Err(", + "Result::Err(", + "std::result::Result::Err(", + "core::result::Result::Err(", + ] + .iter() + .any(|prefix| pattern.starts_with(prefix))) +} + +fn success(node: Node<'_>, context: &mut Context<'_>) -> Result { + if node.kind() != "call_expression" { + return Ok(false); + } + let Some(function) = node.child_by_field_name("function") else { + return Ok(false); + }; + Ok(matches!( + context.compact(function)?.as_str(), + "Ok" | "Result::Ok" | "std::result::Result::Ok" | "core::result::Result::Ok" + )) +} + +fn optional_not_found( + pattern: Node<'_>, + value: Node<'_>, + context: &mut Context<'_>, +) -> Result { + // A typed NotFound guard plus an absent optional value is an explicit + // absence contract, not an unexplained catch-all success fallback. + if context.compact(value)? != "Ok(None)" { + return Ok(false); + } + let pattern = context.compact(pattern)?; + let Some(rest) = pattern.strip_prefix("Err(") else { + return Ok(false); + }; + let Some((binding, guard)) = rest.split_once(")if") else { + return Ok(false); + }; + if binding.is_empty() + || !binding + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_') + { + return Ok(false); + } + Ok( + guard == format!("{binding}.kind()==std::io::ErrorKind::NotFound") + || guard == format!("std::io::ErrorKind::NotFound=={binding}.kind()"), + ) +} diff --git a/atomic-audit/src/substantive/mod.rs b/atomic-audit/src/substantive/mod.rs new file mode 100644 index 00000000..76d2b08c --- /dev/null +++ b/atomic-audit/src/substantive/mod.rs @@ -0,0 +1,192 @@ +//! Executable anti-slop checks over the registry's existing syntax trees. +//! Findings state observed constructs, not whole-program behavioral proof. + +mod branching; +mod rust; + +use crate::extract::{languages, tokens}; +use crate::structural::{ManageabilityEvidence, Rule, StructuralIssue}; +use atomic_semantic::{Language, SyntaxNode as Node}; +use std::collections::BTreeMap; + +pub(super) struct Context<'a> { + source: &'a str, + path: &'a str, + language: Language, + remaining: usize, + promise_shadowed: bool, + subjects: BTreeMap, +} + +impl Context<'_> { + fn charge(&mut self, node: Node<'_>) -> Result<(), &'static str> { + self.remaining = self + .remaining + .checked_sub(node.end_byte() - node.start_byte()) + .ok_or("Substantive audit work budget exceeded; inspection is incomplete")?; + Ok(()) + } + + fn normalized(&mut self, node: Node<'_>) -> Result, &'static str> { + self.charge(node)?; + tokens::leaf_tokens(node, self.source, 80_000) + .map_err(|_| "Substantive audit token budget exceeded") + } + + fn compact(&mut self, node: Node<'_>) -> Result { + Ok(self + .normalized(node)? + .into_iter() + .map(|token| token.text) + .collect()) + } + + fn issue(&self, rule: Rule, node: Node<'_>, detail: impl Into) -> StructuralIssue { + StructuralIssue { + rule, + start_line: node.start_position().row as u32 + 1, + end_line: node.end_position().row as u32 + + u32::from( + node.end_position().column > 0 + || node.end_position().row == node.start_position().row, + ), + source: tokens::text(node, self.source).into(), + detail: detail.into(), + manageability: None, + } + } +} + +fn code_children(node: Node<'_>) -> Vec> { + tokens::named(node) + .into_iter() + .filter(|node| !tokens::comment(*node)) + .collect() +} + +fn tail(mut node: Node<'_>) -> Node<'_> { + loop { + if matches!( + node.kind(), + "block" + | "statement_block" + | "return_expression" + | "return_statement" + | "expression_statement" + | "parenthesized_expression" + ) { + if let Some(child) = code_children(node).last() { + node = *child; + continue; + } + } + return node; + } +} + +pub(crate) fn inspect( + language: Language, + path: &str, + source: &str, + nodes: &[Node<'_>], + issues: &mut Vec, +) -> Result, &'static str> { + let promise_shadowed = nodes.iter().any(|node| { + node.child_by_field_name("name") + .or_else(|| node.child_by_field_name("pattern")) + .is_some_and(|name| tokens::text(name, source) == "Promise") + || (node.kind() == "identifier" + && tokens::text(*node, source) == "Promise" + && node.parent().is_some_and(|parent| { + matches!( + parent.kind(), + "required_parameter" + | "optional_parameter" + | "import_specifier" + | "import_clause" + ) + })) + }); + let mut functions = BTreeMap::<(usize, String), Vec>>::new(); + for &node in nodes.iter().filter(|node| node.kind() == "function_item") { + if let (Some(parent), Some(name)) = (node.parent(), node.child_by_field_name("name")) { + functions + .entry((parent.id(), tokens::text(name, source).into())) + .or_default() + .push(node); + } + } + let mut subjects = BTreeMap::::new(); + for &node in nodes + .iter() + .filter(|node| languages::callable(**node, language)) + { + let (subject, stable) = languages::qualified(node, source, language); + if stable { + *subjects.entry(subject).or_default() += 1; + } + } + let mut context = Context { + source, + path, + language, + remaining: 32 * 1024 * 1024, + promise_shadowed, + subjects, + }; + for &node in nodes { + if matches!( + language, + Language::Rust | Language::TypeScript | Language::Tsx + ) { + branching::inspect(node, &mut context, issues)?; + } + if language == Language::Rust { + rust::inspect(node, &functions, &mut context, issues)?; + } + if languages::callable(node, language) { + manageability(node, &mut context, issues)?; + } + if issues.len() > 100 { + return Err("Substantive audit issue budget exceeded; inspection is incomplete"); + } + } + Ok(context + .subjects + .into_iter() + .filter_map(|(name, count)| (count > 1).then_some(name)) + .collect()) +} + +// Atomic policy, not a universal defect threshold: require BOTH a long body +// and meaningful branching/nesting, not a single large syntax measurement. +fn manageability( + node: Node<'_>, + context: &mut Context<'_>, + issues: &mut Vec, +) -> Result<(), &'static str> { + let Some(body) = languages::body(node, context.language) else { + return Ok(()); + }; + let (subject, stable) = languages::qualified(node, context.source, context.language); + if !stable || context.subjects.get(&subject) != Some(&1) { + return Ok(()); + } + context.charge(body)?; + let code_lines = tokens::code_lines(body, context.source, context.language, true); + let (complexity, nesting) = languages::control_flow(body, context.source, context.language); + if code_lines >= 100 && (complexity >= 15 || nesting >= 4) { + let mut issue = context.issue(Rule::Manageability, node, format!("{subject}: {code_lines} code-bearing body lines, cyclomatic complexity {complexity}, nesting {nesting}. atomic.manageability.v1 requires at least 100 body lines AND complexity >=15 or nesting >=4. This joint concentration increases control-flow review burden; it is not a defect or missing-test verdict.")); + issue.manageability = Some(ManageabilityEvidence { + subject, + code_lines, + complexity, + nesting, + }); + issues.push(issue); + } + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/atomic-audit/src/substantive/rust.rs b/atomic-audit/src/substantive/rust.rs new file mode 100644 index 00000000..436ff7e1 --- /dev/null +++ b/atomic-audit/src/substantive/rust.rs @@ -0,0 +1,542 @@ +use super::*; +use std::collections::{BTreeMap, BTreeSet}; + +pub(super) fn inspect( + node: Node<'_>, + functions: &BTreeMap<(usize, String), Vec>>, + context: &mut Context<'_>, + issues: &mut Vec, +) -> Result<(), &'static str> { + match node.kind() { + "function_item" => { + forwarding_wrapper(node, functions, context, issues)?; + if is_test(node, context) && !has_attribute(node, context, "should_panic") { + if let Some(body) = node.child_by_field_name("body") { + if code_children(body).is_empty() { + issues.push(context.issue(Rule::WeakVerification, node, "This #[test] function has an empty executable body and is not a should_panic test. It succeeds without exercising behavior or checking a result.")); + } + } + } + } + "macro_invocation" => vacuous_assertion(node, context, issues)?, + "block" => guard_across_await(node, context, issues)?, + "unsafe_block" => { + context.charge(node)?; + if !justified(node, context, true) { + let body = tokens::named(node) + .into_iter() + .find(|child| child.kind() == "block"); + if let Some(body) = body { + let mut stack = vec![body]; + let mut operation = None; + while let Some(child) = stack.pop() { + if child.kind() == "call_expression" { + if let Some(function) = child.child_by_field_name("function") { + let target = context.compact(function)?; + if [ + "std::mem::transmute", + "core::mem::transmute", + "std::ptr::read", + "core::ptr::read", + "std::slice::from_raw_parts", + "core::slice::from_raw_parts", + ] + .iter() + .any(|prefix| { + target == *prefix || target.starts_with(&format!("{prefix}::<")) + }) { + operation = Some(target); + break; + } + } + } + stack.extend(code_children(child)); + } + if let Some(operation) = operation { + issues.push(context.issue(Rule::UnsafeShortcuts, node, format!("Unsafe operation `{operation}` has no immediately associated SAFETY explanation of the required memory/layout/lifetime preconditions. This is a missing safety argument at the observed unchecked operation, not proof of undefined behavior."))); + } + } + } + } + "attribute_item" | "inner_attribute_item" => { + let attribute = context.compact(node)?; + if matches!( + attribute.as_str(), + "#[allow(warnings)]" + | "#![allow(warnings)]" + | "#[allow(clippy::all)]" + | "#![allow(clippy::all)]" + ) && !justified(node, context, false) + { + issues.push(context.issue(Rule::UnsafeShortcuts, node, "A blanket warnings/clippy::all suppression disables unrelated current and future diagnostics without a local reason. Narrow the disabled diagnostic or record why the broad bypass is needed.")); + } + } + _ => {} + } + Ok(()) +} + +fn attributes(node: Node<'_>) -> Vec> { + let mut result = Vec::new(); + let mut previous = node.prev_named_sibling(); + while let Some(node) = previous { + if !matches!( + node.kind(), + "attribute_item" | "line_comment" | "block_comment" + ) { + break; + } + if node.kind() == "attribute_item" { + result.push(node); + } + previous = node.prev_named_sibling(); + } + result +} + +fn has_attribute(node: Node<'_>, context: &Context<'_>, expected: &str) -> bool { + attributes(node).into_iter().any(|attribute| { + tokens::named(attribute) + .into_iter() + .filter(|node| node.kind() == "attribute") + .any(|attribute| { + code_children(attribute).first().is_some_and(|path| { + tokens::text(*path, context.source).rsplit("::").next() == Some(expected) + }) + }) + }) +} + +fn is_test(node: Node<'_>, context: &Context<'_>) -> bool { + has_attribute(node, context, "test") +} + +fn justified(mut node: Node<'_>, context: &Context<'_>, safety: bool) -> bool { + let explains = |node| { + let text = tokens::text(node, context.source); + let marker = if safety { "SAFETY:" } else { "Reason:" }; + tokens::comment(node) + && text + .split_once(marker) + .is_some_and(|(_, reason)| reason.trim().len() >= 8) + }; + // Support a comment inside the unsafe block or immediately before its + // enclosing statement. Strings containing SAFETY are never comments. + if code_comment_inside(node, &explains) { + return true; + } + for _ in 0..4 { + if node.prev_named_sibling().is_some_and(explains) { + return true; + } + let Some(parent) = node.parent() else { + break; + }; + if matches!(parent.kind(), "function_item" | "source_file" | "block") { + break; + } + node = parent; + } + false +} + +fn code_comment_inside<'tree>(node: Node<'tree>, explains: &impl Fn(Node<'tree>) -> bool) -> bool { + // Only direct comments in the unsafe body count, not a nested operation's + // unrelated safety note. + tokens::named(node).into_iter().any(|child| { + explains(child) + || (child.kind() == "block" && tokens::named(child).into_iter().any(explains)) + }) +} + +fn forwarding_wrapper( + node: Node<'_>, + functions: &BTreeMap<(usize, String), Vec>>, + context: &mut Context<'_>, + issues: &mut Vec, +) -> Result<(), &'static str> { + let Some(parent) = node + .parent() + .filter(|parent| matches!(parent.kind(), "source_file" | "declaration_list")) + else { + return Ok(()); + }; + if parent.kind() == "declaration_list" + && !parent + .parent() + .is_some_and(|owner| owner.kind() == "mod_item") + { + return Ok(()); + } + if !attributes(node).is_empty() + || node.prev_named_sibling().is_some_and(tokens::comment) + || tokens::named(node).iter().any(|child| { + matches!( + child.kind(), + "visibility_modifier" | "function_modifiers" | "type_parameters" | "where_clause" + ) + }) + { + return Ok(()); + } + let (Some(name), Some(parameters), Some(body)) = ( + node.child_by_field_name("name"), + node.child_by_field_name("parameters"), + node.child_by_field_name("body"), + ) else { + return Ok(()); + }; + if code_children(body).len() != 1 { + return Ok(()); + } + let call = tail(body); + if call.kind() != "call_expression" { + return Ok(()); + } + let (Some(target), Some(arguments)) = ( + call.child_by_field_name("function"), + call.child_by_field_name("arguments"), + ) else { + return Ok(()); + }; + if target.kind() != "identifier" + || tokens::text(target, context.source) == tokens::text(name, context.source) + { + return Ok(()); + } + let params = code_children(parameters); + let args = code_children(arguments); + if params.len() != args.len() { + return Ok(()); + } + for (parameter, argument) in params.iter().zip(&args) { + let Some(pattern) = parameter.child_by_field_name("pattern") else { + return Ok(()); + }; + if pattern.kind() != "identifier" + || argument.kind() != "identifier" + || tokens::text(pattern, context.source) != tokens::text(*argument, context.source) + || tokens::text(pattern, context.source) == tokens::text(target, context.source) + { + return Ok(()); + } + } + let Some(targets) = functions.get(&(parent.id(), tokens::text(target, context.source).into())) + else { + return Ok(()); + }; + let [target_function] = targets.as_slice() else { + return Ok(()); + }; + if !attributes(*target_function).is_empty() + || tokens::named(*target_function).iter().any(|child| { + matches!( + child.kind(), + "visibility_modifier" | "function_modifiers" | "type_parameters" | "where_clause" + ) + }) + { + return Ok(()); + } + let Some(target_parameters) = target_function.child_by_field_name("parameters") else { + return Ok(()); + }; + let target_params = code_children(target_parameters); + if target_params.len() != params.len() { + return Ok(()); + } + for (left, right) in params.iter().zip(&target_params) { + let (Some(left), Some(right)) = ( + left.child_by_field_name("type"), + right.child_by_field_name("type"), + ) else { + return Ok(()); + }; + if context.normalized(left)? != context.normalized(right)? { + return Ok(()); + } + } + let returns = |node: Node<'_>| { + node.child_by_field_name("return_type") + .map(|node| tokens::text(node, context.source).to_string()) + }; + if returns(node) != returns(*target_function) { + return Ok(()); + } + // A single naming wrapper may be a useful boundary. Require a chain of + // private unchanged forwarders rather than flagging every ordinary caller. + let Some(target_body) = target_function.child_by_field_name("body") else { + return Ok(()); + }; + if code_children(target_body).len() != 1 { + return Ok(()); + } + let next = tail(target_body); + if next.kind() != "call_expression" { + return Ok(()); + } + let (Some(next_function), Some(next_arguments)) = ( + next.child_by_field_name("function"), + next.child_by_field_name("arguments"), + ) else { + return Ok(()); + }; + if next_function.kind() != "identifier" + || tokens::text(next_function, context.source) == tokens::text(name, context.source) + || tokens::text(next_function, context.source) == tokens::text(target, context.source) + { + return Ok(()); + } + if !functions + .get(&( + parent.id(), + tokens::text(next_function, context.source).into(), + )) + .is_some_and(|targets| targets.len() == 1) + { + return Ok(()); + } + let next_args = code_children(next_arguments); + if next_args.len() != target_params.len() { + return Ok(()); + } + for (parameter, argument) in target_params.iter().zip(next_args) { + let Some(pattern) = parameter.child_by_field_name("pattern") else { + return Ok(()); + }; + if pattern.kind() != "identifier" + || argument.kind() != "identifier" + || tokens::text(pattern, context.source) != tokens::text(argument, context.source) + || tokens::text(pattern, context.source) == tokens::text(next_function, context.source) + { + return Ok(()); + } + } + issues.push(context.issue(Rule::UnnecessaryMachinery, node, format!("Private standalone `{}` only calls the same-module private `{}` (declared at line {}), which itself only forwards unchanged arguments to `{}`. The first two contracts have identical parameter and return types and no attributes, generics, receiver or visibility boundary; check the purpose of this extra private indirection chain.", tokens::text(name, context.source), tokens::text(target, context.source), target_function.start_position().row + 1, tokens::text(next_function,context.source)))); + Ok(()) +} + +fn vacuous_assertion( + node: Node<'_>, + context: &mut Context<'_>, + issues: &mut Vec, +) -> Result<(), &'static str> { + let mut ancestor = node.parent(); + let mut test = crate::risk::test_support(context.path, ""); + while let Some(parent) = ancestor { + if parent.kind() == "function_item" { + test |= is_test(parent, context); + break; + } + ancestor = parent.parent(); + } + if !test { + return Ok(()); + } + let Some(name) = node.child_by_field_name("macro") else { + return Ok(()); + }; + let name = tokens::text(name, context.source) + .rsplit("::") + .next() + .unwrap_or(""); + let Some(tree) = tokens::named(node) + .into_iter() + .find(|node| node.kind() == "token_tree") + else { + return Ok(()); + }; + let tokens = context.normalized(tree)?; + let values: Vec<_> = tokens.iter().map(|token| token.text.as_str()).collect(); + let assertion = values.get(1..values.len().saturating_sub(1)).unwrap_or(&[]); + let comma = assertion + .iter() + .position(|token| *token == ",") + .unwrap_or(assertion.len()); + let vacuous = if name == "assert" { + assertion[..comma] == ["true"] + } else if name == "assert_eq" && comma < assertion.len() { + let left = &assertion[..comma]; + let rest = &assertion[comma + 1..]; + let end = rest + .iter() + .position(|token| *token == ",") + .unwrap_or(rest.len()); + let simple = |tokens: &[&str]| { + tokens.iter().all(|token| { + *token == "." + || *token == "::" + || token.chars().all(|c| c.is_alphanumeric() || c == '_') + }) + }; + !left.is_empty() && left == &rest[..end] && simple(left) + } else { + false + }; + if vacuous { + let detail = if name == "assert" { + "This test asserts the literal true, so this assertion passes without checking behavior. Other assertions in the test may still be useful." + } else { + "This test compares the same simple expression with itself instead of an independent expected result. Verify that this is deliberately testing reflexivity (for example a non-NaN property), rather than a placeholder or copied expected expression; type-specific equality is not resolved here." + }; + issues.push(context.issue(Rule::WeakVerification, node, detail)); + } + Ok(()) +} + +fn guard_across_await( + block: Node<'_>, + context: &mut Context<'_>, + issues: &mut Vec, +) -> Result<(), &'static str> { + context.charge(block)?; + let mut synchronous = BTreeSet::::new(); + let mut ancestor = block.parent(); + while let Some(parent) = ancestor { + if parent.kind() == "function_item" { + if let Some(parameters) = parent.child_by_field_name("parameters") { + for parameter in code_children(parameters) { + if let (Some(pattern), Some(ty)) = ( + parameter.child_by_field_name("pattern"), + parameter.child_by_field_name("type"), + ) { + let ty = context.compact(ty)?; + if pattern.kind() == "identifier" + && [ + "std::sync::Mutex<", + "std::sync::RwLock<", + "parking_lot::Mutex<", + "parking_lot::RwLock<", + ] + .iter() + .any(|prefix| ty.trim_start_matches('&').starts_with(prefix)) + { + synchronous.insert(tokens::text(pattern, context.source).into()); + } + } + } + } + break; + } + ancestor = parent.parent(); + } + let mut guards = BTreeMap::::new(); + let mut shadowed = Vec::<(String, usize)>::new(); + for statement in code_children(block) { + if statement.kind() == "let_declaration" { + if let Some(pattern) = statement + .child_by_field_name("pattern") + .filter(|pattern| pattern.kind() == "identifier") + { + let name = tokens::text(pattern, context.source).to_string(); + // Shadowing does not run the old binding's destructor. + if let Some(line) = guards.remove(&name) { + shadowed.push((name.clone(), line)); + } + synchronous.remove(&name); + if let Some(initializer) = statement.child_by_field_name("value") { + let expression = context.compact(initializer)?; + if [ + "std::sync::Mutex::new(", + "std::sync::RwLock::new(", + "parking_lot::Mutex::new(", + "parking_lot::RwLock::new(", + ] + .iter() + .any(|prefix| expression.starts_with(prefix)) + { + synchronous.insert(name.clone()); + } + if [ + ".lock().unwrap()", + ".read().unwrap()", + ".write().unwrap()", + ".lock()", + ".read()", + ".write()", + ] + .iter() + .any(|suffix| { + expression + .strip_suffix(suffix) + .is_some_and(|receiver| synchronous.contains(receiver)) + }) { + guards.insert(name, statement.start_position().row + 1); + } + } + } + } + let compact = context.compact(statement)?; + guards.retain(|name, _| { + compact != format!("drop({name});") + && compact != format!("std::mem::drop({name});") + && compact != format!("core::mem::drop({name});") + }); + // A by-value use may transfer or release a guard. Do not claim a + // binding is held when its ownership path is unresolved. + let moved = possible_moves(statement, &guards, context.source); + guards.retain(|name, _| !moved.contains(name)); + if !guards.is_empty() || !shadowed.is_empty() { + let mut stack = vec![statement]; + while let Some(child) = stack.pop() { + if child.kind() == "await_expression" { + let (guard, line) = guards + .first_key_value() + .or_else(|| shadowed.first().map(|(name, line)| (name, line))) + .unwrap(); + issues.push(context.issue(Rule::AsyncResourceSafety, block, format!("Synchronous lock guard `{guard}`, acquired at line {line}, is still lexically live at await line {} in the same block. Holding a std/parking_lot guard across suspension can block executor progress; an explicit drop or a completed inner scope was not observed. Tokio async mutexes are excluded.", child.start_position().row + 1))); + return Ok(()); + } + if child.id() != statement.id() + && (matches!(child.kind(), "block" | "closure_expression" | "async_block") + || languages::callable(child, Language::Rust)) + { + continue; + } + stack.extend(code_children(child)); + } + } + let expression = if statement.kind() == "expression_statement" { + code_children(statement) + .first() + .copied() + .unwrap_or(statement) + } else { + statement + }; + if matches!( + expression.kind(), + "return_expression" | "break_expression" | "continue_expression" + ) { + break; + } + } + Ok(()) +} + +fn possible_moves( + statement: Node<'_>, + guards: &BTreeMap, + source: &str, +) -> BTreeSet { + let mut moved = BTreeSet::new(); + let mut stack = vec![statement]; + while let Some(node) = stack.pop() { + if node.kind() == "identifier" && guards.contains_key(tokens::text(node, source)) { + if let Some(parent) = node.parent() { + let binding = parent.kind() == "let_declaration" + && parent + .child_by_field_name("pattern") + .is_some_and(|pattern| pattern.id() == node.id()); + let borrowed = parent.kind() == "reference_expression" + || (parent.kind() == "unary_expression" + && tokens::text(parent, source).trim_start().starts_with('*')); + if !binding && !borrowed { + moved.insert(tokens::text(node, source).into()); + } + } + } + stack.extend(code_children(node)); + } + moved +} diff --git a/atomic-audit/src/substantive/tests.rs b/atomic-audit/src/substantive/tests.rs new file mode 100644 index 00000000..a80eef33 --- /dev/null +++ b/atomic-audit/src/substantive/tests.rs @@ -0,0 +1,258 @@ +use crate::structural::{inspect, Rule}; +use atomic_semantic::ParserRegistry; + +fn rules(path: &str, source: &str) -> Vec { + let inspection = inspect(&mut ParserRegistry::new(), path, source).unwrap(); + assert!( + !inspection.has_syntax_errors, + "fixture must parse: {source}" + ); + inspection + .issues + .into_iter() + .map(|issue| issue.rule) + .collect() +} + +fn long_function(branches: usize, lines: usize) -> String { + let mut source = String::from("fn large(x:i32) {\n"); + for i in 0..branches { + source.push_str(&format!("if x == {i} {{ work(); }}\n")); + } + for _ in 0..lines { + source.push_str("work();\n"); + } + source.push_str("}\n"); + source +} + +#[test] +fn every_substantive_family_has_an_executable_positive_fixture() { + let large = long_function(15, 100); + for (rule, source) in [ + (Rule::FailureMasking, "fn save()->Result<(),()> { match write() { Ok(()) => Ok(()), Err(_) => Ok(()) } }"), + (Rule::DuplicatedBehavior, "fn f(flag:bool) { if flag { send(1); } else { send(1); } }"), + (Rule::UnnecessaryMachinery, "fn implementation(x:i32)->i32 { x+1 } fn middle(x:i32)->i32 { implementation(x) } fn outer(x:i32)->i32 { middle(x) }"), + (Rule::Manageability, large.as_str()), + (Rule::AsyncResourceSafety, "async fn f() { let m=std::sync::Mutex::new(0); let guard=m.lock().unwrap(); work().await; drop(guard); }"), + (Rule::WeakVerification, "#[test] fn verifies() { let actual=work(); assert_eq!(actual, actual); }"), + (Rule::UnsafeShortcuts, "fn f(bits:u32)->f32 { unsafe { std::mem::transmute::(bits) } }"), + ] { + let inspection = inspect(&mut ParserRegistry::new(), "lib.rs", source).unwrap(); + assert!(!inspection.has_syntax_errors, "{rule:?} fixture must parse"); + let issue = inspection.issues.iter().find(|issue| issue.rule == rule) + .unwrap_or_else(|| panic!("{rule:?} did not execute; found {:?}", inspection.issues)); + assert!(!issue.detail.is_empty() && !issue.source.is_empty()); + assert!(issue.start_line > 0 && issue.end_line >= issue.start_line); + } +} + +#[test] +fn real_error_propagation_and_distinct_branches_are_not_failures() { + for source in [ + "fn f()->Result<(),()> { match work() { Ok(x)=>Ok(x), Err(e)=>Err(e) } }", + "fn f(b:bool) { if b { send(1); } else { send(2); } }", + "fn f(x:Option) { let x=1; if let Some(x)=x { send(x); } else { send(x); } }", + "fn f() { let text=\"Err(_) => Ok(()); unsafe { transmute(x) }\"; /* if b {same()}else{same()} */ }", + ] { + let found = rules("lib.rs", source); + assert!(!found.contains(&Rule::FailureMasking) && !found.contains(&Rule::DuplicatedBehavior), "{found:?}"); + } + assert!(rules( + "lib.rs", + "fn f()->Result<(),()> { if let Err(e)=work() { return Ok(()); } Ok(()) }" + ) + .contains(&Rule::FailureMasking)); +} + +#[test] +fn typed_optional_file_absence_is_not_failure_masking() { + for source in [ + "fn runtime_store()->Result,std::io::Error> { match open() { Ok(x)=>Ok(Some(x)), Err(e) if e.kind()==std::io::ErrorKind::NotFound=>Ok(None), Err(e)=>Err(e) } }", + "fn manifest_plan()->Result,std::io::Error> { match read() { Ok(x)=>Ok(Some(x)), Err(error) if error.kind()==std::io::ErrorKind::NotFound=>return Ok(None), Err(error)=>return Err(error) } }", + ] { assert!(!rules("lib.rs",source).contains(&Rule::FailureMasking)); } + assert!(rules("lib.rs", "fn f()->Result,Error> { match read() { Ok(value)=>Ok(Some(value)), Err(_)=>Ok(None) } }").contains(&Rule::FailureMasking)); +} + +#[test] +fn branching_normalization_ignores_comments_but_preserves_literals() { + assert!(rules( + "lib.rs", + "fn f(b:bool) { if b { /* one */ work(1); } else { work(1); /* two */ } }" + ) + .contains(&Rule::DuplicatedBehavior)); + assert!(!rules( + "lib.rs", + "fn f(b:bool) { if b { work(\"first\"); } else { work(\"second\"); } }" + ) + .contains(&Rule::DuplicatedBehavior)); +} + +#[test] +fn single_wrappers_public_boundaries_and_adapters_are_not_machinery_findings() { + for source in [ + "fn implementation(x:i32)->i32{x+1} fn named_boundary(x:i32)->i32{implementation(x)}", + "fn core(x:i32)->i32{x+1} fn middle(x:i32)->i32{core(x)} pub fn api(x:i32)->i32{middle(x)}", + "fn core(x:i32)->i32{x+1} fn middle(x:i32)->i32{core(x)} #[inline] fn outer(x:i32)->i32{middle(x)}", + "fn core(x:i32)->i32{x+1} fn middle(x:i32)->i32{core(x)} fn outer(x:i32)->i32{middle(x+1)}", + "fn a(x:i32)->i32{b(x)} fn b(x:i32)->i32{a(x)}", + "fn core(x:T)->T{x} fn middle(x:T)->T{core(x)} fn outer(x:T)->T{middle(x)}", + ] { assert!(!rules("lib.rs", source).contains(&Rule::UnnecessaryMachinery), "{source}"); } +} + +#[test] +fn manageability_requires_joint_evidence_not_a_single_large_measurement() { + assert!(!rules("lib.rs", &long_function(0, 200)).contains(&Rule::Manageability)); + assert!(!rules("lib.rs", &long_function(20, 0)).contains(&Rule::Manageability)); + assert!(rules("lib.rs", &long_function(15, 100)).contains(&Rule::Manageability)); +} + +#[test] +fn synchronous_guards_released_before_await_and_async_mutexes_are_excluded() { + for source in [ + "async fn f() { let m=std::sync::Mutex::new(0); let guard=m.lock().unwrap(); drop(guard); work().await; }", + "async fn f() { let m=std::sync::Mutex::new(0); { let guard=m.lock().unwrap(); use_guard(&guard); } work().await; }", + "async fn f() { let m=tokio::sync::Mutex::new(0); let guard=m.lock().await; work().await; drop(guard); }", + "async fn f() { let m=std::sync::Mutex::new(0); let guard=m.lock().unwrap(); let callback=async { work().await; }; drop(guard); callback.await; }", + "async fn f() { let m=std::sync::Mutex::new(0); let guard=m.lock().unwrap(); release(guard); work().await; }", + "async fn f() { let m=std::sync::Mutex::new(0); let guard=m.lock().unwrap(); return; work().await; }", + ] { assert!(!rules("lib.rs", source).contains(&Rule::AsyncResourceSafety), "{source}"); } + assert!(rules("lib.rs", "async fn f() { let m=std::sync::Mutex::new(0); let guard=m.lock().unwrap(); let guard=42; work().await; }").contains(&Rule::AsyncResourceSafety)); + assert!(rules("lib.rs", "async fn f(m:&std::sync::Mutex) { let guard=m.lock().unwrap(); work().await; drop(guard); }").contains(&Rule::AsyncResourceSafety)); +} + +#[test] +fn joint_manageability_reuses_all_registered_language_conventions() { + for (path, header, branch, call, footer) in [ + ( + "app.ts", + "function large(x:number) {\n", + "if(x===0){work();}\n", + "work();\n", + "}\n", + ), + ( + "app.tsx", + "function large(x:number) {\n", + "if(x===0){work();}\n", + "work();\n", + "}\n", + ), + ( + "app.py", + "def large(x):\n", + " if x == 0:\n work()\n", + " work()\n", + "\n", + ), + ( + "app.go", + "package main\nfunc large(x int) {\n", + "if x==0 {work()}\n", + "work()\n", + "}\n", + ), + ( + "App.java", + "class App { void large(int x) {\n", + "if(x==0){work();}\n", + "work();\n", + "} }\n", + ), + ( + "app.c", + "void large(int x) {\n", + "if(x==0){work();}\n", + "work();\n", + "}\n", + ), + ( + "app.cpp", + "void large(int x) {\n", + "if(x==0){work();}\n", + "work();\n", + "}\n", + ), + ( + "app.swift", + "func large(_ x: Int) {\n", + "if x == 0 {work()}\n", + "work()\n", + "}\n", + ), + ] { + let source = format!("{header}{}{}{footer}", branch.repeat(15), call.repeat(100)); + assert!( + rules(path, &source).contains(&Rule::Manageability), + "{path}" + ); + } +} + +#[test] +fn deeply_nested_audit_work_is_explicitly_incomplete() { + let source = format!("fn f() {{ {}work();{} }}", "{".repeat(300), "}".repeat(300)); + let error = inspect(&mut ParserRegistry::new(), "lib.rs", &source).unwrap_err(); + assert!(error.contains("budget exceeded"), "{error}"); +} + +#[test] +fn weak_verification_checks_actual_tests_without_blanket_no_assert_heuristics() { + for source in [ + "fn example() { assert!(true); }", + "#[test] fn verifies() { let actual=work(); assert_eq!(actual, expected()); }", + "#[test] fn verifies() { assert_eq!(next(), next()); }", + "#[test] #[should_panic] fn verifies() {}", + "#[test] fn verifies()->Result<(),Error> { work()?; Ok(()) }", + ] { + assert!( + !rules("lib.rs", source).contains(&Rule::WeakVerification), + "{source}" + ); + } + assert!(rules("lib.rs", "#[test] fn empty() {}").contains(&Rule::WeakVerification)); + assert!(rules("lib.rs", "#[test] fn tautology() { assert!(true); }") + .contains(&Rule::WeakVerification)); +} + +#[test] +fn safety_justifications_and_narrow_suppressions_are_not_blanket_bypasses() { + for source in [ + "fn f(bits:u32)->f32 { // SAFETY: every u32 bit pattern represents a valid f32.\n unsafe { std::mem::transmute::(bits) } }", + "fn f(bits:u32)->f32 { unsafe { // SAFETY: every u32 bit pattern represents a valid f32.\n std::mem::transmute::(bits) } }", + "#[allow(dead_code)] fn f() {}", + "// Reason: generated bindings intentionally mirror the external interface.\n #[allow(warnings)] fn f() {}", + ] { assert!(!rules("lib.rs", source).contains(&Rule::UnsafeShortcuts), "{source}"); } + assert!(rules("lib.rs", "#[allow(warnings)] fn f() {}").contains(&Rule::UnsafeShortcuts)); + assert!(rules("lib.rs", "fn f(x:u32)->f32 { let text=\"SAFETY: pretend\"; unsafe { std::mem::transmute::(x) } }").contains(&Rule::UnsafeShortcuts)); +} + +#[test] +fn typescript_audits_execute_and_exclude_shadowed_promise() { + for (rule, source) in [ + ( + Rule::FailureMasking, + "function f() { try { work(); } catch(e) { return true; } }", + ), + ( + Rule::DuplicatedBehavior, + "function f(b:boolean) { if(b) { work(1); } else { work(1); } }", + ), + ( + Rule::AsyncResourceSafety, + "const result = new Promise(async (resolve,reject) => { await work(); resolve(1); });", + ), + ] { + assert!(rules("app.ts", source).contains(&rule), "{rule:?}"); + } + assert!(!rules( + "app.ts", + "class Promise {} const result = new Promise(async () => { await work(); });" + ) + .contains(&Rule::AsyncResourceSafety)); + assert!(!rules( + "app.ts", + "const result = new Promise((resolve,reject) => { work().then(resolve,reject); });" + ) + .contains(&Rule::AsyncResourceSafety)); +} diff --git a/atomic-canonical/Cargo.toml b/atomic-canonical/Cargo.toml index f91d81bd..edd40d5b 100644 --- a/atomic-canonical/Cargo.toml +++ b/atomic-canonical/Cargo.toml @@ -13,6 +13,7 @@ default = [] dsse-export = ["dep:dsse"] [dependencies] +atomic-audit = { workspace = true } dsse = { version = "=0.1.6", default-features = false, optional = true } serde = { workspace = true } serde_json = { workspace = true, features = ["unbounded_depth"] } diff --git a/atomic-canonical/src/lib.rs b/atomic-canonical/src/lib.rs index a7b6b60a..51df2a56 100644 --- a/atomic-canonical/src/lib.rs +++ b/atomic-canonical/src/lib.rs @@ -44,6 +44,8 @@ pub mod prov; #[cfg(feature = "dsse-export")] pub mod provenance_export; pub mod render; +pub mod review_finding; +pub mod review_graph; pub mod triage_ref; pub mod vocab; diff --git a/atomic-canonical/src/review_finding.rs b/atomic-canonical/src/review_finding.rs new file mode 100644 index 00000000..7f79d564 --- /dev/null +++ b/atomic-canonical/src/review_finding.rs @@ -0,0 +1,279 @@ +//! Analyzer-neutral inspection evidence, not a signed publication approval. +//! +//! Structural analyzers and substantive review skills use the same contract. +//! Empty findings are meaningful only alongside the explicit check coverage. + +use serde::{Deserialize, Serialize}; + +pub const SCHEMA: &str = "atomic.review-analysis.v1"; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Severity { + Info, + Low, + Medium, + High, + Critical, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Confidence { + Low, + Medium, + High, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum IntroductionStatus { + Yes, + No, + Unknown, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Introduction { + pub status: IntroductionStatus, + pub rationale: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SourceSide { + Before, + After, +} + +/// Positions are 1-based, inclusive, on the specified recorded side. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Location { + pub path: String, + pub side: SourceSide, + pub start_line: u32, + pub end_line: u32, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RuleReference { + pub id: String, + pub explanation: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EvidenceKind { + Source, + Diff, + Test, + Command, + Reference, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Evidence { + pub kind: EvidenceKind, + pub reference: String, + pub observation: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ReviewFinding { + pub analyzer: String, + /// Exact recorded change hash, or a domain-separated local snapshot/file + /// comparison reference. Never an inferred working-tree revision. + pub change: String, + pub summary: String, + pub locations: Vec, + pub requirement_or_rule: RuleReference, + pub evidence: Vec, + pub introduced_by_change: Introduction, + pub severity: Severity, + pub confidence: Confidence, + pub proposed_correction: String, + /// Explicit review judgments, never inferred merely from shared file paths. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub acceptance_criteria: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CriterionOutcome { + Unmet, + Unknown, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CriterionAssessment { + pub criterion: String, + pub assessment: CriterionOutcome, + /// Why this finding's evidence contradicts the criterion, or why unknown. + pub rationale: String, +} + +impl ReviewFinding { + /// Reject structurally incomplete findings before presenting them as evidence. + /// This checks presence, not the truth of the reviewer's judgment. + pub fn validate(&self) -> Result<(), &'static str> { + if [ + self.analyzer.as_str(), + &self.change, + &self.summary, + &self.requirement_or_rule.id, + &self.requirement_or_rule.explanation, + &self.introduced_by_change.rationale, + &self.proposed_correction, + ] + .iter() + .any(|value| value.trim().is_empty()) + { + return Err( + "finding requires analyzer, change, summary, rule, rationale and correction", + ); + } + if self.locations.is_empty() + || self.locations.iter().any(|location| { + location.path.trim().is_empty() + || location.start_line == 0 + || location.end_line < location.start_line + }) + { + return Err("finding requires valid 1-based recorded source locations"); + } + if self.evidence.is_empty() + || self + .evidence + .iter() + .any(|item| item.reference.trim().is_empty() || item.observation.trim().is_empty()) + { + return Err("finding requires referenced supporting evidence"); + } + if self + .acceptance_criteria + .iter() + .any(|link| link.criterion.trim().is_empty() || link.rationale.trim().is_empty()) + { + return Err("criterion assessments require an exact criterion and evidenced rationale"); + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CheckStatus { + Completed, + Skipped, + Error, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Check { + pub change: String, + pub path: String, + pub rule: String, + pub status: CheckStatus, + pub detail: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnalysisReport { + pub schema: String, + pub analyzer: String, + pub analyzer_version: String, + pub checks: Vec, + pub findings: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub metrics: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub metric_diagnostics: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub metric_comparison_scope: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub excluded_metadata_paths: Vec, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn legacy_analysis_without_metric_fields_is_not_given_fabricated_measurements() { + let report: AnalysisReport = serde_json::from_value(serde_json::json!({ + "schema": SCHEMA, "analyzer": "legacy", "analyzer_version": "1", "checks": [], "findings": [], + })).unwrap(); + assert!(report.excluded_metadata_paths.is_empty()); + assert!( + report.metrics.is_empty() + && report.metric_diagnostics.is_empty() + && report.metric_comparison_scope.is_empty() + ); + } + + #[test] + fn contract_requires_rule_locations_evidence_and_introduction_rationale() { + let mut finding = ReviewFinding { + analyzer: "review-skill".into(), + change: "exact-recorded-hash".into(), + summary: "An error is silently discarded".into(), + locations: vec![Location { + path: "app.ts".into(), + side: SourceSide::After, + start_line: 3, + end_line: 3, + }], + requirement_or_rule: RuleReference { + id: "error-handling".into(), + explanation: "Handle or propagate failures".into(), + }, + evidence: vec![Evidence { + kind: EvidenceKind::Source, + reference: "app.ts:3".into(), + observation: "catch (error) {}".into(), + }], + introduced_by_change: Introduction { + status: IntroductionStatus::Unknown, + rationale: "Before-content unavailable".into(), + }, + severity: Severity::Medium, + confidence: Confidence::Medium, + proposed_correction: "Propagate the failure or document intentional suppression".into(), + acceptance_criteria: Vec::new(), + }; + finding.validate().unwrap(); + let value = serde_json::to_value(&finding).unwrap(); + assert_eq!(value["introduced_by_change"]["status"], "unknown"); + assert_eq!( + serde_json::from_value::(value).unwrap(), + finding + ); + let complete = finding.clone(); + finding.requirement_or_rule.id.clear(); + assert!(finding.validate().is_err()); + finding = complete.clone(); + finding.introduced_by_change.rationale.clear(); + assert!(finding.validate().is_err()); + finding = complete.clone(); + finding.evidence.clear(); + assert!(finding.validate().is_err()); + finding = complete; + finding.locations[0].start_line = 0; + assert!(finding.validate().is_err()); + finding.locations[0].start_line = 3; + finding.acceptance_criteria.push(CriterionAssessment { + criterion: "actual-criterion".into(), + assessment: CriterionOutcome::Unmet, + rationale: "".into(), + }); + assert!(finding.validate().is_err()); + } +} diff --git a/atomic-canonical/src/review_graph.rs b/atomic-canonical/src/review_graph.rs new file mode 100644 index 00000000..79149426 --- /dev/null +++ b/atomic-canonical/src/review_graph.rs @@ -0,0 +1,202 @@ +//! Read-only review projection. Local graph IDs do not assert persisted KG facts. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::review_finding::{Confidence, CriterionOutcome, Evidence, ReviewFinding}; + +pub const SCHEMA: &str = "atomic.review-graph.v1"; +pub const INPUT_SCHEMA: &str = "atomic.review-findings.v1"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReviewPass { + AntiSlop, + IntentConformance, + BlastRadiusRisk, +} + +impl ReviewPass { + pub const ALL: [Self; 3] = [ + Self::AntiSlop, + Self::IntentConformance, + Self::BlastRadiusRisk, + ]; + + pub fn label(self) -> &'static str { + match self { + Self::AntiSlop => "Anti-slop", + Self::IntentConformance => "Intent conformance", + Self::BlastRadiusRisk => "Blast radius / risk", + } + } + + pub fn id(self) -> &'static str { + match self { + Self::AntiSlop => "pass:anti_slop", + Self::IntentConformance => "pass:intent_conformance", + Self::BlastRadiusRisk => "pass:blast_radius_risk", + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ReviewScope { + pub project: String, + pub view: String, + pub view_state: String, + pub selected_roots: Vec, + pub dependency_closure: Vec, + /// Digest of ordered recorded source membership, including inherited caller + /// context. These are not additional reviewed roots or a duplicated log. + pub source_membership_hash: String, + /// Current intent source hashes, not a claim of historical authentication. + pub intent_sources: BTreeMap, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SubmittedFinding { + pub pass: ReviewPass, + pub finding: ReviewFinding, +} + +/// Optional substantive observations supplied by the actual inspector. This is +/// not signed evidence, and importing it confers no independent approval. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct FindingsInput { + pub schema: String, + pub scope: ReviewScope, + pub findings: Vec, + /// Report-local judgment under the same exact source scope as findings. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub risk_assessment: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RiskRating { + Unknown, + Low, + Medium, + High, + NotApplicable, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RiskCoverage { + Complete, + Partial, + Unavailable, + NotApplicable, +} + +/// Report-local rule estimate or reviewer assessment, not signed approval. +/// Complete coverage means the declared selected scope, not the whole project. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RiskAssessment { + pub rating: RiskRating, + pub confidence: Confidence, + pub coverage: RiskCoverage, + pub rationale: String, + pub evidence: Vec, + pub limitations: Vec, +} + +#[derive(Clone, Debug, Serialize)] +pub struct RiskSummary { + pub assessment: RiskAssessment, + /// reviewer, findings, rule_model, or no_code; never independent approval. + pub basis: String, + pub findings: Vec, + /// Diagnostic edges retained in this bounded graph, not repository totals. + pub unverified_call_candidates: usize, + pub unverified_import_candidates: usize, + pub relationship_coverage: String, + pub signals: Vec, + pub impact: Vec, + pub model: Option, +} + +#[derive(Clone, Debug, Serialize)] +pub struct NumberedFinding { + pub number: u32, + pub id: String, + pub passes: Vec, + pub finding: ReviewFinding, + /// Task/file links are navigation hints only, not failing criterion claims. + pub related_criteria: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub comparison: Option, +} + +#[derive(Clone, Debug, Serialize)] +pub struct FindingComparison { + /// new/existing/resolved/changed/unknown local observations, not a bug verdict. + pub status: String, + pub before: Vec, + pub after: Vec, + pub rationale: String, +} + +#[derive(Clone, Debug, Serialize)] +pub struct CriterionReview { + pub id: String, + pub intent: String, + pub text: String, + pub declared_status: String, + pub review_assessment: CriterionOutcome, + pub findings: Vec, + pub source_hash: String, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum PassStatus { + NotApplicable, + Partial, + Pending, + Blocked, +} + +#[derive(Clone, Debug, Serialize)] +pub struct PassResult { + pub pass: ReviewPass, + pub status: PassStatus, + pub detail: String, +} + +#[derive(Clone, Debug, Serialize)] +pub struct GraphNode { + pub id: String, + pub kind: String, + pub label: String, + pub properties: Value, +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] +pub struct GraphEdge { + pub from: String, + pub relation: String, + pub to: String, +} + +#[derive(Clone, Debug, Serialize)] +pub struct ReviewGraph { + pub schema: String, + pub scope: ReviewScope, + pub passes: Vec, + pub findings: Vec, + pub criteria: Vec, + pub nodes: Vec, + pub edges: Vec, + pub diagnostics: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub risk: Option, +} diff --git a/atomic-cli/Cargo.toml b/atomic-cli/Cargo.toml index 3d6bb7b9..d3a98117 100644 --- a/atomic-cli/Cargo.toml +++ b/atomic-cli/Cargo.toml @@ -30,6 +30,7 @@ path = "src/main.rs" [dependencies] # Internal crates atomic-agent = { workspace = true } +atomic-audit = { workspace = true, features = ["structural"] } atomic-canonical = { workspace = true } atomic-core = { workspace = true } atomic-config = { workspace = true } @@ -94,6 +95,7 @@ uuid = { version = "1.0", features = ["serde", "v4"] } # Utilities serde = { workspace = true } serde_json = { workspace = true } +flate2 = "1.0" serde_yaml_ng = "0.10" toml = { workspace = true } redb = { workspace = true } diff --git a/atomic-cli/README.md b/atomic-cli/README.md index 23b48039..0cf18554 100644 --- a/atomic-cli/README.md +++ b/atomic-cli/README.md @@ -38,6 +38,80 @@ atomic remote add origin https://api.example.com/repo atomic push origin ``` +## Review + +`atomic review` inspects the current recorded intent/change in the current agent +session. It is a deterministic worklist, not an automatic substantive approval: + +```sh +atomic review --json +atomic review --turn : +atomic review --intent +atomic review --change +atomic review --view dev --html +atomic review --from release --to dev --html +atomic review --from release --to dev --json +``` + +Ordinary review is local-only: `atomic-semantic` / `atomic-audit`, no model or +credentials. `--view` audits one recorded snapshot. `--from BEFORE --to AFTER` +compares two recorded views without switching the working copy, showing measured +deltas and new/existing/resolved or uncertain local observations. The offline +HTML embeds Atomic's real logo and colors; no remote assets or analytics load. +Unsupported/missing analysis stays explicit, not a fabricated pass or zero. +Paired-view conformance includes governing-intent criteria and recorded task +evidence. Blast radius includes static callers, contract checks and the local +risk estimate over the two actual view states. Every JSON finding is available +in HTML; contract findings are not truncated at 100. These remain local review +observations, not independent acceptance approval or runtime proof. + +Publish an independent review using one comma-separated view option: + +```sh +atomic review publish --view feature-a +atomic review publish --view feature-a,feature-b +atomic review publish --session +atomic review publish --view feature-a,feature-b --dry-run --json +``` + +The local publisher preflights a trusted issuer, requests one bounded approval, +creates purpose-bound ephemeral credentials without remote enrollment or global +signer rebinding, runs a separate OpenCode process over recorded-only inputs on +the existing logical view, and finalizes through real native `session_end`. +The final signed receipt binds the recorded subject, review, publisher manifest, +native attestations and retained publication artifacts. Source conversations may +continue; publication concerns the frozen recorded snapshot, not future edits. + +The issuer must already be trusted by the repository. A generic read/record grant +is not publication authority: the CLI issues a separate signed, exact-subject +authorization from that trusted issuer. It does not alter the signer allowlist. +Recording credentials are revoked and their secret retired only after successful +finalization or explicit cancellation; public verification material is retained. +`--yes` approves that exact local operation noninteractively; it never grants push. + +Blocked jobs retain diagnostics under `.atomic/review-jobs/`: + +```sh +atomic review publish --resume +atomic review publish --cancel +``` + +Completed jobs are revalidated, not re-executed. Partial signing may resume without +duplicating retained artifacts. An unknown/crashed process outcome is not guessed +successful or blindly relaunched; inspect the retained run or cancel it. Expired +authority is not silently renewed. Retained temporary evidence is not auto-deleted. + +View collections deduplicate shared history and test compatible combined inputs. +Unequal overlapping path deltas, unresolved conflicts and symlink composition +are conservatively refused; prepare an explicit integration view for those cases. +No logical review view is created. Current canonical limits (64 independent roots, +4096 closure changes) fail explicitly rather than truncating coverage. + +Publication means retained signed review approval, **not insertion or push**. +Legacy `atomic triage review` and `atomic triage publication-review` remain valid; +advanced prepare/sign/record/inspect are also under `atomic review publish`. +The single agent-facing wrapper is [`skills/review/SKILL.md`](skills/review/SKILL.md). + ## Global Options | Flag | Description | diff --git a/atomic-cli/skills/review/SKILL.md b/atomic-cli/skills/review/SKILL.md new file mode 100644 index 00000000..816a7551 --- /dev/null +++ b/atomic-cli/skills/review/SKILL.md @@ -0,0 +1,289 @@ +--- +name: Review +description: Review recorded work through anti-slop, intent conformance and blast-radius/risk passes, returning a graph of numbered evidence-backed findings and criterion assessments; or publish an independent view review through Atomic. +--- + +# Review + +One skill, two CLI-owned execution modes. Read installed command help if the +binary's options differ; do not rebuild the workflow in prompts or shell scripts. + +## Default: local-only semantic audit and metrics + +Ordinary review uses `atomic-semantic` and `atomic-audit` against recorded source. +It does not invoke a model, contact an AI provider, start another coding agent or +require credentials. Do not add an AI validation pass to this workflow. All audit +and metric cards are included with their actual local coverage and evidence; +unsupported, skipped, unavailable and error states are explicit, not passing checks. + +```sh +atomic review --json +``` + +The CLI resolves explicit current-session intent context when available, otherwise +the latest recorded change. It never silently expands the default to a full view. +Explicit selectors are mutually exclusive: + +```sh +atomic review --turn : --json +atomic review --intent --json +atomic review --change --json +atomic review --change --html +atomic review --change --html --no-open --output review.html +atomic review --view --html +atomic review --view --json +atomic review --from --to --html +atomic review --from --to --json +``` + +`--view NAME` explicitly audits the current recorded snapshot of that named view, +including inherited/dependency-visible files, once per live path. It never +switches the working copy, reads dirty/staged/untracked files or replays every +historical patch. It is exclusive with change/turn/intent selection and with +change-specific `--findings`/`--risk-profile` inputs. Empty views are valid. +Snapshot reports use `view_snapshot.analysis`; `changes` and `selected_roots` +are empty rather than inventing an authored change. All existing cards remain +available. Source locations use the pinned view-snapshot reference; introduction +is unknown, before values/deltas are not inferred, and HTML shows current snapshot +values. Conformance lists intents explicitly assigned to the named view and their +criteria, independently of change-plan links; this scope context is not inferred +governing-change attribution or acceptance approval. Change-regression risk still +has no baseline in snapshot mode. + +`--from BEFORE --to AFTER` compares two complete recorded view states without a +working-copy switch. Both options are required; they conflict with the other +selectors and change-specific finding/risk inputs. From is before; To is after. +Metrics are extracted independently over each whole supplied corpus and matched +by canonical file inode and qualified subject. The report shows actual numeric +deltas only when both measurements and identities are comparable. Missing data +is unavailable, not an inferred zero. Audit observations are new, existing, +resolved, changed or unknown; changed/unknown are deliberately uncertain rather +than guessed resolutions. Renames use recorded identity, not content similarity. +The v4 `view_comparison.files[*].analysis` units use domain-separated source URIs, +not authored change hashes. All three passes are populated: conformance includes +intents explicitly assigned to the **To** view even without a change-plan link, +plus separately identified membership-delta governing context, pinned recorded +criterion declarations and task/file evidence. Current-vault context is labelled +and source/scope-hashed; unrelated and inherited parent-view assignments are not +silently treated as target work. The left navigation groups acceptance criteria +under searchable intent keys/titles and keeps intents without criteria visible. +Author +claims are not independent acceptance judgments. Blast radius uses the shared +semantic selector over the actual named views for changed functions, callers, +direct-call contracts and the local risk model, not intermediate patch replay. +Compiler/type/runtime behavior remains unproven. Every detected contract finding +is numbered and available in JSON and HTML, with no 100-finding display cap. +See `references/review-contract.md` for matching and coverage limits. + +The offline viewer embeds Atomic's official wordmark and website palette. It +loads no remote fonts, assets or analytics; asset provenance is in +`src/commands/review/assets/README.md`. + +Default terminal output is a location-first three-pass report: anti-slop, intent +conformance, and blast radius / risk. `--json` includes the same `graph.nodes` +and `graph.edges`, numbered `graph.findings` (`F1`, `F2`, ...), criterion +assessments and exact scope. `--details` additionally shows the original worklist +and diffs. Numbers are deterministic within a report, not permanent issue IDs. +Static caller/importer relationships are potential risk context, not automatic +bug findings or proof that tests cover callers. + +The terminal groups concerns by recorded file/region with audit/metric card IDs. +The HTML opens on Summary for report-wide counts, comparison direction/file +states, all-card/coverage tables, conformance context and risk estimates. The +Anti-slop, Conformance and Blast radius tabs start with selected evidence rather +than repeating that overview above every file. Summary links open the relevant +review/card details; returning to a pass retains its selected region. This is a +presentation separation, not a filter or finding limit. +`--html` opens an offline workbench with source, card inspection and separate +anti-slop/conformance/blast-radius tabs. It uses the same scope and finding numbers; +it does not run a different audit or grant approval. HTML artifacts contain source +and evidence, so keep sensitive reports private. `--no-open` supports headless export. + +For an evidenced criterion failure, add an explicit `acceptance_criteria` entry +to the common finding: `criterion` (exact ID), `assessment: unmet`, and +`rationale` connecting the evidence to that criterion. Use `unknown` when the +evidence cannot establish failure. File/task overlap is only a related-criterion +hint. Never infer that every criterion of a touched file is unmet. + +To render substantive observations in the same graph, supply a JSON file via +`atomic review --change --findings [--json]`. The envelope is +`schema: atomic.review-findings.v1`, the exact `scope` copied from `graph.scope`, +and `findings: [{pass, finding}]`. Pass values are `anti_slop`, +`intent_conformance`, and `blast_radius_risk`; `finding` uses the common contract +below. Only link criteria of the change's unambiguous governing intent. Scope, +intent-source hashes, recorded coordinates and evidence are validated; stale or +foreign judgments are refused. Input is limited to 1 MiB / 500 findings. + +An unmet review assessment links back to its numbered findings but does not +rewrite the source intent's declaration, invalidate its signature, or become +signed independent approval. Intent conformance remains pending/partial until +substantive findings are supplied; author `met` labels are not review verdicts. + +Use the returned exact roots, dependency context, diffs, criteria and pending-state +diagnostics as the local review result. Source inspection does not prove tests pass; +do not execute reviewed code or tests as part of HTML export. +Report real findings and verification under their actual authorship and observed +scope. Reuse existing work/review evidence; do not create coordination intents or +claim the author's in-session observations are independent approval. Unfinished +or unrecorded work remains pending, not a reviewed snapshot. + +Include a structural and anti-slop pass. `changes[].analysis` contains the +versioned `atomic.review-analysis.v1` contract, check coverage, and candidate +findings from `atomic-audit` using existing `atomic-semantic` parsers. Audit cards, +metric definitions and advisory policies live in the `atomic-audit` crate; a +catalog entry is not proof that its metric was measured. Use +`changes[].analysis.metrics` for actual values, +recorded-side locations, conventions and deltas; inspect `metric_diagnostics` +and `metric_comparison_scope`. Unknown/not-applicable is not zero, and changed-file +clone counts are not repository-wide duplication scores. Metric observations do +not themselves prove slop or an unmet criterion. Use the same finding structure +for local review observations: see [the review contract](references/review-contract.md). +Paths with an exact `.vault` component are evidence, not application code: exclude +them from code audits, metrics, clone comparisons and static blast-radius parsing. +Retain their diffs, governing intent/criterion context and publication evidence +checks. A vault-only selection has no applicable code passes; do not substitute +an earlier code change or scan the project to fill an empty result. +Every finding must include `analyzer`, exact recorded `change`, `summary`, +`locations` (`path`, `side`: before/after, 1-based inclusive `start_line`/`end_line`), +`requirement_or_rule` (`id`, `explanation`), supporting `evidence` (`kind`, +`reference`, `observation`), `introduced_by_change` (`status`: yes/no/unknown, +`rationale`), `severity` (info/low/medium/high/critical), `confidence` +(low/medium/high), and `proposed_correction`. Evidence kinds are source, diff, +test, command, or reference. Report analyzer/rule versions and coverage gaps. +The linked reference is repository-shipped detail; these required fields remain +self-contained when only this skill file is installed. +An AST match needs contextual judgment; do not infer requirement failure, +authorship, or introduction solely from its presence. Skipped/error checks are +not clean results. No new parser dependency or credentials are required. +The registered local checks cover the audit cards' supported semantic patterns. +Keep their language/pattern limitations visible. Report observed constructs and +consequences, not speculation about AI authorship; do not manufacture findings. + +## Local review workflow + +1. Resolve the exact recorded `--change`, `--intent` or `--turn` selection. Use + `--json` for the machine-readable report or `--html` for the offline viewer. +2. Inspect the audit and metric card coverage, measured values, source spans and + recorded before/after evidence. The viewer's all-cards tables include cards + with no findings or no applicable measurements; nothing is silently passed. +3. Preserve the CLI-assigned finding numbers and selected roots. Keep criterion + declarations distinct from local evidence and explicitly supplied observations; + missing criteria or unsupported semantic checks remain pending/blocked. +4. Do not invoke a model or another agent, add an AI assessment, mutate candidate + source, run reviewed tests or expand dependency references into reviewed roots. + +`--findings` remains an optional import of explicitly supplied observations with +local scope/coordinate validation, not an automatic AI review. The publication +command below is a separate, explicitly selected workflow, not part of HTML export. + +## Review-only budget and stop rule + +### Risk summary and caller investigation + +Use `graph.risk` for rating, confidence, coverage and numbered findings, and +`graph.risk.impact` for recorded changed functions, before/after callers, outgoing +callees, availability/access/arity checks and gaps. Review reuses the existing +semantic parser registry and recorded syntext search: changed entities first, +candidate references second, shared AST context/binding checks third. It does not +parse unrelated files until the budget expires or join global simple names. +Qualified targets, lexical owners, receivers and imports remain available in +shared semantic facts. `statically_bound_direct_call` edges retain binding evidence; +`surviving_reference_to_removed_function` preserves a removed declaration's callers. +Concrete call-contract incompatibilities become automatic numbered risk findings. +Unresolved dynamic/type/cross-crate bindings are not guessed. Normal cfg/attributes +and macros retain source context; configuration-dependent evidence is labeled. +Do not equate scoped static compatibility with implementation correctness or low +overall risk. Inspect relevant unresolved consumers using recorded imports, +visibility, receiver/type context and contracts; discard common-name collisions. +`graph.risk.model` uses researched dimensions and explicit Atomic thresholds to +estimate review risk from breadth, production-consumer exposure and contract churn. +High estimated risk can coexist with zero confirmed defects. Inspect triggered rule +IDs and facts; do not turn rule triggers into F-number findings or criterion failures. +Missing bindings reduce confidence, not measured exposure; unresolved expressions +never count as callers. Test/support changes are not runtime test coverage. +A caller alone is not a bug: a finding +must explain the changed behavior/contract, affected consumer, consequence and +supporting source/diff/test evidence. Stop with an explicit gap when resolution +needs unbounded work. + +The scope-pinned `--findings` envelope optionally accepts `risk_assessment` with +`rating` (unknown/low/medium/high), `confidence` (low/medium/high), `coverage` +(complete/partial/unavailable), `rationale`, common-contract `evidence`, and +`limitations` (a string array). Low requires evidenced, complete selected-scope +inspection, not an empty findings list. Partial/unavailable coverage needs explicit +limitations. An evidenced Medium/High estimate does not require an invented defect; +the assessment cannot downgrade known risk findings. The default versioned rubric +and optional `--risk-profile ` are documented in `atomic-audit/RISK.md`. +These remain report-local judgments, not compiler proof or signed approval. +Human terminal review animates “Thinking...” during recorded analysis; JSON and +pipes stay clean. This indicates actual bounded analysis, not a model invocation. + +A review request authorizes diagnosis, not remediation. Identify what is missing, +sloppy or risky, present numbered evidence-backed findings, then stop. Proposed +corrections are recommendations only; do not implement them, rewrite criteria, +create remediation intents, refactor code or repair the environment without a +separate explicit request. + +Keep investigation proportional: reuse the CLI scope/evidence, inspect changed +code and the most relevant requirements/callers, and run only focused checks +needed to substantiate a finding. Do not launch full-workspace suites, repeated +builds, exhaustive dependency scans or debugging loops to make failures pass. +A failing check is evidence to report, not an instruction to fix it. If further +certainty needs substantial work, report the risk, confidence and coverage gap +instead. Stop after the three bounded passes (or explicit blockers), with a +concise graph/findings summary and observed verification. No automatic fix phase. + +## A view argument means independent publication + +For `@review --view a` or `@review --view a,b`, invoke: + +```sh +atomic review publish --view a +atomic review publish --view a,b +``` + +There is one `--view` option, not a separate `--views` spelling. The CLI freezes +the recorded scope, preflights issuer authority, asks once for bounded local +ephemeral authorization, runs an independent OpenCode publisher in a temporary +recorded-only working copy, dispatches genuine session_end after child completion, +verifies native completion evidence, and retains exact-scope signed approval. +It owns credentials, lifecycle and cleanup. Do not provision grants, launch a +second agent, call session-end, or build a VM/transfer pipeline from this skill. + +Use `--yes` only when the user has already approved the displayed exact local +scope/authority. No production enrollment or shared identity-default mutation is +part of this command. `--identity` selects a trusted local issuer explicitly. + +Other supported operations: + +```sh +atomic review publish --session +atomic review publish --view a,b --dry-run --json +atomic review publish --resume +atomic review publish --cancel +atomic review publish inspect +``` + +An unknown/crashed process outcome is not guessed complete or blindly relaunched: +preserve its job and follow the actual recovery diagnostic. Cancellation retires +recording credentials; it is not withdrawal of a previously published approval. +Collection publication checks combined compatible inputs, deduplicates history, +and rejects ambiguous overlapping deltas or unsupported symlink composition +rather than picking a winner. An explicit integration view is needed for those +cases; the review command never creates one for the user. + +## Results and boundaries + +Distinguish inspection, independent review, native session completion and retained +publication approval. Report the CLI's actual blocker and job ID when blocked. +Do not revoke a still-resumable job merely because one step failed, silently renew +its authorization, weaken policy, infer intent ownership from shared filenames, +or fabricate historical session capture. Native work-session capture and a +present-day retrospective approval remain different evidence. + +Publication means signed review finalization, **not insertion or push**. Those +remain separately requested operations. Legacy triage and advanced external +signing commands remain compatible; they are not extra skill-level workflows. +Never run git, atomic add or atomic record for this workflow: normal agent hooks +record actual work and provenance. If the installed CLI lacks `atomic review`, +report the binary/version mismatch instead of simulating the missing command. diff --git a/atomic-cli/skills/review/references/review-contract.md b/atomic-cli/skills/review/references/review-contract.md new file mode 100644 index 00000000..893b571d --- /dev/null +++ b/atomic-cli/skills/review/references/review-contract.md @@ -0,0 +1,522 @@ +# Structural and anti-slop review contract + +## Local-only execution + +`atomic review --change --html` is a local recorded-source review using +the existing `atomic-semantic` parser/relationship facts and `atomic-audit` checks +and metrics. It does not call a model, use credentials or start another coding +agent. HTML is self-contained and makes no network requests. + +All defined audit and metric cards appear in the viewer's all-cards coverage +tables, including cards with no findings. Audit rows show completed/skipped/error +counts and finding totals. Metric rows show every observation's before/after +measured, not-applicable and unavailable counts. Checked is execution coverage, +not a passing correctness verdict; unsupported cases never become fabricated +passes or zero-valued measurements. Registered pattern/language coverage remains +explicit in each card and in `atomic-audit/AUDITS.md`. +Selecting a metric card also exposes every recorded observation, with its exact +change, path, subject, before/after values and ranges, reasons and delta; no +finding-only filter or representative sample hides the other observations. + +No AI validation or second model stage is part of ordinary review. Explicitly +imported observations and the separate publication workflow are not silently run +by local HTML export. + +The HTML landing page is a dedicated **Summary** tab. Report-wide observation +counts, before/after pins and file states, all-card/coverage tables, governance +context and risk estimates live there once. The three review tabs focus on the +selected file, region or criterion, without repeating those report-wide blocks. +Summary actions and card links open their review details; returning from Summary +preserves the selected region. Summary hides the source navigation, filter bar +and card inspector until a detail section is opened, with keyboard and mobile +tab navigation preserved. No JSON findings or evidence are removed or capped. + +## Entire named view + +```sh +atomic review --view dev +atomic review --view dev --json +atomic review --view dev --html --no-open --output dev-review.html +``` + +`--view NAME` audits each live file in the canonical recorded view snapshot once, +including its parent-chain/dependency visibility. This is not a history replay: +old revisions, deleted paths and unrelated views do not contribute measurements +or old findings. Dirty/staged/untracked files and working-copy attributes are not +used; symlinks are not followed; `.vault` remains excluded from code analysis. +No working-copy view switch or database mutation is performed. Names are exact, +unknown names fail, and empty views produce an honest no-code report with all +cards still available. The view selector is exclusive with turn/intent/change +selectors and with change-specific finding/risk-profile input. + +Snapshot reports have `schema_version: 3`, `selection.kind: view`, and +`view_snapshot` containing `source_ref`, view/state/effective-membership pins, +live paths and `analysis`. Existing change reports retain their v2 shape. +`changes`/`selected_roots` are empty in snapshot mode. Membership is metadata-only +in `dependency_closure`/`dependency_references`; no historical patches or file/token +payloads are included. The references' direct flags are false because there is +no selected change whose direct dependencies are being reviewed. + +`source_ref` is a `urn:atomic:view-snapshot:...` descriptor, not a fabricated change +hash. The existing source-reference fields (`finding.change`, check `change`, +metric-node `change`) carry that URI in this mode. View state and effective +membership are checked through analysis/export, so inherited-parent changes also +invalidate the pin even if the child's own Merkle is unchanged. + +The same local grammars, audit rules and metric extractor run on current recorded +source. Existing issues are visible even when unchanged by the latest change. +Introduction remains unknown; there is no diff/before revision or computed delta. +The uniform metric contract retains an unavailable-before reason, not an absent +file or zero baseline; HTML and terminal present current snapshot values. Formal +conformance includes explicit view-assigned intents and their declared criteria, +not inferred change ownership or automatic acceptance approval. Change-regression +risk is unknown, not guessed from absolute snapshot metrics. Dependency/public-surface metric cards +remain available without claiming a before/after call-contract analysis. + +Whole-view analysis does not inherit the per-change 128-file ceiling. It uses +explicit bounds of 1 MiB per source, 128 MiB total, 2 million tokens, 65,536 subjects +and 2 million clone-pair comparisons, plus the existing per-file extraction limits. +Unsupported/binary/over-budget cases remain skipped/unavailable with reasons, +never silently passed. HTML source-text export retains its separate existing +128-file / 8-MiB limits; all analyzed metric observations remain in JSON/HTML. + +## Compare two recorded views + +```sh +atomic review --from release --to dev +atomic review --from release --to dev --json +atomic review --from release --to dev --html --no-open --output comparison.html +``` + +Both names are exact and required. From is the before state and To is the after +state, not an ancestor range or a sequence of patches to replay. The selectors +conflict with `--view`, change/turn/intent selection and `--findings` / +`--risk-profile`. Self-comparisons, inherited views and empty views are valid. +Both effective memberships and view Merkles are checked through analysis and +HTML export. No working-copy switch, mutation, dirty/staged/untracked source, +model call, credential or runtime network request is involved. + +Comparison reports use `schema_version: 4`, `selection.kind: view_comparison`, +`purpose: local_view_comparison_review` and `view_comparison` with `from`/`to` +pins, diagnostics and `files`. The authored `changes` and `selected_roots` stay +empty; historical changes remain metadata references only. A domain-separated +comparison URI identifies the ordered pair of pins; each file has its own +`source_ref`, before/after path, inode and (when inspected) content hash, file and +content status, `analysis` and `finding_states`. Distinct units may share a +display path during rename-overwrite: resolve sources by reference, not filename. +Metric nodes/findings use the per-file URI; checks retain their side's snapshot +reference. These are report descriptors, not authored change identities. + +File pairing reserves same-path/same-inode matches, then unambiguous inode +renames, then same-path replacements, then additions/removals. It never infers +identity from text or similar names. Canonical recorded name projection excludes +obsolete aliases even if recovery indexes still remember live inode content. +Recreating a path can be a recorded restore of its inode rather than a replacement. +Uninspected/unsupported content is `unavailable`, never falsely `unchanged`. + +Every side is measured independently with the same whole-view bounds described +above. Whole-view duplicate-token counts include all current tokens against the +side-wide same-language corpus, not only tokens changed by the latest patch. +Per-file analyses retain those side-wide results. Named, qualified metric owners +are normalized across recorded file renames; anonymous/overloaded identities are +explicitly ambiguous and never matched numerically by display ordinal. Removed +or replaced file identities do not establish same-named function/class continuity; +file-level path-slot metrics can still compare a replacement. Removed +or added subjects are not numeric zeroes, and diagnostics, syntax recovery and +budgets cannot become absent-subject baselines. `delta` is present only when +both sides are measured under compatible conventions and subject identities. + +The optional `graph.findings[*].comparison` records lifecycle status, before/after +locations and rationale. Exact rule/AST-byte fingerprints in the same recorded +file and qualified metric owner are reserved first as `existing`, regardless of +line shifts or renames. Named manageability owners support continuation through +body edits. Remaining same-rule/owner observations with changed bytes are +`changed`, not claimed equivalent. Unmatched after/before observations are +`new`/`resolved` only with completed counterpart rule coverage or proven file +absence; otherwise they are `unknown`. These are local observation lifecycles, +not defect verdicts or proof of behavioral equivalence. Authored introduction is +unknown. Conformance and blast radius are populated from their own recorded +evidence rather than guessed from audit/metric deltas. The HTML offers direction +labels, lifecycle filters, a file state table and pinned before/after source +controls alongside all twenty cards and all three review passes. + +`view_comparison.conformance.changes` retains the effective membership difference +in both directions (`added_to_after` / `removed_from_after`), path references and +actual recorded governing-plan contexts. Common history is not swept into this +scope. Independently, `conformance.scope.view` identifies the explicitly reviewed +view (To for a comparison), and `conformance.intents` enumerates its explicitly +assigned intents by canonical ID, human key, title, status and source. An intent +does not need a recorded change-plan link to appear in this view-work catalogue. +Neither mere file visibility in an inherited view nor shared task paths assigns +an intent to the target. Actual missing/partial/ambiguous governing bindings stay +diagnostics, not a reason to hide valid view-assigned work or fabricate ownership. + +The Conformance sidebar groups criteria beneath intent keys/titles, includes +selectable intents with no available criteria, and searches intent title/key, +criterion text/ID and related F-numbers. Any actual change-linked criteria outside +the target's explicit assignment are separately labelled change-linked context, +not silently presented as view-assigned work. Single-view reports carry the same +catalogue under `view_snapshot.conformance` without inventing a comparison. + +The conformance `criteria` retain before/after declarations, raw recorded source +hashes, author status, verifier/evidence claims, verification records/required kinds +and linked task/file comparison references. Prefer intent definitions rendered +from each pinned recorded view. Parsing is bounded to 1 MiB per intent and 16 MiB +of intent source per side; omitted/unreadable definitions are explicit. When no +recorded definition is available, a source-hashed current vault DB definition may +be included under `current_context`, labelled `current_vault_context`, with no +invented historical before/after status. That context is checked for drift during +export. The current assignment catalogue is also source-hashed under +`scope.current_inventory_hash`; new/reassigned/removed scoped intents and changed +current definitions invalidate export rather than reusing stale context. Recorded +target-view intent definitions remain available even if their current vault entry +is absent, and are preferred over dirty current definitions. Neither declarations nor evidence-command strings are executed or treated +as independently authenticated approval; arbitrary semantic acceptance judgments +stay unknown. Engineering findings in task files are related navigation evidence, +never automatic unmet-criterion verdicts. + +Blast radius uses the same `RecordedSemanticView` selector and +`atomic_audit::impact::analyze_semantic` policy as ordinary change review, but pins +the two named effective states instead of a current-view patch prefix. Changed +roots are selected before parsing caller context; before/after static callers, +callees, declaration/access/argument-count checks and the rule-based risk estimate +are populated. It does not replay intermediate changes: a break fixed before the +To state is not presented as a current contract break. Source/path/parser/search +budgets and unsupported/dynamic bindings remain explicit coverage gaps. Semantic +callable IDs remain module/path-addressed, so a file rename can change bindings. +Compiler-resolved types, runtime behavior and executed-test coverage are not +claimed. Self-comparisons and metadata-only state differences do not trigger a +code-risk scan. Existing/resolved audit observations do not become new structural +risk alerts. + +Every detected contract issue is projected into the numbered finding set; there +is no 100-finding display truncation. JSON, the embedded HTML startup graph and +the downloadable original JSON contain the same complete finding set. The viewer +renders every finding via its file/region navigation, including beyond F100; +bounded source-text export does not remove findings or their evidence. + +The viewer embeds Atomic's actual wordmark PNG and uses the verified violet/pink +website palette. No remote fonts, website code, analytics or asset requests are +included. See `src/commands/review/assets/README.md` for source URLs, hashes and +the proportional downsample. Local installed font names have system fallbacks. + +## Three-pass graph and numbered findings + +`atomic review` renders a location-first report with anti-slop, intent-conformance and +blast-radius/risk passes. `--json` exposes `graph` (`atomic.review-graph.v1`) +with the same nodes/edges plus exact scope, pass coverage, criterion assessments +and numbered findings. `--details` retains the verbose worklist, raw diffs and +every metric observation without a row cap. + +The default anti-slop report groups numbered concerns by recorded file and line +range, with audit/rule IDs and concise metric-card callouts. It does not expand +the evidence graph or dump every measurement. `--details` preserves full evidence, +audit coverage, all ten metric families and every observation without truncation. +Metrics are not a substitute for executable audits; see `atomic-audit/AUDITS.md` +for supported patterns/languages and exclusions. + +## Offline HTML review workbench + +```sh +atomic review --change --html +atomic review --intent --html +atomic review --change --html --no-open --output review.html +atomic review --change --html --no-open > review.html +``` + +`--html` writes a unique self-contained artifact and opens it using the existing +HTML-export convention. `--no-open` emits HTML to stdout, or to `--output` when +provided; it never opens a browser. HTML conflicts with `--json`/`--details`, and +`--output`/`--no-open` require HTML. The canonical graph schema is unchanged; +the enclosing inspection report is now `schema_version: 2`. + +JSON and HTML use the same export boundary: `changes` contains selected roots +only, with their paths, review results and recorded evidence. `dependency_closure` +includes roots in dependency-first order; `dependency_only` lists non-roots. +`dependency_references` contains only non-root hashes, direct-dependency flags, +current-view membership, header summaries (first line, at most 240 characters), +and dependency hashes. Ancestor paths, patches, file/token payloads, diffs, +analyses and governing intent documents are not collected for normal export. +Dependencies are causal references, not additional reviewed roots. + +The viewer uses the same numbered findings, scope, criteria and risk assessment: + +- **Anti-slop:** file/region navigation, recorded source before/after, exact finding + evidence/corrections, and audit/metric card inspection. Findings open first; + changed/all metric-region filters expose every observation, not just a sample. +- **Conformance:** reviewer assessment is separate from the author's declared + status. Mapped findings navigate to their recorded source. Missing governing + criteria remain blocked; current intent definitions are not authenticated history. +- **Blast radius:** explainable risk rules/profile, production/test-support facts, + actual bound reference evidence and source locations. Caller context is labeled + as context, not an additional reviewed root; unresolved names are not consumers. + +All twenty audit/metric definitions remain available, including their evidence, +counting conventions and exceptions. Enclosing-function metrics are identified as +context rather than measurements of an individual branch. Opposite-side source +highlights require a genuine matched metric/function location; otherwise the UI +states that no reliable region mapping exists. A change diff is explicitly the +whole selected change, not a fabricated per-region diff. + +Additional source snapshots use recorded content APIs only for selected paths, +prioritized by concerns. Caller context retains bounded recorded references and +span-based evidence, never whole caller files outside selected paths. Export is +bounded to 128 eligible file snapshots, 1 MiB per source side and 8 MiB total +source text; omissions are explicit +unavailable states, not silent truncation or dirty-byte fallbacks. `.vault` code +source stays excluded while governing intent/diff evidence remains in the report. + +There are no external scripts, fonts, CDNs, analytics or server requirements. +Embedded JSON escapes markup delimiters; DOM rendering uses text nodes and a +nonce-based restrictive CSP. UI startup uses only the report fields it displays; +the same bounded JSON report (including dependency references and graph edges) is +retained as a gzip archive and restored only when downloading JSON. Native browser +decompression needs no library/network request; older browsers can download JSON.gz. +Downloads preserve original serialized text, including integers outside JavaScript's +precise-number range. The artifact includes +source/evidence: keep it private if that content is sensitive. Neither viewing nor +exporting it performs fixes, changes criterion judgments or grants approval. + +Findings are deterministically numbered F1, F2, ... within that report. An +identical observation shared by several passes has one number. Numbers are +navigation labels, not permanent cross-revision identities. Nodes and local IDs +are a read-only report projection, not newly asserted persistent KG facts. +File resources retain their existing canonical Atomic IDs. Source locations +include exact change, side and line range; enclosing functions/types and static +caller/importer context are connected when available. + +Direct impact uses recorded view-prefix source immediately before/after each +selected change. Earlier unrelated files are caller context, not extra reviewed +roots. No later or dirty source is used. Unavailable/off-view snapshots are gaps. +Changed source is parsed first through the existing `atomic-semantic` registry. +Recorded syntext path/content search selects relevant references before AST +budgets; owner/private scope constrains candidates. Matching source and explicit +import/module context use the same semantic facts, not a review-specific parser. +The adapter bounds selected changes, changed/matching files and context separately; +see `atomic-audit/IMPACT.md`. Search counts and parsed-file counts are distinct. + +`graph.risk.impact` and `direct_impact_analysis` nodes retain changed functions, +before/after callers, outgoing direct callees, binding evidence, compatibility +checks/issues and gaps. Function roots use token-level before/after comparison, +not every function in a changed file. `statically_bound_direct_call` edges require +supported lexical/import/module binding; `surviving_reference_to_removed_function` +preserves a before-bound symbol absent after the change; `inaccessible_direct_reference` +retains a reference rejected by supported export/access rules. These rejected +references are not counted as legal current callers. Review no longer generates +global-name caller candidates. Legacy unverified candidate-count fields remain +zero for compatibility, not measured caller totals. + +Shared source facts preserve qualified targets, receivers, owners, methods and +imports from registered grammars. Ordinary attributes/macros are not reasons to +discard whole files. Supported lexical, declared-receiver and import/module +bindings are checked; ambiguous scopes, unresolved dynamic/type/cross-crate +context and actual truncation remain scoped gaps. Configuration-dependent source +facts are labeled rather than presented as active compiler configuration. +See `atomic-audit/IMPACT.md`. Counts describe scoped static bindings, not +runtime reachability or whole-program proof. All passes retain honest partial/ +pending/blocked states; there is no fabricated semantic-conformance verdict. + +## Risk assessments, confidence and coverage + +`graph.risk` and the `risk_summary` graph node expose a report-local assessment, +its basis (reviewer/findings/rule_model/no_code), numbered risk findings and measured +direct impact. `graph.risk.model` retains `atomic.change-risk.v1`, the expanded +profile, role-separated facts, triggered rule IDs/reasons and recorded references. +See `atomic-audit/RISK.md` for research sources and Atomic-owned thresholds. This +is a review-priority estimate, not defect probability, signed approval or a bug +count. `--risk-profile ` explicitly overrides documented thresholds. + +Default review checks availability/access/arity on affected direct references. Concrete +incompatibilities become `compatibility.resolved-direct-call-contract` findings +without supplied observations, with source/binding evidence and honest introduction +attribution. The direct-call compatibility verdict is separate from overall risk. +Broad production changes, cross-component API churn and existing-consumer exposure +can establish elevated estimated risk with no confirmed issue. Partial coverage +limits confidence, not the measured positive triggers. Unresolved names never count +as callers or raise severity. Tests/support are separated; changing tests does not +prove execution/coverage. Known risk findings remain a severity floor. Rule triggers +are `risk_rule` nodes, not fabricated findings or criterion failures. Metadata-only +code risk remains not applicable; intent/publication checks stay separate. + +The existing exact-scope findings envelope accepts an optional assessment: + +```json +"risk_assessment": { + "rating": "unknown", + "confidence": "low", + "coverage": "partial", + "rationale": "The recorded implementation was inspected but consumer binding remains unresolved.", + "evidence": [ + {"kind": "source", "reference": "", "observation": ""} + ], + "limitations": [""] +} +``` + +Rating is unknown/low/medium/high; confidence is low/medium/high; coverage is +complete/partial/unavailable. Complete means reviewer-declared inspection of the +selected scope, not an exhaustive project certification. Rationale and referenced +evidence are mandatory. Partial/unavailable coverage requires limitations; low +requires complete scoped coverage for an explicit reviewer judgment. An evidenced +Medium/High estimate need not claim a defect; assessments cannot downgrade scoped +medium/high risk findings. Automatic estimates remain retained beside overrides. +The CLI validates scope/contract consistency, not the truth of a reviewer's claims. +Ratings are neither authenticated approval nor automatic acceptance verdicts. + +Substantive reviewers must validate relevant candidate relationships against +recorded imports, visibility, receiver/type context and contracts. A shared name +is insufficient, and a real caller alone is not a finding. Report concrete +implementation/compatibility consequences with locations, evidence and corrections; +keep investigation bounded and state unresolved coverage rather than guessing. + +## Criterion failures are explicit review judgments + +The common finding can include: + +```json +"acceptance_criteria": [ + { + "criterion": "", + "assessment": "unmet", + "rationale": "" + } +] +``` + +Only explicit, evidenced judgments create `assesses_unmet` graph edges and roll +the criterion's `review_assessment` to `unmet`, linked to its finding numbers. +Missing evidence or inconclusive linkage is `unknown`, never an invented pass +or fail. The criterion's separate `declared_status` is preserved. Default review +does not change the signed source intent. Shared file paths produce only +`related_criterion_not_a_verdict` edges within actual governing intent context; +they never establish ownership or failure. + +Use `atomic review --change --json` to obtain the exact `graph.scope`. +An inspector can supply a file to `atomic review --change +--findings ` with this envelope: + +```text +{ + "schema": "atomic.review-findings.v1", + "scope": , + "findings": [ + {"pass": "intent_conformance", "finding": } + ] +} +``` + +This is a template, not literal runnable JSON. `pass` may also be `anti_slop` or +`blast_radius_risk`. A copied structural finding can be enriched with criterion +judgments without creating a second finding number. Input is capped at 1 MiB / +500 findings. Every finding needs evidence and valid recorded coordinates; each +criterion must belong to the finding change's unambiguous governing intent. +The selected roots, source view/state/inherited membership and current intent +source hashes must still match. Reject scope drift, fabricated criteria and +out-of-range coordinates rather than silently widening the review. Supplied +observations are not authenticated independent approval, even when well formed. + +Perform both correctness and anti-slop inspection against the exact recorded +scope. For each selected recorded root, `atomic review --change --json` +returns `changes[].analysis`. Dependency-only changes appear only in +`dependency_references` unless independently selected; do not claim they were inspected. + +Use the analyzer-neutral `atomic.review-analysis.v1` envelope and the typed +`atomic_canonical::review_finding` contract for findings from every analyzer or +review skill. Include analyzer identity/version, checks executed and skipped or +errored, and findings. No findings plus skipped checks does not mean a clean pass. + +Each finding carries: + +- `analyzer`, exact recorded `change`, and a `summary` of the issue/change. +- `locations`: recorded `path`, `side` (`before` or `after`), `start_line`, + `end_line` (1-based, inclusive). The initial structural analyzer emits after-side + locations; substantive review can cite before-side evidence for deletions. +- `requirement_or_rule`: `id` and an explanation of the affected requirement or + engineering rule. Cite an actual requirement when available, otherwise name + the engineering rule; never invent governing intent ownership. +- `evidence`: entries with `kind` (`source`, `diff`, `test`, `command`, + `reference`), `reference` and observed supporting facts in `observation`. +- `introduced_by_change`: `status` (`yes`, `no`, `unknown`) and a `rationale` + based on recorded before/after comparison. Unknown is not yes. +- `severity`: `info`, `low`, `medium`, `high`, or `critical`. +- `confidence`: `low`, `medium`, or `high`. +- `proposed_correction`: an actionable correction, not automatic edits. + +The shared presence validator rejects missing rules, evidence, correction or +valid locations. Presence validation does not authenticate evidence or prove a +finding is true. Skills should report complete fields, not anonymous complaints. + +## Initial deterministic coverage + +Default terminal output lists concerns by file/region rather than expanding graph +edges or coverage inventories. The HTML viewer and --details retain every metric +observation, including real zero values and explicit unavailable/inapplicable states. +Unavailable reasons/paths remain grouped in detailed coverage and attached to their +individual measurements. Counts are observations, not files or clean-code verdicts. + +Exact `.vault` path components are excluded before code-source reads, structural +checks, metric placeholders and clone/static relationship input. JSON retains +`excluded_metadata_paths`; original selected hashes, paths, diffs and governing +intent/criterion evidence remain intact. Vault-only selections report code passes +as `not_applicable` and skip the project relationship scan, not as a clean audit. +This does not suppress intent conformance or independent publication checks. + +The `atomic-audit` crate owns readable audit/metric cards, advisory metric +evaluation and the optional structural checks. The existing +`atomic-semantic::ParserRegistry` supplies tree-sitter trees; parsing does not +depend on audit policy. No ast-grep dependency is added. Metric definitions, +including method/class length, have automatic source-syntax extraction under +`changes[].analysis.metrics`, with before/after locations, values, deltas and +convention `atomic.metrics.syntax.v1`. Check `metric_diagnostics` and the exact +`metric_comparison_scope`; changed-file duplication is not repository-wide. +Unsupported, unresolved and budget-limited measurements remain unavailable; +inapplicable constructs are not zero. Metrics link cards/source nodes in the +graph without manufacturing findings or criterion failures. Ruleset version 2 +also executes seven substantive source audits; it is not merely a measurement +inventory. The original checks remain: + +- `structural.syntax`: syntax error/missing nodes in every registered language. + This is parser evidence, not a compiler verdict; grammar limitations can matter. +- `anti-slop.rust-placeholder`: Rust `todo!` / `unimplemented!` macro invocations, + including qualified calls. Strings/comments are not matches. Shadowed macros, + intentionally unfinished paths and test scaffolding need contextual review. +- `anti-slop.empty-catch`: TypeScript/TSX catch bodies with no named children. + A comment or executable handler is left to substantive review rather than + automatically labeled undocumented suppression. + +Additional executable audit families are failure masking, duplicated behavior, +unnecessary machinery, joint manageability, async/resource safety, weak verification +and unsafe shortcuts. Their exact patterns are exposed in check details and +documented in `atomic-audit/AUDITS.md`. Supported positive matches become common +numbered findings with source evidence, correction and before/after attribution, +not just metric counters. Joint manageability uses existing counting code plus +the explicit `atomic.manageability.v1` policy, suppressing unchanged/improving +before-side burden. Isolated metric values remain observations, not bug verdicts. + +Unsupported languages/rules, absent after-content, binary/non-UTF-8 content, +parser failure and files exceeding 1 MiB are explicitly skipped or errored. +No general anti-slop coverage is claimed for other languages. Syntax recovery +prevents anti-slop matching for that file. More than 100 matches in a file +requires manual inspection rather than silently truncating a clean result. + +Introduction compares exact rule/node-text occurrences as a multiset. Line +shifts alone are not new findings; extra identical occurrences are new syntactic +candidates, not proven behavioral regressions. Missing/unparseable baseline +means unknown, unless an explicit file-creation operation establishes absence. +If the same rule matched different node text before, a changed match is unknown: +editing an existing placeholder does not prove this change introduced it. +The same observed syntax error is pre-existing; different observed errors in two +already-broken revisions have unknown attribution rather than an invented answer. + +## Local semantic audit pass + +Inspect requirement fit, needless abstractions/dependencies, duplicated behavior, +swallowed failures, unexplained fallback success, unsupported documentation +claims, and tests that do not check observable behavior. Report concrete evidence +and consequences, not judgments that code “looks AI-generated.” Do not fabricate +findings when a minimal implementation is appropriate. Record checks and any +coverage gaps even when there are no findings. + +These are inspection candidates, not a new publication gate or signed approval. +Existing publication trust, isolation, lifecycle and verification rules remain +unchanged. Do not repair the implementation in the independent review copy. diff --git a/atomic-cli/src/commands/agent/mod.rs b/atomic-cli/src/commands/agent/mod.rs index 852e8625..30480c1c 100644 --- a/atomic-cli/src/commands/agent/mod.rs +++ b/atomic-cli/src/commands/agent/mod.rs @@ -45,6 +45,7 @@ mod hooks; mod identity; mod lifecycle; mod provenance_rpc; +mod publication; pub(crate) mod receive; mod repair; mod status; @@ -62,6 +63,7 @@ pub use enable::Enable; pub use explain::Explain; pub use identity::Identity; pub use lifecycle::Lifecycle; +pub(crate) use publication::finish_publisher_session; pub use status::AgentStatus; // Agent Command diff --git a/atomic-cli/src/commands/agent/publication.rs b/atomic-cli/src/commands/agent/publication.rs new file mode 100644 index 00000000..faaa4733 --- /dev/null +++ b/atomic-cli/src/commands/agent/publication.rs @@ -0,0 +1,184 @@ +//! Native finalization owned by the review command after its child process exits. + +use std::path::Path; + +use atomic_agent::event::{HookType, TurnEvent}; +use atomic_agent::turn::orchestrator::{ManagedRunContext, TurnOrchestrator}; +use atomic_agent::turn::session::SessionStore; +use atomic_core::change::session::SessionStatus; +use atomic_core::types::Hash; +use atomic_repository::Repository; + +use crate::error::{CliError, CliResult}; + +pub(crate) struct PublisherCompletion { + pub manifest: Hash, + pub attestations: Vec, +} + +fn refused(message: impl Into) -> CliError { + CliError::InvalidArgument { + message: message.into(), + } +} + +/// This is not a generic "mark ended" API. The caller must own and have waited +/// for the successful publisher process. Its hook-written run stamp and recorded +/// turns are checked before the real session-end state machine is dispatched. +pub(crate) fn finish_publisher_session( + root: &Path, + session_id: &str, + run_id: &str, + job_id: &str, + identity: &str, + view: &str, +) -> CliResult { + let repo = Repository::open(root).map_err(CliError::Repository)?; + let store = + SessionStore::new(repo.dot_dir().join("sessions")).map_err(|e| refused(e.to_string()))?; + let session = store + .load(session_id) + .map_err(|e| refused(e.to_string()))? + .ok_or_else(|| { + refused("publisher produced no native hooked session; no completion can be asserted") + })?; + let stamp = session + .managed_run + .clone() + .ok_or_else(|| refused("publisher session has no managed-run binding"))?; + if stamp.run_id != run_id + || stamp.owner_agent != "atomic-review-publish" + || stamp.owner_session_id != job_id + || session.agent_name != "opencode" + || session.view_name != view + { + return Err(refused( + "publisher session/run/view binding does not match the owned process", + )); + } + if session.incomplete().is_some() { + return Err(refused( + "publisher execution is incomplete; preserve it for recovery", + )); + } + drop(repo); + let rt = tokio::runtime::Runtime::new().map_err(|e| refused(e.to_string()))?; + rt.block_on(async { + let mut orchestrator = TurnOrchestrator::new(root) + .await + .map_err(|e| refused(e.to_string()))?; + orchestrator.set_agent("opencode", "OpenCode"); + orchestrator.set_agent_identity(Some(identity.to_string())); + orchestrator.set_managed_run(ManagedRunContext { + stamp, + view: Some(view.to_string()), + }); + orchestrator.set_journal_sink(super::provenance_rpc::sink_for(root)); + let result = orchestrator + .dispatch(TurnEvent::new(session_id, HookType::SessionEnd)) + .await + .map_err(|e| refused(format!("publisher session_end failed: {e}")))?; + if result.incomplete.is_some() { + return Err(refused( + "publisher session_end retained incomplete execution; publication refused", + )); + } + Ok(()) + })?; + let repo = Repository::open(root).map_err(CliError::Repository)?; + let session = store + .load(session_id) + .map_err(|e| refused(e.to_string()))? + .ok_or_else(|| refused("publisher runtime completion disappeared"))?; + if session.turn_count == 0 + || session.recorded_change_hashes.is_empty() + || session.is_turn_active() + { + return Err(refused( + "publisher session_end did not flush nonempty completed review evidence", + )); + } + let (record, _) = repo + .get_session_ledger(session_id) + .map_err(CliError::Repository)? + .ok_or_else(|| refused("publisher completion is missing from the native ledger"))?; + if record.status != SessionStatus::Ended || record.ended_at.is_none() { + return Err(refused( + "publisher session_end did not produce a completed native session", + )); + } + let manifest = repo + .get_session_head(session_id) + .map_err(CliError::Repository)? + .ok_or_else(|| refused("publisher session_end produced no immutable session manifest"))?; + let identities = atomic_identity::IdentityStore::open_default_existing() + .map_err(|e| refused(e.to_string()))?; + let signer = identities + .load_by_name(identity) + .map_err(|e| refused(e.to_string()))?; + let did = atomic_canonical::did::did_for_public_key(&signer.public_key); + let mut attestations = std::collections::BTreeSet::new(); + for change in &session.recorded_change_hashes { + let covering = repo + .find_attestations_for_change(change) + .map_err(CliError::Repository)?; + let mut verified = false; + for (hash, attestation) in covering { + if attestation.session_id == session_id { + if attestation.signer_did() != Some(did.as_str()) + || !attestation.verify_with_did(signer.public_key.as_bytes()) + || !attestation.changes_covered.contains(change) + { + return Err(refused("publisher has invalid or differently signed same-session attestation evidence")); + } + verified = true; + attestations.insert(hash); + } + } + if !verified { + return Err(refused("publisher session_end lacks native review-key-signed coverage; completion is not publishable")); + } + } + Ok(PublisherCompletion { + manifest, + attestations: attestations.into_iter().collect(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use atomic_agent::turn::session::{AgentSession, ManagedRunStamp}; + + #[test] + fn absent_native_hook_evidence_cannot_be_finalized() { + let dir = tempfile::tempdir().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + assert!( + finish_publisher_session(dir.path(), "missing", "run", "job", "reviewer", "dev") + .is_err() + ); + assert!(repo.get_session_ledger("missing").unwrap().is_none()); + } + + #[test] + fn another_managed_job_cannot_be_relabelled_as_this_publishers_completion() { + let dir = tempfile::tempdir().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + let store = SessionStore::new(repo.dot_dir().join("sessions")).unwrap(); + let mut session = AgentSession::new("publisher", "opencode", "OpenCode"); + session.view_name = "dev".into(); + session.managed_run = Some(ManagedRunStamp { + run_id: "run".into(), + owner_agent: "atomic-review-publish".into(), + owner_session_id: "different-job".into(), + work_item_id: None, + }); + store.save(&session).unwrap(); + assert!( + finish_publisher_session(dir.path(), "publisher", "run", "job", "reviewer", "dev") + .is_err() + ); + assert!(!store.load("publisher").unwrap().unwrap().is_ended()); + } +} diff --git a/atomic-cli/src/commands/intent/graph.rs b/atomic-cli/src/commands/intent/graph.rs index bf0b7055..3b1d7a7a 100644 --- a/atomic-cli/src/commands/intent/graph.rs +++ b/atomic-cli/src/commands/intent/graph.rs @@ -5,6 +5,7 @@ //! Use `--details` for complete text and canonical relationships, `--json` for //! machine-readable facts, or `--html` for the interactive browser graph. +use crate::output::html::write_and_open_html; use crate::{ commands::Command, error::{CliError, CliResult}, @@ -115,42 +116,6 @@ impl Command for IntentGraph { } } -fn write_and_open_html( - html: &str, - output: Option<&std::path::Path>, - open_browser: impl FnOnce(&str) -> std::io::Result<()>, -) -> CliResult { - use std::io::Write; - - let path = match output { - Some(path) => { - std::fs::write(path, html)?; - path.to_path_buf() - } - None => { - // Keep the file after the process exits so asynchronous browsers - // can load it. Unique names avoid replacing another open graph. - let path = std::env::temp_dir() - .join(format!("atomic-intent-graph-{}.html", uuid::Uuid::new_v4())); - let mut file = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&path)?; - file.write_all(html.as_bytes())?; - path - } - }; - let path = std::fs::canonicalize(path)?; - let url = url::Url::from_file_path(&path).map_err(|_| CliError::InvalidArgument { - message: format!("cannot convert HTML path to a file URL: {}", path.display()), - })?; - println!("Wrote intent graph to {}", path.display()); - if let Err(error) = open_browser(url.as_str()) { - eprintln!("Could not open a browser: {error}. Open {url} manually."); - } - Ok(path) -} - fn annotate(graph: &Graph, nodes: &mut [atomic_core::KgNode]) { for node in nodes { let role = if node.id == graph.root { diff --git a/atomic-cli/src/commands/mod.rs b/atomic-cli/src/commands/mod.rs index 120afaeb..d60feb32 100644 --- a/atomic-cli/src/commands/mod.rs +++ b/atomic-cli/src/commands/mod.rs @@ -90,6 +90,7 @@ pub mod record; pub mod remove; pub mod repo; pub mod restore; +pub mod review; pub mod revise; pub(crate) mod rpc; pub mod sandbox; @@ -170,6 +171,7 @@ pub use remote::Remote; pub use remove::Remove; pub use repo::Repo; pub use restore::Restore; +pub use review::Review; pub use revise::Revise; pub use sandbox::Sandbox; pub use server::ServerCmd; diff --git a/atomic-cli/src/commands/review/analysis.rs b/atomic-cli/src/commands/review/analysis.rs new file mode 100644 index 00000000..02aaee99 --- /dev/null +++ b/atomic-cli/src/commands/review/analysis.rs @@ -0,0 +1,725 @@ +//! Adapt recorded source inspection to Atomic's analyzer-neutral contract. + +use std::collections::BTreeMap; + +use atomic_audit::extract::{self, ExtractionConfig, FileChange, Source}; +use atomic_audit::structural::{self as review, Rule, StructuralInspection}; +use atomic_canonical::review_finding::{ + AnalysisReport, Check, CheckStatus, Confidence, Evidence, EvidenceKind, Introduction, + IntroductionStatus, Location, ReviewFinding, RuleReference, Severity, SourceSide, SCHEMA, +}; +use atomic_core::{ + change::Change, + crdt::TrunkOp, + types::{Base32, Hash}, +}; +use atomic_repository::Repository; +use atomic_semantic::{Language, ParserRegistry}; + +const ANALYZER: &str = "atomic-audit"; + +fn empty_report() -> AnalysisReport { + AnalysisReport { + schema: SCHEMA.into(), + analyzer: ANALYZER.into(), + analyzer_version: format!( + "{};rules={}", + atomic_audit::VERSION, + review::RULESET_VERSION + ), + checks: vec![], + findings: vec![], + metrics: vec![], + metric_diagnostics: vec![], + metric_comparison_scope: vec![], + excluded_metadata_paths: vec![], + } +} + +pub(super) fn analyze_change( + repo: &Repository, + change: &Change, + hash: &Hash, + paths: &[String], + selected: bool, + on_current_view: bool, + registry: &mut ParserRegistry, +) -> AnalysisReport { + let mut report = empty_report(); + let change_id = hash.to_base32(); + let mut metric_changes = Vec::new(); + let mut metric_bytes = ExtractionConfig::default().max_total_bytes; + for path in paths { + if atomic_repository::is_vault_path(path) { + if selected { + report.excluded_metadata_paths.push(path.clone()); + } + continue; + } + let skip = if !selected { + Some("Dependency context only; not a selected review root") + } else if !on_current_view { + Some("Off current view; exact before/after content not inspected") + } else if Language::detect(path).is_none() { + Some("Unsupported language; no structural or anti-slop rules executed") + } else { + None + }; + if let Some(reason) = skip { + checks(&mut report, &change_id, path, CheckStatus::Skipped, reason); + if selected { + metric_changes.push(FileChange { + path: path.clone(), + before: Source::Unavailable(reason.into()), + after: Source::Unavailable(reason.into()), + }); + } + continue; + } + match repo.get_file_content_after_change(path, hash) { + Ok(Some(after)) => { + let before = repo.get_file_content_before_change(path, hash); + let added = change.file_ops().iter().any(|ops| { + ops.path() == path && matches!(ops.trunk_op(), Some(TrunkOp::Create { .. })) + }); + inspect_content( + &mut report, + registry, + &change_id, + path, + before + .as_ref() + .map(|value| value.as_deref()) + .map_err(|error| error.to_string()), + &after, + added, + ); + metric_changes.push(FileChange { + path: path.clone(), + before: metric_source( + before.map_err(|error| error.to_string()), + &mut metric_bytes, + ), + after: metric_source(Ok(Some(after)), &mut metric_bytes), + }); + } + Ok(None) => { + checks( + &mut report, + &change_id, + path, + CheckStatus::Skipped, + "No recorded after-content; structural after-side checks skipped", + ); + metric_changes.push(FileChange { + path: path.clone(), + before: metric_source( + repo.get_file_content_before_change(path, hash) + .map_err(|error| error.to_string()), + &mut metric_bytes, + ), + after: Source::Absent, + }); + } + Err(error) => { + let reason = format!("Recorded after-content unavailable: {error}"); + checks(&mut report, &change_id, path, CheckStatus::Error, &reason); + metric_changes.push(FileChange { + path: path.clone(), + before: Source::Unavailable(reason.clone()), + after: Source::Unavailable(reason), + }); + } + } + } + if selected { + match extract::extract_changes(&metric_changes, registry, &ExtractionConfig::default()) { + Ok(metrics) => { + report.metrics = metrics.metrics; + report.metric_diagnostics = metrics.diagnostics; + report.metric_comparison_scope = metrics.comparison_paths; + } + Err(reason) => report.metric_diagnostics.push(reason.into()), + } + } + report +} + +pub(super) const SNAPSHOT_BASELINE: &str = + "View snapshot has no before revision; no change introduction or delta is inferred"; + +/// Inspect each supplied live path once, using the exact named-view renderer. +pub(super) fn analyze_snapshot( + repo: &Repository, + view: &str, + reference: &str, + paths: &[String], +) -> Result<(AnalysisReport, BTreeMap), atomic_repository::RepositoryError> { + let mut report = empty_report(); + let mut registry = ParserRegistry::new(); + let mut files = Vec::new(); + let mut eligible = Vec::new(); + // Whole-view mode must not inherit the per-change 128-file/8-MiB limits. + // Cross-file clone work and all other limits remain explicit and bounded. + let config = ExtractionConfig { + max_files: paths.len(), + max_total_bytes: 128 * 1024 * 1024, + max_total_tokens: 2_000_000, + max_total_subjects: 65_536, + max_clone_pairs: 2_000_000, + ..Default::default() + }; + let mut remaining = config.max_total_bytes; + let mut content_hashes = BTreeMap::new(); + for path in paths { + if atomic_repository::is_vault_path(path) { + report.excluded_metadata_paths.push(path.clone()); + } else if Language::detect(path).is_none() { + let reason = "Unsupported language; no structural or anti-slop rules executed"; + checks(&mut report, reference, path, CheckStatus::Skipped, reason); + files.push(FileChange { + path: path.clone(), + before: Source::Unavailable(SNAPSHOT_BASELINE.into()), + after: Source::Unavailable(reason.into()), + }); + } else { + eligible.push(path.clone()); + } + } + repo.for_each_file_content_and_kind_on_view(&eligible, view, |path, bytes, kind| { + let bytes = bytes.ok_or_else(|| atomic_repository::RepositoryError::Output(format!("Recorded view source disappeared while inspecting '{path}'")))?; + let reason = if kind != Some(atomic_core::change::InodeKind::Regular) { + Some("Recorded symlink/non-regular source is not followed or audited as code") + } else if bytes.len() > atomic_semantic::MAX_SOURCE_BYTES || bytes.len() > remaining { + Some("View snapshot source budget exceeded (1 MiB per file, 128 MiB total); source not silently truncated") + } else { None }; + let after = if let Some(reason) = reason { + checks(&mut report, reference, path, CheckStatus::Skipped, reason); + Source::Unavailable(reason.into()) + } else { + remaining -= bytes.len(); + content_hashes.insert(path.to_string(), Hash::of(&bytes).to_base32()); + match parse(&mut registry, path, &bytes) { + Ok(parsed) => inspect_parsed(&mut report, reference, path, parsed, Err(SNAPSHOT_BASELINE.into()), true), + Err(reason) => checks(&mut report, reference, path, CheckStatus::Skipped, &reason), + } + Source::from_bytes(bytes) + }; + // Treat every current token as in scope for the whole-view clone scan. + // Restore the unavailable historical baseline below; no change delta is + // inferred from this extraction-only absent side. + files.push(FileChange { path:path.into(), before:Source::Absent, after }); + Ok(()) + })?; + files.sort_by(|a, b| a.path.cmp(&b.path)); + match extract::extract_changes(&files, &mut registry, &config) { + Ok(metrics) => { + report.metrics = metrics.metrics; + for metric in &mut report.metrics { + metric.observation.before = atomic_audit::Measurement::Unavailable { + reason: SNAPSHOT_BASELINE.into(), + }; + metric.before_location = None; + metric.delta = None; + } + report.metric_diagnostics = metrics.diagnostics; + report.metric_comparison_scope = metrics.comparison_paths; + } + Err(reason) => report.metric_diagnostics.push(reason.into()), + } + Ok((report, content_hashes)) +} + +fn metric_source(bytes: Result>, String>, remaining: &mut usize) -> Source { + match bytes { + // The caller has already verified selected change membership in the + // source view. A successful None is recorded absence, not a failed read. + Ok(None) => Source::Absent, + Ok(Some(bytes)) + if bytes.len() <= atomic_semantic::MAX_SOURCE_BYTES && bytes.len() <= *remaining => + { + *remaining -= bytes.len(); + Source::from_bytes(bytes) + } + Ok(Some(_)) => Source::Unavailable("Recorded metric source byte budget exceeded".into()), + Err(reason) => Source::Unavailable(reason), + } +} + +fn checks( + report: &mut AnalysisReport, + change: &str, + path: &str, + status: CheckStatus, + detail: &str, +) { + for rule in Rule::ALL { + report.checks.push(Check { + change: change.into(), + path: path.into(), + rule: rule.id().into(), + status: status.clone(), + detail: detail.into(), + }); + } +} + +fn parse( + registry: &mut ParserRegistry, + path: &str, + bytes: &[u8], +) -> Result { + if bytes.contains(&0) { + return Err("Binary content is not inspected".into()); + } + let source = std::str::from_utf8(bytes).map_err(|_| "Non-UTF-8 content is not inspected")?; + review::inspect(registry, path, source).map_err(str::to_owned) +} + +fn inspect_content( + report: &mut AnalysisReport, + registry: &mut ParserRegistry, + change: &str, + path: &str, + before: Result, String>, + after: &[u8], + added: bool, +) { + let after = match parse(registry, path, after) { + Ok(after) => after, + Err(reason) => { + checks(report, change, path, CheckStatus::Skipped, &reason); + return; + } + }; + let baseline = match before { + Ok(Some(bytes)) => parse(registry, path, bytes), + Ok(None) if added => Ok(StructuralInspection { + issues: Vec::new(), + has_syntax_errors: false, + ambiguous_manageability_subjects: Vec::new(), + }), + Ok(None) => Err("No before-content and no explicit file-creation operation".into()), + Err(reason) => Err(format!("Recorded before-content unavailable: {reason}")), + }; + inspect_parsed(report, change, path, after, baseline, false); +} + +fn inspect_parsed( + report: &mut AnalysisReport, + change: &str, + path: &str, + after: StructuralInspection, + baseline: Result, + snapshot: bool, +) { + if !snapshot { + report.checks.push(Check { + change: change.into(), + path: path.into(), + rule: "recorded-baseline".into(), + status: if baseline.is_ok() { + CheckStatus::Completed + } else { + CheckStatus::Error + }, + detail: baseline + .as_ref() + .map(|_| "Recorded baseline inspected".into()) + .unwrap_or_else(Clone::clone), + }); + } + let language = Language::detect(path).expect("successful parse has a detected language"); + for rule in Rule::ALL { + let (status, detail) = if !rule.supports(language) { + ( + CheckStatus::Skipped, + "Rule not implemented for this language", + ) + } else if rule != Rule::Syntax && after.has_syntax_errors { + ( + CheckStatus::Skipped, + "Syntax recovery prevents reliable anti-slop inspection", + ) + } else if rule == Rule::Manageability && !after.ambiguous_manageability_subjects.is_empty() + { + (CheckStatus::Skipped, "Ambiguous named-function identities excluded from joint manageability; unique subjects were checked") + } else { + (CheckStatus::Completed, rule.coverage()) + }; + report.checks.push(Check { + change: change.into(), + path: path.into(), + rule: rule.id().into(), + status, + detail: detail.into(), + }); + } + // Compare exact node text as a multiset, not line numbers. A line-only move + // is pre-existing; an extra identical occurrence is a new candidate. This + // is syntactic attribution, not a proof of behavioral regression. + let mut counts = BTreeMap::new(); + if let Ok(before) = &baseline { + for issue in &before.issues { + *counts + .entry((issue.rule, issue.source.as_str())) + .or_insert(0usize) += 1; + } + } + for issue in &after.issues { + // Manageability is joint source/metric evidence, not a threshold on an + // isolated measurement. Existing equal/improving burden is not a new + // manageability finding just because unrelated tokens changed. + let prior_burden = issue.manageability.as_ref().and_then(|current| { + baseline.as_ref().ok().and_then(|before| { + before + .issues + .iter() + .filter_map(|issue| issue.manageability.as_ref()) + .find(|before| before.subject == current.subject) + }) + }); + if let (Some(current), Some(before)) = (&issue.manageability, prior_burden) { + if current.complexity.saturating_sub(before.complexity) < 3 + && current.nesting <= before.nesting + { + continue; + } + } + let (status, rationale) = match &baseline { + Err(reason) => (IntroductionStatus::Unknown, reason.clone()), + Ok(before) if before.has_syntax_errors && issue.rule != Rule::Syntax => ( + IntroductionStatus::Unknown, + "Before-content has syntax errors; anti-slop baseline not evaluated".into(), + ), + Ok(before) if before.has_syntax_errors && issue.rule == Rule::Syntax => { + if !issue.source.is_empty() + && before + .issues + .iter() + .any(|old| old.rule == issue.rule && old.source == issue.source) + { + ( + IntroductionStatus::No, + "The same observed syntax error existed in recorded before-content".into(), + ) + } else { + (IntroductionStatus::Unknown, "Both revisions have syntax errors but the observed error changed; introduction cannot be established".into()) + } + } + Ok(before) if issue.manageability.as_ref().is_some_and(|current| before.ambiguous_manageability_subjects.contains(¤t.subject)) => (IntroductionStatus::Unknown, "Recorded before-side function identity is ambiguous; joint burden introduction cannot be established".into()), + Ok(_) if issue.manageability.is_some() => ( + IntroductionStatus::Yes, + if let Some(before) = prior_burden { + format!("Recorded before-side joint burden for {}: {} code lines, complexity {}, nesting {}; the after-side adds at least 3 decision points or a nesting level while still meeting the joint review policy", before.subject,before.code_lines,before.complexity,before.nesting) + } else { + "Joint long-body/control-flow review trigger was absent in the successfully inspected recorded before-side".into() + }, + ), + Ok(_) => { + let count = counts + .entry((issue.rule, issue.source.as_str())) + .or_default(); + if *count > 0 { + *count -= 1; + (IntroductionStatus::No, "Matching rule and exact AST node text existed before this change (line shifts ignored)".into()) + } else if baseline.as_ref().is_ok_and(|before| { + before.issues.iter().any(|old| old.rule == issue.rule) + && !before + .issues + .iter() + .any(|old| old.rule == issue.rule && old.source == issue.source) + }) { + (IntroductionStatus::Unknown, "The same rule already matched different node text before this change; cannot distinguish a new issue from an edited existing match".into()) + } else { + (IntroductionStatus::Yes, "Additional AST rule match relative to recorded before-content; behavioral impact still requires review".into()) + } + } + }; + let severity = match issue.rule { + Rule::UnnecessaryMachinery | Rule::Manageability | Rule::DuplicatedBehavior => { + Severity::Low + } + _ => Severity::Medium, + }; + let summary = issue.rule.summary(); + let explanation = atomic_audit::AUDIT_CARDS + .iter() + .find(|card| card.id == issue.rule.id()) + .expect("every implemented rule has a card") + .question; + let correction = issue.rule.correction(); + let confidence = Confidence::Medium; + let reference = format!("{change}:{path}:{}-{}", issue.start_line, issue.end_line); + let mut finding = ReviewFinding { + analyzer: ANALYZER.into(), + change: change.into(), + summary: summary.into(), + locations: vec![Location { + path: path.into(), + side: SourceSide::After, + start_line: issue.start_line, + end_line: issue.end_line, + }], + requirement_or_rule: RuleReference { + id: issue.rule.id().into(), + explanation: explanation.into(), + }, + evidence: vec![ + Evidence { + kind: EvidenceKind::Source, + reference: reference.clone(), + observation: format!( + "AST node excerpt for {}: {}", + issue.rule.id(), + issue.source.chars().take(1024).collect::() + ), + }, + Evidence { + kind: EvidenceKind::Source, + reference: reference.clone(), + observation: issue.detail.clone(), + }, + Evidence { + kind: EvidenceKind::Diff, + reference, + observation: rationale.clone(), + }, + ], + introduced_by_change: Introduction { status, rationale }, + severity, + confidence, + proposed_correction: correction.into(), + acceptance_criteria: Vec::new(), + }; + if snapshot { + finding + .evidence + .retain(|evidence| evidence.kind != EvidenceKind::Diff); + finding.evidence.push(Evidence { + kind: EvidenceKind::Reference, + reference: format!("urn:atomic:audit-observation:{}",Hash::of(issue.source.as_bytes()).to_base32()), + observation: "Fingerprint of the exact locally inspected AST node bytes, before display clipping; not an authored change identity.".into(), + }); + } + // This is a presence gate, not an automated acceptance verdict. + if let Err(error) = finding.validate() { + report.checks.push(Check { + change: change.into(), + path: path.into(), + rule: issue.rule.id().into(), + status: CheckStatus::Error, + detail: error.into(), + }); + } else { + report.findings.push(finding); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn analyze(before: Result, String>, after: &[u8], added: bool) -> AnalysisReport { + let mut report = AnalysisReport { + schema: SCHEMA.into(), + analyzer: ANALYZER.into(), + analyzer_version: "test".into(), + checks: vec![], + findings: vec![], + metrics: vec![], + metric_diagnostics: vec![], + metric_comparison_scope: vec![], + excluded_metadata_paths: vec![], + }; + inspect_content( + &mut report, + &mut ParserRegistry::new(), + "recorded-hash", + "lib.rs", + before, + after, + added, + ); + report + } + + #[test] + fn manageability_reports_new_or_worsened_joint_burden_not_unchanged_counts() { + let function = |lines: usize, branches: usize| { + let mut source = String::from("fn large(x:i32) {\n"); + for i in 0..branches { + source.push_str(&format!("if x == {i} {{ work(); }}\n")); + } + for _ in 0..lines { + source.push_str("work();\n"); + } + source.push_str("}\n"); + source + }; + let before = function(100, 15); + let same_burden = before.replace("work()", "other()"); + let unchanged = analyze(Ok(Some(before.as_bytes())), same_burden.as_bytes(), false); + assert!(!unchanged + .findings + .iter() + .any(|finding| finding.requirement_or_rule.id == "anti-slop.manageability")); + for after in [function(101, 15), function(120, 15), function(100, 16)] { + let report = analyze(Ok(Some(before.as_bytes())), after.as_bytes(), false); + assert!( + !report + .findings + .iter() + .any(|finding| finding.requirement_or_rule.id == "anti-slop.manageability"), + "trivial or straight-line growth must not become a finding" + ); + } + let after = function(120, 18); + let increased = analyze(Ok(Some(before.as_bytes())), after.as_bytes(), false); + let finding = increased + .findings + .iter() + .find(|finding| finding.requirement_or_rule.id == "anti-slop.manageability") + .unwrap(); + assert_eq!(finding.introduced_by_change.status, IntroductionStatus::Yes); + assert!(finding + .evidence + .iter() + .any(|evidence| evidence.observation.contains("atomic.manageability.v1"))); + assert!(finding + .introduced_by_change + .rationale + .contains("before-side joint burden")); + let unavailable = analyze(Err("baseline unavailable".into()), after.as_bytes(), false); + assert_eq!( + unavailable + .findings + .iter() + .find(|finding| finding.requirement_or_rule.id == "anti-slop.manageability") + .unwrap() + .introduced_by_change + .status, + IntroductionStatus::Unknown + ); + let ambiguous_before = format!("#[cfg(unix)]\n{before}\n#[cfg(windows)]\n{before}"); + let ambiguous = analyze( + Ok(Some(ambiguous_before.as_bytes())), + after.as_bytes(), + false, + ); + assert_eq!( + ambiguous + .findings + .iter() + .find(|finding| finding.requirement_or_rule.id == "anti-slop.manageability") + .unwrap() + .introduced_by_change + .status, + IntroductionStatus::Unknown + ); + } + + #[test] + fn introduced_and_preexisting_matches_use_recorded_baseline_not_line_numbers() { + let report = analyze( + Ok(Some(b"fn f() { todo!(); }")), + b"\nfn f() { todo!(); todo!(); }", + false, + ); + assert_eq!(report.findings.len(), 2); + assert_eq!( + report.findings[0].introduced_by_change.status, + IntroductionStatus::No + ); + assert_eq!( + report.findings[1].introduced_by_change.status, + IntroductionStatus::Yes + ); + assert!(report + .findings + .iter() + .all(|finding| finding.validate().is_ok())); + } + + #[test] + fn unknown_baseline_is_not_an_introduced_issue_or_a_clean_result() { + for before in [ + Ok(None), + Err("unavailable".into()), + Ok(Some(b"\xff".as_slice())), + ] { + let report = analyze(before, b"fn f() { todo!(); }", false); + assert_eq!( + report.findings[0].introduced_by_change.status, + IntroductionStatus::Unknown + ); + assert!(report + .checks + .iter() + .any(|check| check.status == CheckStatus::Error)); + } + let added = analyze(Ok(None), b"fn f() { todo!(); }", true); + assert_eq!( + added.findings[0].introduced_by_change.status, + IntroductionStatus::Yes + ); + } + + #[test] + fn editing_an_existing_placeholder_does_not_prove_it_was_introduced() { + let report = analyze( + Ok(Some(b"fn f() { todo!(); }")), + b"fn f() { todo!(\"reason\"); }", + false, + ); + assert_eq!( + report.findings[0].introduced_by_change.status, + IntroductionStatus::Unknown + ); + } + + #[test] + fn clean_and_unsupported_checks_are_distinct_and_binary_is_not_clean() { + let clean = analyze(Ok(None), b"fn f() {}", true); + assert!(clean.findings.is_empty()); + assert!(clean.checks.iter().any( + |check| check.rule == "structural.syntax" && check.status == CheckStatus::Completed + )); + assert!(clean + .checks + .iter() + .any(|check| check.rule == "anti-slop.empty-catch" + && check.status == CheckStatus::Skipped)); + let binary = analyze(Ok(None), b"\x00\xff", true); + assert!(binary.findings.is_empty()); + assert!(binary + .checks + .iter() + .all(|check| check.status == CheckStatus::Skipped)); + } + + #[test] + fn syntax_recovery_does_not_claim_anti_slop_checks_passed() { + let broken = analyze(Ok(None), b"fn f( { todo!();", true); + assert!(broken + .findings + .iter() + .all(|finding| finding.requirement_or_rule.id == "structural.syntax")); + assert!(broken + .checks + .iter() + .any(|check| check.rule == "anti-slop.rust-placeholder" + && check.status == CheckStatus::Skipped)); + let repaired = analyze(Ok(Some(b"fn f( { todo!();")), b"fn f() { todo!(); }", false); + assert_eq!( + repaired.findings[0].introduced_by_change.status, + IntroductionStatus::Unknown + ); + let changed_error = analyze(Ok(Some(b"fn old( {")), b"fn different[ {", false); + assert_eq!( + changed_error.findings[0].introduced_by_change.status, + IntroductionStatus::Unknown + ); + } +} diff --git a/atomic-cli/src/commands/review/assets/README.md b/atomic-cli/src/commands/review/assets/README.md new file mode 100644 index 00000000..9803d275 --- /dev/null +++ b/atomic-cli/src/commands/review/assets/README.md @@ -0,0 +1,21 @@ +# Atomic review branding + +The wordmark is the actual asset used by the navigation on : + +- Source: `https://atomic.dev/assets/build/atomic-logo-BQhfUDZM.png?v=20260512-1` +- Original PNG: 1867 × 536, 263237 bytes. +- Original SHA-256: `333c59802d686fa3726f53c5c164acc60d25185c73af25ed6183493326429513`. +- Packaged PNG: downsampled proportionally with macOS `sips -Z 560` to 560 × 160; + 37621 bytes. No mark or lettering was redrawn. +- Packaged SHA-256: `5780bb538faeca8a2644f24a5bef60a503a6c2fc4c9eb2f80edef03137e3102c`. + +Palette/font-stack source: +`https://atomic.dev/assets/build/main-BnTJuKRf.css`. +Verified website tokens used here: background `#07041a`, raised `#0c0726` / +`#130a36`, foreground `#f4eefe`, pink `#ff0a8c`, violet `#8c2eff`, green `#4ade80` +and terminal warning `#ffd166`. Status tints retain readable text contrast. + +The website's `GT America` / `GT America Mono` family names are preferred when +installed, with local system fallbacks. No commercial font files, webfont loader, +analytics, website JavaScript or remote asset reference is bundled or loaded. +The PNG is embedded as a data URL in each self-contained offline report. diff --git a/atomic-cli/src/commands/review/assets/atomic-logo.png b/atomic-cli/src/commands/review/assets/atomic-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..0d8dea68c50a8b11041ba2df7c7a6cff70f90112 GIT binary patch literal 37621 zcmZs@1yo$kvM@S0gaE-^f(CbjyK8WFcV}Sm1b24}?k>Rz?(Xh`yX(uj_n!0R{OiqH zdv@>Ys_tFgCEZm$6Z%bF0_g+Z2LJ$oBqb@T1OPxX{VC_b!~Xe3gI9z3bAvV)k`n>| zYN8Qe4FB~^Vl1g72LOO50RX=M0O08l$nO9EaQ#DgWB>qgrvL!h4jCJG*3`w2#NF1$&Y9btkMw^qxc`*@ z1!g2A`5zP)Yd%s9xo;#Q_D-fG91KhhOr-oDNJvO{olMNQl|;q=kNnRQAE||livu?! zBM=B=0J1XJJDD>wb8&GoGO;kSu+aa(pm+ALb1`(Mw{s@@-$wr3j;N`#v6H2Pi>19C z$-mk)G_rSf;UgveS4aQ({O^03x?BF!lb!SbvGs>R#(&i?GBYqS{-^Cfq`d!va*Np8 z*gGjZ7#f@MGxPor;@_Zudih`MZL)S{V%+iC^7x>hxHU8$P^RGp^LDFolGWl@~S24R{m+Ae3W0Gg2 z&=!YjrFwn-#?HD91i^_BuJSh*Y)1a(bbg9#d(7IbYc}(vaY&;av}1U+({0GsE0tqG zjkKDULPNtVXyU2ShTzmh^TZ0?A5V5sYqPF?THH#o1o`qg`Bh`m_?(qRwn+84Ys*Pc zRz!>|leG}E0?UR4rrsPEoVD}g)zdS_HU?w!ZW}Fey5zY3J(%J(g2V4o-Oadc0!DnS z+@t%Ss8bPb*X$cZn1-_`@R!k~q~CWkYTfoVGK{9}1s!?^~LHn_w<*n`o}naz4Yz-x1Yfz$RqOpvt=8wa5D4aqJ>^4GOAxcYQ0AuxU9h9>#SSO zWTjX)wk#^gdl89M{v$`fs@BTseoBt8kSfoxD50Z=?n&-@eM{3C0B-?Zpz)*jCqxvA zo7VFNKt)|-p(cBOi@x06V~GFRg|uc6^B=i2FNC?`ca3l8Mp^Xp%s=I?G9g4<9C0#e zYG?;IIFQFCuJM$&dw&{af!C3gP`8rP%MrarrnAB&UsLFUTX#`yj6oxzw7}`qn1)P% za|wh;N)KotxCMARzpdKu$yh$oc9|``x*elGFN=96{4IA`j#!eK)Pe=Ylk3VG`U09DBW5vagmp zq^w)AykfwvVdDUUZY6YsedOUz}xZwfCX{Z zx+$y2f%N0j>HMWrl17wu-Icu7;*{AE2tb-@0Zo)p#_{b&tXhO6VH-_x5cwIMixg-h z3y@LWtkxScxG*7QzJ1y~hB2w16lFU^;K0*w90&O_uN1zUHdJ`JryF^c1oefN{@YG0 z641xoM=Se8iRu*cnKVM-Ya*LP4Y!!$cSl?I!G06#>@0XcrtX=%}b{!asMW`o&E%bE4Jgsvp32T`6D*K-UX2N zIWNO$ntpz6ma->dyI7rAbKA|(JlfOFtFGp5_=1z~4SCUkcq&!kM(h1v!=c4U9-0M2 zB=`5|nwk5@dV?`i&y3xc8=>YK^oy2`mlB@w2<~*wW)a@=w=LpvO4e55#(wz#6*Ii1 zvvjX;`Ry<-II+SYoqTomDnS8U)iV@+70~swc-mS(IFh`Oh}R_Wm{;rCuOsD~dXr+>tI3Bla*%FerF0 zk+GZMoplV>o_?w5_M(mSFTEM-h74uQ5T2Pbe$!-Ft})4!*z(&5kDHic)vg~9`yi5v zRIRi|rBp`0R_VoW`kaK|+I!mC5xTH)d@BP*eHk&HovhNTz{j=D(}?(N5`WY%r7k10 zcq*Ti{PyFOMWDSeX~Q=}caZfp>@Qo*VT%~CPe$eKHWJ!$aT5O;LfRJ3V=KSy@r4z` zb?Q|}iG#Q_r}BfDcv{5rblYPn1!~4kRy;hi)sU)gu8i%cSYnYqt=glx=*WczhiA^0 zu)I2bNzhgP#x$e9uRc-j+wuP5qeB1uw*5aIZjp`t+k}K&!V<3mA1~L!FT$1^REy4E zIvBtGB}BxPWzoNv=1`6aESt1fiHd4`5)%3&s&%!H`mUok>GvT6Alq3Uv=X;s)uMjU zAYkZ##`)teglC5UEY1TU`udqBwmiJC+VUQ|imEuRW$@n)wTsfszZct1w6CfG=xS$s z4a_zpJSUyLLe6Cf>z5)|FBz@3Tlbh0e zT99;p;IiRT&6b(sMK6A~HDGZ9oUkX8oJ)6}I4I@tjipknugZMz8_ysjy>IpJrw-0w zAVcDb{=&d|-^Rc7_6uG0p+-)YLS{X##Zbt=I3Jvtyx}Cab&ce+ZrrX%NoiY7n9^vl zO^^T*osspMeY+H5J*Vgu^K{!`+la{_HTlBy@l03WvDK~m%EPhsn68o)RK*QWZ5GF) z(H{O&#p#Ucac91UQe5Ca^PCc=dz<<0&%LI=2^V`8Lgu~O^asb zq4=9iSNF%RZWq5#rv(5z=&;%5`M0e4sA?7EM*fe4%ej4VwKRSBdvHmHzV-RNi?27Y zz@(E7rj_x|6)OXOp#x6&Q<(yT& z+cvb$lfOO46be3*Eg$c;B$}VFM0wFa+o{d?x@IGl?^<@EK$y52`_l)W8y*o8*56UZ zwwP7iR%ToOz~|6-?=o&&=$dJy``Czh4QOzYt1?rOQ_H!APVAvVu4ixg82b?3DXVQiw-W zkn{l{1;6bBZ6?PU(X(=iyWXh74@~xd8)qg{x|lmd^wNZ`5v4k)qSQ?N+Qyx2UGauY zJH6OmF7vrtkQD^W5|0nL$ZBk_rrEL8id8Q0h==bqRQ*fjzCcZua}U;CH=MMa%2;s^ z%1OYTi0#I>W@BaDh?z^R-Rzv*F*m59ju6nRGzqX4CydZ1GD?M~LAlYk_iY+G(>5=A zIyZDZDdt8+TH2L5-azJpGl&N#*j{|G6d?C#{0kfTC5V3QcDZKRj5 z%hRTi5{Btr?TT9(AZn7RT%YUEY?B#6Qu&XEHIUX6^s(-a|B=i<>l^h-!Dy69`D#9$=Z}|WKc;ytD5tWkvjdr>LA2;Qw-CY(4+ZQL z_&R-8lOOaz)!!v&c0}fHO@=@Vik)UziCG-lLOu`Zj_R5dyjfFD7DY&eV&uCHcM~Tc z{FYz^S>>1tS)vNF)9g+kt<9(lM@3bu^d8+3TSIy$LHIj9MyY%*QV>Q=68~}P2E&>p z=RI1LIb9=sqIzZ!dH^WK=}hr6L3Ry3nBpoxqG$n~{r2~GkQf!Y^7}H#qj@VY0!Ve4 zECT>^F3sPyR+vzk5iwmCd)t_Gx=v8Auws9!CG0XpxoZ902{-LVP9vNNVP=z*WkvgV zX-^>WP0)2(oJ2%Q5#1kY8ng^xyTf_n{kSIbx)uOB+j^Z^y=DDXYjdnNURSYsh(I_i zWm%93;a;=jhyHB^VsI7t8{3cOgc1o80+}|{Vi>+sj(B;a?=nlWcxpn{Em2=$ZuB9& zt5>pq{lZ!thNt`RZ$bU0VGu_jbEl2Yaw9VDO!Cb0mUtimU_2DU(b40~`*F1ELThVO zTt6a2n|>ZQi>LuWd*WGgA9?nz48Bf2oqsK}J-IPGbZqwa6mPn~39c2=zI{-;qu@ZNvJAWhRGw(8L*Gj4S$W_*0ZMJOM0xOLHq;1h#pU|+N@PhZ z)5=&B<45405qp{D2?0g-YgQxg-`Yenr;3h-b-8sMMUiP^)pTc8)J?~A*X)C5; zw5{d^SM|zrR`d^kNVs+?d{8U7gn`(3%N@o*NI^>U6qfx$>{G@W4RW^ZWVI5b0hGgb zwq_L)a?OG%b$ZBq_b3Au@6Cezv94R^m^IObk++eVW|6F~4*|lH%@PZpuVUkjPFrF6)|Q zjC<)?iTgAEj_IzU6*Xya7;6QGM}KDHaF~Mw{)Kds=^6R=t5Nnfxa$8h|96r2`9e-*#CwyR2SD2toFNtF3O$vXOF@~6ST+4}9E(01?y^Ot53CsLZ z88<1vU?AF5>Q5oTF~ZS9pe=_xLVBdVzPSQl%Ou0>wS_Rv3RRBgl~Y6i@IrJTmAFw*VNNv@mC;ky)=|TYqmvpGq!8tnpf_OGUUH2 zqS!v!UbT@`o22)BA-!VBIe^jr?)#g*>%Ar~)4PsVZ~s+##3ntEaK4$btx7mNxvMk& zsYWpg0^Pidzf?hqfKeCx_{${0fd*_VWeec$z)-6o8plp=)06PW6-$`BN4QG1ss5RL zZIjgLvO;q=Nq$amglkhoZ?iczy6bwuxII{_#6p#Mvn za=B+bOJ}^?(lvYC+SO%0RSfgZ&)o6X!EnAoX;6ab1^4#+G9HgKI>aglFW@N! z@I-MFZ9};Fg;zo9HHOqAizZ}{6(|mr4+z?jKA30R{uq3d>RiGGHfDKx2NbvsCy63v z&6#CVL8$5tn61Om^$cFZCV`yhQtZg0(HEX$j4GP?jB73D2gdHBXCf+2fCzp$-DE#m zzK28SlAqQ{yc~bz7QgtW*Qb}8U3QVz8wypIw@UzjSQ{zAfA-Ii^*RZ5` z-o0jAA~s+PnSZ_?w9t3XS&A7L$^zAKRcXQdgj1v6ATvnr%3sUzDo)blgexPpXJ0FM z`M;lhva1$NQC z+KJOmXr|!%qW?nuPpmE8z`wN4%B_63aLxXT_SNEyQ@Tx0x|)Doti6WoGOpxKOOv{I z594e}Q$_`Bm83GhG&KJ9FgOmuf<>$t?(F0Fa(`AGss*(_DL`K0`|3Z zoL3#?`C_bX+n**DKN$y%dmK-Vk_`4HQ>f%S*m4!sghbyfdn$j~Lq5|HcEG z(!Y(^+QR1SCY609Lax=8cnkG`-E{DA3$|>hM8~jve(tDv5V1+3%7FEPaZ$9zor=df z^nu(uHM0X9i1tp#@CrqTeL70?=}6axSA5Iq>1{nf0c|jrC~nVKo%N@%V1WwECn;^M z#(P;t6exVc<%EhsJqw7~2M zA8V-47h>DYq)Q|SEi;{vSOufa-EHNq$kURp6(gx0J}okGkn=JWX`!Sq%tdwQuTZe| z%j6Q(ly^$SArHCN@K>qRQL*$Ev<%ncc`7eg?c9ER?^8DI_`1RX?`d3L-q>V&jYg{U z4q4tKE>h`k)^?+j1rCYi#Y5khYVNJrV#xg%V97{!k8f?eNp^k0T9&*2_ePM33(FyU z?!rRmBz{1)?#_O5*=?47MjGv?l0hZnf{J_O!HIYxJkuiTZ7sr>|J~C1IaXlyRPlJL znaYi2DzIrs@IH(gI}&REDfME2J!C-ZSuNINYrdqW@uzx^$f%<$?NQO^Tg=HcYLN+J*^2YF)!_$Nz!y2rTtFkwZ$8-I~g%2~+ zBh5a*gJ1jzM=&$_+IT>L)hc#cB#(cra2*A>{P-@l@$mWMxz6mr_t<};*h$(s9TRvx z-)xq3yY{E;HwX3N^tt0idh%c%^N`}et{2}~`8_?)IIap}P3P+n$Di9H?#)c>kNv1C z{wUvpa-FN?8TmQybf6Za8gASN2=qi!K~!Is2~NF}tP9n^*-sgRNbOdT2yjS>@-Z^* z8>mS^k z6Ty)g&cF|C2My44*qOr5o(^g3zr%xyX=3mgg(Fp9G!x2d3o#QJ=7LnP=lVdw$Tf6t z0rZJTFPc(I^ZCi(+S<1H=s3(hOAm>*Sb?Lw;A_L=CBKBPPCeI}Wv4e}ZD4}uQB?~3 zBmZlsq;!l5Dca1T0e%m;oyA#L7(ceHVxBP^d;ODVpYdQ^e!aid9^KYI2x1fspEo3U zu01`IN|$pshboHh{E_7;d?eGL@TXGoiHBzG@23f4;92zRmJ7 z3cX7n1}Sq*QWLKtQph2+L0ijAc`&$#cfxe6`nqc0`3Zw$zX~$+Fkw!JqRMe7HhuZq zXFvhoE2<4-Z&vj>2LW+&Sm$3W=56|zTN7h~b0IytLB_}XsZ?;gC=;q~7Eebx$s7oA zpj^GYdbniU{m-`f4biQUkm1TS5AHOAZ@J=_ZFyY~+KgKT^NghovqW~faLb6gM24BA z^yu1l$w^ykSxO>Sujfm30YyT9QTlZV@o<AH14FK>FODUl6 z#>nMZGdZkRw$7Px!{7(F`t=_9@SHlf7)63qbtgu_xQJ_(mfD(EdUbgH?kD@*Z`(Po z{Qr`p0}B&BA#HCAK(aj7NDU>hW?EjJIAuH2QmG8vRW@1m!=?xTn&B1ysK^efS(UDKxdqxPzxDl^YtSsB^7lZD&P0w!g93ePYv$sC z*T?o@>(hE=vt^HkpNKoJo5|LvPZjP`J01rOBuMZD(A;V!!J0LO8iwq|+7i?m^vAqi z48g#~h6Fu?ldrWp(>c|t zblyG-V*T9*6@ zoeD&6LgW4~zvfHfp+>@(I#y3{EVRdi`4qZ9)FXIqRoCK!JP~#=U2o*l@w?E|A>Q8D zS!yftdc`LMlzSf6s7&AFWe?Qd2>SAKeRr$#fu&BiA08iN;}<9nj| zZywk@V7JRv3*vOH2{Uhuq6cPD=sG^>ZwgDG+oj9hhX!6WmqM9YsS#dL6!(^s$xoX* zhDpJ8P&y9gW0STg=kC=bEkEz}qL*sf-;Tc5uYw+Hy(^px=+mXXSRTvcuV!7k3GJ_s z0`2!(QFczde-S#`T_)LBLaX|x3`>1@QXXCA9YHrwya}BM`yB-}y4ML?aUP+0=S!^m zjK^cEz3&M@aw_LHu$nT2QyCrQGJ>K`D2+r%i+stIwPHF0(ts=v3@?2VEBq(N#AfW@ zf?Sd`S>X1TBr^Yuo(s4Hv%^bX@Kca3F(eBk7jKsC(B&Dq~ZxJ5mP6|Fwr(0P2@UQHNj3tH<|CUxRQF zFGl5)_$gzJS(>P{3&|w3yWJT)tzllhX6he=v#VJ>Xly-ha}tTb5Wdk!%TEKZQVrT#6VmQg=nzBh-{K7wKESg$+s$37EoZp%BRog*MD zxw@+boSj7+R0qv=QJ^%sv7InD{W3sK&i+3Ak8kU%r67Fl=P;lH! zkq*UYXLx3xZ3uo7b2WXwxY0{@lMi_L3Ljn zdnXTiiF`piwtcllJo(;GxuFa};zq1k`+K2#f>l*|1@TKi>e{qpo0hZeLS#ZR;p8#Z z>-=NZQX_rlalvu%nr!}_!mMudZ&1}r;Z>Y8 zf6haz?+7bT-+Qf3g)50DtQQw`K=zJO4XwF<<8NPQfu> zl?GSq?~m)Rcr1OPxa}~LfwkPBjAhAIaoqOty1H-;b)sf| zMSlW4$AqF%kj2{OMOREM94DqLkPqZvp@?*op1{f-a!muyGPe`wO$}5L;JfR#)m)u_ zB2`wJf&xhrviHl)oIp=g+xs(Qt;!m?R)O~KdFJQ~{pW9J^4G)kw*8D=lYFDdKkv0e z{OS<|-5KrgjoU%?3sWA@9|7B>-I)l%zQqT(DO(a9`!eOqfbQLiMt*E6v=P4?}~F=?T>l38&NwD{@o zgXjVJBW18jC3+J$P0T7qxM8~)_Zx>$Q4 z>1wTs38M{}+DmlvU)YKfmC}8^Z=Op~w&lgw`Ye`L&j)S`l&D(~qWb@&`BUH#^T#za z%jA8=YuW3L&|E5yGIUWY{9n9u2OiT-fH{Vw=>8#3q4)dsj5RB7sOGTlvHP~1l`po9 zZ-g#fQd}+P@SY*$07clUgND>(ZZK^6>-WR?Hx@CdIC7jAx(4!F=48oC zq*vI@J!hU}T$J!*ySoHlgCA9CcA4izrygk{t6xqkxvcQWp@9{8c+>}|84c0Le7&&> z4a*1WW!xJLXf@UHxy+3Hm-bElPuLFT)9(kkENzgRQXKa_4Qo&CB__|op-i?g`Y~Ie zl5eyq>Mh)=-=K>}RqI{8G)^jMxd%_l@?6a8wO*3u@)3t=r#M3zB#hQi#!?PWuhK$9 zXWyIB9BSroVQqGQjxQYJ&aix8H|;>Z6vZ{)K$teq(5g@JCiMs0P4{^d)f3i#TE^R+ zLTp6p^@da>Va;sok|FB)B@#pS$x`!P%7Ux50aZ_7(gzw8;W20^E1h<5Z9po3jtl>K zJL1qiE&24-xHWdS(TU~Y7tEE*_!;2P3v(>kg<;}5fy=R%Yg>+W*tmKu6psJdz)z}} z=8U}Yh2WgMQ8DmUKt3vCN>g2PDr@74n-=3-;M>;DWrq&QxqiyvN8h1guC*|1| zlptb-DkSglkU@d!R5mK=D9l6|s5DNa3P)9mT~m06EBd=5FQ?edR+XJ^$rt9W>2K=S5m2YL(jy@lb+&Q*x2~T}2#52}Fw1SgPv6r{3Ck7~V-WPzV*+ zC(wD<+WB;bcD8XCv|m%VYdi}6F={Lx5JWZ-#j?ZOi+g*mc}!DU1WvLy0?uq)+oS*< zo=)naAij470y~nv^G=mfrd)%-Gm5S;fIV3LjpQrYl#!WJF@CKaCx7qH1$>`n=cn@- z=aF;--?-IEFukMve2FcD8Q+ZON&>x3LhG!nC1kSDA}cVYmJpT+jcBt^Ax_~Dx;Pya zcLQ_we+g)NyPXk0o7@b-c?+BepM5_IN@7YzXda1f9?~R)q5rPstw&m$=3?8L;t^o2 z)6h8d@yYt|$w4xEN|cfdEHkMu&qLmy)SiVR6)fH<@-*rjzM912dxI`Hbt?`&(VJwL zyo)))JYC=_D;{x=BM4Oc2yK$z3XpyBY7f5Rv*b~<{DZV z&L6L@6(PvJ989sk@7AlEesWmyuRD5&bMK^kllR=7M{1m_YOUBAvjm7JQ(kQwH+#=6 z#4kY56uB;S$&_@iu7nx)L$(ZN!VDoC83i9|#ob&EBCHR>9P8?E65-~laBUJvVmGQC z{rDA`W)jVR@O5zqYEk4d2<;V9cWVly z<~Y>)yh(=UzOb4I-R;`J;D08F@|x0u+7f=vZWBwg;Sl%Jit-fKu-D$PY517TuVhHA zLNOuZnOxMXe^_0D@p=@pZ;`%xf9b|{=p?RtdjiR5R%o7zoxxQTU zlX-rfaBo(c&KEdW0r43#7TSJ=W8_Dhm*;vQ`N#ph7*E6tph1EU^qKojTmE#zR=N-# z9X4$Ei@=e`o}2i1R&|5dwuqkIJbD<$+U8LmYdNsReQCz6f4z%6DPdU;D<16kG)TByPJIx)=n8^m4fg3|+Fl6rQ zU4%rSDb4qbaqT=c4Lm~UoCTN3;?FV3n1|w21Hb7~?>Kp=;qLPlZ-a8RGW?K#(Rj}t z>}QLi$@Ou%>R5z?3&KAs^3UKA`9T}J!RtclE_@j1(%JAUw-UFOG;+n@2Y z<@E{8Z|d<0ZZFliN3igW+^(j>)=Xmom05VZGHOfm>d&aBgZgkJq@>@rQ zT`~G1I+beVZ4R2I9V{qkMh4Ky{t1n zWPF|X;j;((5Ghdgk85_R$EI?L;un_Puo(^6t)Pbr@3wryq^{|zG*OTZLyz0Zt7~%l z{LFy;A<#`irs9E}V;Kj(u08xW<{FN3x0|y8mW2n`4X-4)cGu>FoY1Xm5|NVz&zbp2 zultgc|9n?QzK=6L7biY31hDdZ5|bY9!gMf|?t(P&x^XxeKU1y8d6QtWz{mH1Q*yx- z!cHuV!%T_IMlsN(g9u4Cs1n=R=D=&NufiGwo= zLpn-dRz)8f$TrjjqO9OUb-pW75Udewz)OC>-bYh_BdTpARwC{|s2BUZP7PGa`ywDt zQ0+~rAUKbponHNAKIdKo0%q*bY(?4A<6l+ z07KRV`ZU?Gk|L&nn%?qlrHns^WNNeSJqw8+YZ-cBTLxu=)-A81M*4MEY4^8I(~9s(pM*2cPt#-a91f$@O-^HyBov{At}tP3%2DhU6(TD`-Y5r zU)j(oP*z_5TRM2>3-G?6WRZ-!W64b0;dE^-s(RAr@bOwf&=-d&+o zIPQ`bua$i4(I~j=aZzi1O?MM(8_3VpA4NI~(f5zRK3=utj@+ZLtV;3Fq@5 z#yt}b2T;Qol18DzhDG$eSw)zLN=bx6EoJb}b;|abvG`*?O+Se@ArKVOXdyooTa^sX zHUO}v=q27Ppm9yngZ!xRKg-?xoCmu{&7&z=vs>(Tp(KR6uiu>zpk2Xc3SF z^U7K;Ap@7*-G@ z-F(`c*7@Y24x;{sy_`-R(Iyg)MisRqpUXaWbt(Pawe=a533I+kb*Eib%@d#ej7$X% z!@@NoL%`48s2%2L>(W-!yf3hcdkwTXZIrg&6cpbPZLTT0?geFQhHSRw+7KgR1H?Qu za-SP~@!;XtZU&ysT~*(IMI>AtP#~o#ShgZ@7%M-r<3zFv`96N9>GfopWfl^dMdQgF z1~PH@x024)0qztr1d%sYB%fJ0_So?E6#PIb3yR8Kq+w_sczp3PBb=CpReptlQC1pe z``2zSOc$&hyyC5P)|<5yDe$rN=gg{s$UU861cQ0>?_^;$iFci%61y_oj&@EGzbRBn zS!y_*)uRXjY=ereHGSi1k6E@3K@yhw!BokZdC1%zJ0Vulwo~4)5bFq(T@vpxNH5Qg zZcoOg^OPZ$%I zg~+7F+M&;aDVd^kQi@~?Bhlk@-}+w~#ez{PcD?0G!R!dfzlL7RBHm4)mBvp8z61)1 zP%_RO_Yv+T-)UoiU4?}h?D$^stBkjMN2zY$3p=AW?`#cnF-88J{JQWPaLH$4aatyo z3$;W_0kWedyik&zt_wyPd-7hGIKZv)cP+KrP;)yDclaYAS09xF-4nfqu!OEYC2Q$Y zKxxI{u=&yEUcBV&ee1mGFZLgDQ5akk#((rXPXfPopHYxtONev(&ICnDw2!k@wwrm5 zE$P8T^-h6z-t2V&RFukb1LS=UY&C-wR@KtuuId-92BRShL3hm|LCwF_i8fyLpWMYe zbo-@$lFFez%*&9u;$KgzoVYGQ+U%~2g=_c>HvDs3&vsQ623lL*MFc2t`+Hi*2l=#Z zY#9p@x(X>64Bu;|X~s-}H?1QL&qZ0w}=XP(7#`m)F5rgww~{xz3Q3|l6~S}1dJ zxh;FqV3FINaqRTx!?%fEUTlI>5f8-KcGUf<8qC1vu*IL_E2OG)escAldnS^bralEA zXYRI`Aq%dX2a#NwFetOf_o=8XcPET^y)#ruFa`;UX0UZ4(xuNx`N$9Q}{C$rg z?{@#IpWnNJXZVEFT!Hy{U{!x8dRjF9*49J*V-PRXCENmtO}@Rwi=5y7noK^n zW%HppZ0zYcN~v>C5ii1EV|fjfRJLK-HkDT6Ugo5I8~U38VnLHIFHNyXCG6@)IuhM@ zQ8Cmz8b_3u0%6-Hg*3)d?!0(@?0ieEP2H2g)Uqs_7_&T=$MjK;O!2rIPB>yY zouS1nb?YRNz3N@(2t6{?M-T_eX|$rRlT4b~p>hK5>pN`?Yq0?Jfd`v|YjBv;nY z0c@6YFb6ZxJ6nxo>fQZ`Xj1fjtf4FygV>)#;$k~{iP?nTUwLt!ws28VptvCdqmplD zDw4kiYdBTF7|j{Wf(vTe(OFi4r9?Ru>~>4}l@1a;+2};`YB|e6PYZVNxn+`IO=Va1 zDi#~yaH}|v-c1jpVTd|;JoIKq4L(2`3ANF2v&u+`%%S9;6;!z0!-S5WREq34G5K-g zefaQfVk!N)8v0CkM7)J%g_afu)m_R*;pcDa*SxU}!Y$ibKDF_KmsMD1v;0}!w)Ek^ z=O9g@0&KKR!5i0kqjZ4jMFv!suv8@ss0F`%iOS~~{b}{-QZT?PNc!ZK%O=gQ7hVu}wUw>w_B(mno=; zuGb!=7lU9`dk)MreY2=VBlV+tu;~=^xRU;RQ4Up(>Zg&3&lvQ&_3t7h>dU*8uZm+C z#4c6oZ1dJ6e3_5VuKe#UnFCWfh(i7SI|t8@?!fP7_!7i5G%c;qoX`17=~G50HsK zS%G($VD_{4Snn?)yn3fq{L?vO`h!p>ce8QQaox6)%kbffLD8RO`c!VWAT%~}7+=fQ z)Lg&Qd1e4Kmeoe6raC0aMcx6@!X?`}=&3_rWxenuY=^%XLAp1GS`7GB!|h`8tZ3es zdh=QeMIh^ru4LNpj+fzwNVZ2V5mEbLK?u@YBHK-CiFeGx<&;QuT8^fJ8{5LaO6V`@ z*DCO?Sr@%QS7YCCK4e_wNsc=l8m|9Ln<(n_!PFyW{>4}h(N!H0Kp&)rZoedanF=2@ zja>{<@^%^1$QHIl&R!dzRTJO=y9W{6E)mT2>fGYK!cQ|Eh(kmK`Lf@b9;jhDNnw|c zaUGKCw109koSmL({n{>A`z^?gJ~z9 zyp0KI9MD;h4--25CD3)J8RGgD>4I8w&J2kXvTUr-mfPea-5 zfrvHdSnV~DG1tDf!XiD&C%)}Rw!LK3sUg3V`XszBNjovao?MyHQ-zIrPc~(I2F>(N zz?Zb5{jC0vjWLPs`ZgoOm)rtI$u!ct&PNCJwH&>=xp%=fr(}rb&pv<|h&VifDht&H z37Ml})S26%lv=NJ*LvXMrX7iuQByp%%>R=-coCBawiHa?Qu(_ z3=x)mBsXp^DY?w)$-L3m$c<;A&pDXd-BtRZK7O6fKTkO6pw5T-rbJSY>c=_#0^R89 zje0mR<{fk7QZaRJFS&pi$4?g94{Sx~;>89L zbTiDeg=^Y}RZn=E7ad46L63OXXmUlfFvGI=kc6OR=5{-8YPR;b#Jnkyz zFGo<5!Z(RLX_i7;4)pEiZUHE;(HLw;FRYIm(_uw45J zz&X2W_WW_XG0ZZJYKjj(BYUsdsb$F-ou7>2woZ7ezksq>0=(in4p){s+MB;_*~%Hx z-d6NpcFh$)pAnLMdZ47LL=5jx)(ZPY1o}K{!5tfgE&O<}Eiy|Vlm@}X%?v#&?}z*& zO%9T1!~YF3a;Rhu_nY@Eht<%`*O)5f2Um4qq^=iIKF=YUw=crl$xfsga$DGF@q6Y0 zkYb=LXF;UO&rGmFdijDT*jcO$x^Va48vBa{beCkrjr1#%@?3}%c(IbqY1TfW()YW3 z=>&_b7AIB9`r ziF)5jhB|oZzv*wv8o~84Kz?`%LQJ_}PhLQ%q%omcwVaHDcx$K}_%XnKFnzmBMHw{wZUf_dY6de-G(><=WEkyFF zxjlX}vG74xo`u-~>+nJcHB(f+utqW32(ORd%!xg})JF{W9a`m%xHutG=g;s2{_^FmPLrdjB-4mJ%1z1>jQ>o0kC931e@z$9i-AfF>9)@;U zXCsD&10r!QRoc7uxU*~dE2aMZUjQSe38^B3mjl|QDi=7BHzZbUqN9hM zD>fs<4K!Dz&5vvg;~n1*X0aU)5_y7Z38vg?#;>_SdR!BbsCmBE7;+Q6^mCTfgQ)0 zmSgyI_aA<|8fi*JUJOJC3a|tr4R7~I|e^B$y!wb39*e-8p1^zc*6}A zBqOwa$5@@wCOK|XyeFD1Cv+_2nDtCvQ}gj-8I3=JC;HyeZP0v5h9E2xDnhQ&d1sTY zzZ;w@8h!y6D>~YrfauX~#60$MU8ejWF*+KOFaV+%p)1c~VX2g$6Fd^htIH7XF)#VX zkjeB}u#K>ycF%4WhFlEOa?VoiGE7aTFc#wZUa%j3oI1=nNYl9U!Lu8tmW9tUW+bJp z+KCmX1|N50JplDrmB0tU^3>dNa^NG1g!XamVolprkK&+~>}n<|zvEqrbwiEFzM>^`~9^!gt$j;P%K9KJB2Um-lFI z6~@IPL%DIUSX{Y$IXkgxDX&OqM79yjrEhmMspIFFK2bYv_%adv>tZcCs-{oad*Gp6 z2y+Dfj2jvY0y<&i$|yL&&w?3pF8#V_-pEK;S87iT>n!DGC%3vCXKhY^UYC%gY||g4 z&NxK=CdAmPx;u)m2vx>TPwLB)NUofS>aS{TA3eFEoN6uWQ}2~~AfE9HAOIMNF97*w z<_(AbTfHEo46K&I-aU&LeQ@NAIH2e^e2ASrYEHlfdWDMxx zr#U?tc7R^AT5bqn==q9^x~Pz5N|*t&MfCj@HS)@P1WnhZ;wH}efd7TyLNVmllmEaX zG;vyAd8tbae05Q)4rN~XK<+7?`)zWxyJjObJwveG>mkYf~wR5o55pf2(|B~ zbs6q|A{`5Qu)$ea*cV%4W>ET?GKcehs}Wq_F)AzJwI!d$sLyx=z}G-qUZ`S&ZpfzSPJ;Y?hMH72ZR7J7gQya-Y5+x{=8}vCpO;^*P!vCG(Hb=Y2rZBg%)Hv@ zVLqaVP$^$d7?L{1XQLw7dnj{f~< zZY`|j$X;aM)G7E3i%Z7iDJ$Wnkd?a?>5A~Q>(_r-Yw7C=8Ht0!HUUQ z8b?2#eR@D@!vQZOIUPf~ibO`E|gW;hhrd(@Tus|izGQ3YDV!wi-v=ulOY zb5G(9UWQJ%zYB@^=xX8p$4iMSRj3ncv~y~8PB6tJ)mN>rPBJ{u7dJ}B%YmBVsga@N z`rhU50!7US=7|i^lI)~LsF$4Mii0U~Fsd0dws> zmZNAG?4G3T=t0oVagzvX#oeMNyS=fm1w|O_rx0<}hbcd-CslZTKzr|O+|4?&UsITX zFw@uOthG4~lWSV}1p$Pl(6_JPMsqd8yIc`-jeK4m)tQH=d0{_n$=k&X)MSVcCDF6G zBvV*XjRlc;Q@C!I&pX=e(DQ};%I2=R*|6Nio-|l`f~1C??kZ8#EVA zSCC&nB3jI64fXrbL$D|H2}#Qutk{@m8Q5$e(!6{VK@&B~NHal|R|LBEhNH-|%BpD4rM-u5bQCXhh!u zME+WZ~1owUaVy%Q!B+#rZAICX1?9`0O#h0H~h!(~P_q#_jUNSp&rHeXQyIrcuL@q0_41Ge70 zIUgMTXB#0$co2L*pm*WwJkf3$w4{e^*D-h9LTntO{Bli1yp2yvzPWjsCvop|j!IJ* zZvtyq&_$LVa&OZ4_%pGk{2z;kyVi}v%hP)HTZJMnYhwg{PeJJl#SIjL0D;%R4P?h3 z@?x%_?$JJY>0}Mba1M3n_gj(sTG$d{H?qwe2?87b?5S$VS_mk|uP*AY)9f}F;=at* z&S$#BS74SD+X|1+$9rvzlmq{f4>JB?cHqBK!CRWYT<%Mp3E-tCe z&TJjyzn4I0_TEOBO8f+4HyDTW2zfo5g^oLh)Twg{b#mklNmTVErmev$Q};QFo5&|L zZ0Cv&;_lo3iT6q?xFDf(~Z5plOuSo1V+T%Sot)Yed#ZPoo-NIq9$oy6|%?zg#K zg9eJP6rNTZU^A?+V7>Jz1ReE%cZM~=&itXV&Wp#Uh$#=hl zQaFggQQVR;u$3S8b)a0A9&5Vlj_%y3Xdz+ozEMn;qjLK&TbYxGbA?x3ku0$NXW5WsC+=vE4(P5>br}o z7zk35b<}TZVu8&3*V8np^nXHUP@mw2Ml1ZH1?4J6V58U1qAHdMT7}=}3W}Fg4a`;6 zYo{7=#@$FqwSG9q$?UKgR^U6-DFtYdvpMqIeF6}cMPf69iuDEL;GcACjN z3e>|dQfQay>FoyIIqNb7NVeUCb<3F~K-6X_HPrB=Dl~gws8qX=+4c}7XK*;SSno!X z*mepfWk1>M`$x*ixpe#i`Dl;gV`5bAgT;Z-D{`C!lFhEyoKG&uDx6L6((|cE_~kzM&&;cQ8v^J$>r z!-zC^+9X*_mM5M9=j0CrL%oXYBMIvcBQI;p7E4AdlSE0$tq8q#^SKJ?(h~J@kF>?J zxBHR)%3 zxy=OvJgYh>O+&2tFqwkGfa%M{1p+J(%mj`mj>Nx3i-b5pE{Io4Mm_enxgr73fTY)t zldNr&g-NW+w!Crf;J+Eoo5H%gvJm+dXF((Y2mic|Gw(z_0CGonDorztLU3`86+TB1 zqqbBx$BkGT5Zfbb1RZsfwd8M>BEyJkDJYU6sKmlYq)eOXB2^3ICf(_kTg|^B zX{hMA)Bt_lWXf5eJUhFOrcQ=XX_4%b^gF^5XjyH6?Y)*yBNBX zcJioYxdLU5B&v^Y%3BOIkR7zh`qdD7=ea;-Hz$AX7V&5Y0mQraow7`?GpiU?hyIP% zElHmVDcUL$HXoMTfw#d~KqXa~s1P%#LvEAh7Y${MF*k2{}H9&>{k3hk50(wAOD zncVx#BRv(FYw^$Jxv#W}?-5s7u=V9EnvGNpDa&%@3_m3ZOaLX|B z(k-)tbk@xAIZ(pq@a|Tl`&cJ(`6aCg%U`TaAWe)4uV0vR6!OO&zOeL=T) z;(D?x?Oh%Hz+oNWx~PC}6dT$QDuQG`iV0;vnLs(7nKfVB1HNI|@f@rT6P-+wB+bqG zVEqCqcEw$h^Nh5sI%P(MX0VXg&kc+SQJ|HVDY|RijfAy~^jF&hn%4Qd;|`W#z8|mu zv66-FRF1LJaVJ0mz1`YzH)F^&OYkjQ`gO>x=&8G->ag3dX|^*z$qqFY&JB+k|JSXi z5d|pDbiXZbtbwH%sytiv`B;T&_Frx~!&XJJDHksuLAkjSgL+ofxt@e+YG7KDU3pF` zw>%AdTIcv~Dh+3*4>hPkShr~_jP%$JOg~}JNvkEmhnjJinJnNI1BO6&s@BrWI`}E! zkNF%Gj(y_c;>otg6*2bpzv_ctc;T3x@sw5J-|s(8lT#}w$%wre0(X&sBmSP{NukyG z7NVn~_5lKj+3NWOv8AHdB0EobtklLSYUrENgb(78&`d6|QOWOEvg3v?wDwWB9@JO+ zS7B=*p5~K@6ZC`VBj7?}M)~Jw&j4O@g0vqO5Yltk;eW&s2$?2vv)$SF} z(YDRC;0+NugER=jcVk(rdx8r0+NabpPiTYgs+%0yqHlgccND1)a1>@l zN~RnQ{pHh{g7No#eyb|&P>`Lbcbe(3In*Iz>FPZ|Zq8kjc@S4R-m};wxKH}D?G-k! zEfA2t3&|*Ah&?nD93ikiB=!)I-*nLdqPFS)&61#u**cPD`zC$Wx=&pn)GB8--_x^y zfyUoCW$l`IdK48-Y7oxG4fVb>tK&`LW~|p;FPJlJ+MVR3@l9~s#{x^`&Tlakv7rRJ$P`^2M?vWfmf<;f}}*w$ibkG~w#)t7it4mC;^MV7BAQ#j;0!n}0k%F}S0 z${V`TN~`^hykpz9Vz_Am=JpGl`h4hPEJfn_qHAIPVnMQ5^C30xO}=plk9`ImttR0in_^?>LFiLXDc2+ni zB`e7mM{AY4GWAGbQJa%*HY!-4DmqYvF0nw!smCA)xRe99}CLIR;Kxpm`BIr_~T={ zm=CRI*k%O?bJ%a)(G1`Y%=LyapW57wnbLk86)5*=DUO6P1cCP5F4zVb)rjb717UA_vDyAJO%HSsSmZ+UC96WfM=v{uekbEeVKlnk7s@(*t+yh&~ z|A`vNN%k0*OnVr|PuF*GIac<|Br~2C)6^(74}u`ZCTteS4i#){tZeQ%8!hxn;do=w zZiCEm4IEbplu%8|lHzNhD_4Dnb>C*5Lq%3qT zdt2kx-kVsb+q5i3R41_%Hg zt*o?B+SJ`Yna;kc@n;MS4;`Ba(w6u~lT@$hRZ4FfbFp(fb3N!441=n6>L~vIPylxF zmEf_Gu?56r+c6L3Qj^K3Dc=%!;kPRaOMoQ$w03x-&RW*LviaM(d_AeY;Hi&3y>K0b zp3n;{7uF-oceyqd*Ac#RXL!4a3*43bwVfiUjy(d=dfByu0+R1899KUH&$_og?I;%< z{af8#1}1OM6lioS6Z-(l@aEbA?<^OeD}V0QiJ-z0w3zagEbC7L?hP zb%GxcG&((bD+XRiPrr5l_3E#D&U78Ed3pOi!hl3RXnjHKrT7_liM~#Nt!|m-zTZFo z9^sF^B|5Ctv&3DgZlRaJyVK}ohxaYeFEaFMFVgnGTL?!~OMYIbz-Dfukp7LuNMFNa z)Y0&}XF_KhKJC=mK}kb*p+s*o&4c5$7vaws+>IJ@Le|A*`aQdzm<#fz4az;x#K6!@ zBusQR+dqO{s6u-x)O6+Jl@{&M8>QTCfY z;Fi;$Nsmc!0(UL#YSin#96wI~?{W3^R=HUmzs*%;sEuu}-QY<(=NysWq2Thc9B`3IKq{VI$W$4V7w&! z;*KTzTt4eeMk7!wZhfBh1Lm3YO}j&erA2}6%h-7^TxSmr6%UZTI}~2n}4iA676fOr0s(4`OZb)~_sOa;QXIU$7#?a=b z;qq|Ow#7RAtTH!?`}I4if2zHJsl0%(dMz!_Fv3CO|^16+P#NuUC1-XQuIUvB$3jy5Y0l#@<*9Mujg*L0BHO9my3QZYFhg-OVES=ysX z)O*7r3QREPefB5SwY>$uZzp|ERVA!ZC<1>8?6`yh=IAquM|<#bx#Tw`a((6#r*D5) z%<~C(3^_NEa9R2V3zev}VNb^B$Bk0wiOO`?AMjMM@B()@JbgUz{oDcprHo?on!iDO zwo*7l;nA^Trskwyxvy2v&(I$X$%^P#T=25!5Wh&$=QyfHxoF7pR`S@zik`p9WL+x0VgFcv)c2+)_5>I> z=RXT?#5Hh}i_grM=lEraBy~XO7p+E72$gQedrX6mWwVgH(Al44=|_va3Kx^lO;cM% zI5RtU`4&mn)3ESWH%Jl;vTu(_?Cce6$-m5d9ZecsOKvO3R~?*fR$0g{!)!6_&H7_} z9A#JM7e385>5k_6S0x2neqLHw>>xJ%<0Pw1eTS};xuikN9064#ehO7U4y2M$`PQh4 zAc`On=aFDKkQJjNQBErMo%q;VnL~01BHf4+QS1|!pbIGi<4p&w;7aacBxy96wf-<> zD>}wzO}kY*3LkmUprGdc0c9kOYsqMK>OV7;u@4#G-adL*ne!Xyi*h;KGAv~#GVIlG zEwu9D>4Cvr;<3O<;Wm5yS(!q0Ukn>kcAKnR!!2G@@K&0)%SKt!++F|dN%o0V;oNQI z&NseTy;zBpS{LDB8mpOiZhUqpFLpe?q&9SkV#(~>>CJZX2Ou#IFEo-Ho~QN}_XrP0 zpvF56Y%FRFpFDHcpX0gc2(=V*w~Jbhd8EQ`U?a1*BLFP)Fciks5#Kf6>-|Jw!#W^G z@s!fnn-~X8B`YX!k7?z0zbzD!+uBb&QTi3kzHw2Y;uQVzBPpL?T)j-KL0Ds+PhI{P z9nUAUyuw<;c1Q9hVWIAKtpf74Xgnm?3?{@}4${6kOm-^Dt zMqMX!C7g%(0<9E9En>(A^vZrM3W3Lc|c+8rD{7~sa#RfEg6zza8VSO!sG2b)TUJ& zYQ(>C!B#UiVB$X6PMs`xF?bSWQT#KVyN3f41@++ zCxcBAZB-Tcr$n%Ko+hkUh$f7Ur3El5Z(=fw8!t<`)$kbR(QnrpiGf7t;nu8ml8iBW zTFHIky=>9rB15aI%k5*Jle5Bdy4C zVm9D36_E!Kir%X2Ksn`dURVwy{N`#^3Z_iCb1)st@78J0m{Cr{09>W8A9K3GE)hLh z!ZeaDqxbMw(Um}c7wzJvYNR?EA5s2{S?`}j#d?xsGg1*cP$2ld0zGhqN;Kb79P^KS zhj|u!y6#+6UinsT)S0JLo;~w}{anmk@TIDV9c@yoe3P0B;)B&m9zTUDM?T@R2e?DE z32kDk%;SLsey(x^_pjc~()@cOaWk~}^mA!J3>Vvl=S$F&ylz<&1y_(MJH1PX56yd_ z4raK@;W8g4I?^kEsr$E#+PGbR|Cd4o2I;r ztC4_Q*Yk_ONWjXI7hvRN%&5VDGKj$aX zDpKv#5^k-n6H`=~H!I9P$2sSNJu0Ef%AvV?`_K#e`G%{`wrUS!Hjb-^6IauGbn*XD7Bn1{{#JVqq0vB&|@3LqS$hAQ!(Bc!IIOuiAx};;AdSNiOxE9V-O42$f;b86re zq%N$~csm6iXPOPZf6G{$jvxTu1*it;W~2vSacPx z<&Zb4{hNCCRF#k(*w1h*A)1(zdcJF@dPBkWFhmW7Rs}_;1FH;7+5Z%!J?%!bTScfk zTZ%6j5dL=|ZI>(VU45$iB`Oy!kUn5~&bfs@-QxSEN91@YA(+q|m5ZcKFVf~8DPj@G z^~298NH8^@*7r;y`szdni{5kQOt`n;c1#iaH`zyOT#`F@FXb;uR8j|ow)GDqZ3i-zkYu~_?&VCh;; zJ?_yeYzBCv7AT>xet|KG1z4hLG$!kj@(VT@-r2v?h%*9;5qGsr&D?S5qRsw6iYqE` zR!@T_XL`OC1A+?}brRDrT_C`$Z32*N{q4zsqREE@lP8Cx`)~9vSZoK)p-(!}Ce#gi zK2*5;j``?X|A;3oc#xjL5Cai|pZtG^wgjJlQWaIBOV8XfpBbDnoY~JI%vGPQP8e>0 zH(fE#)x-;g)l-0IY`@az#!%;TQqcQBotz5uiX39kj?NwHa=g@NMjyIUcQFRG1d>@) zNqg1=fFmvd31BsaIyBgv1f*(6(9(nuC@(7rWiU;212R5{vTLD4X9F>Wbwy*m8G#%p zWItNqQ5@RA7P!g#oG@S6;qW9id>J=S`!}yzXgz8sq!Eqoa%<8)!i|@MClM(Nw%jDk z*=#K>_iW>|X6-R_W;?*X^>a8=y?R#cL?!Ey-Qf6z$#dhWn*!mb!z1(n3_zY3dc>Wu zr5V-W;)@F0%ZFJ!%Ts}_%14{F&7ChnTALAT4zylEg&wjFaq1Z=1jFRCnG_R<66ioK zD(OC1aN5C1s~@Dsb_(!3o+;G%hdBub!%f&Wdrs*z(y?YU#Atun<)JaNFJ$-^VjgKVKs0 z(n%I98=|53t>w$lOB2*wQ@MEdf_z&Z6g-|k98?$_dw8F{WSQ<*Jy&EvW8#abSJKDU*%qxE)N(5HZ4cRM@e1SY;wX>Xlw@;H4nb0ljRfORb?uZR*Gfqr~dYStSQl=3mr01}h(J z@%!6~4DgKLM|q(@8Je%8ur81&q@cI<+%V(m-xnUBfaCqj4`uZEd7G9px4ZY<@>XnW z$VKKcE^-WLLz$%FiLdiX`mI3ftXrNO?X zLQov6y6V371`_Q@5FGY8S!;#F0r|NqfnYVZ1Lh}ZIe51kUW+4&#m+J^;#Ws_9AaT3 zKK)f-#XG-JHN^L!2O{u?rwWeWRzL~`MiHTp|M-q z|3nwyMI6}#m43fRk~%f~*THIGOpt7!9rwWmCE^3x?~ftkuhcf)GSMJi#+fpy=Lkl> zFJ$E`6gX>CY5SJ#G~fX>rhN}$G?AU2_?CqC#U`|B63-24vVq&k0WvZdYJdmP4{J-y zH;-|>!m^fFJ8m%*$nj}7C8!;-iOv3@ELLPR;!BseNYkk?T40kj^Yw*^es^H}vE)r( zSg*o=wPeIUkl8S0`F_~Id>C-M`j0wxhKi%5citnizxn_><0e<3hA5h>A6#f|KpSgj zfYYxOeCvI?W;=bBpUi(G=7aFa^wcEewEUQ{?c+3>fKIpuk;F{6 zP<7B1rXdx%A_`?0x+moH1*!=K!C&0k#BH$qi3V@`NXfnb?lzg>cVaW|WqLB`7k~Iw zDgR11utP9KH*PxTmM6$SLv6`iX6)mH9(%^$1%~dAJ6fWWAtnK)IvVw7sX!(D87{nJ z))Rm$7I@?h!xKS5Y_5mm#FT0>Y)raX(x~jl!XoNQOAwF{0r(_7wSi?+_|{;C?kXVl z->sZ3bNHI3P`>O1K;qL0Xu7N0m*0V+@E<|zXoW1{`HNwL_fVrLbRjg-C-)V9!Ifu9 z=P(imEd^{78D>#tqgt9*xIFFewMX4h%y)aMhHI2d!PzLs&H2-Rptc#|wh^U}U#Nl^ z!I09l2Jj%5C|wkOEV-u;i0)tv`}2+4QA4W{ZrxxsucY-Hh20PB##5b z5yqs)zS6-j%5>d?te^G>?GDZdN&phq=MTLEVYFd(5q48DXS+5iqUCQ|1cQ5hOT>qs(Gp|M${J*0ME^@!5Q27;5Kb@COoD*6}Hk6BU8W~HBm%(S_2iGZ2_ zCLbOs5kW@{xx65nzB&=IBxWw*xQECeUkjM z#$X?AJV!<$WVg*z*k(9kSS<5w65=77JaGJ_pJZ*zdLpn334xDEJU%FFmPsFL77BWu zWBhH%_{spSmt1`57rcv=y=fKB#GLK*n9&#v@K!r6zT6BLad3j8%>GebNy`&>zKM z{b3tDLGeU#3!&L!XIxyp?5+5;BoFeRA+Jj^kDa*?+P-SaSuVJJ`%q3kM=p3W97&Jd zM*lWPV2u)_qk59+*&y9K@%YEzy3f_uZ9?i+yWdfWP`?%SMan8qos7rgJAjxP_;>3v zbNv0RX`PePbMlF?pi{EQjI6INQdF@#&H)Kk4!j@rva#)CLBlG zYktmeHr&4z8ri-c5!e4x_f)%Z0T71Vw_VGc zn<7XWrxEbW2xeHsHaB${cAWm6@bR9eqmg^E8YoR@LWLQYA5#jRl`4hA`_&ziTru(+ zRUfB7mUd<3A2xgCIA?}Xj17)Mgj9u82#A>3%Qor%%=v#zcrZ$68xVT3D*cRrzu?4a zu1JCEuT`$_3zj$?TNo)qmO9xyifkYkAiPmutCM^ga zzMezbOoq*rVKv@WuHQYnw3h3L?l8|P$p1rv3DWj*IKhXxk)>F&<9gQ+W7nhF`))rm zTKh)0-GSU(iDq=H_9b#{;7DZn+J|sC+MbcUHpL>-Aknt)sEh5!gERrxdw_y)sq%<% zI~xb^aF7_oSAuAx8aoV-#lb*{8UL*UD>bsfgX2bEG*qP(@zC#HZ?iE&ebiB&&iVg5 z)c+i4B|mT+P^P4#rWB+xYA*iPCP5VKFcCP}ltkC-z;;1X0%;yND)-p^)1OqzHp$! z5p_|2up;nkZU;#NF`)N_zrpu&*=dS2ZE`+Jr>G0d8F#i>YM173T0YcLdSCyZWKmI^ z_%HQr;wdCzUU1zQRtJbc_Oboi6h7LOnar|sB=I{5Di;p;+W(m49y?}0C;+~&QR3C& zP_3jrJ%Fo;QV3Gkn3%pe10I3NhMEKtlcJX0+^G(7@xh?$8*DrcdMCa8MC`YKoa@QM z^ilv&34qxW)Tu%!H3(d#``BiN!FQP|MI}NSL{~sPgv7LW5;gw?rFs%r)0?L$7VlnY zDkA%s^ek?=)MUBRzO>ek;peMlW?h2dS_<;jPV1<+<`G=RH1~SgruFDCL^K#9r-|jK z#iJiIcOAhlG8@n+b=1TM1Cz+yKkxty*q{;IcAE*i#Xc-GwC>cXk+! za@`c3k$I!GMiz~+`}16PosLtFSM>A6t?@`eoR_IWJa^F3bqSAU$fl5z6o}h8Z(#_>{D= z+8VgCuhQA3Y}sJKJha5OaS%*gcF|QjjaY|w(SObR+3z3d+wUA2w zn6BWL%u?4UfT<0twT6frtaz3v88;v&H|7L2!5!x+dtIK6&<;N-eZg(CT!N7g3IZCX z;yC(+7D*-Eem>o0Ew67$dDjnZ*JS05E0{0G)eEVc_IB$S?-Y_5<>9#1ZKX?$u3Qy2mrdXJy++bvb`uCj*X%v%s0m3_n_8{b@*Oux5V<-<-g$z9y{PCSh|9Z#PHTYE%O@_QTa3 zLY>IL0Feu%NPj@=xPMf!uMA4!*~NN_56!}RwF)va>cbI56WhB6P_K3| z0=Ge%@6AMG4UTU!P4QI3truCExxfFAYT7A5XiP0npZ!gD>Sc5u(=h4rzraz*5j+&Z z$nr1#-Qh8S*@Bpxo;**f%qTX!?v6=(F`dG9X47<64s^&rkiw^DJ9wt&pD(h|)I?!T z{EUObXMoerfH^R*_by}3CwWryCW3CHR| zW6oSdqFS-AVM4kOc|D)(Zlzk8^6xK)Fru(}_+;sED=-!pv}dS_WpS9pW+pOo6Y;ws zIXStF9;gx`DuuiMg@FN(Bz3}oP+yt5gDeJW!|>>}YV8E+$wbf8f%GBPiUn5=F;x5j zXdNLWxvwoll-RmWOv`j&kzgeE9_ED*SI?|Aulx+sJE1fI)j`*YWd4=3h<%h8P@L zeNE;{!T|vkJcacuf{w4N$LKOBGDeE<9FtGiLF@Qa9cl$TC=6j z$!3uf)SIxw7;bZD%GtF34A}T!OGcx5<*!3_L-tS=*=^u|(B>X8mIOElR^QyI+6xc| zZ-oUlQ`deN*iLMQqcn!%2|)bmLvcv084$uSa8u(48oZZ-4#=3$Ah+UaKroE{EcCW> zy30!OOSs2;lmZ^u0SAA&rF=nj6B7sO_q)uv=ziUv1xc1C6s!(=A6|0aH-!~zezrbGb4g@e68oLR-gOevGp4&hHxMrmLuzJiVI%Ee{)oR+sE(x=(iZKXGQoH=|uNR1C}vFB=l!b znw8s0E%dbF;T9}<4O8{?3FGboyEkq2O5&HQnZoY=-Q;LT(J9J}Ku8!5Zv0Pdiy*ei zg;s5rn*sy)F|s_eN4ZXpr}KGBq?N>5m4(#OHS_uT(_bS+c}L;5?Mx60gCxg#;J6$k z0ojmxYS`r~w0Bl)yFx9a zJ?4ZB3mw-@P;2@k72 zfottf%xs!_LqTyyW6xDUJ*k;g5t?)O;Up~xn)Mwt zZ$Tx*D#%r%5Y-!^ZQ1E@(v3PhP^libE27mZhk7cwckcgtBMg-=5(9yU8vI~#4?84(C!BK7hGh@WYa}`X;00$y%Sq_|rX-pZT$&f;`->QM78CXvkbcT-0%}m%V_<$M z`<4CUEnct7CSN+nQUSAX1f}PETC>(w4px;5@{`#}w3lw(T~361`Mph& zd-}A=0wTG}WavOA1qxHq^bYbeQ;eD4HIpMb^J0WXv;{SbqbLjRzktffg_P+45IX2n zoApL#F0BAI*M^b{2?)9IzsK4T2}D|CNIjFbDA1HrMxdiA^u+!rO~oZuvk=(L?A15O z43Njvr(KNu3i7s*Oiwbo?H?jNX0f@`e;aje$T8uDOzlO=?#$nvb~J;Nd+3Wg+yi#K zhOzm4QPqK_uzfPWXlYnkOR~#F@&|E_l&hCw6>linRHRy?^EW4Ppmm6E)4U*@AC2k^ zrboO`?BIYnHT)+gFJT8LZ$>kz&*;DU-MxI#$zJ?pUU>hsqx-ZxKq7+FUh>4V@&_Sq zq#7|$6LL>**dT=>+8 z`}+=M4FLEdBrPVaHqhJne<*$#B|v$aEXna*5HXLpTwBNDKy8~^>q$DPr$n<86?VuL zp_amHX3O%R35WL=*PBW)SPVs$cq3}rrt$3L&PDMxspjOU-zMYqs$!BM15`W+M*@0R zP0}D{RYJY<#6okn)TTgQH$E$yeb{t_RQ;xLd3gpQ&EBS>+JT5xb1!_C1DeJGho!03 z2nVuoA7)YZ+}H!u0#uo1R1yESWb*G{9D$5m)}RT0{*Vq*!H81gqEB08z==CtYTHarDR*z_*MF#LAg{m+<#srZtpsQAUL=RI9 z*4~i~7D9?n2n3u*^c)AL0f(mqGXeH$(RQ%dD62_1Xsgac^Z&f~suQ>b{{L6hb%(RT zz3mX2&|0->uPS1;Mr}c?+Osu7ZHiY>Gc`&R)QG)TZ6cxe4oa0!YF4e*>YJi!wf+3A zul1gP&p+on=YGy}-}iH_=k%r%rnJLOzBQy>em4sBXGWz-FlbyWRaNyg=!SZ%YtyG~ z@)$GW68XENIS<5?@G_vNjft_%(vu6-Q*l6c<*O%% zB@8oDLuKRm(HD>Ht{Ph#Tt=B^z~r3)ukjO~TaFbKXpmO3z)sz&O8}x6v|0v=AgYkl z(0HYuQu0Iw=r-z>0ZHjNRy!R_+juX`7|*W!nGIj8pvMm5hla%r(0Pwr_C)tl*%lgcbJMTO7+!f= zW)n+bAiJT~ie!hPbwBaZ)&*a;5-~F0p_YzXUr|2Qm85!Zo?Pi21szhIlm)4W$U&4C zC2}xZ0->!iSXL^DwsQH0g*I#8SWnxW_K;4F|7j82^h%^la1*nW_Dy1?kJ+%k4sdxK- zM+mt8l5l-iu$__-*`t{h%%VV-=`y|^#W|(|wyck4C1%MQ_#pxbM*2geweS?GWc%qW zMUl92-PUSTZ&8Kia?bz<|wa zYfC3zPE1Z)$@sNlgOWe`4|_lD!FN{;Oi4ZKl*@~L_9)+=qrRLa7v-M z=u8j__CV6Bl~Vp_x-33&?8*J1oJA$a?lPIaxiB=6} zFPenQgyWP-Jc}Unn{`ho^wp8UrInJMQ#8O2HPI=Eq1%JCi-73eW+vO%4$Q>?vlqbh0zyei(A|;i@ofUFmZZb{62TRMwqT(Y{VFy z`CTPGWb#2g#xAJblQqf!!sdja0Qnq4b43u5VvZ%jcVYJpo z>`?Qlw0))o)NKySVXl2Hm;dQ~B_W zuC#T{i4UFA)>D7sOEu&Q#2S_PkR#cWHUg67!{_}1WJG;K|M>J39MPFfy%K&GL3s75 zrKHx>ZiMB_NO<;(_ZKI;0M)Z$ZUmg3m}dEdp28HBDQ`LUmECL$vu6esb7}!psKpdh z6o}1p#}kJ)Z*BJ~Fvr@KkwvV8a;-FyK3@51f^V`i8VuHZ z-)@8)Kf_F$FDCXTqd7_GnPc_myKHCJ88B{&%D9e)))IHIugRR*fA-PTEu z9P%6n2w8vS>vbTWJ*xKJ@mCsFr8vhmu`&18CT_bj>%&EefCBAh&2A5u$K;A0J=24Y znnyaii->wwX;qLXkX3Mf;Z>H+ES+k?1x+R4Qr9(|YqlmWirHBD?qh?$lsgyqlBJWW zHxk)Bc>m`Lwd=Yb3<0oEgL`GcwdHS2rC-8&U_@;Dxci|gXZ?wSlDX@-tH6SUT< zC^WdH;}se0)pa#?K!4!CVnJdzl^xS88C)IGlNM>8w0`c}mvniAza{RRCVj4?ppj~H zwRt~AUu!J38JC^QzwVlY$kELynCC&PS~esIj-zL19F36gem&c^A{Ey=kkbb_^a#6b{H3$gK*zDIf}bEv9tPBOcA=hF_zW$yGZ-?2&T zz3opX`1=Nd=k%?#?HEJAtlp0&P3}LYqi9abjNF-&X()|tZJaDzoZfHLJ}DI*G4gRE zZ;NgQr_bHZl_MLeWREewTa0Eac@?QQTZ>haSQV+_d%H1n?;OW9Q_RL?R`wja2&vvm zdvq~0gflH;7z52#KtBSdtzz;%{{e%B_9~MSkby3;nsey)hJchyNW7N{9hXTb+XY|B zDxFWpR^3@y&rUOtgf}NVUq8@&`3*v5P9CISY|| zj-l?DY38xXr^1b=e+VAfW6lAl9bLFCOGs-di078OFExAqCm%HU8b<*vPbas}9EXN4 zOLr()y|ci9@&JV7x3LkYHut<@B!;nZjgbN6E#xaK8z2B~oBaTOz# zflvu<{AbW!@6iMbYxE^`!-Y=rb zOw4-h90gZK2b1Z3P=ABd%C63)_sOFyia)c^nQqy(gy(&;9zGx=6;|@2yfupsa$0FG z=2U$_+0-FYw`NGCN#BA@S^nVF6r@$Y$g@cub7#Kr;qjN1za~(oEOBm_;A!g8B$7fL zhZr|~h?nhw+SKUrYUx9BAH)DDDIX|m?>5PZPQ`h;5R^LvREE) zm0VIF4r$~P$HG}J`+nJ3_wB07Upy8CFVk{2^P#+t2WZ9>382y^0LHyI)|8+K*vqIm zXxQqqsED?UaAh-d*{nDY)GVK{&zKNXcKINoZNoP_)j;J~)y7c3wQ~QL&U0UCreE&` z4V?=6qU4jjNJ8s70G9QDJlrSAZ57fgCysQQua+;xS-p%Hle7GazM2TSsR1Cptl+gt)`)Dm?iW$AUk zJF`Vo02qgvsnBwn1))qulNFo)w8S45TfjMbZ9S8ZLwt3^VHk{yp{h=J6e<;}uOKkt z1Bnes?_pNVR8p%dt=A3;Z(OAm8b#s;T>t~56fRI<{^c-~eoX(cFaz6qiJstbqt1H% z@Tc52|Bc@35sDh~$*P)X{rN3R#eJ^VZ(2+Z1YVKd^voCVtq7cGD+33{2emxROuc8o z!sWlWo4M8YMXP+9832dga;4y~sci*BLf<`O={wLb-8Rn4KIHH0<_QxMai+neKfA*N z4(+?KHpTwz7hze_R%gnnQDYIGX^SPH!dT<|^LU*(=i=SF|E*e@xFHB&%7lWggMaTv zh6tevKK=yYJH6kpX<4Od^)#Jd5?cF2$CIo=7l@)YUEt2!siQ!Nh72QshnNRat&c*&Wt+KPs;!FZ4uGn z2oOkAbPLO3cq;e=DEobn_JfyZ(8Qwb9Kwfe1n%<#xJdiI}@4d zdJAm(>}FK7NSgQz&7l2a98`+~7WW&x@mue)8Z7_m44xBK#FS69A=X?xIXLRSMQ?^E~H zzbN^3X%`r{>2SkS|Mo6trH$1JdB>oAY&mgJJha;FxXMUWdx^|>pChnVp7h^8jO>4P o$-h) -> CliError { + CliError::InvalidArgument { + message: message.into(), + } +} + +fn encode(value: &impl serde::Serialize) -> Value { + serde_json::to_value(value).expect("review graph types are serializable") +} + +fn local_id(kind: &str, value: &impl serde::Serialize) -> String { + format!( + "{kind}:{}", + Hash::of(&serde_json::to_vec(value).expect("serializable graph identity")).to_base32() + ) +} + +pub(super) fn finding_id(finding: &ReviewFinding) -> String { + let mut finding = finding.clone(); + finding.acceptance_criteria.clear(); + finding.locations.sort_by_key(|location| { + ( + location.path.clone(), + format!("{:?}", location.side), + location.start_line, + location.end_line, + ) + }); + finding + .evidence + .sort_by_key(|evidence| serde_json::to_string(evidence).unwrap()); + local_id("finding", &serde_json::to_string(&finding).unwrap()) +} + +pub(super) fn membership_hash(repo: &Repository, view: &str) -> CliResult { + let membership: Vec<_> = repo + .effective_history(Some(view)) + .map_err(CliError::Repository)? + .into_iter() + .map(|entry| entry.hash.to_base32()) + .collect(); + Ok(Hash::of(&serde_json::to_vec(&membership).expect("serializable membership")).to_base32()) +} + +struct IntentCriteria { + node: CanonicalNode, + aliases: BTreeSet, + source_hash: String, +} + +fn governed(change: &ChangeInspection, intent: &IntentCriteria) -> bool { + change.intent_context["status"] == "recorded" + && change.intent_context["plans"] + .as_array() + .is_some_and(|plans| { + plans.iter().any(|plan| { + [ + plan["plan_id"].as_str(), + plan["intent"]["uid"].as_str(), + plan["intent"]["id"].as_str(), + ] + .into_iter() + .flatten() + .any(|alias| intent.aliases.contains(alias)) + }) + }) +} + +fn catalog(report: &IncrementalReport) -> Vec { + report + .intents + .iter() + .filter_map(|document| { + let node: CanonicalNode = + serde_json::from_value(document["current_document_criteria_and_tasks"].clone()) + .ok()?; + Some(IntentCriteria { + aliases: [ + Some(node.id.clone()), + Some(node.human_key.clone()), + document["id"].as_str().map(str::to_owned), + document["frontmatter"]["uid"].as_str().map(str::to_owned), + ] + .into_iter() + .flatten() + .collect(), + node, + source_hash: document["source_hash"].as_str().unwrap_or_default().into(), + }) + }) + .filter(|intent| { + report + .changes + .iter() + .any(|change| change.selected_root && governed(change, intent)) + || (report.selection.kind == "intent" + && report + .selection + .value + .as_ref() + .is_some_and(|id| intent.aliases.contains(id))) + }) + .collect() +} + +pub(super) fn build( + repo: &Repository, + report: &IncrementalReport, + input: Option<&Path>, + risk_profile: Option<&Path>, +) -> CliResult { + let profile = if let Some(path) = risk_profile { + let mut bytes = Vec::new(); + std::fs::File::open(path)? + .take(64 * 1024 + 1) + .read_to_end(&mut bytes)?; + if bytes.len() > 64 * 1024 { + return Err(invalid("risk profile exceeds 64 KiB")); + } + serde_json::from_slice::(&bytes) + .map_err(|error| invalid(format!("invalid risk profile: {error}")))? + } else { + atomic_audit::risk::RiskProfile::default() + }; + profile.validate().map_err(invalid)?; + let intents = catalog(report); + let mut criterion_ids = BTreeSet::new(); + for intent in &intents { + for criterion in &intent.node.has_acceptance_criterion { + if !criterion_ids.insert(&criterion.id) { + return Err(invalid("ambiguous duplicate criterion ID in review scope")); + } + } + } + let scope = ReviewScope { + project: repo.project_id().map_err(CliError::Repository)?.to_urn(), + view: report.source["view"].as_str().unwrap_or_default().into(), + view_state: report.source["view_state"] + .as_str() + .unwrap_or_default() + .into(), + selected_roots: report.selected_roots.clone(), + dependency_closure: report.dependency_closure.clone(), + source_membership_hash: membership_hash( + repo, + report.source["view"].as_str().unwrap_or_default(), + )?, + intent_sources: intents + .iter() + .map(|intent| (intent.node.id.clone(), intent.source_hash.clone())) + .collect(), + }; + if repo + .get_view_info(&scope.view) + .map_err(CliError::Repository)? + .state + .to_base32() + != scope.view_state + { + return Err(invalid( + "review source changed while resolving graph scope; retry inspection", + )); + } + let mut observations: Vec<_> = report + .analyses() + .flat_map(|(_, analysis)| { + analysis + .findings + .iter() + .cloned() + .map(|finding| SubmittedFinding { + pass: ReviewPass::AntiSlop, + finding, + }) + }) + .collect(); + let mut risk_assessment = None; + if let Some(path) = input { + let mut bytes = Vec::new(); + std::fs::File::open(path)? + .take(1024 * 1024 + 1) + .read_to_end(&mut bytes)?; + if bytes.len() > 1024 * 1024 { + return Err(invalid("review findings input exceeds 1 MiB")); + } + let mut imported: FindingsInput = serde_json::from_slice(&bytes) + .map_err(|error| invalid(format!("invalid review findings input: {error}")))?; + if imported.schema != INPUT_SCHEMA || imported.scope != scope { + return Err(invalid("review findings scope/schema is stale or differs from the selected roots, source view or intent revisions")); + } + if imported.findings.len() > 500 { + return Err(invalid("review findings input exceeds 500 findings")); + } + for observation in &imported.findings { + validate_input(repo, report, &intents, observation)?; + } + risk_assessment = imported.risk_assessment.take(); + observations.append(&mut imported.findings); + } + + let (impact_reports, mut contract_findings) = if let Some(comparison) = &report.view_comparison + { + super::view_comparison::inspect_impact(repo, comparison) + } else if report.view_snapshot.is_some() { + (vec![], vec![]) + } else { + super::impact::inspect(repo, report) + }; + let impact_comparison_states: BTreeMap = + if report.view_comparison.is_some() { + impact_reports + .iter() + .flat_map(|report| &report.issues) + .zip(&contract_findings) + .map(|(issue, submitted)| { + ( + finding_id(&submitted.finding), + super::impact::comparison_state(issue), + ) + }) + .collect() + } else { + BTreeMap::new() + }; + observations.append(&mut contract_findings); + + // Identical observations across passes have one number. Criterion judgments + // can enrich an existing observation without creating another copy of it. + let mut unique = BTreeMap::)>::new(); + for observation in observations { + let mut finding = observation.finding; + finding.locations.sort_by_key(|location| { + ( + location.path.clone(), + format!("{:?}", location.side), + location.start_line, + location.end_line, + ) + }); + finding + .evidence + .sort_by_key(|evidence| serde_json::to_string(evidence).unwrap()); + let mut identity = finding.clone(); + identity.acceptance_criteria.clear(); + let key = serde_json::to_string(&identity).unwrap(); + let (existing, passes) = unique + .entry(key) + .or_insert_with(|| (identity, BTreeSet::new())); + passes.insert(observation.pass); + for link in finding.acceptance_criteria { + if let Some(previous) = existing + .acceptance_criteria + .iter() + .find(|old| old.criterion == link.criterion) + { + if previous != &link { + return Err(invalid( + "conflicting assessments for the same finding and criterion", + )); + } + } else { + existing.acceptance_criteria.push(link); + } + } + existing + .acceptance_criteria + .sort_by(|a, b| a.criterion.cmp(&b.criterion)); + } + let mut findings = Vec::new(); + let comparison_states: BTreeMap<_, _> = report + .view_comparison + .iter() + .flat_map(|comparison| comparison.files.iter()) + .flat_map(|file| file.finding_states.iter()) + .collect(); + for (index, (identity, (finding, passes))) in unique.into_iter().enumerate() { + let change = report + .changes + .iter() + .find(|change| change.hash == finding.change); + let related_criteria = if let Some(change) = change { + intents + .iter() + .filter(|intent| governed(change, intent)) + .flat_map(|intent| intent.node.has_task.iter()) + .filter(|task| { + task.touches_file.iter().any(|path| { + finding + .locations + .iter() + .any(|location| location.path == *path) + }) + }) + .flat_map(|task| task.satisfies.as_slice().iter().cloned()) + .filter(|id| { + intents.iter().any(|intent| { + intent + .node + .has_acceptance_criterion + .iter() + .any(|criterion| criterion.id == *id) + }) + }) + .collect::>() + .into_iter() + .collect() + } else if let Some(conformance) = report.conformance() { + conformance + .criteria + .iter() + .filter(|criterion| { + criterion + .before + .iter() + .chain(&criterion.after) + .chain(&criterion.current_context) + .flat_map(|declaration| &declaration.tasks) + .flat_map(|task| &task.files) + .any(|file| { + finding.locations.iter().any(|location| { + file["path"].as_str() == Some(location.path.as_str()) + }) + }) + }) + .map(|criterion| criterion.id.clone()) + .collect() + } else { + Vec::new() + }; + let id = local_id("finding", &identity); + let comparison_state = comparison_states + .get(&id) + .map(|state| (*state).clone()) + .or_else(|| impact_comparison_states.get(&id).cloned()); + findings.push(NumberedFinding { + number: index as u32 + 1, + id: local_id("finding", &identity), + passes: passes.into_iter().collect(), + finding, + related_criteria, + comparison: comparison_state, + }); + } + let mut criteria = BTreeMap::new(); + for intent in &intents { + for criterion in &intent.node.has_acceptance_criterion { + let numbers: Vec<_> = findings + .iter() + .filter(|finding| { + finding.finding.acceptance_criteria.iter().any(|link| { + link.criterion == criterion.id && link.assessment == CriterionOutcome::Unmet + }) + }) + .map(|finding| finding.number) + .collect(); + criteria.insert( + criterion.id.clone(), + CriterionReview { + id: criterion.id.clone(), + intent: intent.node.id.clone(), + text: criterion.text.clone(), + declared_status: criterion.ac_status.clone(), + review_assessment: if numbers.is_empty() { + CriterionOutcome::Unknown + } else { + CriterionOutcome::Unmet + }, + findings: numbers, + source_hash: intent.source_hash.clone(), + }, + ); + } + } + let has_assessments = findings + .iter() + .any(|finding| !finding.finding.acceptance_criteria.is_empty()); + if let Some(conformance) = report.conformance() { + for criterion in conformance.reviews() { + criteria.insert(criterion.id.clone(), criterion); + } + } + let mut graph = ReviewGraph { + schema: SCHEMA.into(), scope, + passes: vec![ + PassResult { pass: ReviewPass::AntiSlop, status: PassStatus::Partial, detail: "Executable audit checks over recorded before/after source; supported patterns and language coverage are explicit, not whole-program behavioral proof".into() }, + PassResult { pass: ReviewPass::IntentConformance, status: if criteria.is_empty() { PassStatus::Blocked } else if !has_assessments { PassStatus::Pending } else { PassStatus::Partial }, detail: if criteria.is_empty() { "No unambiguous governing acceptance criteria were resolved; conformance is not evaluated. File associations alone do not establish ownership." } else { "Criterion assessments come from explicit supplied findings, not author status, shared paths or automatic semantic judgment; no source intent was changed" }.into() }, + PassResult { pass: ReviewPass::BlastRadiusRisk, status: PassStatus::Partial, detail: "Recorded before/after direct-call binding, changed-function fan-out and declared call-contract checks; not whole-program/type/runtime proof".into() }, + ], findings, criteria: criteria.into_values().collect(), nodes: vec![], edges: vec![], diagnostics: vec!["Report-local judgments are not signed approval. Current intent definitions are source-hashed context, not authenticated historical criteria.".into()], risk: None, + }; + let code_changes: Vec<_> = report + .changes + .iter() + .filter(|change| { + change.selected_root + && change + .paths + .iter() + .any(|path| !atomic_repository::is_vault_path(path)) + }) + .collect(); + let metadata_only = !report.selected_roots.is_empty() + && report + .changes + .iter() + .filter(|change| change.selected_root) + .any(|change| !change.paths.is_empty()) + && code_changes.is_empty(); + if metadata_only { + for (index, pass, detail) in [ + (0, ReviewPass::AntiSlop, "No code to analyze: selected paths are .vault metadata; code audits and metrics were not run."), + (2, ReviewPass::BlastRadiusRisk, "No code changed: .vault metadata excluded; no project scan was started."), + ] { + graph.passes[index].status = if graph.findings.iter().any(|finding| finding.passes.contains(&pass)) { PassStatus::Partial } else { PassStatus::NotApplicable }; + graph.passes[index].detail = detail.into(); + } + } + if let Some(snapshot) = &report.view_snapshot { + graph.passes[0].detail = "Local audits over each live recorded view file once; no historical replay, before baseline or introduction attribution. Language and resource gaps remain explicit.".into(); + if snapshot + .paths + .iter() + .all(|path| atomic_repository::is_vault_path(path)) + { + graph.passes[0].status = PassStatus::NotApplicable; + graph.passes[0].detail = + "No code to analyze: the recorded view is empty or contains only .vault metadata." + .into(); + } + graph.passes[1].status = if snapshot + .conformance + .as_ref() + .is_some_and(|context| !context.intents.is_empty() || !context.criteria.is_empty()) + { + PassStatus::Partial + } else { + PassStatus::Blocked + }; + graph.passes[1].detail = + "View-assigned intents and their declared acceptance criteria are review context, independent of change-plan links. Recorded definitions are preferred; current-vault definitions are labelled context. View assignment is not governing-change attribution or an acceptance verdict." + .into(); + if let Some(context) = &snapshot.conformance { + graph + .diagnostics + .extend(context.diagnostics.iter().cloned()); + } + graph.passes[2].status = PassStatus::Pending; + graph.passes[2].detail = "Snapshot metrics include declared public surface and dependency fan-out. Change-regression risk and before/after call-contract checks have no baseline in this mode.".into(); + } + if let Some(comparison) = &report.view_comparison { + graph.passes[0].detail="Local audit observations from both recorded view states, classified as new/existing/resolved/changed/unknown with explicit source coverage. These are not authored-change or behavioral-proof claims.".into(); + if comparison + .files + .iter() + .all(|file| file.analysis.checks.is_empty()) + { + graph.passes[0].status = PassStatus::NotApplicable; + } + graph.passes[1].status = + if !comparison.conformance.intents.is_empty() || !graph.criteria.is_empty() { + PassStatus::Partial + } else if comparison.conformance.changes.is_empty() { + PassStatus::NotApplicable + } else { + PassStatus::Blocked + }; + graph.passes[1].detail="Intents explicitly assigned to the To view and their acceptance criteria are included independently of recorded change-plan links. Actual membership-delta governance remains separate context. Recorded definitions are preferred; current-vault fallback is labelled context only. Scope, author claims and file overlap do not establish an independent acceptance verdict.".into(); + graph + .diagnostics + .extend(comparison.conformance.diagnostics.iter().cloned()); + let paths = super::view_comparison::changed_paths(comparison); + graph.passes[2].status = if paths.is_empty() { + PassStatus::NotApplicable + } else { + PassStatus::Partial + }; + graph.passes[2].detail="Shared semantic analysis of the pinned From/To states: changed functions, before/after bound callers, direct-call contracts and local risk estimate. Source-selection gaps are explicit; compiler/type/runtime behavior is not proven.".into(); + } + if !impact_reports.is_empty() { + graph.diagnostics.push(if report.view_comparison.is_some() { "Direct impact compares the two named effective recorded snapshots. Unchanged sources are caller context, not additional changed roots; no patch-prefix replay or dirty-source fallback." } else { "Direct impact uses recorded before/after view-prefix snapshots for each selected change; other files are caller context only, never later or dirty source." }.into()); + } + project(repo, report, &mut graph); + super::impact::project(&mut graph, &impact_reports); + if report.view_snapshot.is_some() { + super::risk::attach_snapshot(&mut graph); + } else { + super::risk::attach(&mut graph, risk_assessment, impact_reports, &profile) + .map_err(invalid)?; + } + if membership_hash(repo, &graph.scope.view)? != graph.scope.source_membership_hash + || repo + .get_view_info(&graph.scope.view) + .map_err(CliError::Repository)? + .state + .to_base32() + != graph.scope.view_state + { + return Err(invalid("review source membership changed during graph inspection; retry without reusing stale findings")); + } + for intent in &intents { + let inputs = atomic_repository::intent_bridge::read_intent(repo, &intent.node.human_key) + .map_err(CliError::Repository)?; + if atomic_repository::intent_bridge::source_content_hash(&inputs) != intent.source_hash { + return Err(invalid("review criterion source changed during graph inspection; retry without reusing stale judgments")); + } + } + graph.diagnostics.sort(); + graph.diagnostics.dedup(); + Ok(graph) +} + +fn validate_input( + repo: &Repository, + report: &IncrementalReport, + intents: &[IntentCriteria], + observation: &SubmittedFinding, +) -> CliResult<()> { + let finding = &observation.finding; + finding.validate().map_err(invalid)?; + let change = report + .changes + .iter() + .find(|change| change.selected_root && change.hash == finding.change) + .ok_or_else(|| invalid("finding is not about an exact selected root"))?; + if observation.pass == ReviewPass::IntentConformance && finding.acceptance_criteria.is_empty() { + return Err(invalid( + "intent-conformance finding requires an explicit acceptance-criterion assessment", + )); + } + let mut linked = BTreeSet::new(); + for link in &finding.acceptance_criteria { + if !linked.insert(&link.criterion) { + return Err(invalid("duplicate criterion assessment")); + } + if !intents + .iter() + .filter(|intent| governed(change, intent)) + .any(|intent| { + intent + .node + .has_acceptance_criterion + .iter() + .any(|criterion| criterion.id == link.criterion) + }) + { + return Err(invalid("finding criterion is missing or does not belong to this change's unambiguous governing intent")); + } + } + let hash = Hash::from_base32(finding.change.as_bytes()) + .ok_or_else(|| invalid("invalid finding change"))?; + for location in &finding.locations { + if location.path.is_empty() + || Path::new(&location.path) + .components() + .any(|part| !matches!(part, Component::Normal(_))) + { + return Err(invalid( + "finding requires a repository-relative recorded path", + )); + } + let bytes = match location.side { + SourceSide::Before => repo.get_file_content_before_change(&location.path, &hash), + SourceSide::After => repo.get_file_content_after_change(&location.path, &hash), + } + .map_err(CliError::Repository)? + .ok_or_else(|| invalid("finding location has no recorded content on the requested side"))?; + let source = std::str::from_utf8(&bytes) + .map_err(|_| invalid("finding source location is not UTF-8 text"))?; + if location.end_line as usize > source.split('\n').count() { + return Err(invalid( + "finding location exceeds the recorded source line range", + )); + } + } + Ok(()) +} + +#[derive(Default)] +struct Projection { + nodes: BTreeMap, + edges: BTreeSet, +} +impl Projection { + fn node(&mut self, id: &str, kind: &str, label: &str, properties: Value) { + self.nodes.entry(id.into()).or_insert_with(|| GraphNode { + id: id.into(), + kind: kind.into(), + label: label.into(), + properties, + }); + } + fn edge(&mut self, from: &str, relation: &str, to: &str) { + self.edges.insert(GraphEdge { + from: from.into(), + relation: relation.into(), + to: to.into(), + }); + } +} + +fn project(repo: &Repository, report: &IncrementalReport, graph: &mut ReviewGraph) { + let mut out = Projection::default(); + let project = repo.project_id().expect("resolved project"); + out.node( + "review", + "review", + "Three-pass review (not independent approval)", + encode(&graph.scope), + ); + let excluded: BTreeSet<_> = report + .analyses() + .flat_map(|(_, analysis)| analysis.excluded_metadata_paths.iter()) + .collect(); + if !excluded.is_empty() { + out.node( + "excluded-vault", + "analysis_exclusion", + ".vault metadata excluded from code analysis (retained as evidence)", + json!({"paths": excluded}), + ); + out.edge("review", "excludes_from_code_analysis", "excluded-vault"); + } + for pass in &graph.passes { + out.node( + pass.pass.id(), + "review_pass", + pass.pass.label(), + encode(pass), + ); + out.edge("review", "has_pass", pass.pass.id()); + } + for change in report.changes.iter().filter(|change| change.selected_root) { + let id = + iri::mint_change(&Hash::from_base32(change.hash.as_bytes()).expect("resolved hash")); + out.node(&id, "change", &change.hash, json!({"hash": change.hash})); + out.edge("review", "reviews", &id); + project_checks(&mut out, &change.analysis); + project_metrics(&mut out, &change.hash, &change.analysis, &project, None); + } + if let Some(snapshot) = &report.view_snapshot { + out.node(&snapshot.source_ref,"view_snapshot",&format!("Recorded view {}",snapshot.view),json!({"source_ref":snapshot.source_ref,"view":snapshot.view,"state":snapshot.state,"membership_hash":snapshot.membership_hash,"paths":snapshot.paths,"conformance":snapshot.conformance})); + out.edge("review", "reviews_snapshot", &snapshot.source_ref); + project_checks(&mut out, &snapshot.analysis); + project_metrics( + &mut out, + &snapshot.source_ref, + &snapshot.analysis, + &project, + Some("view_snapshot"), + ); + } + if let Some(comparison) = &report.view_comparison { + out.node( + &comparison.source_ref, + "view_comparison", + "Paired recorded views", + json!({"from":comparison.from,"to":comparison.to,"diagnostics":comparison.diagnostics,"conformance":comparison.conformance}), + ); + out.edge("review", "compares_views", &comparison.source_ref); + for file in &comparison.files { + out.node(&file.source_ref,"compared_file",&file.path,json!({"path":file.path,"before_path":file.before_path,"after_path":file.after_path,"status":file.status,"content_status":file.content_status})); + out.edge(&comparison.source_ref, "compares_file", &file.source_ref); + project_checks(&mut out, &file.analysis); + project_metrics( + &mut out, + &file.source_ref, + &file.analysis, + &project, + Some("view_comparison"), + ); + } + } + if let Some(conformance) = report.conformance() { + for intent in &conformance.intents { + out.node( + &intent.id, + "intent", + &format!("{} · {}", intent.human_key, intent.title), + encode(intent), + ); + out.edge( + ReviewPass::IntentConformance.id(), + "includes_view_scoped_intent", + &intent.id, + ); + } + } + for criterion in &graph.criteria { + out.node( + &criterion.id, + "acceptance_criterion", + &criterion.text, + encode(criterion), + ); + out.node( + &criterion.intent, + "intent", + &criterion.intent, + json!({"source_hash": criterion.source_hash}), + ); + out.edge(&criterion.intent, "declares", &criterion.id); + out.edge( + ReviewPass::IntentConformance.id(), + "assesses", + &criterion.id, + ); + } + let mut parser = None::; + for finding in &graph.findings { + out.node( + &finding.id, + "finding", + &format!("F{}: {}", finding.number, finding.finding.summary), + encode(finding), + ); + for pass in &finding.passes { + out.edge(pass.id(), "reports", &finding.id); + } + let rule = format!("rule:{}", finding.finding.requirement_or_rule.id); + out.node( + &rule, + "engineering_rule", + &finding.finding.requirement_or_rule.explanation, + encode(&finding.finding.requirement_or_rule), + ); + out.edge(&finding.id, "concerns_rule", &rule); + for criterion in &finding.related_criteria { + out.edge(&finding.id, "related_criterion_not_a_verdict", criterion); + } + for link in &finding.finding.acceptance_criteria { + out.edge( + &finding.id, + if link.assessment == CriterionOutcome::Unmet { + "assesses_unmet" + } else { + "assessment_unknown" + }, + &link.criterion, + ); + } + for location in &finding.finding.locations { + let id = local_id("location", &(&finding.finding.change, location)); + out.node( + &id, + "code_location", + &format!( + "{}:{}-{} ({:?})", + location.path, location.start_line, location.end_line, location.side + ), + json!({"change": finding.finding.change, "location": location}), + ); + out.edge(&finding.id, "located_at", &id); + let file = iri::mint_file(&project, &location.path); + out.node(&file, "file", &location.path, json!({"resource": file})); + out.edge(&id, "in_file", &file); + // Automatic contract findings already carry pinned semantic symbol + // identities; impact projection links them without another parse. + if finding.finding.requirement_or_rule.id + == "compatibility.resolved-direct-call-contract" + && finding + .finding + .analyzer + .starts_with("atomic-audit;direct-call-contracts=") + { + continue; + } + if atomic_repository::is_vault_path(&location.path) { + continue; + } + // Snapshot structure anchors already come from its metrics. Do not + // re-render and reparse a view file once for each located finding. + if report.is_view_review() { + continue; + } + let hash = Hash::from_base32(finding.finding.change.as_bytes()).expect("finding hash"); + let bytes = match location.side { + SourceSide::Before => repo.get_file_content_before_change(&location.path, &hash), + SourceSide::After => repo.get_file_content_after_change(&location.path, &hash), + }; + if let Ok(Some(bytes)) = bytes { + if bytes.len() > atomic_semantic::MAX_SOURCE_BYTES { + continue; + } + if let Ok(source) = std::str::from_utf8(&bytes) { + let entities = parser + .get_or_insert_with(ParserRegistry::new) + .extract(&location.path, source); + if let Some(entity) = entities + .iter() + .filter(|entity| { + entity.line <= location.start_line + && entity.end_line >= location.end_line + }) + .min_by_key(|entity| entity.end_line - entity.line) + { + let entity_id = local_id( + "structure", + &( + &finding.finding.change, + location.side.clone(), + &entity.file, + &entity.name, + entity.line, + ), + ); + out.node(&entity_id, "code_structure", &format!("{} {}", entity.kind, entity.name), json!({"change": finding.finding.change, "side": location.side, "entity": entity})); + out.edge(&id, "within", &entity_id); + out.edge(&entity_id, "in_file", &file); + } + } + } + } + for evidence in &finding.finding.evidence { + let id = local_id("evidence", evidence); + out.node(&id, "evidence", &evidence.observation, encode(evidence)); + out.edge(&finding.id, "supported_by", &id); + } + } + graph.nodes = out.nodes.into_values().collect(); + graph.edges = out.edges.into_iter().collect(); +} + +fn project_checks(out: &mut Projection, analysis: &AnalysisReport) { + for check in &analysis.checks { + let id = local_id("check", check); + out.node( + &id, + "check", + &format!("{}: {}", check.rule, check.path), + encode(check), + ); + out.edge(ReviewPass::AntiSlop.id(), "has_check", &id); + } +} + +fn measurement_label(value: &atomic_audit::Measurement) -> String { + match value { + atomic_audit::Measurement::Measured { value } => value.to_string(), + atomic_audit::Measurement::Unavailable { reason } => format!("unknown ({reason})"), + atomic_audit::Measurement::NotApplicable { .. } => "N/A".into(), + } +} + +fn project_metrics( + out: &mut Projection, + reference: &str, + analysis: &AnalysisReport, + project: &atomic_core::kg::project_id::ProjectId, + view_mode: Option<&str>, +) { + use atomic_audit::Metric; + if analysis.metrics.is_empty() { + return; + } + let scope = local_id("metric-scope", &reference); + out.node(&scope, "metric_comparison_scope", if view_mode.is_some() { "Recorded view corpus (see view/comparison root; language/subject/resource limits apply)" } else { "Recorded supplied paths only (not a repository-wide clone scan)" }, json!({ + "change": reference, "paths": analysis.metric_comparison_scope, "diagnostics": analysis.metric_diagnostics, + })); + for record in &analysis.metrics { + let metric = record.observation.metric; + let pass = if matches!(metric, Metric::DependencyFanOut | Metric::PublicSurface) { + ReviewPass::BlastRadiusRisk + } else { + ReviewPass::AntiSlop + }; + let id = local_id("metric", &(&reference, metric, &record.observation.subject)); + let delta = record + .delta + .map(|delta| format!(" (delta {delta:+})")) + .unwrap_or_default(); + let label = if view_mode == Some("view_snapshot") { + format!( + "{} {}: {} (recorded view snapshot)", + metric.id(), + record.observation.subject, + measurement_label(&record.observation.after) + ) + } else { + format!( + "{} {}: {} → {}{delta}", + metric.id(), + record.observation.subject, + measurement_label(&record.observation.before), + measurement_label(&record.observation.after) + ) + }; + let mut properties = encode(record); + properties["change"] = json!(reference); + if let Some(kind) = view_mode { + properties["scope_kind"] = json!(kind); + } + out.node(&id, "metric", &label, properties); + out.edge(pass.id(), "measures", &id); + out.edge(&id, "within_comparison_scope", &scope); + let card = atomic_audit::METRIC_CARDS + .iter() + .find(|card| card.metric == metric) + .expect("metric card"); + let card_id = format!("metric-card:{}", metric.id()); + out.node(&card_id, "metric_card", card.title, encode(card)); + out.edge(&id, "defined_by", &card_id); + let (location, side) = if let Some(location) = &record.after_location { + (Some(location), SourceSide::After) + } else { + (record.before_location.as_ref(), SourceSide::Before) + }; + if let Some(location) = location { + let location = atomic_canonical::review_finding::Location { + path: record.path.clone(), + side, + start_line: location.start_line, + end_line: location.end_line, + }; + let anchor = local_id("location", &(&reference, &location)); + out.node( + &anchor, + "code_location", + &format!( + "{}:{}-{} ({:?})", + location.path, location.start_line, location.end_line, location.side + ), + json!({"change": reference, "location": location}), + ); + out.edge(&id, "located_at", &anchor); + let file = iri::mint_file(project, &record.path); + out.node(&file, "file", &record.path, json!({"resource": file})); + out.edge(&anchor, "in_file", &file); + if matches!( + record.scope, + atomic_audit::catalog::MetricScope::Function + | atomic_audit::catalog::MetricScope::Class + ) { + let subject = local_id( + "metric-subject", + &(&reference, &record.observation.subject, &location.side), + ); + out.node( + &subject, + "code_structure", + &record.observation.subject, + json!({"change": reference, "scope": record.scope, "location": location}), + ); + out.edge(&id, "measures_structure", &subject); + out.edge(&subject, "located_at", &anchor); + } + } + } +} + +/// Terminal presentation uses the same numbered findings and source anchors. +#[cfg(test)] +pub(super) fn render(graph: &ReviewGraph) -> String { + render_with_details(graph, false) +} + +pub(super) fn render_with_details(graph: &ReviewGraph, details: bool) -> String { + super::terminal::render(graph, details) +} diff --git a/atomic-cli/src/commands/review/html.rs b/atomic-cli/src/commands/review/html.rs new file mode 100644 index 00000000..6952b539 --- /dev/null +++ b/atomic-cli/src/commands/review/html.rs @@ -0,0 +1,475 @@ +//! Offline review artifact. All source reads are pinned to the selected change, +//! and exported text is data, never trusted HTML or executable JavaScript. + +use super::{incremental::IncrementalReport, presentation}; +use crate::error::{CliError, CliResult}; +use atomic_canonical::review_finding::SourceSide; +use atomic_canonical::review_graph::ReviewGraph; +use atomic_core::types::{Base32, Hash}; +use atomic_repository::Repository; +use serde::Serialize; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Debug, Serialize)] +#[serde(tag = "status", rename_all = "snake_case")] +enum SourceText { + Present { text: String }, + Absent, + Unavailable { reason: String }, +} + +impl SourceText { + fn unavailable(reason: impl Into) -> Self { + Self::Unavailable { + reason: reason.into(), + } + } +} + +#[derive(Debug, Serialize)] +struct Snapshot { + change: String, + path: String, + reviewed_root: bool, + before: SourceText, + after: SourceText, +} + +#[derive(Default)] +struct Request { + known: BTreeSet, + absent: BTreeSet, + findings: bool, +} + +pub(super) fn render(repo: &Repository, report: &IncrementalReport) -> CliResult { + super::view_snapshot::verify(repo, report)?; + let graph = report.graph.as_ref().expect("resolved review graph"); + let regions = presentation::regions(graph); + let sources = sources(repo, report, ®ions); + super::view_snapshot::verify(repo, report)?; + let patterns: BTreeMap<_, _> = atomic_audit::structural::Rule::ALL + .into_iter() + .map(|rule| (rule.id(), rule.coverage())) + .collect(); + // Archive exactly the same bounded report as --json, without a JavaScript + // number roundtrip. Dependency-only changes carry references, not patches. + let mut archive = std::io::BufWriter::new(flate2::write::GzEncoder::new( + Vec::new(), + flate2::Compression::fast(), + )); + serde_json::to_writer(&mut archive, report) + .map_err(|error| CliError::Internal(error.into()))?; + let archive = archive + .into_inner() + .map_err(|error| CliError::Internal(error.into()))? + .finish()?; + let archive = data_encoding::BASE64.encode(&archive); + let view = json!({ + "selected_roots":report.selected_roots,"warnings":report.warnings, + "view_snapshot":report.view_snapshot.as_ref().map(|snapshot|json!({"source_ref":snapshot.source_ref,"view":snapshot.view,"state":snapshot.state,"membership_hash":snapshot.membership_hash,"file_count":snapshot.paths.len(),"conformance":snapshot.conformance})), + "view_comparison":report.view_comparison.as_ref().map(|comparison|json!({"source_ref":comparison.source_ref,"from":comparison.from,"to":comparison.to,"diagnostics":comparison.diagnostics,"conformance":comparison.conformance,"files":comparison.files.iter().map(|file|json!({"source_ref":file.source_ref,"path":file.path,"before_path":file.before_path,"after_path":file.after_path,"status":file.status,"content_status":file.content_status})).collect::>()})), + "changes":report.changes.iter().filter(|change|change.selected_root).map(|change|json!({"hash":change.hash,"diff":change.diff,"diff_status":change.diff_status})).collect::>(), + "graph":{"scope":graph.scope,"passes":graph.passes,"findings":graph.findings,"criteria":graph.criteria,"diagnostics":graph.diagnostics,"risk":graph.risk, + "nodes":graph.nodes.iter().filter(|node|matches!(node.kind.as_str(),"metric"|"check")).collect::>()} + }); + let profile_json = graph + .risk + .as_ref() + .and_then(|risk| risk.model.as_ref()) + .map(|model| serde_json::to_string_pretty(&model.profile)) + .transpose() + .map_err(|error| CliError::Internal(error.into()))?; + emit( + json!({"schema":"atomic.review-viewer.v1","local_only":true,"view":view,"report_archive":{"encoding":"gzip+base64","data":archive},"profile_json":profile_json,"regions":regions,"sources":sources,"audit_cards":atomic_audit::AUDIT_CARDS,"metric_cards":atomic_audit::METRIC_CARDS,"patterns":patterns}), + &super::terminal::render(graph, false), + ) +} + +fn collect_requests( + graph: &ReviewGraph, + regions: &[presentation::Region], +) -> BTreeMap<(String, String), Request> { + let mut requests = BTreeMap::<(String, String), Request>::new(); + for region in regions { + let request = requests + .entry((region.change.clone(), region.path.clone())) + .or_default(); + request.findings |= !region.findings.is_empty(); + if !region.findings.is_empty() || !region.impact.is_empty() { + request.known.insert(region.side.clone()); + } + } + for node in graph.nodes.iter().filter(|node| node.kind == "metric") { + let (Some(change), Some(path)) = ( + node.properties["change"].as_str(), + node.properties["path"].as_str(), + ) else { + continue; + }; + let request = requests.entry((change.into(), path.into())).or_default(); + for side in ["before", "after"] { + let value = &node.properties["observation"][side]; + if value["status"] == "measured" + && presentation::metric_location(node, side).0.is_some() + { + request.known.insert(side.into()); + } + if value["status"] == "not_applicable" + && value["reason"] == "File is absent in this revision" + { + request.absent.insert(side.into()); + } + } + } + // Explicit source locations also cover supplied findings without metrics. + for finding in &graph.findings { + for location in &finding.finding.locations { + requests + .entry((finding.finding.change.clone(), location.path.clone())) + .or_default() + .known + .insert( + match location.side { + SourceSide::Before => "before", + SourceSide::After => "after", + } + .into(), + ); + } + } + requests +} + +fn sources( + repo: &Repository, + report: &IncrementalReport, + regions: &[presentation::Region], +) -> Vec { + let graph = report.graph.as_ref().expect("resolved review graph"); + let mut requests = collect_requests(graph, regions) + .into_iter() + .collect::>(); + let reviewed: BTreeSet<_> = report + .changes + .iter() + .filter(|change| change.selected_root) + .flat_map(|change| { + change + .paths + .iter() + .map(|path| (change.hash.clone(), path.clone())) + }) + .chain(report.view_snapshot.iter().flat_map(|snapshot| { + snapshot + .paths + .iter() + .map(|path| (snapshot.source_ref.clone(), path.clone())) + })) + .chain(report.view_comparison.iter().flat_map(|comparison| { + comparison.files.iter().flat_map(|file| { + std::iter::once(file.path.as_str()) + .chain(file.before_path.as_deref()) + .chain(file.after_path.as_deref()) + .map(|path| (file.source_ref.clone(), path.to_owned())) + }) + })) + .chain(report.view_comparison.iter().flat_map(|comparison| { + comparison + .files + .iter() + .flat_map(|file| file.before_path.iter().chain(&file.after_path)) + .map(|path| (comparison.source_ref.clone(), path.clone())) + })) + .collect(); + requests.sort_by(|(left, a), (right, b)| { + b.findings + .cmp(&a.findings) + .then(reviewed.contains(right).cmp(&reviewed.contains(left))) + .then(b.known.len().cmp(&a.known.len())) + .then(left.cmp(right)) + }); + let config = atomic_audit::extract::ExtractionConfig::default(); + let mut bytes = config.max_total_bytes; + let mut files = 0; + let mut result = Vec::new(); + for ((change, path), request) in requests { + let reviewed_root = reviewed.contains(&(change.clone(), path.clone())); + let comparison_file = report + .view_comparison + .as_ref() + .and_then(|comparison| comparison.file(&change)); + let comparable_bytes = comparison_file + .is_some_and(|file| file.before_hash.is_some() || file.after_hash.is_some()); + // References and unavailable observations consume no source-read budget. + let limited = if !reviewed_root || (request.known.is_empty() && !comparable_bytes) { + false + } else if files >= config.max_files { + true + } else { + files += 1; + false + }; + let on_view = report + .changes + .iter() + .any(|item| item.hash == change && item.selected_root && item.on_current_view); + let hash = Hash::from_base32(change.as_bytes()); + let mut load = |side: &str| { + if let Some(comparison) = report + .view_comparison + .as_ref() + .filter(|comparison| comparison.source_ref == change) + { + if atomic_repository::is_vault_path(&path) { + return SourceText::unavailable( + "Vault definitions are conformance evidence, not code-source export", + ); + } + let pin = if side == "before" { + &comparison.from + } else { + &comparison.to + }; + let belongs = comparison.files.iter().any(|file| { + if side == "before" { + file.before_path.as_ref() == Some(&path) + } else { + file.after_path.as_ref() == Some(&path) + } + }); + if !belongs { + return SourceText::Absent; + } + let inspected = comparison.files.iter().any(|file| { + if side == "before" { + file.before_path.as_ref() == Some(&path) && file.before_hash.is_some() + } else { + file.after_path.as_ref() == Some(&path) && file.after_hash.is_some() + } + }); + if !inspected { + return SourceText::unavailable("This recorded side was unavailable, non-regular or outside the source inspection budget"); + } + if limited || bytes == 0 { + return SourceText::unavailable("HTML source export budget exceeded; evidence and every finding remain in the report"); + } + return source_text(repo.get_file_content_on_view(&path, &pin.view), &mut bytes); + } + if let (Some(comparison), Some(file)) = (&report.view_comparison, comparison_file) { + let (actual, pin, hash) = if side == "before" { + (&file.before_path, &comparison.from, &file.before_hash) + } else { + (&file.after_path, &comparison.to, &file.after_hash) + }; + let Some(actual) = actual else { + return SourceText::Absent; + }; + if atomic_repository::is_vault_path(actual) { + return SourceText::unavailable( + "Vault metadata is excluded from code-source export", + ); + } + if !request.known.contains(side) && hash.is_none() { + return SourceText::unavailable("This recorded comparison side was not reliably inspected; no working-copy fallback"); + } + if limited || bytes == 0 { + return SourceText::unavailable( + "HTML source export budget exceeded; source is not silently truncated", + ); + } + return source_text(repo.get_file_content_on_view(actual, &pin.view), &mut bytes); + } + if report.view_snapshot.is_some() && side == "before" { + return SourceText::unavailable(super::analysis::SNAPSHOT_BASELINE); + } + if !reviewed_root { + return SourceText::unavailable("Caller context is a bounded recorded reference, not a reviewed path; full caller source is excluded from export"); + } + if atomic_repository::is_vault_path(&path) { + return SourceText::unavailable("Vault metadata is excluded from code-source export; intent and recorded diff evidence remain in the report"); + } + if request.absent.contains(side) && !request.known.contains(side) { + return SourceText::Absent; + } + if !request.known.contains(side) { + return SourceText::unavailable("Source was unavailable or not inspected for this recorded side; no working-copy fallback"); + } + if limited || bytes == 0 { + return SourceText::unavailable( + "HTML source export budget exceeded; source is not silently truncated", + ); + } + if let Some(snapshot) = &report.view_snapshot { + if snapshot.source_ref != change { + return SourceText::unavailable( + "Source does not belong to the pinned view snapshot", + ); + } + return source_text( + repo.get_file_content_on_view(&path, &snapshot.view), + &mut bytes, + ); + } + if !on_view { + return SourceText::unavailable( + "Exact recorded snapshot is off the selected source view", + ); + } + let Some(hash) = &hash else { + return SourceText::unavailable("Invalid recorded change reference"); + }; + read_source(repo, hash, &path, side, &mut bytes) + }; + // Most concern anchors are after-side; preserve their source first when + // the explicit total budget cannot hold both snapshots. + let after = load("after"); + let before = load("before"); + result.push(Snapshot { + change, + path, + reviewed_root, + before, + after, + }); + } + result +} + +fn read_source( + repo: &Repository, + hash: &Hash, + path: &str, + side: &str, + bytes: &mut usize, +) -> SourceText { + let result = if side == "before" { + repo.get_file_content_before_change(path, hash) + } else { + repo.get_file_content_after_change(path, hash) + }; + source_text(result, bytes) +} + +fn source_text( + result: Result>, atomic_repository::RepositoryError>, + bytes: &mut usize, +) -> SourceText { + match result { + Ok(Some(content)) + if content.len() <= atomic_semantic::MAX_SOURCE_BYTES && content.len() <= *bytes => + { + if content.contains(&0) { + return SourceText::unavailable("Recorded content is binary"); + } + match String::from_utf8(content) { + Ok(text) => { + *bytes -= text.len(); + SourceText::Present { text } + } + Err(_) => SourceText::unavailable("Recorded content is not UTF-8"), + } + } + Ok(Some(_)) => { + SourceText::unavailable("Recorded source exceeds the HTML source byte budget") + } + Ok(None) => SourceText::unavailable( + "Recorded source reference could not be materialized; no working-copy fallback", + ), + Err(error) => SourceText::unavailable(format!("Recorded source unavailable: {error}")), + } +} + +fn escape(text: &str) -> String { + text.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) + .replace('\'', "'") +} + +fn emit(document: Value, fallback: &str) -> CliResult { + let data = serde_json::to_string(&document) + .map_err(|error| CliError::Internal(error.into()))? + .replace('<', "\\u003c") + .replace('>', "\\u003e") + .replace('&', "\\u0026") + .replace('\u{2028}', "\\u2028") + .replace('\u{2029}', "\\u2029"); + let nonce = uuid::Uuid::new_v4().simple().to_string(); + Ok(format!( + include_str!("viewer.html"), + nonce = nonce, + logo = data_encoding::BASE64.encode(include_bytes!("assets/atomic-logo.png")), + css = include_str!("viewer.css"), + script = include_str!("viewer.js"), + data = data, + fallback = escape(fallback) + )) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn source_and_metadata_cannot_break_out_of_the_embedded_document() { + let hostile = "&\u{2028}\u{2029}"; + let html = emit(json!({"hostile":hostile}), hostile).unwrap(); + assert!(!html.contains(hostile)); + assert!(!html.contains("') + .unwrap() + .1 + .split("") + .next() + .unwrap(); + assert_eq!( + serde_json::from_str::(data).unwrap()["hostile"], + hostile + ); + assert!(html.contains("default-src 'none'") && html.contains("connect-src 'none'")); + assert!(!html.contains("") + .next() + .unwrap(); + let document: Value = serde_json::from_str(encoded).unwrap(); + let compressed = data_encoding::BASE64 + .decode( + document["report_archive"]["data"] + .as_str() + .unwrap() + .as_bytes(), + ) + .unwrap(); + let mut restored = String::new(); + flate2::read::GzDecoder::new(compressed.as_slice()) + .read_to_string(&mut restored) + .unwrap(); + assert_eq!(restored, original); + assert!(include_str!("viewer.js").contains("new DecompressionStream('gzip')")); + } +} diff --git a/atomic-cli/src/commands/review/impact.rs b/atomic-cli/src/commands/review/impact.rs new file mode 100644 index 00000000..2de35ce9 --- /dev/null +++ b/atomic-cli/src/commands/review/impact.rs @@ -0,0 +1,273 @@ +//! Recorded snapshot adapter for pure-source direct-call contract analysis. + +use atomic_audit::impact::ImpactReport; +use atomic_canonical::review_finding::{ + Confidence, Evidence, EvidenceKind, Introduction, IntroductionStatus, Location, ReviewFinding, + RuleReference, Severity, SourceSide, +}; +use atomic_canonical::review_graph::{ + FindingComparison, GraphEdge, GraphNode, ReviewGraph, ReviewPass, SubmittedFinding, +}; +use atomic_core::types::{Base32, Hash}; +use atomic_repository::{repository::RecordedSemanticView, Repository}; +use atomic_semantic::ParserRegistry; +use std::collections::BTreeSet; + +use super::incremental::IncrementalReport; + +pub(super) fn inspect( + repo: &Repository, + report: &IncrementalReport, +) -> (Vec, Vec) { + let (mut results, mut findings) = (Vec::new(), Vec::new()); + let mut parser = ParserRegistry::new(); + for change in report.changes.iter().filter(|change| { + change.selected_root + && change + .paths + .iter() + .any(|path| !atomic_repository::is_vault_path(path)) + }) { + let mut result = ImpactReport { + change: change.hash.clone(), + code_changed: true, + ..Default::default() + }; + let paths: Vec<_> = change + .paths + .iter() + .filter(|path| !atomic_repository::is_vault_path(path)) + .cloned() + .collect(); + if !paths.iter().any(|path| atomic_semantic::is_supported(path)) { + result.gaps.push("No supported source in selected paths; non-code/runtime configuration effects require separate inspection".into()); + results.push(result); + continue; + } + if results.len() >= 4 { + result.gaps.push( + "Impact snapshot budget reached (4 selected changes); remaining roots not analyzed" + .into(), + ); + results.push(result); + continue; + } + let hash = Hash::from_base32(change.hash.as_bytes()).expect("resolved selected hash"); + match ( + repo.semantic_view_at_change(&hash, false), + repo.semantic_view_at_change(&hash, true), + ) { + (Ok(before_view), Ok(after_view)) => { + result = inspect_views(&before_view, &after_view, &paths, &mut parser); + result.change = hash.to_base32(); + } + (before, after) => { + if let Err(error) = before { + result + .gaps + .push(format!("Before snapshot unavailable: {error}")); + } + if let Err(error) = after { + result + .gaps + .push(format!("After snapshot unavailable: {error}")); + } + } + } + findings.extend(contract_findings(&result)); + results.push(result); + } + (results, findings) +} + +pub(super) fn inspect_views( + before_view: &RecordedSemanticView<'_>, + after_view: &RecordedSemanticView<'_>, + paths: &[String], + parser: &mut ParserRegistry, +) -> ImpactReport { + let before = before_view.changed_sources(paths, parser); + let after = after_view.changed_sources(paths, parser); + let callable = |kind: atomic_semantic::EntityKind| { + matches!( + kind, + atomic_semantic::EntityKind::Function | atomic_semantic::EntityKind::Method + ) + }; + let old: std::collections::BTreeMap<_, _> = before + .files + .iter() + .flat_map(|file| &file.symbols) + .filter(|symbol| callable(symbol.entity.kind)) + .map(|symbol| (&symbol.id, symbol)) + .collect(); + let new: std::collections::BTreeMap<_, _> = after + .files + .iter() + .flat_map(|file| &file.symbols) + .filter(|symbol| callable(symbol.entity.kind)) + .map(|symbol| (&symbol.id, symbol)) + .collect(); + let targets: Vec<_> = old + .values() + .chain(new.values()) + .filter(|symbol| { + !old.get(&symbol.id) + .zip(new.get(&symbol.id)) + .is_some_and(|(a, b)| { + a.tokens == b.tokens + && a.public == b.public + && a.restricted == b.restricted + && a.parent_visible == b.parent_visible + && a.conditional == b.conditional + }) + }) + .map(|symbol| (*symbol).clone()) + .collect(); + match ( + before_view.select_context(before, &targets, parser), + after_view.select_context(after, &targets, parser), + ) { + (Ok(before), Ok(after)) => atomic_audit::impact::analyze_semantic(before, after, paths), + (before, after) => { + let mut result = ImpactReport { + code_changed: true, + ..Default::default() + }; + if let Err(error) = before { + result + .gaps + .push(format!("Before semantic selection unavailable: {error}")); + } + if let Err(error) = after { + result + .gaps + .push(format!("After semantic selection unavailable: {error}")); + } + result + } + } +} + +pub(super) fn contract_findings(result: &ImpactReport) -> Vec { + let mut findings = Vec::new(); + let reference = &result.change; + let comparison = reference.starts_with("urn:atomic:view-comparison:"); + for issue in &result.issues { + let location = &issue.primary_location; + let side = if issue.primary_before { + SourceSide::Before + } else { + SourceSide::After + }; + findings.push(SubmittedFinding { pass: ReviewPass::BlastRadiusRisk, finding: ReviewFinding { + analyzer: format!("atomic-audit;direct-call-contracts=v1;{}", atomic_audit::VERSION), + change: reference.clone(), summary: issue.summary.clone(), + locations: vec![Location { path: location.path.clone(), side, start_line: location.start_line, end_line: location.end_line }], + requirement_or_rule: RuleReference { id: "compatibility.resolved-direct-call-contract".into(), explanation: "Supported direct references must satisfy declaration availability, declared visibility/export access, and fixed/optional/rest argument-count contracts.".into() }, + evidence: vec![ + Evidence { kind: EvidenceKind::Source, reference: format!("{}:after:{}:{}-{}", reference, issue.call.location.path, issue.call.location.start_line, issue.call.location.end_line), observation: format!("Caller {} targets {}. {}", issue.call.caller, issue.function, issue.evidence) }, + Evidence { kind: EvidenceKind::Diff, reference: issue.before_declaration.as_ref().map(|location| format!("{}:before:{}:{}-{}", reference, location.path, location.start_line, location.end_line)).unwrap_or_else(|| format!("{}:before", reference)), observation: if comparison { "Static declaration and call-expression evidence between the pinned From/To view states; not attribution to an authored change." } else if issue.introduced { "Recorded binding/call-expression comparison establishes an introduced incompatible call or a surviving previously compatible call broken by the selected declaration change." } else { "An after-side incompatibility is established, but baseline coverage/binding does not establish introduction by this change." }.into() }, + ], + introduced_by_change: Introduction { status: if issue.introduced && !comparison { IntroductionStatus::Yes } else { IntroductionStatus::Unknown }, rationale: if comparison { "Compared recorded view states establish static contract evidence, not introduction by one authored change." } else if issue.introduced { "Recorded before/after declaration and call-expression comparison attributes the new incompatible direct call to the selected change." } else { "After-side binding/arity is incompatible, but introduction is not established by the available baseline." }.into() }, + severity: Severity::High, confidence: if issue.call.configuration_dependent { Confidence::Medium } else { Confidence::High }, + proposed_correction: "Update the affected consumer and declaration together, or preserve a compatible adapter; add a focused regression test for the recorded call contract.".into(), acceptance_criteria: vec![], + }}); + } + findings +} + +pub(super) fn comparison_state(issue: &atomic_audit::impact::ContractIssue) -> FindingComparison { + FindingComparison { + status: if issue.introduced { "new" } else { "unknown" }.into(), + before: issue.before_declaration.iter().map(|location|Location {path:location.path.clone(),side:SourceSide::Before,start_line:location.start_line,end_line:location.end_line}).collect(), + after: vec![Location {path:issue.call.location.path.clone(),side:SourceSide::After,start_line:issue.call.location.start_line,end_line:issue.call.location.end_line}], + rationale:"Static call-contract evidence between the two pinned view states; not introduction by one authored change or whole-program proof.".into(), + } +} + +pub(super) fn project(graph: &mut ReviewGraph, reports: &[ImpactReport]) { + let mut present: BTreeSet<_> = graph.nodes.iter().map(|node| node.id.clone()).collect(); + for report in reports { + let id = format!("direct-impact:{}", report.change); + graph.nodes.push(GraphNode { + id: id.clone(), + kind: "direct_impact_analysis".into(), + label: "Recorded before/after direct-call and contract evidence".into(), + properties: serde_json::to_value(report).expect("impact report serializes"), + }); + graph.edges.push(GraphEdge { + from: ReviewPass::BlastRadiusRisk.id().into(), + relation: "analyzes_direct_impact".into(), + to: id, + }); + for (side, calls) in [ + ("before", &report.callers_before), + ("after", &report.callers_after), + ("after", &report.callees_after), + ] { + for call in calls { + let from = format!("bound-function:{}:{side}:{}", report.change, call.caller); + let to = format!("bound-function:{}:{side}:{}", report.change, call.callee); + for (id, name) in [(&from, &call.caller), (&to, &call.callee)] { + if present.insert(id.clone()) { + graph.nodes.push(GraphNode { + id: id.clone(), + kind: "bound_function".into(), + label: name.clone(), + properties: serde_json::json!({"change": report.change, "side": side}), + }); + } + } + graph.edges.push(GraphEdge { + from, + relation: if !call.target_present { + "surviving_reference_to_removed_function" + } else if !call.visibility_compatible { + "inaccessible_direct_reference" + } else { + "statically_bound_direct_call" + } + .into(), + to, + }); + } + } + for finding in graph.findings.iter().filter(|finding| { + finding.finding.change == report.change + && finding.finding.requirement_or_rule.id + == "compatibility.resolved-direct-call-contract" + }) { + for issue in report.issues.iter().filter(|issue| { + issue.summary == finding.finding.summary + && finding.finding.locations.iter().any(|location| { + location.path == issue.primary_location.path + && location.start_line == issue.primary_location.start_line + && location.end_line == issue.primary_location.end_line + }) + }) { + let symbol = + if issue.primary_location == issue.call.location && !issue.primary_before { + &issue.call.caller + } else { + &issue.function + }; + let side = if issue.primary_before { + "before" + } else { + "after" + }; + let id = format!("bound-function:{}:{side}:{symbol}", report.change); + if present.contains(&id) { + graph.edges.push(GraphEdge { + from: finding.id.clone(), + relation: "concerns_callable".into(), + to: id, + }); + } + } + } + } + graph.edges.sort(); + graph.edges.dedup(); +} diff --git a/atomic-cli/src/commands/review/incremental.rs b/atomic-cli/src/commands/review/incremental.rs new file mode 100644 index 00000000..8c6da02a --- /dev/null +++ b/atomic-cli/src/commands/review/incremental.rs @@ -0,0 +1,3188 @@ +//! Bounded-by-selection, read-only inspection. This is not a review approval. + +use std::collections::{BTreeMap, BTreeSet}; + +use atomic_agent::turn::session::{AgentSession, SessionStore}; +use atomic_core::change::session::{SessionRecord, SessionTurn}; +use atomic_core::kg::iri; +use atomic_core::pristine::{GraphTxnT, ViewMembershipSet}; +use atomic_core::types::{Base32, Hash}; +use atomic_repository::intent_bridge as bridge; +use atomic_repository::{graph_visibility_from_membership, Repository}; +use clap::Args; +use serde::Serialize; +use serde_json::{json, Value}; + +use crate::commands::find_repository_root; +use crate::error::{CliError, CliResult}; + +#[derive(Args, Debug, Clone, Default)] +pub struct IncrementalArgs { + /// Inspect exactly one ledger turn (SESSION:TURN), including pending work. + #[arg(long, value_name = "SESSION:TURN", conflicts_with_all = ["intent", "change", "view"])] + pub turn: Option, + /// Inspect changes with an actual recorded governing intent declaration. + #[arg(long, value_name = "ID", conflicts_with_all = ["turn", "change", "view"])] + pub intent: Option, + /// Inspect one recorded change (full hash or unambiguous Base32 prefix). + #[arg(long, value_name = "HASH", conflicts_with_all = ["turn", "intent", "view"])] + pub change: Option, + /// Audit every live recorded file in this view, including inherited files. + #[arg(long, value_name = "NAME", conflicts_with_all = ["turn", "intent", "change", "findings", "risk_profile"])] + pub view: Option, + /// Before view for a local recorded-view comparison (requires --to). + #[arg(long, value_name="VIEW", requires="to", conflicts_with_all=["view","change","turn","intent","findings","risk_profile"])] + pub from: Option, + /// After view for a local recorded-view comparison (requires --from). + #[arg(long, value_name="VIEW", requires="from", conflicts_with_all=["view","change","turn","intent","findings","risk_profile"])] + pub to: Option, + #[arg(long, conflicts_with = "html")] + pub json: bool, + /// Open an offline file/region review viewer in the default browser. + #[arg(long, conflicts_with = "details")] + pub html: bool, + /// Do not open a browser; emit HTML to stdout or --output. + #[arg(long, requires = "html")] + pub no_open: bool, + /// Write the requested HTML report to this file. + #[arg(short, long, requires = "html", value_name = "FILE")] + pub output: Option, + /// Add exact-scope reviewer findings, criterion judgments and risk assessment. + #[arg(long, value_name = "FILE")] + pub findings: Option, + /// Override the versioned change-review risk thresholds with a JSON profile. + #[arg(long, value_name = "FILE")] + pub risk_profile: Option, + /// Include the inspection worklist, intent text and diffs below the graph. + #[arg(long)] + pub details: bool, +} + +/// Exact selected roots are separate from their required causal context. +#[derive(Debug, Serialize)] +pub struct IncrementalReport { + pub schema_version: u32, + pub purpose: &'static str, + pub independent_approval: bool, + pub selection: Selection, + pub source: Value, + pub selected_roots: Vec, + /// Includes roots, in canonical dependency-first order. + pub dependency_closure: Vec, + pub dependency_only: Vec, + /// Dependency-only causal references, never ancestor review payloads. + pub dependency_references: Vec, + /// Full inspections belong exclusively to selected roots. + pub changes: Vec, + /// Whole-view snapshot evidence, not an invented authored change. + #[serde(skip_serializing_if = "Option::is_none")] + pub view_snapshot: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub view_comparison: Option, + pub turns: Vec, + /// Live work on this view, explicitly outside the recorded selection. + pub pending_work_outside_selection: Vec, + pub intents: Vec, + pub warnings: Vec, + pub graph: Option, +} + +#[derive(Debug, Serialize)] +pub struct ViewInspection { + #[serde(skip_serializing_if = "Option::is_none")] + pub conformance: Option, + pub source_ref: String, + pub view: String, + pub state: String, + pub membership_hash: String, + pub paths: Vec, + pub analysis: atomic_canonical::review_finding::AnalysisReport, + #[serde(skip)] + pub(crate) content_hashes: BTreeMap, +} + +impl IncrementalReport { + pub(super) fn analyses( + &self, + ) -> impl Iterator { + self.changes + .iter() + .filter(|change| change.selected_root) + .map(|change| (change.hash.as_str(), &change.analysis)) + .chain( + self.view_snapshot + .iter() + .map(|snapshot| (snapshot.source_ref.as_str(), &snapshot.analysis)), + ) + .chain(self.view_comparison.iter().flat_map(|comparison| { + comparison + .files + .iter() + .map(|file| (file.source_ref.as_str(), &file.analysis)) + })) + } + + pub(super) fn is_view_review(&self) -> bool { + self.view_snapshot.is_some() || self.view_comparison.is_some() + } + + pub(super) fn conformance(&self) -> Option<&super::view_comparison::Conformance> { + self.view_comparison + .as_ref() + .map(|comparison| &comparison.conformance) + .or_else(|| self.view_snapshot.as_ref()?.conformance.as_ref()) + } +} + +#[derive(Debug, Serialize)] +pub struct DependencyReference { + pub hash: String, + pub direct: bool, + pub on_current_view: bool, + /// First header line, at most 240 Unicode characters; not the full message. + pub summary: String, + pub dependencies: Vec, +} + +#[derive(Debug, Serialize)] +pub struct Selection { + pub kind: String, + pub value: Option, + pub reason: String, +} + +#[derive(Debug, Serialize)] +pub struct ChangeInspection { + pub hash: String, + pub selected_root: bool, + pub on_current_view: bool, + pub metadata: Value, + pub dependencies: Vec, + pub paths: Vec, + pub intent_context: Value, + pub recorded_patch: Value, + pub diff: Option, + pub diff_status: String, + pub analysis: atomic_canonical::review_finding::AnalysisReport, +} + +#[derive(Debug, Serialize)] +pub struct TurnInspection { + pub session_id: String, + pub view_name: Option, + pub turn_number: u32, + pub status: String, + pub session_status: String, + pub plan_id: Option, + pub provenance_hash: Option, + pub change_hashes: Vec, + pub outcome: Value, +} + +fn invalid(message: impl Into) -> CliError { + CliError::InvalidArgument { + message: message.into(), + } +} + +fn encode(value: &T) -> CliResult { + serde_json::to_value(value).map_err(|e| CliError::Internal(e.into())) +} + +fn validate_session(id: &str) -> CliResult<()> { + // Match SessionStore's path-component contract even when no store exists. + if id.is_empty() || id.len() > 255 || id.contains("..") || id.contains(['/', '\\', '\0']) { + return Err(invalid("Invalid session ID in turn/session context")); + } + Ok(()) +} + +fn parse_turn(input: &str) -> CliResult<(&str, u32)> { + let (session, number) = input + .rsplit_once(':') + .ok_or_else(|| invalid("--turn must be SESSION:TURN"))?; + validate_session(session)?; + if number.is_empty() || !number.bytes().all(|b| b.is_ascii_digit()) { + return Err(invalid("--turn requires a nonnegative ledger turn number")); + } + let number = number + .parse::() + .map_err(|_| invalid("Turn number exceeds u32"))?; + Ok((session, number)) +} + +fn runtime_store(repo: &Repository) -> CliResult> { + let directory = repo.dot_dir().join("sessions"); + // SessionStore::new creates directories. Never call it on an absent store. + match std::fs::metadata(&directory) { + Ok(metadata) if metadata.is_dir() => SessionStore::new(directory) + .map(Some) + .map_err(|e| CliError::Internal(e.into())), + Ok(_) => Err(invalid("Session store is not a directory")), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(CliError::Internal(e.into())), + } +} + +fn runtime_session(store: Option<&SessionStore>, id: &str) -> CliResult> { + validate_session(id)?; + let session = store + .map(|s| s.load(id)) + .transpose() + .map_err(|e| CliError::Internal(e.into()))? + .flatten(); + if session.as_ref().is_some_and(|s| s.session_id != id) { + return Err(invalid( + "Runtime session identity does not match its filename", + )); + } + Ok(session) +} + +fn intent_key(repo: &Repository, reference: &str) -> CliResult { + if reference.trim() != reference || reference.is_empty() { + return Err(invalid( + "Intent selector must not be empty or padded with whitespace", + )); + } + let key = repo + .resolve_intent_key(reference) + .map_err(CliError::Repository)?; + // resolve_intent_key intentionally permits not-yet-created human keys. + repo.vault_intent_show(&key).map_err(CliError::Repository)?; + Ok(key) +} + +fn same_intent(repo: &Repository, reference: &str, key: &str) -> bool { + repo.resolve_intent_key(reference) + .is_ok_and(|resolved| resolved == key) +} + +fn current_plan( + repo: &Repository, + store: Option<&SessionStore>, + session_id: &str, +) -> CliResult> { + let runtime = runtime_session(store, session_id)?; + let ledger = repo + .get_session_ledger(session_id) + .map_err(CliError::Repository)?; + if runtime.is_none() && ledger.is_none() { + return Err(invalid(format!( + "Unknown explicit session context: {session_id}" + ))); + } + let mut keys = BTreeSet::new(); + let runtime_active = runtime.as_ref().is_some_and(AgentSession::is_turn_active); + if let Some(runtime) = runtime { + if runtime.view_name != repo.current_view() { + return Err(invalid( + "Explicit session context belongs to a different view", + )); + } + if runtime.is_turn_active() { + let turn = runtime + .turn_count + .checked_add(1) + .ok_or_else(|| invalid("Turn overflow"))?; + if let Some(binding) = store + .map(|s| s.turn_intent_binding(session_id, turn)) + .transpose() + .map_err(|e| CliError::Internal(e.into()))? + .flatten() + { + keys.insert(intent_key(repo, &binding.intent_uid)?); + } + if let Some(work_item) = runtime.managed_run.and_then(|run| run.work_item_id) { + keys.insert(intent_key(repo, &work_item)?); + } + } + } + if let Some((record, turns)) = ledger.filter(|_| !runtime_active) { + if record + .view_name + .as_deref() + .is_some_and(|view| view != repo.current_view()) + { + return Err(invalid( + "Explicit session ledger belongs to a different view", + )); + } + for plan in turns.iter().filter_map(|turn| turn.plan_id.as_deref()) { + keys.insert(intent_key(repo, plan)?); + } + } + if keys.len() > 1 { + return Err(invalid( + "Ambiguous governing intent in explicit session context", + )); + } + Ok(keys.into_iter().next()) +} + +/// Read the selection-relevant projection of the existing lifecycle manifest. +/// Its CLI type and loader are private to `commands::agent`; unlike that hook +/// loader, inspection does not discard malformed manifests or clean up leases. +/// These declarations select work; they are never authentication/approval. +fn manifest_plan(repo: &Repository) -> CliResult> { + let directory = repo.dot_dir().join("agent-lifecycle"); + let entries = match std::fs::read_dir(&directory) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(CliError::Internal(error.into())), + }; + let root = repo + .root() + .canonicalize() + .map_err(|e| CliError::Internal(e.into()))?; + let now = chrono::Utc::now().timestamp(); + let mut paths = entries + .map(|entry| entry.map(|entry| entry.path())) + .collect::, _>>() + .map_err(|e| CliError::Internal(e.into()))?; + paths.sort(); + let mut plans = BTreeSet::new(); + for path in paths { + if path.extension().and_then(|ext| ext.to_str()) != Some("json") { + continue; + } + let bytes = std::fs::read(&path).map_err(|e| CliError::Internal(e.into()))?; + let manifest: Value = serde_json::from_slice(&bytes).map_err(|e| { + invalid(format!( + "Malformed lifecycle manifest {}: {e}", + path.display() + )) + })?; + let failure = || invalid(format!("Malformed lifecycle manifest {}", path.display())); + let run_id = manifest["run_id"].as_str().ok_or_else(failure)?; + if path.file_stem().and_then(|stem| stem.to_str()) != Some(run_id) { + return Err(failure()); + } + let expires_at = manifest["expires_at"].as_i64().ok_or_else(failure)?; + let workdir = manifest["workdir"].as_str().ok_or_else(failure)?; + if expires_at <= now || !manifest["stop_state"].is_null() { + continue; + } + let workdir = std::path::Path::new(workdir); + if !workdir.is_absolute() { + return Err(failure()); + } + // Do not infer that a run in another worktree, subdirectory or view + // governs this physical source root. + if !root.starts_with(workdir) { + continue; + } + if manifest + .get("view") + .filter(|view| !view.is_null()) + .is_some_and(|view| view.as_str() != Some(repo.current_view())) + { + continue; + } + if let Some(work_item) = manifest.get("work_item_id").filter(|item| !item.is_null()) { + plans.insert(intent_key(repo, work_item.as_str().ok_or_else(failure)?)?); + } + } + if plans.len() > 1 { + return Err(invalid("Ambiguous governing intents in active lifecycle manifests; select --intent, --turn or --change explicitly")); + } + Ok(plans.into_iter().next()) +} + +fn inspect_turn(record: &SessionRecord, turn: &SessionTurn) -> CliResult { + let mut hashes: Vec<_> = turn.change_hashes.iter().map(Hash::to_base32).collect(); + hashes.sort(); + hashes.dedup(); + Ok(TurnInspection { + session_id: record.session_id.clone(), + view_name: record.view_name.clone(), + turn_number: turn.turn_number, + status: if hashes.is_empty() { + "no_recorded_changes" + } else { + "recorded" + } + .into(), + session_status: record.status.label().into(), + plan_id: turn.plan_id.clone(), + provenance_hash: Some(turn.provenance_hash.to_base32()), + change_hashes: hashes, + outcome: encode(&turn.outcome)?, + }) +} + +fn pending_turn(store: &SessionStore, session: &AgentSession) -> CliResult> { + if !session.is_turn_active() { + return Ok(None); + } + let number = session + .turn_count + .checked_add(1) + .ok_or_else(|| invalid("Turn overflow"))?; + let binding = store + .turn_intent_binding(&session.session_id, number) + .map_err(|e| CliError::Internal(e.into()))?; + Ok(Some(TurnInspection { + session_id: session.session_id.clone(), + view_name: Some(session.view_name.clone()), + turn_number: number, + status: "pending_active_unrecorded".into(), + session_status: session.status.label().into(), + plan_id: binding.map(|b| b.intent_uid).or_else(|| { + session + .managed_run + .as_ref() + .and_then(|run| run.work_item_id.clone()) + }), + provenance_hash: None, + change_hashes: vec![], + outcome: Value::Null, + })) +} + +/// Resolve without mutation, network requests, model invocation or approval. +/// Only an explicit `ATOMIC_SESSION_ID` can supply ambient session context. +pub fn resolve(repo: &Repository, args: &IncrementalArgs) -> CliResult { + if args.from.is_some() || args.to.is_some() { + return super::view_comparison::resolve(repo, args); + } + if args.view.is_some() { + return super::view_snapshot::resolve(repo, args); + } + let session = match std::env::var("ATOMIC_SESSION_ID") { + Ok(session) => Some(session), + Err(std::env::VarError::NotPresent) => None, + Err(std::env::VarError::NotUnicode(_)) => { + return Err(invalid("ATOMIC_SESSION_ID is not valid Unicode")) + } + }; + resolve_with_session(repo, args, session.as_deref()) +} + +fn resolve_with_session( + repo: &Repository, + args: &IncrementalArgs, + session_context: Option<&str>, +) -> CliResult { + if args.from.is_some() || args.to.is_some() { + return super::view_comparison::resolve(repo, args); + } + if [&args.turn, &args.intent, &args.change, &args.view] + .iter() + .filter(|s| s.is_some()) + .count() + > 1 + { + return Err(invalid( + "--turn, --intent, --change and --view are mutually exclusive", + )); + } + if args.view.is_some() { + return super::view_snapshot::resolve(repo, args); + } + let store = runtime_store(repo)?; + let mut selection = Selection { + kind: String::new(), + value: None, + reason: String::new(), + }; + let mut selected_intent = args + .intent + .as_deref() + .map(|id| intent_key(repo, id)) + .transpose()?; + if args.turn.is_none() && args.change.is_none() && selected_intent.is_none() { + if let Some(session) = session_context { + selected_intent = current_plan(repo, store.as_ref(), session)?; + if selected_intent.is_some() { + selection.reason = + format!("Unambiguous governing declaration for explicit session {session}"); + } + } + if selected_intent.is_none() && session_context.is_none() { + selected_intent = manifest_plan(repo)?; + if selected_intent.is_some() { + selection.reason = "Unambiguous governing declaration in active lifecycle manifest for this source root/view".into(); + } + } + } + let mut roots = BTreeMap::::new(); + let mut turns = BTreeMap::<(String, u32), TurnInspection>::new(); + let mut related_intents = BTreeSet::new(); + let mut warnings = vec![ + "Inspection only: supplied criterion assessments are review observations, not independent signed approval or automatic acceptance/test-passing verdicts.".into(), + "Current intent documents are not authenticated historical snapshots; signature verification is not performed.".into(), + "Working-copy bytes are not part of the recorded selection. Active turns are pending; working-copy status is not inferred.".into(), + ]; + let ledgers = if let Some(input) = &args.turn { + let (session, _) = parse_turn(input)?; + repo.get_session_ledger(session) + .map_err(CliError::Repository)? + .into_iter() + .collect() + } else if selected_intent.is_some() { + repo.list_session_ledgers(usize::MAX) + .map_err(CliError::Repository)? + } else { + Vec::new() + }; + + if let Some(input) = &args.change { + let upper = input.to_ascii_uppercase(); + if !(4..=52).contains(&upper.len()) + || !upper + .bytes() + .all(|b| b.is_ascii_uppercase() || (b'2'..=b'7').contains(&b)) + || (upper.len() == 52 && Hash::from_base32(upper.as_bytes()).is_none()) + { + return Err(invalid( + "--change requires a 4–52 character Base32 hash, not a sequence or view selector", + )); + } + let hash = repo + .find_change_by_prefix(&upper) + .map_err(CliError::Repository)? + .ok_or_else(|| CliError::ChangeNotFound { + hash: input.clone(), + })?; + roots.insert(hash.to_base32(), hash); + selection = Selection { + kind: "change".into(), + value: Some(hash.to_base32()), + reason: "Explicit change selector".into(), + }; + } else if let Some(input) = &args.turn { + let (session, number) = parse_turn(input)?; + let mut found = false; + for (record, entries) in &ledgers { + if record.session_id != session { + continue; + } + for turn in entries.iter().filter(|turn| turn.turn_number == number) { + if found { + return Err(invalid("Ambiguous session turn in ledger")); + } + if turn.session_id != session { + return Err(invalid("Session-turn identity mismatch")); + } + found = true; + for hash in &turn.change_hashes { + roots.insert(hash.to_base32(), *hash); + } + turns.insert((session.into(), number), inspect_turn(record, turn)?); + if let Some(plan) = &turn.plan_id { + related_intents.insert(plan.clone()); + } + } + } + if let Some(runtime) = runtime_session(store.as_ref(), session)? { + if let Some(pending) = store + .as_ref() + .map(|s| pending_turn(s, &runtime)) + .transpose()? + .flatten() + { + if pending.turn_number == number { + if found { + return Err(invalid( + "Turn is both active and recorded; retry after checkpoint publication", + )); + } + found = true; + if let Some(plan) = &pending.plan_id { + related_intents.insert(plan.clone()); + } + turns.insert((session.into(), number), pending); + } + } + } + if !found { + return Err(invalid(format!("Unknown session turn: {input}"))); + } + selection = Selection { + kind: "turn".into(), + value: Some(input.clone()), + reason: "Exact session-ledger turn; other turns are excluded".into(), + }; + } else if let Some(key) = &selected_intent { + selection.kind = "intent".into(); + selection.value = Some(key.clone()); + if selection.reason.is_empty() { + selection.reason = + "Explicit governing intent selector (document-edit associations are excluded)" + .into(); + } + related_intents.insert(key.clone()); + // Canonical per-change governance resolution, not KG path-touch heuristics + // or the session/turn that happened to create the intent document. + for hash in repo.iter_changes() { + let hash = hash.map_err(CliError::Repository)?; + let change = repo.load_change(&hash).map_err(CliError::Repository)?; + if change.kind().is_snapshot() { + continue; + } + let graphs = repo + .find_provenance_for_change(&hash) + .map_err(CliError::Repository)?; + let context = repo.change_intent_context(&hash, &change, &graphs); + if context + .plans + .iter() + .any(|plan| same_intent(repo, &plan.plan_id, key)) + { + if context.status == "ambiguous" || context.status == "partial" { + return Err(invalid(format!( + "Incomplete or ambiguous governance for change {}", + hash.to_base32() + ))); + } + roots.insert(hash.to_base32(), hash); + } + } + for (record, entries) in &ledgers { + for turn in entries { + if turn + .plan_id + .as_deref() + .is_some_and(|plan| same_intent(repo, plan, key)) + { + // Preserve observation-only/unrecorded turns too. Recorded + // roots above require actual change-specific governance. + turns.insert( + (record.session_id.clone(), turn.turn_number), + inspect_turn(record, turn)?, + ); + } + } + } + if let Some(store) = &store { + for session in store + .list_sessions() + .map_err(|e| CliError::Internal(e.into()))? + { + if let Some(pending) = pending_turn(store, &session)? { + if pending + .plan_id + .as_deref() + .is_some_and(|plan| same_intent(repo, plan, key)) + { + turns.insert((pending.session_id.clone(), pending.turn_number), pending); + } + } + } + } + if roots.is_empty() && turns.is_empty() { + return Err(invalid(format!( + "Intent {key} has no recorded governing changes or matching turns" + ))); + } + } else { + // effective_history includes inherited membership; do not silently + // widen a default review into the entire view's candidate set. + let history = repo.effective_history(None).map_err(CliError::Repository)?; + let mut latest = None; + for entry in history.iter().rev() { + let change = repo + .load_change(&entry.hash) + .map_err(CliError::Repository)?; + if !change.kind().is_snapshot() { + latest = Some(entry.hash); + break; + } + } + let hash = latest.ok_or_else(|| invalid("Current view has no recorded change to inspect; choose --turn or --intent for pending work"))?; + roots.insert(hash.to_base32(), hash); + selection = Selection { + kind: "change".into(), + value: Some(hash.to_base32()), + reason: + "Latest recorded change on current view; no unambiguous current intent declaration" + .into(), + }; + } + + // Validate exactly the selected root membership through the canonical + // fail-closed dependency API, never through the whole-view triage API. + let txn = repo + .pristine() + .read_txn() + .map_err(|e| CliError::Internal(e.into()))?; + let mut ids = Vec::new(); + for hash in roots.values() { + ids.push( + txn.get_internal(hash) + .map_err(|e| CliError::Internal(e.into()))? + .ok_or_else(|| { + invalid(format!( + "Selected change {} is not registered locally", + hash.to_base32() + )) + })?, + ); + } + let closure = graph_visibility_from_membership(&txn, &ViewMembershipSet::from_ordered(ids)) + .map_err(CliError::Repository)?; + let mut closure_hashes = Vec::new(); + for id in closure.iter_dependency_first() { + closure_hashes.push( + txn.get_external(*id) + .map_err(|e| CliError::Internal(e.into()))? + .ok_or_else(|| { + invalid("Dependency closure contains a change with no external hash") + })?, + ); + } + drop(txn); + let current_members: BTreeSet<_> = repo + .effective_history(None) + .map_err(CliError::Repository)? + .into_iter() + .map(|entry| entry.hash.to_base32()) + .collect(); + let mut changes = Vec::new(); + let mut dependency_references = Vec::new(); + let mut registry = atomic_semantic::ParserRegistry::new(); + for hash in &closure_hashes { + let change = repo.load_change(hash).map_err(CliError::Repository)?; + let mut dependencies: Vec<_> = change + .hashed + .dependencies + .iter() + .map(Hash::to_base32) + .collect(); + dependencies.sort(); + dependencies.dedup(); + let on_current_view = current_members.contains(&hash.to_base32()); + // Stop at the reference boundary before collecting provenance, intent + // documents, paths, diffs, patch/token evidence or analysis for ancestors. + if !roots.contains_key(&hash.to_base32()) { + dependency_references.push(DependencyReference { + hash: hash.to_base32(), + direct: false, + on_current_view, + summary: change + .hashed + .header + .message + .lines() + .next() + .unwrap_or_default() + .chars() + .take(240) + .collect(), + dependencies, + }); + continue; + } + let graphs = repo + .find_provenance_for_change(hash) + .map_err(CliError::Repository)?; + let context = repo.change_intent_context(hash, &change, &graphs); + for plan in &context.plans { + related_intents.insert(plan.plan_id.clone()); + } + if selected_intent.is_none() && args.turn.is_none() && roots.contains_key(&hash.to_base32()) + { + let sessions: BTreeSet<_> = graphs + .iter() + .map(|(_, graph)| graph.session_id.as_str()) + .filter(|session| !session.is_empty()) + .collect(); + for session in sessions { + if let Some((record, entries)) = repo + .get_session_ledger(session) + .map_err(CliError::Repository)? + { + for turn in entries.iter().filter(|turn| { + turn.change_hashes.contains(hash) + && graphs.iter().any(|(graph_hash, graph)| { + graph.session_id == turn.session_id + && *graph_hash == turn.provenance_hash + }) + }) { + turns.insert( + (record.session_id.clone(), turn.turn_number), + inspect_turn(&record, turn)?, + ); + } + } + } + } + let mut paths = repo + .change_modified_paths(hash) + .map_err(CliError::Repository)?; + paths.sort(); + paths.dedup(); + let (diff, diff_status) = if on_current_view { + match recorded_diff(repo, &change, hash) { + Ok(diff) if !diff.is_empty() || paths.is_empty() => { + (Some(diff), "available_current_view_context".into()) + } + Ok(_) => { + warnings.push(format!( + "Diff builder returned no display hunks for {}; use recorded_patch", + hash.to_base32() + )); + (None, "unavailable; inspect recorded_patch".into()) + } + Err(error) => { + warnings.push(format!( + "Diff unavailable for {}: {error}", + hash.to_base32() + )); + (None, "unavailable; inspect recorded_patch".into()) + } + } + } else { + (None, "off_current_view; inspect recorded_patch".into()) + }; + let patch = repo + .patch_evidence(&iri::mint_change(hash), Default::default()) + .map_err(CliError::Repository)?; + let analysis = super::analysis::analyze_change( + repo, + &change, + hash, + &paths, + roots.contains_key(&hash.to_base32()), + on_current_view, + &mut registry, + ); + changes.push(ChangeInspection { + hash: hash.to_base32(), + selected_root: roots.contains_key(&hash.to_base32()), + on_current_view, + metadata: encode(&change.hashed.header)?, + dependencies, + paths, + intent_context: encode(&context)?, + recorded_patch: encode(&patch)?, + diff, + diff_status, + analysis, + }); + } + let direct_dependencies: BTreeSet<_> = changes + .iter() + .flat_map(|change| change.dependencies.iter()) + .collect(); + for reference in &mut dependency_references { + reference.direct = direct_dependencies.contains(&reference.hash); + } + let mut pending_work = BTreeMap::new(); + if let Some(store) = &store { + for session in store + .list_sessions() + .map_err(|e| CliError::Internal(e.into()))? + { + if session.view_name != repo.current_view() { + continue; + } + if let Some(pending) = pending_turn(store, &session)? { + let key = (pending.session_id.clone(), pending.turn_number); + if !turns.contains_key(&key) { + pending_work.insert(key, pending); + } + } + } + } + let mut intents = BTreeMap::new(); + for reference in related_intents { + match intent_key(repo, &reference) + .and_then(|key| inspect_intent(repo, &key).map(|value| (key, value))) + { + Ok((key, value)) => { + intents.insert(key, value); + } + Err(error) => warnings.push(format!("Related intent {reference} unavailable: {error}")), + } + } + let view = repo + .get_view_info(repo.current_view()) + .map_err(CliError::Repository)?; + let working_copy = repo + .working_copy_id() + .map(|id| repo.working_copy_record(id)) + .transpose() + .map_err(CliError::Repository)?; + let project = repo.project_identity().map_err(CliError::Repository)?; + let closure_strings: Vec<_> = closure_hashes.iter().map(Hash::to_base32).collect(); + let dependency_only = closure_strings + .iter() + .filter(|hash| !roots.contains_key(*hash)) + .cloned() + .collect(); + warnings.sort(); + warnings.dedup(); + let mut report = IncrementalReport { + schema_version: 2, + purpose: "incremental_inspection_worklist", + independent_approval: false, + selection, + source: json!({ + "repository_root": repo.root(), "atomic_directory": repo.dot_dir(), + "project_identity": encode(&project)?, "view": view.name, + "view_state": view.state.to_base32(), "view_scope": view.kind_label(), + "parent_view": view.parent_name, "view_change_count": view.change_count, + "working_copy": working_copy.map(|wc| json!({ + "id": wc.id.to_string(), "location_fingerprint": wc.location_fingerprint.to_base32(), + "desired_view_id": wc.desired_view, "desired_state": wc.desired_state.to_base32(), + "materialized_state": wc.materialized_state.map(|state| state.to_base32()), + "materialized_manifest": wc.materialized_manifest.map(|state| state.to_base32()), + })), "working_copy_status": "not_scanned", + }), + selected_roots: roots.into_keys().collect(), + dependency_closure: closure_strings, + dependency_only, + dependency_references, + changes, + view_snapshot: None, + view_comparison: None, + turns: turns.into_values().collect(), + pending_work_outside_selection: pending_work.into_values().collect(), + intents: intents.into_values().collect(), + warnings, + graph: None, + }; + report.graph = Some(super::graph::build( + repo, + &report, + args.findings.as_deref(), + args.risk_profile.as_deref(), + )?); + Ok(report) +} + +fn inspect_intent(repo: &Repository, key: &str) -> CliResult { + let inputs = bridge::read_intent(repo, key).map_err(CliError::Repository)?; + let freshness = + match bridge::load_attestation(repo, key, &inputs).map_err(CliError::Repository)? { + bridge::Attestation::Fresh(_) => "fresh_not_signature_verified", + bridge::Attestation::Stale(_) => "stale", + bridge::Attestation::None => "missing", + }; + let (node, lift_error) = match bridge::lift(&inputs) { + Ok(node) => (encode(&node)?, Value::Null), + Err(error) => (Value::Null, json!(error.to_string())), + }; + Ok( + json!({ "id": key, "authenticated": false, "attestation_status": freshness, + "source_hash": bridge::source_content_hash(&inputs), + "source": "current_vault_document_not_historical_signed_snapshot", + "frontmatter": inputs.frontmatter, "body": inputs.body, + "authenticated_criteria": Value::Null, + "current_document_criteria_and_tasks": node, "lift_error": lift_error, + "acceptance_verdict": "not_evaluated" }), + ) +} + +fn recorded_diff( + repo: &Repository, + change: &atomic_core::change::Change, + hash: &Hash, +) -> CliResult { + use atomic_repository::diff_engine::{change_file_diffs, DiffOutputConfig}; + let (mut files, _) = change_file_diffs( + repo, + change, + hash, + &DiffOutputConfig::new().with_color(false), + ) + .map_err(CliError::Repository)?; + files.sort_by(|a, b| (&a.new_path, &a.old_path).cmp(&(&b.new_path, &b.old_path))); + let mut output = String::new(); + for file in files { + output.push_str(&format!("--- {}\n+++ {}\n", file.old_path, file.new_path)); + if file.is_binary { + output.push_str("Binary content differs\n"); + } + let total: usize = file.hunks.iter().map(|hunk| hunk.lines.len()).sum(); + if total > 3000 { + output.push_str(&format!( + "[diff omitted: {total} lines; use atomic diff -c {}]\n", + hash.to_base32() + )); + continue; + } + for hunk in file.hunks { + output.push_str(&hunk.header()); + output.push('\n'); + for line in hunk.lines { + output.push_str(&line.to_string()); + output.push('\n'); + } + } + } + Ok(output) +} + +pub fn run(args: &IncrementalArgs) -> CliResult<()> { + let root = find_repository_root()?; + let repo = crate::commands::open_readonly_repository(&root).map_err(CliError::Repository)?; + let thinking = super::progress::Thinking::start(args.json || args.html); + let report = resolve(&repo, args); + drop(thinking); + let report = report?; + if args.html { + let html = super::html::render(&repo, &report)?; + if !args.no_open { + crate::output::html::write_and_open_html(&html, args.output.as_deref(), |url| { + open::that(url) + })?; + } else if let Some(path) = &args.output { + std::fs::write(path, html)?; + } else { + print!("{html}"); + } + return Ok(()); + } + if args.json { + println!( + "{}", + serde_json::to_string_pretty(&report).map_err(|e| CliError::Internal(e.into()))? + ); + } else { + print!( + "{}", + super::graph::render_with_details( + report.graph.as_ref().expect("resolved review graph"), + args.details + ) + ); + if !args.details { + for turn in &report.turns { + println!( + "Turn {}:{} — {}", + turn.session_id, turn.turn_number, turn.status + ); + } + for turn in &report.pending_work_outside_selection { + println!( + "Pending outside recorded selection: {}:{} — {}", + turn.session_id, turn.turn_number, turn.status + ); + } + for warning in &report.warnings { + println!("Warning: {warning}"); + } + return Ok(()); + } + println!("Incremental inspection worklist — NOT independent signed approval"); + println!( + "Selection: {} {}", + report.selection.kind, + report.selection.value.as_deref().unwrap_or("") + ); + println!("{}", report.selection.reason); + println!( + "Source: {} (state {})", + report.source["view"].as_str().unwrap_or("unavailable"), + report.source["view_state"] + ); + println!("Selected roots: {}", report.selected_roots.join(", ")); + println!("Dependency context: {}", report.dependency_only.join(", ")); + for turn in &report.turns { + println!( + "Turn {}:{} — {}", + turn.session_id, turn.turn_number, turn.status + ); + } + for turn in &report.pending_work_outside_selection { + println!( + "Pending outside recorded selection: {}:{} — {}", + turn.session_id, turn.turn_number, turn.status + ); + } + for intent in &report.intents { + println!( + "\nIntent {} (unauthenticated current document):\n{}", + intent["id"], + intent["body"].as_str().unwrap_or("") + ); + } + for change in &report.changes { + println!( + "\n{} {}\n{}", + if change.selected_root { + "Selected" + } else { + "Dependency" + }, + change.hash, + change.metadata["message"].as_str().unwrap_or("") + ); + println!( + "Paths: {}\nDiff: {}", + change.paths.join(", "), + change.diff_status + ); + if let Some(diff) = &change.diff { + print!("{diff}"); + } + println!( + "Analyzer: {} ({})", + change.analysis.analyzer, change.analysis.analyzer_version + ); + for check in &change.analysis.checks { + println!( + " {:?} {} {}: {}", + check.status, check.rule, check.path, check.detail + ); + } + for finding in &change.analysis.findings { + println!( + " {:?} / {:?}: {} [{}; introduced: {:?}]", + finding.severity, + finding.confidence, + finding.summary, + finding.requirement_or_rule.id, + finding.introduced_by_change.status + ); + for location in &finding.locations { + println!( + " {}:{}-{}", + location.path, location.start_line, location.end_line + ); + } + for evidence in &finding.evidence { + println!( + " Evidence {}: {}", + evidence.reference, evidence.observation + ); + } + println!(" Correction: {}", finding.proposed_correction); + } + } + for warning in &report.warnings { + println!("Warning: {warning}"); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use atomic_core::change::{Change, ChangeHeader, ProvenanceGraph}; + use atomic_repository::record::RecordOptions; + use atomic_repository::tracking::TrackingOptions; + use atomic_repository::{IntentCreateOptions, IntentCreateResult}; + use clap::Parser; + + fn fixture() -> (tempfile::TempDir, Repository) { + let dir = tempfile::tempdir().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + repo.init_vault().unwrap(); + (dir, repo) + } + + fn record(repo: &Repository, content: &str) -> Hash { + record_path(repo, "subject.txt", content) + } + + fn record_path(repo: &Repository, relative: &str, content: &str) -> Hash { + let path = repo.root().join(relative); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + let exists = path.exists(); + std::fs::write(path, content).unwrap(); + let wc = repo.require_working_copy_id().unwrap(); + if !exists { + repo.add(wc, relative, TrackingOptions::default()).unwrap(); + } + *repo + .record( + wc, + ChangeHeader::new(content), + RecordOptions::new() + .with_all(true) + .save_to_store(true) + .apply_after_record(true) + .enrich_kg(false), + ) + .unwrap() + .hash() + } + + fn work(repo: &Repository, title: &str, session: Option<&str>) -> IntentCreateResult { + repo.vault_intent_create(IntentCreateOptions { + title: title.into(), + priority: None, + assignee: None, + labels: vec![], + session_id: session.map(str::to_owned), + turn_id: session.map(|_| 1), + kind: None, + }) + .unwrap() + } + + fn checkpoint( + repo: &Repository, + session: &str, + timestamp: i64, + hashes: Vec, + plan: Option<&str>, + ) -> u32 { + let mut builder = ProvenanceGraph::builder(session, "test").timestamp(timestamp); + let previous = repo + .get_session_ledger(session) + .unwrap() + .and_then(|(_, turns)| turns.last().map(|turn| turn.provenance_hash)); + if let Some(previous) = previous { + builder = builder.previous(previous); + } + for hash in &hashes { + builder = builder.add_change_explained(*hash); + } + if let Some(plan) = plan { + builder = builder.plan_id(plan); + } + let graph = builder.build(); + let graph_hash = Hash::of(&graph.serialize().unwrap()); + repo.publish_provenance_checkpoint( + &graph, + SessionTurn { + session_id: session.into(), + turn_number: 0, + goal: None, + provenance_hash: graph_hash, + change_hashes: hashes, + previous_provenance: previous, + timestamp, + plan_id: plan.map(str::to_owned), + todos: vec![], + boundary_start: None, + boundary_end: None, + outcome: None, + }, + ) + .unwrap(); + repo.get_session_ledger(session) + .unwrap() + .unwrap() + .1 + .into_iter() + .find(|turn| turn.provenance_hash == graph_hash) + .unwrap() + .turn_number + } + + fn inspect(repo: &Repository, args: IncrementalArgs) -> CliResult { + resolve_with_session(repo, &args, None) + } + + fn graph_fixture() -> (tempfile::TempDir, Repository, IntentCreateResult, Hash) { + let (dir, repo) = fixture(); + let intent = work(&repo, "Deliver work", None); + repo.vault_intent_update(&intent.id, atomic_repository::IntentUpdateOptions { + content: Some(format!(":::why\nDeliver working behavior.\n:::\n\n:::acceptance-criterion{{#{}-ac-1 status=met verifiedBy=author evidence=claimed}}\nCalling work returns successfully.\n:::\n\n:::task{{#{}-1 status=done criteria={}-ac-1}}\nImplement work.\n::file-ref{{path=src/lib.rs}}\n:::\n", intent.uid, intent.uid, intent.uid)), + ..Default::default() + }).unwrap(); + let hash = record_path(&repo, "src/lib.rs", "pub fn work() { todo!(); }\n"); + checkpoint( + &repo, + "review-graph-source", + 10, + vec![hash], + Some(&intent.uid), + ); + (dir, repo, intent, hash) + } + + fn input_file( + repo: &Repository, + report: &IncrementalReport, + findings: Vec, + ) -> std::path::PathBuf { + let path = repo.root().join("review-observations.json"); + std::fs::write( + &path, + serde_json::to_vec(&atomic_canonical::review_graph::FindingsInput { + schema: atomic_canonical::review_graph::INPUT_SCHEMA.into(), + scope: report.graph.as_ref().unwrap().scope.clone(), + findings, + risk_assessment: None, + }) + .unwrap(), + ) + .unwrap(); + path + } + + #[test] + fn graph_links_numbered_findings_to_unmet_criteria_without_rewriting_intents() { + use atomic_canonical::{ + review_finding::{CriterionAssessment, CriterionOutcome}, + review_graph::{ReviewPass, SubmittedFinding}, + }; + let (_dir, repo, intent, hash) = graph_fixture(); + let args = IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }; + let before = inspect(&repo, args.clone()).unwrap(); + let graph = before.graph.as_ref().unwrap(); + assert_eq!(graph.passes.len(), 3); + assert_eq!(graph.criteria.len(), 1); + assert_eq!(graph.criteria[0].declared_status, "met"); + assert_eq!( + graph.criteria[0].review_assessment, + CriterionOutcome::Unknown + ); + assert_eq!(graph.findings.len(), 1); + assert_eq!(graph.findings[0].number, 1); + assert_eq!( + graph.findings[0].related_criteria, + vec![graph.criteria[0].id.clone()] + ); + assert!(!graph + .edges + .iter() + .any(|edge| edge.relation == "assesses_unmet")); + let mut finding = graph.findings[0].finding.clone(); + finding.acceptance_criteria.push(CriterionAssessment { + criterion: graph.criteria[0].id.clone(), + assessment: CriterionOutcome::Unmet, + rationale: "The unshadowed todo! macro panics instead of returning successfully".into(), + }); + let path = input_file( + &repo, + &before, + vec![SubmittedFinding { + pass: ReviewPass::IntentConformance, + finding, + }], + ); + let database_before = std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap(); + let source_before = + bridge::source_content_hash(&bridge::read_intent(&repo, &intent.id).unwrap()); + let reviewed = inspect( + &repo, + IncrementalArgs { + findings: Some(path), + ..args + }, + ) + .unwrap(); + let graph = reviewed.graph.as_ref().unwrap(); + assert_eq!( + graph.findings.len(), + 1, + "same finding across passes is numbered once" + ); + assert_eq!( + graph.findings[0].passes, + vec![ReviewPass::AntiSlop, ReviewPass::IntentConformance] + ); + assert_eq!(graph.criteria[0].review_assessment, CriterionOutcome::Unmet); + assert_eq!(graph.criteria[0].findings, vec![1]); + assert!(graph + .edges + .iter() + .any(|edge| edge.from == graph.findings[0].id + && edge.relation == "assesses_unmet" + && edge.to == graph.criteria[0].id)); + assert!(graph.edges.iter().any(|edge| edge.relation == "within")); + assert!(graph + .edges + .iter() + .all(|edge| graph.nodes.iter().any(|node| node.id == edge.from) + && graph.nodes.iter().any(|node| node.id == edge.to))); + let rendered = super::super::graph::render(graph); + for expected in [ + "F1", + "Anti-slop", + "Intent conformance", + "Blast radius / risk", + "review=Unmet", + "1–1 (after)", + "src/lib.rs", + "declared=met", + ] { + assert!(rendered.contains(expected), "{expected}: {rendered}"); + } + if let Some(path) = std::env::var_os("ATOMIC_REVIEW_CONFORMANCE_ARTIFACT") { + std::fs::write(path, super::super::html::render(&repo, &reviewed).unwrap()).unwrap(); + } + assert_eq!( + source_before, + bridge::source_content_hash(&bridge::read_intent(&repo, &intent.id).unwrap()) + ); + assert_eq!( + database_before, + std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap() + ); + } + + #[test] + fn graph_rejects_stale_foreign_unsupported_and_unevidenced_judgments() { + use atomic_canonical::{ + review_finding::{CriterionAssessment, CriterionOutcome}, + review_graph::{ReviewPass, SubmittedFinding}, + }; + let (_dir, repo, _intent, hash) = graph_fixture(); + let args = IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }; + let report = inspect(&repo, args.clone()).unwrap(); + let mut finding = report.graph.as_ref().unwrap().findings[0].finding.clone(); + finding.acceptance_criteria.push(CriterionAssessment { + criterion: report.graph.as_ref().unwrap().criteria[0].id.clone(), + assessment: CriterionOutcome::Unmet, + rationale: "The placeholder panics".into(), + }); + let observation = SubmittedFinding { + pass: ReviewPass::IntentConformance, + finding, + }; + for mutation in [ + "criterion", + "evidence", + "path", + "line", + "change", + "scope", + "source_hash", + "membership", + "rationale", + "conflict", + ] { + let path = input_file(&repo, &report, vec![observation.clone()]); + let mut input: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + match mutation { + "criterion" => { + input["findings"][0]["finding"]["acceptance_criteria"][0]["criterion"] = + json!("urn:atomic:ac:unrelated") + } + "evidence" => input["findings"][0]["finding"]["evidence"] = json!([]), + "path" => { + input["findings"][0]["finding"]["locations"][0]["path"] = json!("../lib.rs") + } + "line" => input["findings"][0]["finding"]["locations"][0]["end_line"] = json!(100), + "change" => input["findings"][0]["finding"]["change"] = json!("unselected-change"), + "scope" => input["scope"]["view_state"] = json!("stale-state"), + "source_hash" => { + let id = report.graph.as_ref().unwrap().criteria[0].intent.clone(); + input["scope"]["intent_sources"][id] = json!("stale-source"); + } + "membership" => { + input["scope"]["source_membership_hash"] = json!("stale-membership") + } + "rationale" => { + input["findings"][0]["finding"]["acceptance_criteria"][0]["rationale"] = + json!("") + } + "conflict" => { + let mut conflicting = input["findings"][0].clone(); + conflicting["finding"]["acceptance_criteria"][0]["assessment"] = + json!("unknown"); + input["findings"].as_array_mut().unwrap().push(conflicting); + } + _ => unreachable!(), + } + std::fs::write(&path, serde_json::to_vec(&input).unwrap()).unwrap(); + assert!( + inspect( + &repo, + IncrementalArgs { + findings: Some(path), + ..args.clone() + } + ) + .is_err(), + "accepted {mutation}" + ); + } + let unrelated = work(&repo, "Unrelated intent", None); + repo.vault_intent_update(&unrelated.id, atomic_repository::IntentUpdateOptions { + content: Some(format!(":::why\nUnrelated work.\n:::\n\n:::acceptance-criterion{{#{}-ac-1 status=unmet}}\nA different requirement.\n:::\n", unrelated.uid)), + ..Default::default() + }).unwrap(); + let unrelated_node = + bridge::lift(&bridge::read_intent(&repo, &unrelated.id).unwrap()).unwrap(); + let path = input_file(&repo, &report, vec![observation]); + let mut input: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + input["findings"][0]["finding"]["acceptance_criteria"][0]["criterion"] = + json!(unrelated_node.has_acceptance_criterion[0].id); + std::fs::write(&path, serde_json::to_vec(&input).unwrap()).unwrap(); + assert!(inspect( + &repo, + IncrementalArgs { + findings: Some(path), + ..args + } + ) + .unwrap_err() + .to_string() + .contains("governing intent")); + } + + #[test] + fn graph_numbers_are_deterministic_and_input_order_does_not_duplicate_findings() { + use atomic_canonical::review_graph::{ReviewPass, SubmittedFinding}; + let (_dir, repo) = fixture(); + let hash = record_path( + &repo, + "src/lib.rs", + "fn a() { todo!(); }\nfn b() { unimplemented!(); }\n", + ); + let args = IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }; + let report = inspect(&repo, args.clone()).unwrap(); + let observations: Vec<_> = report + .graph + .as_ref() + .unwrap() + .findings + .iter() + .map(|finding| SubmittedFinding { + pass: ReviewPass::BlastRadiusRisk, + finding: finding.finding.clone(), + }) + .collect(); + let path = input_file(&repo, &report, observations.clone()); + let forward = inspect( + &repo, + IncrementalArgs { + findings: Some(path), + ..args.clone() + }, + ) + .unwrap(); + let path = input_file(&repo, &report, observations.into_iter().rev().collect()); + let reverse = inspect( + &repo, + IncrementalArgs { + findings: Some(path), + ..args + }, + ) + .unwrap(); + assert_eq!( + encode(&forward.graph).unwrap(), + encode(&reverse.graph).unwrap() + ); + let graph = forward.graph.unwrap(); + assert_eq!( + graph + .findings + .iter() + .map(|finding| finding.number) + .collect::>(), + vec![1, 2] + ); + assert!(graph + .findings + .iter() + .all(|finding| finding.passes.len() == 2)); + assert!( + graph.criteria.is_empty(), + "no governance must not become invented criteria" + ); + } + + #[test] + fn graph_risk_context_includes_prior_callers_but_not_later_or_dirty_source() { + let (_dir, repo) = fixture(); + record_path( + &repo, + "src/api.ts", + "export function changed() { return 1; }\n", + ); + record_path( + &repo, + "src/caller.ts", + "import { changed } from './api';\nexport function consumer() { return changed(); }\n", + ); + let selected = record_path( + &repo, + "src/api.ts", + "export function changed() { return 2; }\n", + ); + record_path( + &repo, + "src/caller.ts", + "export function later() { return 3; }\n", + ); + std::fs::write( + repo.root().join("src/caller.ts"), + "export function dirty() {}\n", + ) + .unwrap(); + let report = inspect( + &repo, + IncrementalArgs { + change: Some(selected.to_base32()), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(report.selected_roots, vec![selected.to_base32()]); + let html = super::super::html::render(&repo, &report).unwrap(); + let document = html + .split("id=\"review-data\"") + .nth(1) + .unwrap() + .split_once('>') + .unwrap() + .1 + .split("") + .next() + .unwrap(); + let document: Value = serde_json::from_str(document).unwrap(); + let snapshot = document["sources"] + .as_array() + .unwrap() + .iter() + .find(|snapshot| snapshot["path"] == "src/caller.ts") + .expect("caller reference remains visible as context"); + assert_eq!(snapshot["reviewed_root"], false); + for side in ["before", "after"] { + assert_eq!(snapshot[side]["status"], "unavailable"); + assert!(snapshot[side]["text"].is_null()); + } + let graph = report.graph.unwrap(); + assert!( + graph + .edges + .iter() + .any(|edge| edge.relation == "statically_bound_direct_call"), + "{}", + serde_json::to_string_pretty(&graph).unwrap() + ); + assert!(graph + .nodes + .iter() + .any(|node| node.label.contains("consumer"))); + assert!(!graph + .nodes + .iter() + .any(|node| node.label.contains("#later") || node.label.contains("#dirty"))); + assert!(graph + .diagnostics + .iter() + .any(|diagnostic| diagnostic.contains("context only"))); + let risk = graph.risk.as_ref().unwrap(); + assert_eq!( + risk.assessment.rating, + atomic_canonical::review_graph::RiskRating::Medium + ); + assert_eq!(risk.impact[0].callers_after.len(), 1); + let text = super::super::graph::render(&graph); + assert!(text.contains("Risk: Medium") && text.contains("Direct impact:")); + assert!(!text.contains("(potential impact)") && !text.contains("#consumer")); + } + + #[test] + fn automatic_impact_measures_callers_and_reports_real_contract_breakage() { + use atomic_canonical::review_graph::RiskRating; + let (_dir, repo) = fixture(); + record_path( + &repo, + "src/api.ts", + "export function work(x: number) { return x; }\n", + ); + record_path(&repo, "src/user.ts", "import {work as invoke} from './api';\nexport function consumer() { return invoke(1); }\n"); + let hash = record_path( + &repo, + "src/api.ts", + "export function work(x: number, y: number) { return x + y; }\n", + ); + record_path( + &repo, + "src/user.ts", + "export function later() { return 0; }\n", + ); + std::fs::write(repo.root().join("src/user.ts"), "function dirty() {}\n").unwrap(); + let database_before = std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap(); + let report = inspect( + &repo, + IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }, + ) + .unwrap(); + let graph = report.graph.as_ref().unwrap(); + let risk = graph.risk.as_ref().unwrap(); + assert_eq!(risk.assessment.rating, RiskRating::High); + assert_eq!(risk.impact[0].changed_functions.len(), 1); + assert_eq!(risk.impact[0].callers_before.len(), 1); + assert_eq!(risk.impact[0].callers_after.len(), 1); + assert_eq!(risk.impact[0].checked_call_contracts, 1); + assert_eq!(risk.impact[0].issues.len(), 1); + assert_eq!(graph.findings.len(), 1); + assert_eq!( + graph.findings[0].finding.requirement_or_rule.id, + "compatibility.resolved-direct-call-contract" + ); + assert_eq!(graph.findings[0].finding.locations[0].path, "src/api.ts"); + assert!(graph.findings[0] + .finding + .evidence + .iter() + .any(|evidence| evidence.reference.contains("src/user.ts") + && evidence.observation.contains("consumer"))); + assert!(graph + .edges + .iter() + .any(|edge| edge.relation == "statically_bound_direct_call")); + assert!(graph + .edges + .iter() + .all(|edge| graph.nodes.iter().any(|node| node.id == edge.from) + && graph.nodes.iter().any(|node| node.id == edge.to))); + assert!(!graph + .nodes + .iter() + .any(|node| node.label.contains("#later") || node.label.contains("#dirty"))); + let text = super::super::graph::render(graph); + assert!(text.contains("Risk: High") && text.contains("1 current bound caller(s)")); + assert!(text.contains("F1") && text.contains("1 incompatible after-contract(s)")); + assert_eq!( + database_before, + std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap() + ); + } + + #[test] + fn added_bad_call_is_a_numbered_risk_issue_without_user_submitted_findings() { + let (_dir, repo) = fixture(); + let hash = record_path( + &repo, + "src/lib.rs", + "fn work(x: i32) {} fn consumer() { work(); }\n", + ); + let report = inspect( + &repo, + IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }, + ) + .unwrap(); + let graph = report.graph.as_ref().unwrap(); + assert_eq!(graph.findings.len(), 1); + assert_eq!( + graph.findings[0].finding.introduced_by_change.status, + atomic_canonical::review_finding::IntroductionStatus::Yes + ); + assert!(graph.findings[0].finding.validate().is_ok()); + assert_eq!( + graph.risk.as_ref().unwrap().assessment.rating, + atomic_canonical::review_graph::RiskRating::High + ); + } + + #[test] + fn removed_function_preserves_before_side_finding_and_caller_evidence() { + let (_dir, repo) = fixture(); + record_path(&repo, "src/api.ts", "export function work() {}\n"); + record_path( + &repo, + "src/user.ts", + "import {work} from './api'; function consumer() { work(); }\n", + ); + let hash = record_path(&repo, "src/api.ts", "\n"); + let report = inspect( + &repo, + IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }, + ) + .unwrap(); + let graph = report.graph.as_ref().unwrap(); + assert_eq!(graph.findings.len(), 1); + assert_eq!( + graph.findings[0].finding.locations[0].side, + atomic_canonical::review_finding::SourceSide::Before + ); + assert_eq!( + graph.risk.as_ref().unwrap().impact[0].callers_before.len(), + 1 + ); + assert!(graph + .edges + .iter() + .any(|edge| edge.relation == "surviving_reference_to_removed_function")); + } + + #[test] + fn semantic_review_searches_before_ast_budgets_and_reaches_late_changed_files() { + let (_dir, repo) = fixture(); + let wc = repo.require_working_copy_id().unwrap(); + std::fs::create_dir_all(repo.root().join("a_noise")).unwrap(); + for index in 0..300 { + // Deliberately unreliable unrelated syntax: neither AST errors nor + // normal cfg/macro limitations should enter this change's review. + std::fs::write( + repo.root().join(format!("a_noise/{index:03}.rs")), + format!("#[cfg(test)] macro_noise_{index}!(); invalid value {{{{\n"), + ) + .unwrap(); + } + repo.add(wc, "a_noise", TrackingOptions::default()).unwrap(); + record_path( + &repo, + "z_api.ts", + "export function work(x:number) { return x; } function value(x:number) { return x; }\n", + ); + record_path( + &repo, + "z_user.ts", + "import {work as invoke} from './z_api'; function consumer() { return invoke(1); }\n", + ); + let hash = record_path( + &repo, + "z_api.ts", + "export function work(x:number,y:number) { return x+y; } function value(x:number) { return x+1; }\n", + ); + let report = inspect( + &repo, + IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }, + ) + .unwrap(); + let graph = report.graph.as_ref().unwrap(); + let impact = &graph.risk.as_ref().unwrap().impact[0]; + assert!(impact.searched_files_before >= 300 && impact.searched_files_after >= 300); + assert_eq!(impact.inspected_files_before, 2); + assert_eq!(impact.inspected_files_after, 2); + assert_eq!(impact.callers_after.len(), 1); + assert_eq!(impact.issues.len(), 1); + assert_eq!( + graph.risk.as_ref().unwrap().assessment.rating, + atomic_canonical::review_graph::RiskRating::High + ); + assert!(!impact + .gaps + .iter() + .any(|gap| gap.contains("a_noise") || gap.contains("256 files"))); + } + + #[test] + fn risk_profile_is_explicit_validated_and_cannot_lower_a_known_issue_floor() { + let (_dir, repo) = fixture(); + record_path( + &repo, + "src/lib.rs", + "fn work(x:i32) {} fn caller() { work(1); }\n", + ); + let hash = record_path( + &repo, + "src/lib.rs", + "fn work(x:i32,y:i32) {} fn caller() { work(1); }\n", + ); + let path = repo.root().join("risk-profile.json"); + std::fs::write( + &path, + r#"{"name":"team-calibration","broad_functions":1000,"api_growth":1000}"#, + ) + .unwrap(); + let args = IncrementalArgs { + change: Some(hash.to_base32()), + risk_profile: Some(path.clone()), + ..Default::default() + }; + let report = inspect(&repo, args.clone()).unwrap(); + let risk = report.graph.as_ref().unwrap().risk.as_ref().unwrap(); + assert_eq!( + risk.assessment.rating, + atomic_canonical::review_graph::RiskRating::High + ); + assert_eq!( + risk.model.as_ref().unwrap().profile.name, + "team-calibration" + ); + assert_eq!(risk.findings.len(), 1); + std::fs::write(path, r#"{"api_growth":0}"#).unwrap(); + assert!(inspect(&repo, args).is_err()); + } + + #[test] + fn common_name_collisions_remain_diagnostics_and_never_set_risk() { + let (_dir, repo) = fixture(); + record_path( + &repo, + "unrelated.ts", + "function run() { return 1; }\nfunction consumer() { return run(); }\n", + ); + let hash = record_path(&repo, "tests/helper.ts", "function run() { return 2; }\n"); + let report = inspect( + &repo, + IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }, + ) + .unwrap(); + let graph = report.graph.as_ref().unwrap(); + let risk = graph.risk.as_ref().unwrap(); + assert_eq!( + risk.impact[0].callers_after.len(), + 0, + "unrelated same-name functions are not callers" + ); + assert_eq!( + risk.assessment.rating, + atomic_canonical::review_graph::RiskRating::Low + ); + assert_eq!(risk.basis, "rule_model"); + assert_eq!( + risk.model + .as_ref() + .unwrap() + .facts + .observed_production_callers, + 0 + ); + assert!(risk.findings.is_empty()); + let text = super::super::graph::render(graph); + assert!(!text.contains("#consumer") && !text.contains("potential impact")); + assert!(graph + .edges + .iter() + .all(|edge| graph.nodes.iter().any(|node| node.id == edge.from) + && graph.nodes.iter().any(|node| node.id == edge.to))); + } + + #[test] + fn reviewer_risk_is_scope_pinned_and_cannot_downgrade_numbered_issues() { + use atomic_canonical::review_graph::{ + ReviewPass, RiskCoverage, RiskRating, SubmittedFinding, + }; + let (_dir, repo, _intent, hash) = graph_fixture(); + let args = IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }; + let report = inspect(&repo, args.clone()).unwrap(); + let mut issue = report.graph.as_ref().unwrap().findings[0].finding.clone(); + issue.severity = atomic_canonical::review_finding::Severity::High; + issue.confidence = atomic_canonical::review_finding::Confidence::Medium; + issue.summary = + "The selected placeholder panics when invoked, violating the caller's success contract" + .into(); + let path = input_file( + &repo, + &report, + vec![SubmittedFinding { + pass: ReviewPass::BlastRadiusRisk, + finding: issue, + }], + ); + let reviewed = inspect( + &repo, + IncrementalArgs { + findings: Some(path.clone()), + ..args.clone() + }, + ) + .unwrap(); + let graph = reviewed.graph.as_ref().unwrap(); + let risk = graph.risk.as_ref().unwrap(); + assert_eq!(risk.assessment.rating, RiskRating::High); + assert_eq!(risk.assessment.coverage, RiskCoverage::Partial); + assert_eq!( + risk.assessment.confidence, + atomic_canonical::review_finding::Confidence::Medium + ); + assert_eq!(risk.basis, "findings"); + assert_eq!(risk.findings.len(), 1); + let text = super::super::graph::render_with_details(graph, true); + assert!( + text.contains("Risk: High") + && text.contains("success contract") + && text.contains("Correction:") + ); + let mut input: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + input["risk_assessment"] = json!({ + "rating": "low", "confidence": "high", "coverage": "complete", + "rationale": "Claims low risk", "limitations": [], + "evidence": [{"kind": "source", "reference": "src/lib.rs:1", "observation": "Selected source inspected"}], + }); + std::fs::write(&path, serde_json::to_vec(&input).unwrap()).unwrap(); + assert!(inspect( + &repo, + IncrementalArgs { + findings: Some(path), + ..args + } + ) + .is_err()); + } + + #[test] + fn public_api_growth_gets_an_estimate_without_inventing_findings() { + use atomic_canonical::review_graph::RiskRating; + let (_dir, repo) = fixture(); + let hash = record_path( + &repo, + "src/api.ts", + "export function work() { return 1; }\n", + ); + let args = IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }; + let report = inspect(&repo, args.clone()).unwrap(); + assert_eq!( + report + .graph + .as_ref() + .unwrap() + .risk + .as_ref() + .unwrap() + .assessment + .rating, + RiskRating::Medium + ); + let path = input_file(&repo, &report, vec![]); + let mut input: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + input["risk_assessment"] = json!({ + "rating": "low", "confidence": "medium", "coverage": "complete", + "rationale": "Reviewed the selected return contract and supported consumers", "limitations": [], + "evidence": [{"kind": "source", "reference": "src/api.ts:1", "observation": "Selected function returns a constant; caller and export inspection found no incompatible consumers in scoped recorded context"}], + }); + std::fs::write(&path, serde_json::to_vec(&input).unwrap()).unwrap(); + let database_before = std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap(); + let reviewed = inspect( + &repo, + IncrementalArgs { + findings: Some(path.clone()), + ..args.clone() + }, + ) + .unwrap(); + let graph = reviewed.graph.as_ref().unwrap(); + assert_eq!( + graph.risk.as_ref().unwrap().assessment.rating, + RiskRating::Low + ); + assert_eq!(graph.risk.as_ref().unwrap().basis, "reviewer"); + assert_eq!( + graph.risk.as_ref().unwrap().model.as_ref().unwrap().rating, + atomic_audit::risk::RiskLevel::Medium + ); + assert!(graph.findings.is_empty()); + assert!(super::super::graph::render(graph).contains("Risk: Low")); + assert_eq!( + database_before, + std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap() + ); + input["scope"]["view_state"] = json!("stale"); + std::fs::write(&path, serde_json::to_vec(&input).unwrap()).unwrap(); + assert!(inspect( + &repo, + IncrementalArgs { + findings: Some(path), + ..args + } + ) + .is_err()); + } + + #[derive(Parser)] + struct Cli { + #[command(flatten)] + args: IncrementalArgs, + } + + #[test] + fn clap_selectors_are_exclusive_but_json_is_orthogonal() { + let cli = Cli::try_parse_from([ + "review", + "--change", + "ABCD", + "--findings", + "observations.json", + "--details", + "--json", + ]) + .unwrap(); + assert!(cli.args.details && cli.args.json && cli.args.findings.is_some()); + assert!(Cli::try_parse_from(["review", "--turn", "s:0", "--intent", "1"]).is_err()); + assert!(Cli::try_parse_from(["review", "--intent", "1", "--change", "ABCD"]).is_err()); + assert!(Cli::try_parse_from(["review", "--turn", "s:0", "--change", "ABCD"]).is_err()); + assert!( + Cli::try_parse_from(["review", "--change", "ABCD", "--json"]) + .unwrap() + .args + .json + ); + } + + #[test] + fn html_flags_follow_existing_export_conventions_without_leaking_to_json() { + let cli = Cli::try_parse_from([ + "review", + "--change", + "ABCD", + "--html", + "--no-open", + "--output", + "review.html", + ]) + .unwrap(); + assert!(cli.args.html && cli.args.no_open); + assert_eq!( + cli.args.output.unwrap(), + std::path::PathBuf::from("review.html") + ); + for args in [ + vec!["review", "--html", "--json"], + vec!["review", "--html", "--details"], + vec!["review", "--no-open"], + vec!["review", "--output", "review.html"], + ] { + assert!(Cli::try_parse_from(args).is_err()); + } + } + + #[test] + fn html_exports_recorded_source_and_card_references_not_dirty_bytes() { + let (_dir, repo) = fixture(); + let source = + "fn work() { let label = r#\"\"#; todo!(); }\n"; + let hash = record_path(&repo, "src/lib.rs", source); + std::fs::write( + repo.root().join("src/lib.rs"), + "fn UNRECORDED_VIEWER_PAYLOAD() {}\n", + ) + .unwrap(); + let mut report = inspect( + &repo, + IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }, + ) + .unwrap(); + let before = std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap(); + let archive_only = "selected patch archive probe ".repeat(20_000); + report.changes[0].recorded_patch["archive_only_probe"] = + json!({"payload":&archive_only,"id":u64::MAX}); + let html = super::super::html::render(&repo, &report).unwrap(); + assert!( + html.len() < archive_only.len() / 2, + "selected patch archive must not inflate viewer startup" + ); + assert!(!html.contains("UNRECORDED_VIEWER_PAYLOAD") && !html.contains("') + .unwrap() + .1 + .split("") + .next() + .unwrap(); + let document: Value = serde_json::from_str(data).unwrap(); + let compressed = data_encoding::BASE64 + .decode( + document["report_archive"]["data"] + .as_str() + .unwrap() + .as_bytes(), + ) + .unwrap(); + let original: Value = + serde_json::from_reader(flate2::read::GzDecoder::new(compressed.as_slice())).unwrap(); + assert_eq!(original, serde_json::to_value(&report).unwrap()); + assert_eq!( + document["view"]["graph"]["findings"], + original["graph"]["findings"] + ); + assert!(document["view"]["changes"][0] + .get("recorded_patch") + .is_none()); + assert_eq!(document["audit_cards"].as_array().unwrap().len(), 10); + assert_eq!(document["metric_cards"].as_array().unwrap().len(), 10); + let snapshot = document["sources"] + .as_array() + .unwrap() + .iter() + .find(|source| source["path"] == "src/lib.rs") + .unwrap(); + assert_eq!(snapshot["after"]["text"], source); + assert_eq!(snapshot["before"]["status"], "absent"); + let graph = report.graph.as_ref().unwrap(); + let projected = super::super::presentation::regions(graph); + let metric_ids: BTreeSet<_> = projected + .iter() + .flat_map(|region| region.metrics.iter().cloned()) + .collect(); + assert_eq!( + metric_ids, + graph + .nodes + .iter() + .filter(|node| node.kind == "metric") + .map(|node| node.id.clone()) + .collect() + ); + assert!(projected.iter().any(|region| region.findings.contains(&1))); + assert_eq!( + before, + std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap() + ); + } + + #[test] + fn analysis_uses_selected_recorded_bytes_not_later_or_dirty_content() { + use atomic_canonical::review_finding::IntroductionStatus; + let (_dir, repo) = fixture(); + record_path(&repo, "src/lib.rs", "pub fn work() {}\n"); + let selected = record_path(&repo, "src/lib.rs", "pub fn work() { todo!(); }\n"); + record_path( + &repo, + "src/lib.rs", + "pub fn work() { println!(\"done\"); }\n", + ); + std::fs::write( + repo.root().join("src/lib.rs"), + "pub fn work() { unimplemented!(); }\n", + ) + .unwrap(); + let report = inspect( + &repo, + IncrementalArgs { + change: Some(selected.to_base32()), + ..Default::default() + }, + ) + .unwrap(); + let root = report + .changes + .iter() + .find(|change| change.selected_root) + .unwrap(); + assert_eq!(root.analysis.findings.len(), 1); + let finding = &root.analysis.findings[0]; + assert_eq!(finding.change, selected.to_base32()); + assert_eq!(finding.requirement_or_rule.id, "anti-slop.rust-placeholder"); + assert_eq!(finding.introduced_by_change.status, IntroductionStatus::Yes); + assert!(finding.evidence[0].observation.contains("todo!()")); + assert!(!finding.evidence[0].observation.contains("unimplemented")); + assert_eq!(report.changes.len(), 1); + assert!(!report.dependency_references.is_empty()); + assert!(report.changes.iter().all(|change| change.selected_root)); + assert!(!report.independent_approval); + assert_eq!( + serde_json::to_value(&root.analysis).unwrap()["schema"], + "atomic.review-analysis.v1" + ); + } + + #[test] + fn automatic_metrics_use_recorded_baselines_and_graph_anchors_without_failing_criteria() { + use atomic_audit::{Measurement, Metric}; + let (_dir, repo) = fixture(); + record_path( + &repo, + "src/measure.ts", + "export class C {\n run(x: number) { return x; }\n}\n", + ); + let selected = record_path(&repo, "src/measure.ts", "export class C {\n run(x: number, y: number) {\n if (x) {\n return x + y;\n }\n return y;\n }\n private helper() { return 0; }\n}\n"); + record_path(&repo, "src/measure.ts", "export class Later {}\n"); + std::fs::write( + repo.root().join("src/measure.ts"), + "export class Dirty {}\n", + ) + .unwrap(); + let database_before = std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap(); + let report = inspect( + &repo, + IncrementalArgs { + change: Some(selected.to_base32()), + ..Default::default() + }, + ) + .unwrap(); + let change = report + .changes + .iter() + .find(|change| change.selected_root) + .unwrap(); + assert_eq!( + change + .analysis + .metrics + .iter() + .map(|record| record.observation.metric) + .collect::>(), + Metric::ALL.into_iter().collect() + ); + for (metric, subject, before, after) in [ + (Metric::MethodLength, "function:C::run:1", 1, 6), + (Metric::ParameterCount, "function:C::run:1", 1, 2), + (Metric::CyclomaticComplexity, "function:C::run:1", 1, 2), + (Metric::MethodCount, "class:C:1", 1, 2), + (Metric::ClassLength, "class:C:1", 3, 9), + (Metric::ClassComplexity, "class:C:1", 1, 3), + (Metric::PublicSurface, "src/measure.ts", 2, 2), + ] { + let record = change + .analysis + .metrics + .iter() + .find(|record| { + record.observation.metric == metric + && record.observation.subject.ends_with(subject) + }) + .unwrap(); + assert_eq!( + record.observation.before, + Measurement::Measured { value: before }, + "{metric:?}" + ); + assert_eq!( + record.observation.after, + Measurement::Measured { value: after }, + "{metric:?}" + ); + assert_eq!(record.delta, Some(i64::from(after) - i64::from(before))); + assert!(record.before_location.is_some() && record.after_location.is_some()); + } + let graph = report.graph.as_ref().unwrap(); + assert_eq!( + graph + .nodes + .iter() + .filter(|node| node.kind == "metric_card") + .count(), + 10 + ); + assert!(graph.nodes.iter().any(|node| node.kind == "metric")); + assert!(graph.edges.iter().any(|edge| edge.relation == "defined_by")); + assert!(graph + .edges + .iter() + .all(|edge| graph.nodes.iter().any(|node| node.id == edge.from) + && graph.nodes.iter().any(|node| node.id == edge.to))); + assert!( + graph.findings.is_empty(), + "metric values are not automatic bug findings" + ); + assert!(!graph + .edges + .iter() + .any(|edge| edge.relation == "assesses_unmet")); + let text = super::super::graph::render(graph); + assert!(!text.contains("Metric changes") && !text.contains("├──")); + assert!(text.contains("--html") && text.contains("No numbered audit findings")); + let details = super::super::graph::render_with_details(graph, true); + assert!(details.contains("metric.method-length") && details.contains("delta +5")); + for metric in graph.nodes.iter().filter(|node| node.kind == "metric") { + assert!(details.contains(&metric.label), "missing {}", metric.label); + } + for card in atomic_audit::METRIC_CARDS { + assert!(details.contains(card.title), "missing {}", card.title); + } + assert!(details.contains("Audit Invalid or missing syntax: 0 finding(s)")); + assert!(details.contains("Audit Failure reported as success: 0 finding(s)")); + assert!(!text.contains("Not automatically audited:")); + assert!(!change.analysis.metrics.iter().any(|record| record + .observation + .subject + .contains("Later") + || record.observation.subject.contains("Dirty"))); + assert_eq!( + database_before, + std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap() + ); + } + + #[test] + fn vault_only_changes_skip_code_analysis_without_losing_intent_evidence() { + use atomic_canonical::review_graph::PassStatus; + let (_dir, repo, intent, _) = graph_fixture(); + let hash = record_path( + &repo, + ".vault/memory/generated.ts", + "not valid TypeScript {{{\n", + ); + checkpoint( + &repo, + "vault-only-review", + 20, + vec![hash], + Some(&intent.uid), + ); + let report = inspect( + &repo, + IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(report.selected_roots, vec![hash.to_base32()]); + let change = report + .changes + .iter() + .find(|change| change.selected_root) + .unwrap(); + assert!(change.paths.contains(&".vault/memory/generated.ts".into())); + assert!(change + .diff + .as_ref() + .unwrap() + .contains("not valid TypeScript")); + assert_eq!( + change.analysis.excluded_metadata_paths, + vec![".vault/memory/generated.ts"] + ); + assert!( + change.analysis.checks.is_empty() + && change.analysis.metrics.is_empty() + && change.analysis.findings.is_empty() + ); + assert!(change.analysis.metric_comparison_scope.is_empty()); + assert!( + !report.intents.is_empty(), + "vault remains available as intent evidence" + ); + let graph = report.graph.as_ref().unwrap(); + assert!(!graph.criteria.is_empty()); + assert_eq!(graph.passes[0].status, PassStatus::NotApplicable); + assert_eq!(graph.passes[2].status, PassStatus::NotApplicable); + assert_eq!( + graph.risk.as_ref().unwrap().assessment.rating, + atomic_canonical::review_graph::RiskRating::NotApplicable + ); + assert!(!graph + .nodes + .iter() + .any(|node| node.kind == "metric" || node.kind == "check")); + assert!(!graph + .diagnostics + .iter() + .any(|message| message.contains("Static risk context") + || message.contains("Static relationship budget"))); + let text = super::super::graph::render(graph); + assert!(text.contains("No code to analyze") && text.contains("retained as evidence")); + if let Some(path) = std::env::var_os("ATOMIC_REVIEW_EMPTY_ARTIFACT") { + std::fs::write(path, super::super::html::render(&repo, &report).unwrap()).unwrap(); + } + assert!(!text.contains("metric.class-") && !text.contains("Unsupported language")); + } + + #[test] + fn mixed_code_and_vault_changes_measure_only_the_code() { + let (_dir, repo) = fixture(); + record_path(&repo, ".vault/generated.ts", "invalid {{{\n"); + std::fs::write( + repo.root().join(".vault/generated.ts"), + "still invalid }}}\n", + ) + .unwrap(); + let hash = record_path( + &repo, + "src/real.ts", + "export class C { work(x: number) { return x; } }\n", + ); + let report = inspect( + &repo, + IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }, + ) + .unwrap(); + let change = report + .changes + .iter() + .find(|change| change.selected_root) + .unwrap(); + assert!(change.paths.contains(&".vault/generated.ts".into())); + assert!(change + .analysis + .excluded_metadata_paths + .contains(&".vault/generated.ts".into())); + assert!(!change.analysis.metrics.is_empty()); + assert!(change + .analysis + .metrics + .iter() + .all(|record| record.path == "src/real.ts")); + assert!(change + .analysis + .checks + .iter() + .all(|check| check.path == "src/real.ts")); + assert_eq!(change.analysis.metric_comparison_scope, vec!["src/real.ts"]); + assert!(!change.analysis.findings.iter().any(|finding| finding + .locations + .iter() + .any(|location| atomic_repository::is_vault_path(&location.path)))); + } + + #[test] + fn all_seven_substantive_audits_produce_numbered_recorded_findings() { + let (_dir, repo) = fixture(); + let mut source = String::from( + r#" +fn masking() -> Result<(),()> { match write() { Ok(())=>Ok(()), Err(_)=>Ok(()) } } +fn duplicate(b:bool) { if b { send(1); } else { send(1); } } +fn implementation(x:i32)->i32 { x+1 } +fn middle(x:i32)->i32 { implementation(x) } +fn outer(x:i32)->i32 { middle(x) } +async fn locking() { let m=std::sync::Mutex::new(0); let guard=m.lock().unwrap(); work().await; drop(guard); } +#[test] fn weak_test() { let result=work(); assert_eq!(result,result); } +fn unsafe_cast(bits:u32)->f32 { unsafe { std::mem::transmute::(bits) } } +fn large(x:i32) { +"#, + ); + for i in 0..15 { + source.push_str(&format!("if x == {i} {{ work(); }}\n")); + } + for _ in 0..100 { + source.push_str("work();\n"); + } + source.push_str("}\n"); + let hash = record_path(&repo, "src/audited.rs", &source); + // Later and dirty source must not replace the recorded audit evidence. + std::fs::write(repo.root().join("src/audited.rs"), "fn clean() {}\n").unwrap(); + let report = inspect( + &repo, + IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }, + ) + .unwrap(); + let graph = report.graph.as_ref().unwrap(); + let expected: BTreeSet<_> = [ + "anti-slop.failure-masking", + "anti-slop.duplicated-behavior", + "anti-slop.unnecessary-machinery", + "anti-slop.manageability", + "anti-slop.async-resource-safety", + "anti-slop.weak-verification", + "anti-slop.unsafe-shortcuts", + ] + .into_iter() + .collect(); + assert_eq!( + graph + .findings + .iter() + .map(|finding| finding.finding.requirement_or_rule.id.as_str()) + .collect::>(), + expected + ); + assert_eq!(graph.findings.len(), 7); + for finding in &graph.findings { + assert!(finding.finding.validate().is_ok()); + assert_eq!(finding.finding.change, hash.to_base32()); + assert_eq!( + finding.finding.introduced_by_change.status, + atomic_canonical::review_finding::IntroductionStatus::Yes + ); + assert!(finding + .finding + .locations + .iter() + .all(|location| location.path == "src/audited.rs")); + assert!(!finding.finding.evidence.is_empty()); + } + let text = super::super::graph::render(graph); + for number in 1..=7 { + assert!(text.contains(&format!("F{number} ·"))); + } + assert!(!text.contains("Not automatically audited:")); + assert!(text.contains("Audit/rule: anti-slop.failure-masking")); + assert!(!text.contains("├──")); + } + + #[test] + fn structural_findings_precede_metric_signals_and_audit_coverage_is_named() { + let (_dir, repo) = fixture(); + let hash = record_path(&repo, "src/lib.rs", "fn work() { todo!(); }\n"); + let report = inspect( + &repo, + IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }, + ) + .unwrap(); + let graph = report.graph.as_ref().unwrap(); + let text = super::super::graph::render_with_details(graph, true); + assert!(text.contains("Audit Unfinished required behavior: 1 finding(s) · 1 completed")); + assert!( + text.contains("Audit Undocumented empty catch: 0 finding(s) · 0 completed · 1 skipped") + ); + assert!(text.find("F1 ·").unwrap() < text.find("Metric changes").unwrap()); + assert!(!text.contains("Not automatically audited:")); + assert!(text.contains("Tests or completion claims without behavioral evidence")); + assert_eq!( + graph.findings.len(), + 1, + "metric signals must not manufacture findings" + ); + } + + #[test] + fn terminal_groups_noncode_metrics_without_discarding_json_observations() { + let (_dir, repo) = fixture(); + let wc = repo.require_working_copy_id().unwrap(); + for (path, content) in [ + ("README.md", "# Example\n"), + ("package.json", "{}\n"), + ("package-lock.json", "{}\n"), + ("tsconfig.json", "{}\n"), + ("test/cli.test.mjs", "console.log('test');\n"), + ] { + let absolute = repo.root().join(path); + std::fs::create_dir_all(absolute.parent().unwrap()).unwrap(); + std::fs::write(absolute, content).unwrap(); + repo.add(wc, path, TrackingOptions::default()).unwrap(); + } + let hash = record_path(&repo, "src/cli.ts", "console.log('hello');\n"); + let report = inspect( + &repo, + IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }, + ) + .unwrap(); + let analysis = &report + .changes + .iter() + .find(|change| change.selected_root) + .unwrap() + .analysis; + assert_eq!(analysis.metrics.len(), 60); + let graph = report.graph.as_ref().unwrap(); + let json_before = serde_json::to_value(graph).unwrap(); + let compact = super::super::graph::render(graph); + assert!(!compact.contains("Unsupported language") && !compact.contains("N/A → N/A")); + let text = super::super::graph::render_with_details(graph, true); + assert_eq!( + text.split("Metric coverage gaps") + .nth(1) + .unwrap() + .matches("Unsupported language") + .count(), + 1 + ); + assert!(text.contains("5 path(s), 50 observation(s)")); + assert!(text.contains("test/cli.test.mjs")); + assert!(text.contains("Metric changes (subject counts, not findings)")); + assert!(text.contains("Risk: Medium") && text.contains("Declared public surface")); + let duplication_row = text + .lines() + .find(|line| { + line.trim_start_matches("│ ") + .starts_with("Duplicated tokens in changed code ") + }) + .unwrap(); + assert!( + duplication_row.ends_with(" 0 0 0 1 0 5 0"), + "{duplication_row}" + ); + assert!(text.contains("metric.duplicated-tokens src/cli.ts: N/A → 0")); + assert!(!compact.contains("README.md#")); + assert!(text.contains("Intent conformance [Blocked]")); + assert_eq!(json_before, serde_json::to_value(graph).unwrap()); + assert_eq!( + graph + .nodes + .iter() + .filter(|node| node.kind == "metric") + .count(), + 60 + ); + } + + #[test] + fn analysis_reports_explicit_skips_for_unregistered_file_languages() { + use atomic_canonical::review_finding::CheckStatus; + let (_dir, repo) = fixture(); + let hash = record(&repo, "not a supported code file\n"); + let report = inspect( + &repo, + IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }, + ) + .unwrap(); + let analysis = &report + .changes + .iter() + .find(|change| change.selected_root) + .unwrap() + .analysis; + assert!(analysis.findings.is_empty()); + assert!(!analysis.checks.is_empty()); + assert!(analysis + .checks + .iter() + .all(|check| check.status == CheckStatus::Skipped + && check.detail.contains("Unsupported language"))); + } + + #[test] + fn exact_change_has_only_its_causal_context_and_real_diff() { + let (_dir, repo) = fixture(); + let first = record(&repo, "first\n"); + let second = record(&repo, "second\n"); + let third = record(&repo, "third\n"); + let report = inspect( + &repo, + IncrementalArgs { + change: Some(second.to_base32()), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(report.selected_roots, vec![second.to_base32()]); + assert!(report.dependency_only.contains(&first.to_base32())); + assert!(!report.dependency_closure.contains(&third.to_base32())); + let selected = report + .changes + .iter() + .find(|change| change.selected_root) + .unwrap(); + assert_eq!(selected.metadata["message"], "second\n"); + let diff = selected.diff.as_deref().unwrap(); + assert!(diff.contains("+second"), "{diff}"); + assert!(diff.contains("-first"), "{diff}"); + assert!(!report.independent_approval); + } + + #[test] + fn exact_turn_does_not_sweep_other_turns_in_session() { + let (_dir, repo) = fixture(); + let first = record(&repo, "first\n"); + let second = record(&repo, "second\n"); + let turn = checkpoint(&repo, "same-session", 10, vec![first], None); + checkpoint(&repo, "same-session", 20, vec![second], None); + let report = inspect( + &repo, + IncrementalArgs { + turn: Some(format!("same-session:{turn}")), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(report.selected_roots, vec![first.to_base32()]); + assert!(!report.dependency_closure.contains(&second.to_base32())); + assert_eq!(report.turns.len(), 1); + assert_eq!(report.turns[0].turn_number, turn); + } + + #[test] + fn dependency_references_preserve_edges_without_duplicating_selected_ancestors() { + let (_dir, repo) = fixture(); + let first = record(&repo, "first\n"); + let second = record(&repo, "second\n"); + let third = record(&repo, "third\n"); + let fourth = record(&repo, "fourth\n"); + let turn = checkpoint(&repo, "multi-root", 10, vec![third, fourth], None); + let report = inspect( + &repo, + IncrementalArgs { + turn: Some(format!("multi-root:{turn}")), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(report.changes.len(), 2); + assert!(report.changes.iter().all(|change| change.selected_root)); + assert_eq!(report.dependency_references.len(), 2); + let references: BTreeMap<_, _> = report + .dependency_references + .iter() + .map(|reference| (reference.hash.as_str(), reference)) + .collect(); + // Graph context may depend directly on older changes as well as the + // immediately preceding one. Use recorded edges, never chronology. + for reference in references.values() { + assert_eq!( + reference.direct, + report + .changes + .iter() + .any(|change| change.dependencies.contains(&reference.hash)) + ); + } + assert!(references[second.to_base32().as_str()].direct); + assert!(references[second.to_base32().as_str()] + .dependencies + .contains(&first.to_base32())); + assert!(!references.contains_key(third.to_base32().as_str())); + assert!(!references.contains_key(fourth.to_base32().as_str())); + } + + #[test] + fn exact_intent_uses_governance_not_creation_session_or_path_overlap() { + let (_dir, repo) = fixture(); + let selected = work(&repo, "Selected work", Some("shared-session")); + let other = work(&repo, "Other work", Some("shared-session")); + let first = record(&repo, "first\n"); + let second = record(&repo, "second\n"); + checkpoint( + &repo, + "shared-session", + 10, + vec![first], + Some(&selected.uid), + ); + checkpoint(&repo, "shared-session", 20, vec![second], Some(&other.id)); + let report = inspect( + &repo, + IncrementalArgs { + intent: Some(selected.id.clone()), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(report.selected_roots, vec![first.to_base32()]); + assert!(!report.dependency_closure.contains(&second.to_base32())); + assert_eq!(report.turns.len(), 1); + assert_eq!(report.intents[0]["authenticated"], false); + assert_eq!(report.intents[0]["acceptance_verdict"], "not_evaluated"); + } + + #[test] + fn empty_turn_is_reported_without_falling_back_to_latest() { + let (_dir, repo) = fixture(); + record(&repo, "unrelated\n"); + let turn = checkpoint(&repo, "observation", 10, vec![], None); + let report = inspect( + &repo, + IncrementalArgs { + turn: Some(format!("observation:{turn}")), + ..Default::default() + }, + ) + .unwrap(); + assert!(report.selected_roots.is_empty()); + assert!(report.dependency_closure.is_empty()); + assert_eq!(report.turns[0].status, "no_recorded_changes"); + } + + #[test] + fn unknown_and_malformed_selectors_fail_closed() { + let (_dir, repo) = fixture(); + for turn in [ + "", + "session", + ":1", + "../escape:1", + "s:-1", + "s:one", + "s:4294967296", + "unknown:0", + ] { + assert!( + inspect( + &repo, + IncrementalArgs { + turn: Some(turn.into()), + ..Default::default() + } + ) + .is_err(), + "{turn}" + ); + } + for hash in [ + "", + "A", + "@", + "@~1", + "bad/hash", + "ABCDEFG1", + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + ] { + assert!( + inspect( + &repo, + IncrementalArgs { + change: Some(hash.into()), + ..Default::default() + } + ) + .is_err(), + "{hash}" + ); + } + assert!(inspect( + &repo, + IncrementalArgs { + change: Some(Hash::of(b"absent").to_base32()), + ..Default::default() + } + ) + .is_err()); + assert!(inspect( + &repo, + IncrementalArgs { + intent: Some("UNKNOWN::nobody::999".into()), + ..Default::default() + } + ) + .is_err()); + assert!(inspect( + &repo, + IncrementalArgs { + turn: Some("s:1".into()), + change: Some("ABCD".into()), + ..Default::default() + } + ) + .is_err()); + } + + #[test] + fn known_intent_without_governance_is_no_match_not_whole_view() { + let (_dir, repo) = fixture(); + let intent = work(&repo, "Creation is not governance", Some("s")); + let hash = record(&repo, "unrelated\n"); + checkpoint(&repo, "s", 10, vec![hash], None); + let result = inspect( + &repo, + IncrementalArgs { + intent: Some(intent.id), + ..Default::default() + }, + ); + assert!(result.is_err()); + assert!(result + .unwrap_err() + .to_string() + .contains("no recorded governing")); + } + + #[test] + fn default_selects_only_latest_and_empty_view_errors() { + let (_dir, repo) = fixture(); + assert!(inspect(&repo, IncrementalArgs::default()).is_err()); + record(&repo, "first\n"); + let latest = record(&repo, "latest\n"); + let report = inspect(&repo, IncrementalArgs::default()).unwrap(); + assert_eq!(report.selected_roots, vec![latest.to_base32()]); + assert_eq!(report.selection.kind, "change"); + } + + #[test] + fn active_turn_and_default_explicit_context_do_not_invent_recorded_changes() { + let (_dir, repo) = fixture(); + let intent = work(&repo, "Pending work", None); + let store = SessionStore::new(repo.dot_dir().join("sessions")).unwrap(); + let mut session = AgentSession::new("active", "test", "Test"); + session.view_name = repo.current_view().into(); + session.phase = atomic_agent::turn::phase::Phase::Active; + session.begin_turn(); + store.save(&session).unwrap(); + store + .bind_turn_intent("active", Some(1), &intent.uid) + .unwrap(); + let report = + resolve_with_session(&repo, &IncrementalArgs::default(), Some("active")).unwrap(); + assert_eq!(report.selection.kind, "intent"); + assert_eq!(report.selection.value, Some(intent.id)); + assert!(report.selected_roots.is_empty()); + assert_eq!(report.turns[0].status, "pending_active_unrecorded"); + let turn = inspect( + &repo, + IncrementalArgs { + turn: Some("active:1".into()), + ..Default::default() + }, + ) + .unwrap(); + assert!(turn.changes.is_empty()); + assert_eq!(turn.turns[0].status, "pending_active_unrecorded"); + assert!(resolve_with_session(&repo, &IncrementalArgs::default(), Some("missing")).is_err()); + } + + #[test] + fn missing_dependency_fails_instead_of_returning_partial_closure() { + use atomic_core::pristine::MutTxnT; + let (_dir, repo) = fixture(); + let mut change = Change::empty(ChangeHeader::new("incomplete")); + change + .hashed + .dependencies + .push(Hash::of(b"missing dependency")); + let hash = repo.save_change(&change).unwrap(); + let mut txn = repo.pristine().write_txn().unwrap(); + txn.register_change(&hash).unwrap(); + txn.commit().unwrap(); + let result = inspect( + &repo, + IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }, + ); + assert!(result.is_err()); + } + + #[test] + fn ambiguous_hash_and_intent_prefixes_are_errors() { + let (_dir, repo) = fixture(); + // Search headers in memory and persist only the colliding pair. This + // exercises the real shared prefix resolver, not a mocked lookup. + let mut seen = BTreeMap::::new(); + let mut pair = None; + for index in 0..16384 { + let change = Change::empty(ChangeHeader::new(format!("collision-{index}"))); + let prefix = change.hash().unwrap().to_base32()[..4].to_owned(); + if let Some(previous) = seen.remove(&prefix) { + pair = Some((prefix, previous, change)); + break; + } + seen.insert(prefix, change); + } + let (prefix, first, second) = pair.expect("deterministic four-character prefix collision"); + repo.save_change(&first).unwrap(); + repo.save_change(&second).unwrap(); + let error = inspect( + &repo, + IncrementalArgs { + change: Some(prefix), + ..Default::default() + }, + ) + .unwrap_err(); + assert!(error.to_string().to_ascii_lowercase().contains("ambiguous")); + let first = work(&repo, "First", None); + let second = work(&repo, "Second", None); + let prefix: String = first + .uid + .chars() + .zip(second.uid.chars()) + .take_while(|(left, right)| left == right) + .map(|(ch, _)| ch) + .collect(); + assert!(prefix.chars().any(|ch| ch.is_ascii_alphabetic())); + let error = inspect( + &repo, + IncrementalArgs { + intent: Some(prefix), + ..Default::default() + }, + ) + .unwrap_err(); + assert!(error.to_string().to_ascii_lowercase().contains("ambiguous")); + } + + fn manifest(repo: &Repository, run: &str, intent: &str, expires_at: i64) { + let directory = repo.dot_dir().join("agent-lifecycle"); + std::fs::create_dir_all(&directory).unwrap(); + std::fs::write( + directory.join(format!("{run}.json")), + serde_json::to_vec(&json!({ + "run_id": run, "owner_agent": "test", "owner_session_id": "owner", + "work_item_id": intent, "view": repo.current_view(), "workdir": repo.root(), + "created_at": 1, "updated_at": 1, "expires_at": expires_at, + })) + .unwrap(), + ) + .unwrap(); + } + + #[test] + fn default_uses_unambiguous_active_manifest_and_rejects_conflicts() { + let (_dir, repo) = fixture(); + let selected = work(&repo, "Manifest work", None); + let other = work(&repo, "Other work", None); + let first = record(&repo, "first\n"); + checkpoint(&repo, "recorded", 10, vec![first], Some(&selected.uid)); + let latest = record(&repo, "latest unrelated\n"); + manifest( + &repo, + "selected", + &selected.id, + chrono::Utc::now().timestamp() + 3600, + ); + manifest(&repo, "expired", &other.id, 1); + let report = inspect(&repo, IncrementalArgs::default()).unwrap(); + assert_eq!(report.selection.kind, "intent"); + assert_eq!(report.selected_roots, vec![first.to_base32()]); + assert!(!report.dependency_closure.contains(&latest.to_base32())); + manifest( + &repo, + "conflict", + &other.id, + chrono::Utc::now().timestamp() + 3600, + ); + assert!(inspect(&repo, IncrementalArgs::default()) + .unwrap_err() + .to_string() + .contains("Ambiguous")); + // Explicit selectors are not affected by unrelated ambient manifests. + assert!(inspect( + &repo, + IncrementalArgs { + change: Some(latest.to_base32()), + ..Default::default() + } + ) + .is_ok()); + } + + #[test] + fn malformed_manifest_and_corrupt_explicit_session_fail_closed() { + let (_dir, repo) = fixture(); + record(&repo, "latest\n"); + let directory = repo.dot_dir().join("agent-lifecycle"); + std::fs::create_dir_all(&directory).unwrap(); + std::fs::write(directory.join("broken.json"), b"{").unwrap(); + assert!(inspect(&repo, IncrementalArgs::default()).is_err()); + let store = SessionStore::new(repo.dot_dir().join("sessions")).unwrap(); + std::fs::write(store.sessions_dir().join("broken.json"), b"{").unwrap(); + assert!(resolve_with_session(&repo, &IncrementalArgs::default(), Some("broken")).is_err()); + } + + #[test] + fn explicit_ledger_context_requires_unambiguous_governance() { + let (_dir, repo) = fixture(); + let first_intent = work(&repo, "First", None); + let second_intent = work(&repo, "Second", None); + let first = record(&repo, "first\n"); + checkpoint(&repo, "ledger", 10, vec![first], Some(&first_intent.id)); + let report = + resolve_with_session(&repo, &IncrementalArgs::default(), Some("ledger")).unwrap(); + assert_eq!(report.selection.value, Some(first_intent.id)); + let second = record(&repo, "second\n"); + checkpoint(&repo, "ledger", 20, vec![second], Some(&second_intent.id)); + assert!(resolve_with_session(&repo, &IncrementalArgs::default(), Some("ledger")).is_err()); + } + + #[test] + fn inspection_reopened_readonly_does_not_change_database_or_create_session_store() { + let (dir, repo) = fixture(); + let hash = record(&repo, "stable\n"); + let database = repo.dot_dir().join("atomic.redb"); + drop(repo); + let before = std::fs::read(&database).unwrap(); + let repo = Repository::open_readonly(dir.path()).unwrap(); + let args = IncrementalArgs { + change: Some(hash.to_base32()), + ..Default::default() + }; + let first = encode(&inspect(&repo, args.clone()).unwrap()).unwrap(); + let second = encode(&inspect(&repo, args).unwrap()).unwrap(); + assert_eq!(first, second); + assert_eq!(before, std::fs::read(&database).unwrap()); + assert!(!repo.dot_dir().join("sessions").exists()); + } +} diff --git a/atomic-cli/src/commands/review/metric_output.rs b/atomic-cli/src/commands/review/metric_output.rs new file mode 100644 index 00000000..5bdee6a9 --- /dev/null +++ b/atomic-cli/src/commands/review/metric_output.rs @@ -0,0 +1,559 @@ +//! Compact terminal projection; the graph/JSON retains every observation. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt::Write; + +use atomic_canonical::review_graph::GraphNode; + +const MAX_REASONS: usize = 6; +const MAX_PATHS: usize = 6; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Comparison { + Up, + Down, + Same, + New, + Removed, + Unknown, + NotApplicable, +} + +fn value(side: &serde_json::Value) -> Option { + (side["status"] == "measured") + .then(|| side["value"].as_u64()) + .flatten() +} + +fn absent(side: &serde_json::Value) -> bool { + side["status"] == "not_applicable" + && matches!( + side["reason"].as_str(), + Some("File is absent in this revision" | "Subject is not present in this revision") + ) +} + +fn comparison(node: &GraphNode) -> Comparison { + let observation = &node.properties["observation"]; + let before = &observation["before"]; + let after = &observation["after"]; + match (value(before), value(after)) { + (Some(before), Some(after)) => match after.cmp(&before) { + std::cmp::Ordering::Greater => Comparison::Up, + std::cmp::Ordering::Less => Comparison::Down, + std::cmp::Ordering::Equal => Comparison::Same, + }, + (None, Some(_)) if absent(before) => Comparison::New, + (Some(_), None) if absent(after) => Comparison::Removed, + (None, None) + if before["status"] == "not_applicable" && after["status"] == "not_applicable" => + { + Comparison::NotApplicable + } + _ => Comparison::Unknown, + } +} + +fn delta(node: &GraphNode) -> Option { + let observation = &node.properties["observation"]; + value(&observation["before"]) + .zip(value(&observation["after"])) + .map(|(before, after)| i128::from(after) - i128::from(before)) +} + +fn render_observation(text: &mut String, stem: &str, node: &GraphNode, details: bool) { + let side = if value(&node.properties["observation"]["after"]).is_some() { + "after" + } else { + "before" + }; + let location = &node.properties[format!("{side}_location")]; + let anchor = location["start_line"] + .as_u64() + .map(|line| { + let end = location["end_line"].as_u64().unwrap_or(line); + format!(" · {side} line {line}-{end}") + }) + .unwrap_or_default(); + let snapshot = node.properties["scope_kind"] == "view_snapshot"; + let change = if node.properties["scope_kind"] == "view_comparison" { + " · recorded view comparison".into() + } else if snapshot { + " · recorded view snapshot".into() + } else { + node.properties["change"] + .as_str() + .map(|hash| format!(" · change {}", hash.chars().take(12).collect::())) + .unwrap_or_default() + }; + writeln!(text, "{stem} {}{anchor}{change}", node.label).unwrap(); + if details { + for side in ["before", "after"] { + let sample = &node.properties["observation"][side]; + if sample["status"] == "not_applicable" { + if let Some(reason) = sample["reason"].as_str() { + writeln!(text, "{stem} {side} N/A: {reason}").unwrap(); + } + } + } + } +} + +pub(super) fn render_metrics(text: &mut String, stem: &str, metrics: &[&GraphNode], details: bool) { + let mut families: BTreeMap> = atomic_audit::METRIC_CARDS + .iter() + .map(|card| (card.title.into(), Vec::new())) + .collect(); + for node in metrics { + let value = &node.properties["observation"]["metric"]; + let metric = serde_json::from_value::(value.clone()).ok(); + let title = atomic_audit::METRIC_CARDS + .iter() + .find(|card| Some(card.metric) == metric) + .map(|card| card.title) + .unwrap_or_else(|| value.as_str().unwrap_or("Unknown metric")); + families.entry(title.into()).or_default().push(node); + } + let width = families.keys().map(String::len).max().unwrap().max(6); + if metrics + .iter() + .any(|node| node.properties["scope_kind"] == "view_snapshot") + { + writeln!( + text, + "{stem}View snapshot metrics (current subjects; no change comparison):" + ) + .unwrap(); + writeln!( + text, + "{stem}{:8} {:>5} {:>11}", + "Metric", "Measured", "N/A", "Unavailable" + ) + .unwrap(); + for (title, observations) in &families { + let measured = observations + .iter() + .filter(|node| value(&node.properties["observation"]["after"]).is_some()) + .count(); + let absent = observations + .iter() + .filter(|node| { + node.properties["observation"]["after"]["status"] == "not_applicable" + }) + .count(); + if observations.is_empty() { + writeln!(text, "{stem}{title:8} {absent:>5} {:>11}", + observations.len() - measured - absent + ) + .unwrap(); + } + if details { + for node in observations { + render_observation(text, stem, node, true); + } + } + } + return; + } + writeln!(text, "{stem}Metric changes (subject counts, not findings):").unwrap(); + writeln!( + text, + "{stem}{:4} {:>4} {:>5} {:>5} {:>7} {:>7} {:>5}", + "Metric", "Up", "Down", "Same", "New", "Removed", "Unknown", "N/A" + ) + .unwrap(); + writeln!(text, "{stem}{} {}", "-".repeat(width), "-".repeat(43)).unwrap(); + for (title, observations) in &mut families { + observations + .sort_by(|left, right| left.label.cmp(&right.label).then(left.id.cmp(&right.id))); + if observations.is_empty() { + writeln!(text, "{stem}{title:4} {:>4} {:>5} {:>5} {:>7} {:>7} {:>5}", + count(Comparison::Up), + count(Comparison::Down), + count(Comparison::Same), + count(Comparison::New), + count(Comparison::Removed), + count(Comparison::Unknown), + count(Comparison::NotApplicable) + ) + .unwrap(); + } + writeln!(text, "{stem}Up/Down/Same compare numeric values, not code changes. New/Removed require recorded subject absence; Unknown has no reliable comparison.").unwrap(); + if details { + writeln!( + text, + "{stem}All metric observations (before → after; no truncation):" + ) + .unwrap(); + for observations in families.values() { + for node in observations { + render_observation(text, stem, node, true); + } + } + } else { + let mut highlights = String::new(); + for (title, observations) in &families { + let mut increases: Vec<_> = observations + .iter() + .copied() + .filter(|node| comparison(node) == Comparison::Up) + .collect(); + increases + .sort_by(|left, right| delta(right).cmp(&delta(left)).then(left.id.cmp(&right.id))); + let mut new: Vec<_> = observations + .iter() + .copied() + .filter(|node| comparison(node) == Comparison::New) + .collect(); + new.sort_by(|left, right| { + value(&right.properties["observation"]["after"]) + .cmp(&value(&left.properties["observation"]["after"])) + .then(left.id.cmp(&right.id)) + }); + if increases.is_empty() && new.is_empty() { + continue; + } + writeln!( + highlights, + "{stem}{title} — {} increase(s), {} new value(s):", + increases.len(), + new.len() + ) + .unwrap(); + for node in increases.iter().take(3).chain(new.iter().take(1)) { + render_observation(&mut highlights, stem, node, false); + } + } + if !highlights.is_empty() { + writeln!(text, "{stem}Review signals — largest 3 increases and highest new value per family; not defect verdicts:").unwrap(); + text.push_str(&highlights); + } + writeln!( + text, + "{stem}All values, decreases and missing-value reasons: --details or --json." + ) + .unwrap(); + } +} + +/// Deduplicate both repeated metric families and the same reason on both sides. +/// Keep real failures visible, including missing baselines on measured subjects. +pub(super) fn render_coverage(text: &mut String, nodes: &[GraphNode]) { + let mut gaps: BTreeMap<&str, (BTreeSet<&str>, usize)> = BTreeMap::new(); + for node in nodes.iter().filter(|node| node.kind == "metric") { + let reasons: BTreeSet<_> = ["before", "after"] + .iter() + .filter_map(|side| { + let value = &node.properties["observation"][side]; + (value["status"] == "unavailable").then(|| { + value["reason"] + .as_str() + .unwrap_or("Unspecified analysis failure") + }) + }) + .collect(); + for reason in reasons { + let (paths, observations) = gaps.entry(reason).or_default(); + paths.insert(node.properties["path"].as_str().unwrap_or("unknown path")); + *observations += 1; + } + } + if gaps.is_empty() { + return; + } + writeln!(text, "Metric coverage gaps (full observations in --json):").unwrap(); + for (reason, (paths, observations)) in gaps.iter().take(MAX_REASONS) { + let sample = paths + .iter() + .copied() + .take(MAX_PATHS) + .collect::>() + .join(", "); + let rest = if paths.len() > MAX_PATHS { + format!(", +{} more", paths.len() - MAX_PATHS) + } else { + String::new() + }; + writeln!( + text, + " • {reason} — {} path(s), {observations} observation(s): {sample}{rest}", + paths.len() + ) + .unwrap(); + } + if gaps.len() > MAX_REASONS { + writeln!( + text, + " {} further unavailable reasons retained in --json", + gaps.len() - MAX_REASONS + ) + .unwrap(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{json, Value}; + + fn node(path: &str, before: Value, after: Value) -> GraphNode { + GraphNode { + id: path.into(), + kind: "metric".into(), + label: format!("measured {path}: {before} → {after}"), + properties: json!({"path": path, "observation": {"metric": "method_length", "before": before, "after": after}}), + } + } + + #[test] + fn repeated_missing_facts_collapse_but_zero_and_partial_values_remain() { + let unsupported = json!({"status": "unavailable", "reason": "Unsupported language"}); + let na = json!({"status": "not_applicable", "reason": "No class"}); + let mut nodes = vec![]; + for path in ["README.md", "package.json", "test/cli.test.mjs"] { + for _ in 0..10 { + nodes.push(node(path, unsupported.clone(), unsupported.clone())); + } + } + nodes.push(node("empty.ts", na.clone(), na.clone())); + nodes.push(node( + "zero.ts", + na, + json!({"status": "measured", "value": 0}), + )); + nodes.push(node( + "partial.ts", + json!({"status": "unavailable", "reason": "Baseline read failed"}), + json!({"status": "measured", "value": 2}), + )); + let snapshot = serde_json::to_value(&nodes).unwrap(); + let mut text = String::new(); + render_metrics(&mut text, "", &nodes.iter().collect::>(), false); + render_coverage(&mut text, &nodes); + assert_eq!( + counts(&text, "Method/function length"), + [0, 0, 0, 0, 0, 32, 1] + ); + assert!(!text.contains("measured zero.ts") && !text.contains("measured partial.ts")); + assert!(!text.contains("measured empty.ts") && !text.contains("measured README.md")); + assert_eq!(text.matches("Unsupported language").count(), 1); + assert!(text + .contains("3 path(s), 30 observation(s): README.md, package.json, test/cli.test.mjs")); + assert!(text.contains("Baseline read failed")); + assert_eq!( + snapshot, + serde_json::to_value(nodes).unwrap(), + "rendering cannot discard JSON evidence" + ); + } + + #[test] + fn value_reason_and_path_lists_are_bounded_and_deterministic() { + let mut nodes = vec![]; + for i in 0..30 { + nodes.push(node( + &format!("src/{i:02}.ts"), + json!({"status": "measured", "value": 1}), + json!({"status": "measured", "value": 2}), + )); + nodes.push(node( + &format!("metadata/{i:02}.json"), + json!({"status": "unavailable", "reason": "Unsupported language"}), + json!({"status": "not_applicable"}), + )); + } + for i in 0..8 { + nodes.push(node( + "broken.ts", + json!({"status": "unavailable", "reason": format!("Failure {i}")}), + json!({"status": "unavailable", "reason": "Unsupported language"}), + )); + } + let render = |nodes: &[GraphNode]| { + let mut text = String::new(); + render_metrics(&mut text, "", &nodes.iter().collect::>(), false); + render_coverage(&mut text, nodes); + text + }; + let text = render(&nodes); + assert_eq!( + counts(&text, "Method/function length"), + [30, 0, 0, 0, 0, 38, 0] + ); + assert!(!text.contains("further measured observations")); + assert!(text.contains("3 further unavailable reasons retained in --json")); + nodes.reverse(); + assert_eq!(text, render(&nodes)); + // Exercise path truncation without the reason cap hiding this group. + let mut coverage = String::new(); + render_coverage( + &mut coverage, + &nodes + .into_iter() + .filter(|node| { + node.properties["path"] + .as_str() + .unwrap() + .starts_with("metadata/") + }) + .collect::>(), + ); + assert!(coverage.contains("+24 more")); + } + + #[test] + fn every_measured_family_is_shown_without_a_location_cap() { + let mut nodes = Vec::new(); + for metric in ["cyclomatic_complexity", "method_length", "public_surface"] { + for i in 0..30 { + let mut observation = node( + &format!("src/{metric}/{i}.rs"), + json!({"status": "measured", "value": 0}), + json!({"status": "measured", "value": 2}), + ); + observation.properties["observation"]["metric"] = json!(metric); + nodes.push(observation); + } + } + let snapshot = serde_json::to_value(&nodes).unwrap(); + let render = |nodes: &[GraphNode]| { + let mut text = String::new(); + render_metrics(&mut text, "│ ", &nodes.iter().collect::>(), false); + text + }; + let text = render(&nodes); + for title in [ + "Function cyclomatic complexity", + "Method/function length", + "Declared public surface", + ] { + assert_eq!(counts(&text, title), [30, 0, 0, 0, 0, 0, 0]); + } + assert!(text.lines().all(|line| line.starts_with("│ "))); + assert!(text.contains("src/") && !text.contains("further measured")); + for card in atomic_audit::METRIC_CARDS { + assert!( + text.contains(card.title), + "{} must not disappear", + card.title + ); + } + assert_eq!(snapshot, serde_json::to_value(&nodes).unwrap()); + nodes.reverse(); + assert_eq!(text, render(&nodes)); + } + + #[test] + fn no_measurements_keep_families_visible_without_fabricating_values() { + let mut text = String::new(); + render_metrics(&mut text, "", &[], false); + assert_eq!(text.matches("not measured").count(), 10); + text.clear(); + let missing = node( + "src/lib.rs", + json!({"status":"unavailable"}), + json!({"status":"not_applicable"}), + ); + render_metrics(&mut text, "", &[&missing], false); + assert_eq!( + counts(&text, "Method/function length"), + [0, 0, 0, 0, 0, 1, 0] + ); + assert_eq!(text.matches("not measured").count(), 9); + } + + fn counts(text: &str, title: &str) -> Vec { + text.lines() + .find_map(|line| { + let line = line.trim_start_matches("│ ").trim_start(); + line.strip_prefix(title) + .filter(|suffix| suffix.starts_with(" ")) + .map(|suffix| { + suffix + .split_whitespace() + .map(|count| count.parse().unwrap()) + .collect() + }) + }) + .unwrap() + } + + #[test] + fn categories_require_comparable_values_or_explicit_absence() { + let measured = |value| json!({"status":"measured", "value":value}); + let absent = + json!({"status":"not_applicable", "reason":"Subject is not present in this revision"}); + let unavailable = json!({"status":"unavailable", "reason":"Ambiguous identity"}); + let inapplicable = json!({"status":"not_applicable", "reason":"Declaration has no executable source body"}); + let cases = [ + (measured(0), measured(3), Comparison::Up), + (measured(3), measured(0), Comparison::Down), + (measured(0), measured(0), Comparison::Same), + (absent.clone(), measured(9), Comparison::New), + (measured(9), absent, Comparison::Removed), + (unavailable, measured(9), Comparison::Unknown), + (inapplicable.clone(), measured(9), Comparison::Unknown), + ( + inapplicable.clone(), + inapplicable, + Comparison::NotApplicable, + ), + ]; + let nodes: Vec<_> = cases + .iter() + .enumerate() + .map(|(i, (before, after, expected))| { + let node = node(&format!("src/{i}.rs"), before.clone(), after.clone()); + assert_eq!(comparison(&node), *expected); + node + }) + .collect(); + let mut text = String::new(); + render_metrics(&mut text, "", &nodes.iter().collect::>(), false); + assert_eq!( + counts(&text, "Method/function length"), + [1, 1, 1, 1, 1, 2, 1] + ); + } + + #[test] + fn details_include_every_observation_and_default_ranks_values_not_names() { + let mut nodes: Vec<_> = (0..40) + .map(|i| { + node( + &format!("src/{i:02}.rs"), + json!({"status":"measured", "value":0}), + json!({"status":"measured", "value":i + 1}), + ) + }) + .collect(); + nodes[39].properties["after_location"] = json!({"start_line":42,"end_line":43}); + let refs = nodes.iter().collect::>(); + let mut summary = String::new(); + render_metrics(&mut summary, "", &refs, false); + assert!(summary.contains("src/39.rs") && summary.contains("after line 42")); + assert!(!summary.contains("src/00.rs")); + assert_eq!(summary.matches(" measured src/").count(), 3); + let snapshot = serde_json::to_value(&nodes).unwrap(); + let mut details = String::new(); + render_metrics(&mut details, "", &refs, true); + assert_eq!(details.matches(" measured src/").count(), 40); + assert!(details.contains("src/00.rs") && details.contains("src/39.rs")); + assert_eq!(snapshot, serde_json::to_value(&nodes).unwrap()); + } +} diff --git a/atomic-cli/src/commands/review/mod.rs b/atomic-cli/src/commands/review/mod.rs new file mode 100644 index 00000000..b94496a2 --- /dev/null +++ b/atomic-cli/src/commands/review/mod.rs @@ -0,0 +1,121 @@ +//! Incremental, in-session inspection and independently finalized publication. +//! +//! The command owns execution; skills only select the scope and explain results. + +mod analysis; +mod graph; +mod html; +mod impact; +mod incremental; +mod metric_output; +mod presentation; +mod progress; +mod publish; +mod risk; +mod risk_facts; +mod scope; +mod terminal; +mod view_comparison; +mod view_snapshot; + +use crate::commands::Command; +use crate::error::CliResult; +use clap::{Args, Subcommand}; + +/// Review the current recorded intent/change, or publish a frozen review scope. +#[derive(Debug, Args)] +#[command(args_conflicts_with_subcommands = true)] +pub struct Review { + #[command(flatten)] + incremental: incremental::IncrementalArgs, + #[command(subcommand)] + action: Option, +} + +#[derive(Debug, Subcommand)] +enum Action { + /// Run an independent ephemeral publisher and finalize at its session end. + Publish(publish::PublishArgs), +} + +impl Command for Review { + fn run(&self) -> CliResult<()> { + match &self.action { + Some(Action::Publish(args)) => publish::run(args), + None => incremental::run(&self.incremental), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser; + + #[derive(Parser)] + struct Cli { + #[command(flatten)] + review: Review, + } + + #[test] + fn default_is_incremental_and_needs_no_agent() { + assert!(Cli::try_parse_from(["review"]) + .unwrap() + .review + .action + .is_none()); + } + + #[test] + fn publication_uses_one_comma_separated_view_option() { + let cli = Cli::try_parse_from(["review", "publish", "--view", "a,b", "--dry-run"]).unwrap(); + assert!(matches!(cli.review.action, Some(Action::Publish(_)))); + assert!(Cli::try_parse_from(["review", "publish", "--views", "a,b"]).is_err()); + } + + #[test] + fn inspection_selectors_cannot_leak_into_publication() { + assert!(Cli::try_parse_from(["review", "--intent", "work", "publish"]).is_err()); + } + + #[test] + fn bundled_skill_is_a_thin_wrapper_for_the_implemented_routes() { + let skill = include_str!("../../../skills/review/SKILL.md"); + assert!(skill.contains("atomic review --json")); + assert!(skill.contains("atomic review publish --view a,b")); + assert!(!skill.contains("identity agent create")); + assert!(!skill.contains("smolvm machine")); + assert!(skill.contains("changes[].analysis")); + let contract = include_str!("../../../skills/review/references/review-contract.md"); + assert!(contract.contains("introduced_by_change")); + assert!(contract.contains("Local semantic audit pass")); + for flag in [ + "--review-model", + "--review-runner", + "--review-timeout-seconds", + ] { + assert_eq!( + Cli::try_parse_from(["review", flag, "unused"]) + .err() + .unwrap() + .kind(), + clap::error::ErrorKind::UnknownArgument + ); + } + assert_eq!( + Cli::try_parse_from(["review", "--preflight-only"]) + .err() + .unwrap() + .kind(), + clap::error::ErrorKind::UnknownArgument + ); + for args in [ + vec!["review", "--json"], + vec!["review", "publish", "--view", "a,b"], + vec!["review", "publish", "--view", "a,b", "--dry-run", "--json"], + ] { + assert!(Cli::try_parse_from(args).is_ok()); + } + } +} diff --git a/atomic-cli/src/commands/review/presentation.rs b/atomic-cli/src/commands/review/presentation.rs new file mode 100644 index 00000000..4acd5be2 --- /dev/null +++ b/atomic-cli/src/commands/review/presentation.rs @@ -0,0 +1,302 @@ +//! File/region navigation shared by terminal and HTML. No analysis or new findings. + +use atomic_canonical::review_finding::SourceSide; +use atomic_canonical::review_graph::{GraphNode, ReviewGraph}; +use serde::Serialize; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Clone, Debug, Default, Serialize)] +pub(super) struct Region { + pub id: String, + pub change: String, + pub path: String, + pub side: String, + pub start_line: Option, + pub end_line: Option, + pub subjects: BTreeSet, + pub findings: BTreeSet, + pub metrics: BTreeSet, + pub context_metrics: BTreeSet, + pub impact: Vec, +} + +type Key = (String, String, String, Option, Option); + +fn at<'a>( + regions: &'a mut BTreeMap, + change: &str, + path: &str, + side: &str, + start: Option, + end: Option, +) -> &'a mut Region { + regions + .entry((change.into(), path.into(), side.into(), start, end)) + .or_insert_with(|| Region { + change: change.into(), + path: path.into(), + side: side.into(), + start_line: start, + end_line: end, + ..Default::default() + }) +} + +pub(super) fn metric_location(node: &GraphNode, side: &str) -> (Option, Option) { + let location = &node.properties[format!("{side}_location")]; + ( + location["start_line"] + .as_u64() + .and_then(|n| n.try_into().ok()), + location["end_line"] + .as_u64() + .and_then(|n| n.try_into().ok()), + ) +} + +pub(super) fn regions(graph: &ReviewGraph) -> Vec { + let mut regions = BTreeMap::new(); + let metrics: Vec<_> = graph + .nodes + .iter() + .filter(|node| node.kind == "metric") + .collect(); + for node in &metrics { + let Some(path) = node.properties["path"].as_str() else { + continue; + }; + let change = node.properties["change"].as_str().unwrap_or(""); + let side = if metric_location(node, "after").0.is_some() + || metric_location(node, "before").0.is_none() + { + "after" + } else { + "before" + }; + let (start, end) = metric_location(node, side); + let region = at(&mut regions, change, path, side, start, end); + region.metrics.insert(node.id.clone()); + if let Some(subject) = node.properties["observation"]["subject"].as_str() { + region.subjects.insert(subject_label(subject).into()); + } + } + for finding in &graph.findings { + for location in &finding.finding.locations { + let side = match location.side { + SourceSide::Before => "before", + SourceSide::After => "after", + }; + at( + &mut regions, + &finding.finding.change, + &location.path, + side, + Some(location.start_line), + Some(location.end_line), + ) + .findings + .insert(finding.number); + } + } + if let Some(risk) = &graph.risk { + for report in &risk.impact { + for function in &report.changed_functions { + for (side, location) in [ + ("before", function.before.as_ref()), + ("after", function.after.as_ref()), + ] { + if let Some(location) = location { + let region = at( + &mut regions, + &report.change, + &location.path, + side, + Some(location.start_line), + Some(location.end_line), + ); + region.subjects.insert(subject_label(&function.id).into()); + region + .impact + .push(json!({"kind":"changed_function", "function":function})); + } + } + } + for (side, kind, calls) in [ + ("before", "caller_before", &report.callers_before), + ("after", "caller_after", &report.callers_after), + ("after", "outgoing_call", &report.callees_after), + ] { + for call in calls { + at( + &mut regions, + &report.change, + &call.location.path, + side, + Some(call.location.start_line), + Some(call.location.end_line), + ) + .impact + .push(json!({"kind":kind,"call":call})); + } + } + } + } + // A branch-level finding can use the enclosing function's measurements as + // context, but module totals are not repeated as if they measured the branch. + for region in regions + .values_mut() + .filter(|region| !region.findings.is_empty() && region.metrics.is_empty()) + { + let Some((start, end)) = region.start_line.zip(region.end_line) else { + continue; + }; + let enclosing: Vec<_> = metrics + .iter() + .filter_map(|node| { + if node.properties["scope"] != "function" + || node.properties["path"] != region.path + || node.properties["change"] != region.change + { + return None; + } + let (lo, hi) = metric_location(node, ®ion.side); + lo.zip(hi) + .filter(|(lo, hi)| *lo <= start && *hi >= end) + .map(|(lo, hi)| (hi - lo, *node)) + }) + .collect(); + if let Some(minimum) = enclosing.iter().map(|(width, _)| *width).min() { + for (_, node) in enclosing.into_iter().filter(|(width, _)| *width == minimum) { + region.context_metrics.insert(node.id.clone()); + if let Some(subject) = node.properties["observation"]["subject"].as_str() { + region.subjects.insert(subject_label(subject).into()); + } + } + } + } + regions + .into_values() + .enumerate() + .map(|(index, mut region)| { + region.id = format!("region-{}", index + 1); + region + }) + .collect() +} + +pub(super) fn subject_label(subject: &str) -> &str { + let Some((_, local)) = subject.split_once('#') else { + return subject; + }; + let local = local + .strip_prefix("function:") + .or_else(|| local.strip_prefix("class:")) + .unwrap_or(local); + local + .rsplit_once(':') + .filter(|(_, ordinal)| !ordinal.is_empty() && ordinal.chars().all(|c| c.is_ascii_digit())) + .map(|(name, _)| name) + .unwrap_or(local) +} + +pub(super) fn metric_id(node: &GraphNode) -> String { + serde_json::from_value::(node.properties["observation"]["metric"].clone()) + .map(|metric| metric.id().into()) + .unwrap_or_else(|_| "metric.unknown".into()) +} + +pub(super) fn metric_value(node: &GraphNode) -> String { + let observation = &node.properties["observation"]; + let label = |side: &str| { + let value = &observation[side]; + match value["status"].as_str() { + Some("measured") => value["value"].to_string(), + Some("not_applicable") => "N/A".into(), + _ => "unknown".into(), + } + }; + let delta = node.properties["delta"] + .as_i64() + .map(|n| format!(" ({n:+})")) + .unwrap_or_default(); + if node.properties["scope_kind"] == "view_snapshot" { + return format!("{} (snapshot)", label("after")); + } + format!("{} → {}{delta}", label("before"), label("after")) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn labels_preserve_qualified_names_without_inventing_anonymous_identity() { + assert_eq!( + subject_label("src/lib.rs#function:api::work:1"), + "api::work" + ); + assert_eq!( + subject_label("src/lib.rs#function:f:::1"), + "f::" + ); + assert_eq!(subject_label("src/lib.rs"), "src/lib.rs"); + } + + #[test] + fn physical_regions_preserve_all_metrics_and_keep_changes_and_sides_separate() { + let node = |id: &str, change: &str, side: &str, subject: &str| { + let mut properties = json!({"change":change,"path":"src/lib.rs","scope":"function","observation":{"metric":"method_length","subject":subject,"before":{"status":"measured","value":1},"after":{"status":"measured","value":2}}}); + properties[format!("{side}_location")] = json!({"start_line":10,"end_line":20}); + GraphNode { + id: id.into(), + kind: "metric".into(), + label: id.into(), + properties, + } + }; + let graph = ReviewGraph { + schema: "atomic.review-graph.v1".into(), + scope: atomic_canonical::review_graph::ReviewScope { + project: "project".into(), + view: "dev".into(), + view_state: "state".into(), + selected_roots: vec!["a".into(), "b".into()], + dependency_closure: vec![], + source_membership_hash: "source".into(), + intent_sources: BTreeMap::new(), + }, + passes: vec![], + findings: vec![], + criteria: vec![], + edges: vec![], + diagnostics: vec![], + risk: None, + nodes: vec![ + node("a1", "a", "after", "src/lib.rs#function:first:1"), + node("a2", "a", "after", "src/lib.rs#function:second:1"), + node("a3", "a", "before", "src/lib.rs#function:first:1"), + node("b1", "b", "after", "src/lib.rs#function:first:1"), + ], + }; + let result = regions(&graph); + assert_eq!(result.len(), 3); + assert_eq!( + result + .iter() + .map(|region| region.metrics.len()) + .sum::(), + 4 + ); + assert!(result + .iter() + .any(|region| region.metrics.len() == 2 && region.subjects.len() == 2)); + assert_eq!( + result + .iter() + .map(|region| ®ion.id) + .collect::>() + .len(), + 3 + ); + } +} diff --git a/atomic-cli/src/commands/review/progress.rs b/atomic-cli/src/commands/review/progress.rs new file mode 100644 index 00000000..f6f2f417 --- /dev/null +++ b/atomic-cli/src/commands/review/progress.rs @@ -0,0 +1,68 @@ +use indicatif::ProgressBar; +use std::io::IsTerminal; + +pub(super) struct Thinking(Option); + +fn enabled(json: bool, stdout_terminal: bool, stderr_terminal: bool, dumb: bool) -> bool { + !json && stdout_terminal && stderr_terminal && !dumb +} + +impl Thinking { + pub(super) fn start(json: bool) -> Self { + Self( + enabled( + json, + std::io::stdout().is_terminal(), + std::io::stderr().is_terminal(), + std::env::var("TERM").is_ok_and(|term| term == "dumb"), + ) + .then(|| { + crate::output::progress::create_spinner( + "Analyzing recorded syntax, semantic relationships and metrics...", + ) + }), + ) + } +} + +impl Drop for Thinking { + fn drop(&mut self) { + if let Some(spinner) = &self.0 { + spinner.finish_and_clear(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn animation_is_only_for_interactive_human_output() { + assert!(enabled(false, true, true, false)); + for args in [ + (true, true, true, false), + (false, false, true, false), + (false, true, false, false), + (false, true, true, true), + ] { + assert!(!enabled(args.0, args.1, args.2, args.3)); + } + } + + #[test] + fn guard_clears_the_spinner_on_success_and_error_paths() { + for fail in [false, true] { + let spinner = ProgressBar::hidden(); + let result = (|| -> Result<(), ()> { + let _thinking = Thinking(Some(spinner.clone())); + if fail { + return Err(()); + } + Ok(()) + })(); + assert_eq!(result.is_err(), fail); + assert!(spinner.is_finished()); + } + } +} diff --git a/atomic-cli/src/commands/review/publish.rs b/atomic-cli/src/commands/review/publish.rs new file mode 100644 index 00000000..80ba8336 --- /dev/null +++ b/atomic-cli/src/commands/review/publish.rs @@ -0,0 +1,1329 @@ +//! An owned, bounded independent publisher. No view is created or switched. +use std::collections::{BTreeMap, BTreeSet}; +use std::fs::{self, File, OpenOptions}; +use std::io::Write; +use std::path::{Component, Path, PathBuf}; +use std::process::{Command as Process, Stdio}; +use std::time::{Duration, Instant}; + +use atomic_canonical::publication_review::PublicationReview; +use atomic_core::types::Base32; +use atomic_identity::delegation::{Delegation, DelegationPermission, DelegationScope}; +use atomic_identity::{Identity, IdentityStore, IdentityType, IdentityUsage, KeyPair}; +use atomic_repository::{ + intent_bridge, PublicationGateConfig, Repository, ViewEntry, ViewEntryKind, +}; +use clap::Args; +use fs2::FileExt; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +use super::scope::{self, invalid, Scope}; +use crate::commands::triage::publication_review::{Action as Advanced, PublicationReviewCommand}; +use crate::commands::{find_repository_root, Command}; +use crate::error::{CliError, CliResult}; + +#[derive(Debug, Args)] +#[command(args_conflicts_with_subcommands = true)] +pub(super) struct PublishArgs { + /// One literal view or a comma-separated collection of views. + #[arg(long, conflicts_with_all = ["session", "resume", "cancel"])] + view: Option, + /// Publish this session's recorded changes, not its inherited view history. + #[arg(long, conflicts_with_all = ["view", "resume", "cancel"])] + session: Option, + /// Resume a retained publication job without widening its original scope. + #[arg(long, conflicts_with = "cancel")] + resume: Option, + /// Cancel a retained job and retire its temporary recording credentials. + #[arg(long)] + cancel: Option, + /// Trusted local identity issuing this exact review-publication authorization. + #[arg(long)] + identity: Option, + /// OpenCode executable. An executable path, not a shell command. + #[arg(long, default_value = "opencode")] + runner: PathBuf, + /// Maximum publisher process lifetime; no automatic renewal. + #[arg(long, default_value_t = 1800, value_parser = clap::value_parser!(u64).range(1..=3300))] + timeout_seconds: u64, + /// Show the frozen scope without credentials, agents, or repository writes. + #[arg(long, conflicts_with_all = ["resume", "cancel"])] + dry_run: bool, + /// Approve the displayed local, purpose-bound ephemeral review operation. + #[arg(long)] + yes: bool, + #[arg(long)] + json: bool, + /// Advanced external/local signing primitives; legacy spellings still work. + #[command(subcommand)] + advanced: Option, +} + +#[derive(Debug, Serialize, Deserialize)] +struct Job { + schema: String, + id: String, + scope: Scope, + phase: String, + issuer: String, + reviewer: String, + reviewer_did: String, + delegation: String, + expires_at: String, + workdir: PathBuf, + runner: PathBuf, + run_id: Option, + publisher_session: Option, + publisher_manifest: Option, + #[serde(default)] + publisher_attestations: Vec, + review: Option, + artifacts: Vec, + error: Option, + credentials_retired: bool, + #[serde(default)] + inputs_ready: bool, +} + +fn bad(error: impl std::fmt::Display) -> CliError { + invalid(error.to_string()) +} + +pub(super) fn run(args: &PublishArgs) -> CliResult<()> { + if let Some(action) = &args.advanced { + return PublicationReviewCommand { + action: action.clone(), + } + .run(); + } + let root = find_repository_root()?; + let repo = if args.dry_run { + Repository::open_readonly(&root) + } else { + Repository::open(&root) + } + .map_err(CliError::Repository)?; + let id = args.resume.as_ref().or(args.cancel.as_ref()); + if let Some(id) = id { + let id = + uuid::Uuid::parse_str(id).map_err(|_| invalid("publication job ID must be a UUID"))?; + let dir = repo.dot_dir().join("review-jobs").join(id.to_string()); + let _lock = lock_job(&dir)?; + let mut job: Job = serde_json::from_slice(&fs::read(dir.join("job.json"))?).map_err(bad)?; + if job.id != id.to_string() || job.schema != "atomic.review-job.v1" { + return Err(invalid("publication job identity/schema mismatch")); + } + verify_job_owner(&repo, &dir, &job)?; + if args.cancel.is_some() { + // Cleanup of an owned recording credential is not conditional on + // continued validity of a previously retained review approval. + retire_credentials(&mut job)?; + if job.phase != "published" { + job.phase = "cancelled".into(); + } + save_job(&dir, &job)?; + return output(args, &job); + } + if job.phase != "published" && dir.join("published.json").exists() { + // Recover the crash window after immutable receipt persistence but + // before the mutable job checkpoint, without signing another copy. + verify_completed_job(&repo, &dir, &job)?; + job.phase = "published".into(); + save_job(&dir, &job)?; + } + if job.phase == "published" { + if !job.credentials_retired { + retire_credentials(&mut job)?; + save_job(&dir, &job)?; + } + verify_completed_job(&repo, &dir, &job)?; + return output(args, &job); + } + if job.phase == "cancelled" { + // Never re-execute the independent agent for a completed receipt. + return output(args, &job); + } + if chrono::DateTime::parse_from_rfc3339(&job.expires_at).map_err(bad)? <= chrono::Utc::now() + { + return Err(invalid(format!("job authority expired; cancel job {} to retire its credentials; no renewal was performed",job.id))); + } + return execute_job(args, &root, &dir, &mut job); + } + let scope = scope::resolve(&repo, args.view.as_deref(), args.session.as_deref())?; + if args.dry_run { + let plan = json!({"status":"plan","operation":"review-publication","scope":scope, + "execution":"fresh OpenCode session and process-local ephemeral reviewer", + "insertion":false,"push":false,"production_enrollment":false}); + println!("{}", serde_json::to_string_pretty(&plan).map_err(bad)?); + return Ok(()); + } + let runner = executable(&args.runner)?; + let store = IdentityStore::open_default_existing().map_err(bad)?; + let issuer = match &args.identity { + Some(name) => store.load_by_name(name).map_err(bad)?, + None => store + .get_default() + .map_err(bad)? + .ok_or_else(|| invalid("no local publication issuer selected; pass --identity"))?, + }; + let config = PublicationGateConfig::from_repo(&repo).map_err(CliError::Repository)?; + if issuer.identity_type.is_agent() || issuer.identity_type.is_delegated() { + return Err(invalid("an ephemeral review must be authorized by a trusted human issuer, not a delegation chain")); + } + let issuer_did = atomic_canonical::did::did_for_public_key(&issuer.public_key); + if config + .trust + .evaluate(&issuer_did, config.repository_identity.as_deref()) + != atomic_config::SignerTrust::Trusted + { + return Err(invalid(format!("publication issuer {issuer_did} is not trusted by this repository; no agent or credential was created"))); + } + // Check the signing key BEFORE asking an independent reviewer to do work. + let pair = store.load_keypair(&issuer.id, None).map_err(bad)?; + if scope.intent_sources.is_empty() { + return Err(invalid("no source-backed work intent was resolved for this scope; supply genuine intent associations before publication")); + } + if !args.yes && !dialoguer::Confirm::new() + .with_prompt(format!("Authorize a local ephemeral publisher for {} view(s), {} recorded changes, at most {} seconds? No insertion, push or production enrollment",scope.views.len(),scope.closure.len(),args.timeout_seconds)) + .default(false).interact().map_err(bad)? + { return Err(invalid("publication cancelled before credentials or agent creation")); } + let id = uuid::Uuid::new_v4().to_string(); + let dir = repo.dot_dir().join("review-jobs").join(&id); + fs::create_dir_all(&dir)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&dir, fs::Permissions::from_mode(0o700))?; + } + let _lock = lock_job(&dir)?; + let temp = tempfile::Builder::new() + .prefix("atomic-review-") + .tempdir()? + .keep(); + let reviewer_pair = KeyPair::generate(); + let reviewer = Identity::builder(format!("review-{id}")) + .identity_type(IdentityType::Agent) + .usage(IdentityUsage::Bot) + .public_key(reviewer_pair.public.clone()) + .delegated_by(issuer.id) + .build() + .map_err(bad)?; + let expiry = + chrono::Utc::now() + chrono::Duration::seconds((args.timeout_seconds + 300) as i64); + let mut builder = DelegationScope::builder() + .permissions(vec![ + DelegationPermission::Read, + DelegationPermission::Record, + ]) + .project( + scope + .project + .strip_prefix("urn:atomic:project:") + .unwrap_or(&scope.project), + ) + .server(format!( + "atomic-local://{}", + scope + .project + .strip_prefix("urn:atomic:project:") + .unwrap_or(&scope.project) + )) + .max_changes(3); + for pin in &scope.views { + builder = builder.view(&pin.name); + } + let terms = Delegation::new(&issuer, &reviewer, builder.build()).expires_in( + chrono::Duration::seconds((args.timeout_seconds + 300) as i64), + ); + let certificate = atomic_canonical::delegation::mint(&issuer, &pair, &terms); + let document = atomic_canonical::delegation::encode_for_storage(&certificate).map_err(bad)?; + let mut job = Job { + schema: "atomic.review-job.v1".into(), + id, + scope, + phase: "prepared".into(), + issuer: issuer.name.clone(), + reviewer: reviewer.name.clone(), + reviewer_did: atomic_canonical::did::did_for_public_key(&reviewer.public_key), + delegation: terms.id.to_base32(), + expires_at: expiry.to_rfc3339(), + workdir: temp, + runner, + run_id: None, + publisher_session: None, + publisher_manifest: None, + publisher_attestations: vec![], + review: None, + artifacts: vec![], + error: None, + credentials_retired: false, + inputs_ready: false, + }; + // Persist recovery identifiers before effects. There are never shared default + // signer/profile mutations, remote enrollment, or credential copies. + save_job(&dir, &job)?; + let ownership = atomic_canonical::proof::attest_value(job_ownership(&job), &issuer, &pair); + fs::write( + dir.join("owner.json"), + serde_json::to_vec_pretty(&ownership).map_err(bad)?, + )?; + store + .save_with_keypair(&reviewer, &reviewer_pair, None) + .map_err(bad)?; + store + .save_delegation(&job.delegation, &document) + .map_err(bad)?; + drop(reviewer_pair); + drop(pair); + drop(store); + drop(repo); + execute_job(args, &root, &dir, &mut job) +} + +fn execute_job(args: &PublishArgs, root: &Path, dir: &Path, job: &mut Job) -> CliResult<()> { + let result = execute_inner(args, root, dir, job); + match result { + Ok(()) => { + job.phase = "published".into(); + job.error = None; + // The retained purpose-bound approval remains valid historically. + // Revoke the recording credential, NOT the publication approval. + let cleanup = retire_credentials(job); + save_job(dir, job)?; + output(args, job)?; + cleanup + } + Err(error) => { + job.phase = "blocked".into(); + job.error = Some(error.to_string()); + save_job(dir, job)?; + eprintln!("Review job {} retained at {}. Resume with `atomic review publish --resume {}` or cancel with `--cancel {}`; credentials were not prematurely revoked.",job.id,dir.display(),job.id,job.id); + Err(error) + } + } +} + +fn execute_inner(args: &PublishArgs, root: &Path, dir: &Path, job: &mut Job) -> CliResult<()> { + let repo = Repository::open(root).map_err(CliError::Repository)?; + verify_job_owner(&repo, dir, job)?; + let workspace = job.workdir.join("reviewer"); + if job.publisher_session.is_none() { + if job.run_id.is_some() && dir.join("agent.jsonl").exists() { + // A missing durable exit receipt must not be repaired by guessing a + // prior process completed or blindly starting a duplicate reviewer. + return Err(invalid("previous publisher execution has no verified completion receipt; inspect the retained run or cancel this job before starting another")); + } + scope::recheck(&repo, &job.scope, None, None)?; + if !workspace.exists() { + repo.provision_recorded_sandbox(&workspace, &job.scope.views[0].name) + .map_err(CliError::Repository)?; + } + // Directory existence or a mutable job-state flag is not evidence that + // compatible, complete collection inputs were prepared. + prepare_inputs(&repo, dir, job)?; + job.inputs_ready = true; + save_job(dir, job)?; + let brief = dir.join("reviewer.md"); + fs::write(&brief, brief_text(job, dir)?)?; + let scope_bytes = serde_json::to_vec_pretty(&job.scope).map_err(bad)?; + fs::write(dir.join("scope.json"), scope_bytes)?; + let begin = atomic_output( + &workspace, + &[ + "agent", + "lifecycle", + "begin", + "--owner", + "atomic-review-publish", + "--session", + &job.id, + "--executor", + "opencode", + "--view", + &job.scope.views[0].name, + "--workdir", + workspace + .to_str() + .ok_or_else(|| invalid("non-UTF8 reviewer workdir"))?, + "--ttl-seconds", + &(args.timeout_seconds + 300).to_string(), + "--json", + ], + )?; + let value: Value = serde_json::from_slice(&begin).map_err(bad)?; + job.run_id = Some( + value + .get("run_id") + .and_then(Value::as_str) + .ok_or_else(|| invalid("lifecycle begin returned no run_id"))? + .into(), + ); + job.phase = "running".into(); + save_job(dir, job)?; + let log = dir.join("agent.jsonl"); + let mut process = Process::new(&job.runner); + process.current_dir(&workspace).env("ATOMIC_AGENT_IDENTITY",&job.reviewer) + .args(["run","--standalone","--format","json","--title"]) + .arg(format!("Atomic publication {}",job.id)).arg("--file").arg(&brief) + .arg("Perform the independently authorized review in the attached bounded CLI handoff. Do not invoke review publish recursively. Save prepared unsigned publication documents, and finish your turn for automatic recording.") + .stdin(Stdio::null()).stdout(File::create(&log)?).stderr(File::create(dir.join("agent.stderr"))?); + let status = run_bounded(&mut process, Duration::from_secs(args.timeout_seconds))?; + if !status.success() { + return Err(invalid(format!( + "publisher process failed ({status}); see {}", + dir.join("agent.stderr").display() + ))); + } + job.publisher_session = Some(read_session_id(&log)?); + save_job(dir, job)?; + } + let session = job + .publisher_session + .as_deref() + .ok_or_else(|| invalid("missing publisher session"))?; + let review_id = find_review(&repo, &job.reviewer_did)?; + // Tests may create build products, but may not change the source bytes or + // modes in the compatible collection tree and attest those repaired bytes + // as though the original frozen implementation passed. + recheck_input_sources(&repo, job)?; + let inputs = intent_bridge::read_intent(&repo, &review_id).map_err(CliError::Repository)?; + let node = intent_bridge::lift(&inputs).map_err(CliError::Repository)?; + let uid = review_id + .strip_prefix("urn:atomic:intent:") + .unwrap_or(&review_id); + scope::recheck(&repo, &job.scope, Some(uid), Some(session))?; + if node.status != "done" + || node.kind != "review" + || node.has_acceptance_criterion.is_empty() + || node + .has_acceptance_criterion + .iter() + .any(|ac| ac.ac_status != "met") + { + return Err(invalid( + "independent review has unresolved findings or is not complete; publication refused", + )); + } + for work in job.scope.intent_sources.keys() { + if !node + .depends_on + .iter() + .any(|r| r.edge == "reviews" && &r.to == work) + { + return Err(invalid(format!( + "independent review does not cover work intent {work}" + ))); + } + } + job.review = Some(review_id.clone()); + let run = job + .run_id + .as_deref() + .ok_or_else(|| invalid("missing owned publisher run"))?; + let completion = crate::commands::agent::finish_publisher_session( + &workspace, + session, + run, + &job.id, + &job.reviewer, + &job.scope.views[0].name, + )?; + job.publisher_manifest = Some(completion.manifest.to_base32()); + job.publisher_attestations = completion + .attestations + .iter() + .map(Base32::to_base32) + .collect(); + job.phase = "session-ended".into(); + save_job(dir, job)?; + let _ = atomic_output( + &workspace, + &["agent", "lifecycle", "end", "--run-id", run, "--json"], + )?; + let _publication_boundary = repo + .lock_review_publication() + .map_err(CliError::Repository)?; + scope::recheck(&repo, &job.scope, Some(uid), Some(session))?; + // Final signatures are added only after authentic native session_end. The + // independently prepared documents bind pre-output snapshots, avoiding a + // recursive requirement to review a publication's own generated receipt. + let store = IdentityStore::open_default_existing().map_err(bad)?; + let issuer = store.load_by_name(&job.issuer).map_err(bad)?; + let issuer_pair = store.load_keypair(&issuer.id, None).map_err(bad)?; + let reviewer = store.load_by_name(&job.reviewer).map_err(bad)?; + let reviewer_pair = store.load_keypair(&reviewer.id, None).map_err(bad)?; + let config = PublicationGateConfig::from_repo(&repo).map_err(CliError::Repository)?; + let keys = atomic_repository::repository::provenance_gate::local_did_key_provider(&repo); + for (index, pin) in job.scope.views.iter().enumerate() { + if let Some(hash) = job.artifacts.get(index) { + let all = repo.publication_reviews().map_err(CliError::Repository)?; + let retained = all + .iter() + .find(|r| r.artifact_hash() == *hash) + .ok_or_else(|| invalid("partial publication artifact is missing"))?; + if retained + .subject + .roots + .iter() + .cloned() + .collect::>() + != pin.roots.iter().cloned().collect() + || retained.subject.review.id != review_id + || retained.attributed_to != job.reviewer_did + || !repo + .validate_publication_review(retained, &config, &keys) + .map_err(CliError::Repository)? + .conforms + { + return Err(invalid( + "partial publication no longer matches this job's verified scope", + )); + } + continue; + } + let prepared_path = dir.join(format!("prepared-{index}.json")); + if fs::metadata(&prepared_path)?.len() + > atomic_canonical::publication_review::MAX_BYTES as u64 + { + return Err(invalid( + "prepared publication exceeds the canonical document size budget", + )); + } + let prepared = fs::read(prepared_path)?; + let value = atomic_canonical::jcs::admit_document(&prepared).map_err(bad)?; + let value = value.get("document").unwrap_or(&value); + let mut review = + PublicationReview::parse(&serde_json::to_vec(value).map_err(bad)?).map_err(bad)?; + let selected: BTreeSet<_> = review.subject.roots.iter().cloned().collect(); + if selected != pin.roots.iter().cloned().collect() + || review.subject.review.id != review_id + || review.attributed_to != job.reviewer_did + || review.subject.project != job.scope.project + || review.subject.view_chain.first().map(|p| p.name.as_str()) != Some(pin.name.as_str()) + || review.proof.is_some() + { + return Err(invalid("publisher prepared a different project/review/view/change scope or an already signed document")); + } + scope::check_prepared_context(pin, &review.subject)?; + let pending = dir.join(format!("signed-{index}.json")); + if pending.exists() { + let retained = PublicationReview::parse(&fs::read(&pending)?).map_err(bad)?; + if retained.subject != review.subject || retained.attributed_to != job.reviewer_did { + return Err(invalid( + "pending signature belongs to another publication subject", + )); + } + repo.record_publication_review(&retained, &config, &keys) + .map_err(CliError::Repository)?; + job.artifacts.push(retained.artifact_hash()); + save_job(dir, job)?; + continue; + } + atomic_repository::repository::review_authorization::mint_and_store( + &repo, + &review.subject, + &reviewer.public_key, + &issuer, + &issuer_pair, + chrono::DateTime::parse_from_rfc3339(&job.expires_at) + .map_err(bad)? + .with_timezone(&chrono::Utc), + &config, + ) + .map_err(CliError::Repository)?; + review.reviewed_at = chrono::Utc::now().to_rfc3339(); + if !atomic_repository::repository::review_authorization::reviewer_may_sign_now( + &repo, &review, &config, &keys, + ) + .map_err(CliError::Repository)? + { + return Err(invalid("exact-scope publication authority was not accepted; no publication signature retained")); + } + let signed = + atomic_canonical::proof::attest_value(review.value(), &reviewer, &reviewer_pair); + let signed: PublicationReview = serde_json::from_value(signed).map_err(bad)?; + // Persist exact signed bytes BEFORE the canonical retention effect, so + // a crash cannot turn retry into a new timestamp/new approval artifact. + write_immutable(&pending, &serde_json::to_vec_pretty(&signed).map_err(bad)?)?; + repo.record_publication_review(&signed, &config, &keys) + .map_err(CliError::Repository)?; + let artifact = signed.artifact_hash(); + if !job.artifacts.contains(&artifact) { + job.artifacts.push(artifact); + } + save_job(dir, job)?; + } + scope::recheck(&repo, &job.scope, Some(uid), Some(session))?; + let receipt = json!({"schema":"atomic.review-publication-receipt.v1","job":job.id,"scope":job.scope, + "review":review_id,"publisher_session":session,"session_end_manifest":job.publisher_manifest, + "session_end_attestations":job.publisher_attestations,"artifacts":job.artifacts, + "attributedTo":job.reviewer_did,"meaning":"finalized independent review; not insertion or push"}); + let receipt = atomic_canonical::proof::attest_value(receipt, &reviewer, &reviewer_pair); + write_immutable( + &dir.join("published.json"), + &serde_json::to_vec_pretty(&receipt).map_err(bad)?, + )?; + Ok(()) +} + +fn verify_completed_job(repo: &Repository, dir: &Path, job: &Job) -> CliResult<()> { + let store = IdentityStore::open_default_existing().map_err(bad)?; + let reviewer = store.load_by_name(&job.reviewer).map_err(bad)?; + let value = atomic_canonical::jcs::admit_document(&fs::read(dir.join("published.json"))?) + .map_err(bad)?; + atomic_canonical::proof::verify_value(&value, &reviewer.public_key).map_err(bad)?; + if value.get("job") != Some(&json!(job.id)) + || value.get("scope") != Some(&json!(job.scope)) + || value.get("artifacts") != Some(&json!(job.artifacts)) + || value.get("session_end_manifest") != Some(&json!(job.publisher_manifest)) + || value.get("session_end_attestations") != Some(&json!(job.publisher_attestations)) + || value.get("publisher_session") != Some(&json!(job.publisher_session)) + || value.get("review") != Some(&json!(job.review)) + || value.get("attributedTo") != Some(&json!(job.reviewer_did)) + { + return Err(invalid( + "retained job differs from its signed publication receipt", + )); + } + let session = job + .publisher_session + .as_deref() + .ok_or_else(|| invalid("published receipt has no publisher session"))?; + let manifest = scope::hashes(&[job + .publisher_manifest + .clone() + .ok_or_else(|| invalid("missing publisher end manifest"))?])?[0]; + let manifest = repo + .get_session_manifest(&manifest) + .map_err(CliError::Repository)? + .ok_or_else(|| invalid("retained publisher manifest is unavailable"))?; + if manifest.session_id != session || job.publisher_attestations.is_empty() { + return Err(invalid( + "publisher completion evidence does not match the signed receipt", + )); + } + let mut covered = BTreeSet::new(); + for hash in scope::hashes(&job.publisher_attestations)? { + let attest = repo.load_attestation(&hash).map_err(CliError::Repository)?; + if attest.session_id != session + || attest.signer_did() != Some(job.reviewer_did.as_str()) + || !attest.verify_with_did(reviewer.public_key.as_bytes()) + { + return Err(invalid( + "retained publisher attestation signature/binding failed", + )); + } + covered.extend(attest.changes_covered); + } + if manifest + .turns + .iter() + .flat_map(|t| &t.change_hashes) + .any(|h| !covered.contains(h)) + { + return Err(invalid( + "retained publisher attestation does not cover its recorded review turns", + )); + } + for change in manifest.turns.iter().flat_map(|turn| &turn.change_hashes) { + for (_, attestation) in repo + .find_attestations_for_change(change) + .map_err(CliError::Repository)? + { + if attestation.session_id == session + && (attestation.signer_did() != Some(job.reviewer_did.as_str()) + || !attestation.verify_with_did(reviewer.public_key.as_bytes())) + { + return Err(invalid("invalid later same-session evidence cannot be hidden by a previously published receipt")); + } + } + } + let config = PublicationGateConfig::from_repo(repo).map_err(CliError::Repository)?; + let keys = atomic_repository::repository::provenance_gate::local_did_key_provider(repo); + let all = repo.publication_reviews().map_err(CliError::Repository)?; + if job.artifacts.len() != job.scope.views.len() || job.artifacts.is_empty() { + return Err(invalid( + "published receipt lacks exact per-view publication coverage", + )); + } + for (index, hash) in job.artifacts.iter().enumerate() { + let artifact = all + .iter() + .find(|r| r.artifact_hash() == *hash) + .ok_or_else(|| invalid("retained publication artifact is missing"))?; + if artifact + .subject + .roots + .iter() + .cloned() + .collect::>() + != job.scope.views[index].roots.iter().cloned().collect() + || artifact.subject.review.id != job.review.as_deref().unwrap_or("") + || artifact.attributed_to != job.reviewer_did + { + return Err(invalid( + "retained artifact does not cover this job's exact selected view roots", + )); + } + let report = repo + .validate_publication_review(artifact, &config, &keys) + .map_err(CliError::Repository)?; + if !report.conforms { + return Err(invalid( + "retained publication no longer conforms to current authority/evidence policy", + )); + } + } + Ok(()) +} + +fn job_ownership(job: &Job) -> Value { + json!({"schema":"atomic.review-job-ownership.v1","job":job.id,"scope":job.scope, + "issuer":job.issuer,"reviewer":job.reviewer,"reviewer_did":job.reviewer_did, + "delegation":job.delegation,"expires_at":job.expires_at,"workdir":job.workdir,"runner":job.runner}) +} + +fn verify_job_owner(repo: &Repository, dir: &Path, job: &Job) -> CliResult<()> { + let store = IdentityStore::open_default_existing().map_err(bad)?; + let issuer = store.load_by_name(&job.issuer).map_err(bad)?; + let document = + atomic_canonical::jcs::admit_document(&fs::read(dir.join("owner.json"))?).map_err(bad)?; + atomic_canonical::proof::verify_value(&document, &issuer.public_key).map_err(bad)?; + for (key, value) in job_ownership(job) + .as_object() + .ok_or_else(|| invalid("invalid job ownership scope"))? + { + if document.get(key) != Some(value) { + return Err(invalid( + "mutable job scope differs from its issuer-signed ownership record", + )); + } + } + if repo.project_id().map_err(CliError::Repository)?.to_urn() != job.scope.project { + return Err(invalid("publication job belongs to a different project")); + } + if job.reviewer != format!("review-{}", job.id) { + return Err(invalid( + "publication job does not own this ephemeral identity name", + )); + } + let reviewer = store.load_by_name(&job.reviewer).map_err(bad)?; + if !reviewer.identity_type.is_agent() + || reviewer.delegated_by != Some(issuer.id) + || atomic_canonical::did::did_for_public_key(&reviewer.public_key) != job.reviewer_did + { + return Err(invalid( + "publication recovery refuses credentials not created for this issuer-owned job", + )); + } + Ok(()) +} + +fn brief_text(job: &Job, dir: &Path) -> CliResult { + Ok(format!("# Independent publisher job {}\n\nWork only in your current recorded-only working copy on existing view {}. Verify native project {}, same-view lifecycle run, and process identity {} before edits. Do not create/switch views, grant credentials, change defaults, push, insert, repair implementation or run atomic add/record. This is independent substantive inspection, not adoption of author conclusions.\n\nFrozen scope and work-intent source hashes:\n```json\n{}\n```\n\nRead the implementation, provenance and each listed work intent. Run relevant tests. For multiple views inspect per-view inputs and the combined compatible tree in {} and test interactions; do not approve separate views as an untested merge. Scope associations are context, not inferred governing ownership.\n\nReuse an appropriate group kind:review intent under your own identity, or create ONE using atomic intent new --review and explicit reviews links to every listed work intent. Record actual criterion judgments and exact scoped passing verification only when justified. Do not invent original capture evidence. Sign explicitly with --identity {}. Leave work intent definitions and lifecycle untouched. Finish your existing group review as done only if all its criteria genuinely pass; blockers must remain visible and must not yield a prepared passing publication.\n\nBefore ending this turn, for EACH views[index], run atomic triage publication-review prepare --review --view with that pin's exact roots as repeated --change. Read returned requiredVerification. Add genuine scope-check records with exact ref and observedAtMerkle to your SAME review (preserving actual test observation pins), sync/re-attest the final review revision, and re-prepare each envelope after final review edits. Save final UNSIGNED prepared envelopes to {}/prepared-.json. Do not invoke sign/record or review publish: coordinator finalizes your real session_end and only then signs eligible prepared subjects. No new views and no recursive reviews of reviews.\n\nLet normal hooks automatically record your final review turn. Do not manually call session-end or manufacture completion. Return your review ID, findings and results.\n",job.id,job.scope.views[0].name,job.scope.project,job.reviewer, + serde_json::to_string_pretty(&job.scope).map_err(bad)?,job.workdir.join("inputs").display(),job.reviewer,dir.display())) + .map(|mut brief| { + brief.push_str("\n\n"); + brief.push_str(include_str!("../../../skills/review/references/review-contract.md")); + brief + }) +} + +fn find_review(repo: &Repository, did: &str) -> CliResult { + let mut found = Vec::new(); + for info in repo.vault_intent_list(None).map_err(CliError::Repository)? { + let inputs = intent_bridge::read_intent(repo, &info.id).map_err(CliError::Repository)?; + let node = intent_bridge::lift(&inputs).map_err(CliError::Repository)?; + if node.kind == "review" && node.attributed_to.as_deref() == Some(did) { + found.push(node.id); + } + // Lifted source does not carry its proof: consult the signed revision. + else if node.kind == "review" { + if let intent_bridge::Attestation::Fresh(signed) = + intent_bridge::load_attestation(repo, &info.id, &inputs) + .map_err(CliError::Repository)? + { + if signed.attributed_to.as_deref() == Some(did) { + found.push(signed.id); + } + } + } + } + if found.len() != 1 { + return Err(invalid("publisher must produce exactly one attributable group review; missing or ambiguous review evidence")); + } + Ok(found.remove(0)) +} + +fn prepare_inputs(repo: &Repository, _dir: &Path, job: &Job) -> CliResult<()> { + if job.scope.views.len() < 2 { + return Ok(()); + } + let mut trees = Vec::new(); + let mut common: Option> = None; + // Use the shared ancestor as a real three-way baseline. If none exists, + // never pretend concatenating unrelated file trees is an integration. + let ancestry = |view: &str| -> CliResult> { + let mut names = Vec::new(); + let mut next = Some(view.to_string()); + while let Some(name) = next { + if names.contains(&name) || names.len() > 256 { + return Err(invalid("cyclic or excessive view ancestry")); + } + next = repo + .get_view_info(&name) + .map_err(CliError::Repository)? + .parent_name; + names.push(name); + } + Ok(names) + }; + let chains = job + .scope + .views + .iter() + .map(|p| ancestry(&p.name)) + .collect::>>()?; + let ancestor = chains[0] + .iter() + .find(|name| chains.iter().all(|c| c.contains(name))) + .ok_or_else(|| invalid("view collection has no common recorded ancestor"))?; + for name in + std::iter::once(ancestor.as_str()).chain(job.scope.views.iter().map(|p| p.name.as_str())) + { + let mut tree = BTreeMap::new(); + repo.materialize_view_entries(name, |entry| { + tree.insert(entry.path.clone(), entry); + Ok::<_, CliError>(()) + }) + .map_err(CliError::Repository)??; + if common.is_none() { + common = Some(tree); + } else { + trees.push(tree); + } + } + let combined = scope::compose(&common.unwrap_or_default(), &trees)?; + let output = job.workdir.join("inputs"); + if output.exists() { + verify_inputs_tree(&output, &combined)?; + return stamp_input_sources(repo, _dir, job, &combined); + } + let staging = tempfile::Builder::new() + .prefix("inputs-stage-") + .tempdir_in(&job.workdir)?; + for (path, entry) in &combined { + let relative = Path::new(&path); + if relative + .components() + .any(|c| !matches!(c, Component::Normal(_))) + || relative.as_os_str().is_empty() + || matches!(relative.components().next(),Some(Component::Normal(n)) if n==".atomic" || n==".git" || n==".atomic-sandbox") + { + return Err(invalid("unsafe path in combined recorded snapshot")); + } + if entry.mode & !0o777 != 0 { + return Err(invalid( + "collection snapshot contains unsupported special permission bits", + )); + } + let dest = staging.path().join(relative); + if entry.kind == ViewEntryKind::Directory { + fs::create_dir_all(&dest)?; + continue; + } + if let Some(parent) = dest.parent() { + fs::create_dir_all(parent)?; + } + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&dest)?; + file.write_all(&entry.content)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&dest, fs::Permissions::from_mode(entry.mode as u32 & 0o777))?; + } + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mut directories: Vec<_> = combined + .iter() + .filter(|(_, e)| e.kind == ViewEntryKind::Directory) + .collect(); + directories.sort_by_key(|(path, _)| std::cmp::Reverse(path.len())); + for (path, entry) in directories { + fs::set_permissions( + staging.path().join(path), + fs::Permissions::from_mode(entry.mode as u32), + )?; + } + } + verify_inputs_tree(staging.path(), &combined)?; + fs::rename(staging.path(), &output)?; + let _ = staging.keep(); + stamp_input_sources(repo, _dir, job, &combined)?; + Ok(()) +} + +#[derive(Debug, Serialize, Deserialize)] +struct InputSource { + path: String, + kind: ViewEntryKind, + mode: u16, + hash: String, +} + +fn stamp_input_sources( + repo: &Repository, + dir: &Path, + job: &Job, + entries: &BTreeMap, +) -> CliResult<()> { + scope::recheck(repo, &job.scope, None, None)?; + let sources: Vec<_> = entries + .values() + .map(|e| InputSource { + path: e.path.clone(), + kind: e.kind, + mode: e.mode, + hash: atomic_core::types::Hash::of(&e.content).to_base32(), + }) + .collect(); + let store = IdentityStore::open_default_existing().map_err(bad)?; + let issuer = store.load_by_name(&job.issuer).map_err(bad)?; + let key = store.load_keypair(&issuer.id, None).map_err(bad)?; + let document = json!({"schema":"atomic.review-input-sources.v1","job":job.id,"scope":job.scope,"sources":sources}); + let signed = atomic_canonical::proof::attest_value(document, &issuer, &key); + fs::write( + dir.join("inputs.json"), + serde_json::to_vec_pretty(&signed).map_err(bad)?, + )?; + Ok(()) +} + +fn recheck_input_sources(repo: &Repository, job: &Job) -> CliResult<()> { + if job.scope.views.len() < 2 { + return Ok(()); + } + let store = IdentityStore::open_default_existing().map_err(bad)?; + let issuer = store.load_by_name(&job.issuer).map_err(bad)?; + let dir = repo.dot_dir().join("review-jobs").join(&job.id); + let document = + atomic_canonical::jcs::admit_document(&fs::read(dir.join("inputs.json"))?).map_err(bad)?; + atomic_canonical::proof::verify_value(&document, &issuer.public_key).map_err(bad)?; + if document.get("job") != Some(&json!(job.id)) + || document.get("scope") != Some(&json!(job.scope)) + { + return Err(invalid( + "collection source fingerprints do not belong to the issuer-approved job", + )); + } + let sources: Vec = serde_json::from_value( + document + .get("sources") + .cloned() + .ok_or_else(|| invalid("collection source fingerprints are missing"))?, + ) + .map_err(bad)?; + verify_source_files(&job.workdir.join("inputs"), &sources) +} + +fn verify_source_files(root: &Path, sources: &[InputSource]) -> CliResult<()> { + for source in sources { + let relative = Path::new(&source.path); + if relative.as_os_str().is_empty() + || relative + .components() + .any(|c| !matches!(c, Component::Normal(_))) + { + return Err(invalid("unsafe path in collection source fingerprint")); + } + let mut path = root.to_path_buf(); + for component in relative.components() { + path.push(component.as_os_str()); + if fs::symlink_metadata(&path)?.file_type().is_symlink() { + return Err(invalid( + "publisher replaced a frozen collection source with a symlink", + )); + } + } + let metadata = fs::symlink_metadata(&path)?; + if (source.kind == ViewEntryKind::Directory) != metadata.is_dir() + || (source.kind == ViewEntryKind::File + && atomic_core::types::Hash::of(&fs::read(&path)?).to_base32() != source.hash) + { + return Err(invalid("publisher changed frozen collection source bytes; its repaired-tree test result cannot approve the original inputs")); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if metadata.permissions().mode() & 0o777 != source.mode as u32 & 0o777 { + return Err(invalid( + "publisher changed frozen collection source permissions", + )); + } + } + } + Ok(()) +} + +fn verify_inputs_tree(root: &Path, expected: &BTreeMap) -> CliResult<()> { + let mut expected_paths = BTreeSet::new(); + for (path, entry) in expected { + let relative = Path::new(path); + if relative + .components() + .any(|c| !matches!(c, Component::Normal(_))) + { + return Err(invalid("unsafe recorded input path")); + } + let mut parent = Some(relative); + while let Some(path) = parent { + if !path.as_os_str().is_empty() { + expected_paths.insert(path.to_path_buf()); + } + parent = path.parent(); + } + let actual = root.join(relative); + let metadata = fs::symlink_metadata(&actual)?; + if metadata.file_type().is_symlink() + || (entry.kind == ViewEntryKind::Directory) != metadata.is_dir() + || (entry.kind == ViewEntryKind::File && fs::read(&actual)? != entry.content) + { + return Err(invalid( + "retained collection inputs differ from the frozen recorded composition", + )); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if metadata.permissions().mode() & 0o777 != entry.mode as u32 & 0o777 { + return Err(invalid("retained collection input permissions changed")); + } + } + } + let mut actual_paths = BTreeSet::new(); + let mut pending = vec![root.to_path_buf()]; + while let Some(directory) = pending.pop() { + for entry in fs::read_dir(&directory)? { + let entry = entry?; + let path = entry.path(); + let metadata = fs::symlink_metadata(&path)?; + if metadata.file_type().is_symlink() { + return Err(invalid("unexpected symlink in retained collection inputs")); + } + actual_paths.insert(path.strip_prefix(root).map_err(bad)?.to_path_buf()); + if metadata.is_dir() { + pending.push(path); + } + } + } + if actual_paths != expected_paths { + return Err(invalid( + "retained collection inputs contain missing or extra files", + )); + } + Ok(()) +} + +fn retire_credentials(job: &mut Job) -> CliResult<()> { + if job.credentials_retired { + return Ok(()); + } + let store = IdentityStore::open_default_existing().map_err(bad)?; + let issuer = store.load_by_name(&job.issuer).map_err(bad)?; + let issuer_pair = store.load_keypair(&issuer.id, None).map_err(bad)?; + let id = atomic_identity::delegation::DelegationId::from_base32(&job.delegation) + .ok_or_else(|| invalid("invalid recording delegation ID in retained job"))?; + let revoke = atomic_canonical::delegation::mint_revocation( + &issuer, + &issuer_pair, + &id, + Some("Owned review publication finished or explicitly cancelled"), + ); + store + .save_revocation( + &job.delegation, + &serde_json::to_string_pretty(&revoke).map_err(bad)?, + ) + .map_err(bad)?; + let reviewer = store.load_by_name(&job.reviewer).map_err(bad)?; + if atomic_canonical::did::did_for_public_key(&reviewer.public_key) != job.reviewer_did { + return Err(invalid("refusing to retire a different identity")); + } + // Keep public identity material so past signatures remain verifiable. + store.retire_secret_key(&reviewer.id).map_err(bad)?; + job.credentials_retired = true; + Ok(()) +} + +fn executable(path: &Path) -> CliResult { + let candidates = if path.components().count() > 1 { + vec![path.to_path_buf()] + } else { + std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()) + .map(|p| p.join(path)) + .collect() + }; + candidates.into_iter().find(|p| p.is_file()).ok_or_else(|| { + invalid(format!( + "publisher executable '{}' not found; no credentials created", + path.display() + )) + }) +} + +fn atomic_output(root: &Path, args: &[&str]) -> CliResult> { + let output = Process::new(std::env::current_exe()?) + .current_dir(root) + .args(args) + .output()?; + if !output.status.success() { + return Err(invalid(format!( + "Atomic lifecycle refused: {}", + String::from_utf8_lossy(&output.stderr) + ))); + } + Ok(output.stdout) +} + +fn run_bounded(command: &mut Process, timeout: Duration) -> CliResult { + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + command.process_group(0); + } + struct OwnedChild { + child: std::process::Child, + finished: bool, + } + impl Drop for OwnedChild { + fn drop(&mut self) { + if !self.finished { + #[cfg(unix)] + unsafe { + libc::kill(-(self.child.id() as i32), libc::SIGKILL); + } + let _ = self.child.kill(); + let _ = self.child.wait(); + } + } + } + let mut owned = OwnedChild { + child: command.spawn()?, + finished: false, + }; + let start = Instant::now(); + loop { + if let Some(status) = owned.child.try_wait()? { + owned.finished = true; + return Ok(status); + } + if start.elapsed() >= timeout { + // Drop kills only the process group created and owned here, never + // a PID restored from mutable recovery metadata. + return Err(invalid("publisher timed out; no successful session_end or publication asserted; job retained for recovery")); + } + std::thread::sleep(Duration::from_millis(100)); + } +} + +fn read_session_id(path: &Path) -> CliResult { + if fs::metadata(path)?.len() > 64 * 1024 * 1024 { + return Err(invalid("publisher output exceeds the bounded session-discovery budget; retained log was not truncated into approval")); + } + let mut ids = BTreeSet::new(); + for line in fs::read_to_string(path)?.lines() { + let Ok(value) = serde_json::from_str::(line) else { + continue; + }; + if let Some(id) = value.get("sessionID").and_then(Value::as_str) { + ids.insert(id.to_string()); + } + } + if ids.len() != 1 { + return Err(invalid( + "publisher output has no unique native session identity", + )); + } + Ok(ids.into_iter().next().unwrap()) +} + +fn lock_job(dir: &Path) -> CliResult { + let file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(dir.join("job.lock"))?; + file.try_lock_exclusive() + .map_err(|_| invalid("publication job is already owned by another process; retry later"))?; + Ok(file) +} + +fn save_job(dir: &Path, job: &Job) -> CliResult<()> { + let mut temp = tempfile::NamedTempFile::new_in(dir)?; + temp.write_all(&serde_json::to_vec_pretty(job).map_err(bad)?)?; + temp.as_file().sync_all()?; + temp.persist(dir.join("job.json")).map_err(bad)?; + Ok(()) +} + +fn write_immutable(path: &Path, bytes: &[u8]) -> CliResult<()> { + if fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_symlink()) { + return Err(invalid( + "immutable publication recovery output must not be a symlink", + )); + } + if path.exists() { + if fs::read(path)? == bytes { + return Ok(()); + } + return Err(invalid( + "immutable publication recovery bytes already exist and differ; refusing replacement", + )); + } + let parent = path + .parent() + .ok_or_else(|| invalid("publication receipt has no parent directory"))?; + let mut staging = tempfile::NamedTempFile::new_in(parent)?; + staging.write_all(bytes)?; + staging.as_file().sync_all()?; + match staging.persist_noclobber(path) { + Ok(_) => Ok(()), + Err(e) + if e.error.kind() == std::io::ErrorKind::AlreadyExists && fs::read(path)? == bytes => + { + Ok(()) + } + Err(e) => Err(bad(e)), + } +} + +fn output(args: &PublishArgs, job: &Job) -> CliResult<()> { + if args.json { + println!("{}", serde_json::to_string_pretty(job).map_err(bad)?); + } else { + println!("review publication {}: {}\nreview: {}\nartifacts: {}\ncredentials retired: {}\nNo insertion or push performed.",job.id,job.phase,job.review.as_deref().unwrap_or("none"),job.artifacts.len(),job.credentials_retired); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser; + #[derive(Parser)] + struct Cli { + #[command(flatten)] + args: PublishArgs, + } + #[test] + fn scope_forms_are_exclusive() { + assert!(Cli::try_parse_from(["publish", "--view", "a,b", "--session", "s"]).is_err()); + assert!(Cli::try_parse_from(["publish", "--view", "a", "--resume", "id"]).is_err()); + assert!(Cli::try_parse_from(["publish", "--timeout-seconds", "0"]).is_err()); + } + #[test] + fn session_identity_is_never_guessed_from_ambiguous_agent_output() { + let file = tempfile::NamedTempFile::new().unwrap(); + fs::write( + file.path(), + "{\"sessionID\":\"a\"}\n{\"sessionID\":\"b\"}\n", + ) + .unwrap(); + assert!(read_session_id(file.path()).is_err()); + fs::write( + file.path(), + "{\"sessionID\":\"a\"}\n{\"sessionID\":\"a\"}\n", + ) + .unwrap(); + assert_eq!(read_session_id(file.path()).unwrap(), "a"); + } + #[test] + fn job_lock_refuses_concurrent_owners() { + let dir = tempfile::tempdir().unwrap(); + let _first = lock_job(dir.path()).unwrap(); + assert!(lock_job(dir.path()).is_err()); + } + #[test] + fn signature_recovery_bytes_are_idempotent_and_never_replaced() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("signed-0.json"); + write_immutable(&path, b"original signed bytes").unwrap(); + write_immutable(&path, b"original signed bytes").unwrap(); + assert!(write_immutable(&path, b"new approval must not replace original").is_err()); + assert_eq!(fs::read(path).unwrap(), b"original signed bytes"); + } + #[test] + fn recording_certificate_is_local_only_and_has_no_push() { + let issuer_key = KeyPair::generate(); + let issuer = Identity::new("issuer", &issuer_key); + let reviewer_key = KeyPair::generate(); + let reviewer = Identity::builder("temporary-reviewer") + .identity_type(IdentityType::Agent) + .public_key(reviewer_key.public) + .delegated_by(issuer.id) + .build() + .unwrap(); + let scope = DelegationScope::builder() + .permissions(vec![ + DelegationPermission::Read, + DelegationPermission::Record, + ]) + .server("atomic-local://project") + .project("project") + .view("view") + .max_changes(3) + .build(); + let grant = + Delegation::new(&issuer, &reviewer, scope).expires_in(chrono::Duration::minutes(30)); + let value = atomic_canonical::delegation::mint(&issuer, &issuer_key, &grant); + let encoded = atomic_canonical::delegation::encode_for_storage(&value).unwrap(); + assert!(encoded.contains("atomic-local://project")); + assert!(!encoded.contains("\"push\"")); + } + #[test] + fn collection_tests_may_add_build_outputs_but_not_repair_the_reviewed_sources() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source.ts"); + fs::write(&source, b"original").unwrap(); + #[cfg(unix)] + let mode = { + use std::os::unix::fs::PermissionsExt; + fs::metadata(&source).unwrap().permissions().mode() as u16 & 0o777 + }; + #[cfg(not(unix))] + let mode = 0o644; + let sources = vec![InputSource { + path: "source.ts".into(), + kind: ViewEntryKind::File, + mode, + hash: atomic_core::types::Hash::of(b"original").to_base32(), + }]; + fs::create_dir(dir.path().join("target")).unwrap(); + fs::write(dir.path().join("target/build-output"), b"not source").unwrap(); + verify_source_files(dir.path(), &sources).unwrap(); + fs::write(&source, b"repaired by reviewer").unwrap(); + assert!(verify_source_files(dir.path(), &sources).is_err()); + } + #[cfg(unix)] + #[test] + fn failing_or_timed_out_runner_cannot_be_reported_successful() { + assert!(!run_bounded( + Process::new("/bin/sh").args(["-c", "exit 7"]), + Duration::from_secs(1) + ) + .unwrap() + .success()); + assert!(run_bounded( + Process::new("/bin/sleep").arg("2"), + Duration::from_millis(10) + ) + .is_err()); + } +} diff --git a/atomic-cli/src/commands/review/risk.rs b/atomic-cli/src/commands/review/risk.rs new file mode 100644 index 00000000..59302129 --- /dev/null +++ b/atomic-cli/src/commands/review/risk.rs @@ -0,0 +1,480 @@ +//! Evidence-based risk presentation, separate from heuristic relationship counts. + +use atomic_audit::impact::ImpactReport; +use atomic_audit::risk::{RiskLevel, RiskProfile}; +use std::collections::BTreeSet; +use std::fmt::Write; + +use atomic_canonical::review_finding::{Confidence, Evidence, EvidenceKind, Severity}; +use atomic_canonical::review_graph::{ + PassStatus, ReviewGraph, ReviewPass, RiskAssessment, RiskCoverage, RiskRating, RiskSummary, +}; + +fn severity(severity: &Severity) -> u8 { + match severity { + Severity::Info => 0, + Severity::Low => 1, + Severity::Medium => 2, + Severity::High | Severity::Critical => 3, + } +} + +fn rating(rating: RiskRating) -> u8 { + match rating { + RiskRating::High => 3, + RiskRating::Medium => 2, + RiskRating::Low => 1, + RiskRating::Unknown | RiskRating::NotApplicable => 0, + } +} + +fn confidence(confidence: &Confidence) -> u8 { + match confidence { + Confidence::Low => 0, + Confidence::Medium => 1, + Confidence::High => 2, + } +} + +fn validate(assessment: &RiskAssessment, known_risk: u8) -> Result<(), &'static str> { + if assessment.rationale.trim().is_empty() + || assessment.evidence.is_empty() + || assessment + .evidence + .iter() + .any(|item| item.reference.trim().is_empty() || item.observation.trim().is_empty()) + || assessment + .limitations + .iter() + .any(|item| item.trim().is_empty()) + { + return Err( + "risk assessment requires rationale, referenced evidence and nonempty limitation text", + ); + } + if assessment.rating == RiskRating::NotApplicable + || assessment.coverage == RiskCoverage::NotApplicable + { + return Err("not-applicable risk is derived only from a metadata-only selection"); + } + if assessment.rating == RiskRating::Low && assessment.coverage != RiskCoverage::Complete { + return Err("low risk requires complete reviewer-declared coverage of the selected scope"); + } + if assessment.coverage != RiskCoverage::Complete && assessment.limitations.is_empty() { + return Err("incomplete risk assessment requires explicit coverage limitations"); + } + if assessment.rating == RiskRating::Unknown && assessment.coverage == RiskCoverage::Complete { + return Err("unknown risk cannot claim complete assessment coverage"); + } + if assessment.rating != RiskRating::Unknown && assessment.coverage == RiskCoverage::Unavailable + { + return Err("unavailable risk assessment cannot supply a known rating"); + } + if known_risk >= 2 && rating(assessment.rating) < known_risk { + return Err("risk assessment cannot downgrade the severity of scoped risk findings"); + } + Ok(()) +} + +fn signals(nodes: &[atomic_canonical::review_graph::GraphNode]) -> Vec { + let mut signals = Vec::new(); + for (metric, title) in [ + ("dependency_fan_out", "Declared dependency fan-out"), + ("public_surface", "Declared public surface"), + ] { + let (mut increased, mut growth, mut added, mut added_values) = (0, 0u64, 0, 0u64); + for node in nodes.iter().filter(|node| { + node.kind == "metric" && node.properties["observation"]["metric"] == metric + }) { + let observation = &node.properties["observation"]; + let Some(after) = observation["after"]["value"] + .as_u64() + .filter(|_| observation["after"]["status"] == "measured") + else { + continue; + }; + if let Some(before) = observation["before"]["value"] + .as_u64() + .filter(|_| observation["before"]["status"] == "measured") + { + if after > before { + increased += 1; + growth += after - before; + } + } else if observation["before"]["status"] == "not_applicable" && after > 0 { + added += 1; + added_values += after; + } + } + if increased > 0 || added > 0 { + signals.push(format!("{title}: {increased} increased file observation(s) (+{growth}); {added} added-file observation(s) ({added_values} declared). Not a severity score.")); + } + } + signals +} + +pub(super) fn attach( + graph: &mut ReviewGraph, + submitted: Option, + impact: Vec, + profile: &RiskProfile, +) -> Result<(), &'static str> { + let pass = graph + .passes + .iter() + .find(|pass| pass.pass == ReviewPass::BlastRadiusRisk) + .expect("risk pass"); + let findings: Vec<_> = graph + .findings + .iter() + .filter(|finding| finding.passes.contains(&ReviewPass::BlastRadiusRisk)) + .collect(); + let known_risk = findings + .iter() + .map(|finding| severity(&finding.finding.severity)) + .max() + .unwrap_or(0); + let model = if pass.status == PassStatus::NotApplicable { + None + } else { + Some(atomic_audit::risk::assess( + super::risk_facts::collect(&graph.nodes, &impact), + profile, + )?) + }; + let (assessment, basis) = if pass.status == PassStatus::NotApplicable { + if submitted.is_some() { + return Err("metadata-only selection has no application-code risk assessment"); + } + ( + RiskAssessment { + rating: RiskRating::NotApplicable, + confidence: Confidence::High, + coverage: RiskCoverage::NotApplicable, + rationale: + "No application code selected; metadata evidence checks remain separate.".into(), + evidence: vec![], + limitations: vec![], + }, + "no_code", + ) + } else if let Some(assessment) = submitted { + validate(&assessment, known_risk)?; + (assessment, "reviewer") + } else { + let strongest = findings + .iter() + .filter(|finding| severity(&finding.finding.severity) == known_risk) + .min_by_key(|finding| confidence(&finding.finding.confidence)); + let estimate = model.as_ref().expect("code risk model"); + let estimated_rating = match estimate.rating { + RiskLevel::High => RiskRating::High, + RiskLevel::Medium => RiskRating::Medium, + RiskLevel::Low => RiskRating::Low, + RiskLevel::Unknown => RiskRating::Unknown, + }; + let established = known_risk >= 2 && known_risk >= rating(estimated_rating); + let confidence = if established { + strongest.unwrap().finding.confidence.clone() + } else if estimate.evidence_complete { + Confidence::Medium + } else { + Confidence::Low + }; + let evidence = if established { + strongest.unwrap().finding.evidence.clone() + } else { + estimate + .rules + .iter() + .take(3) + .flat_map(|rule| { + rule.references.iter().map(|reference| Evidence { + kind: EvidenceKind::Reference, + reference: reference.clone(), + observation: format!("{}: {}", rule.id, rule.reason), + }) + }) + .take(8) + .collect() + }; + (RiskAssessment { + rating: if established { if known_risk >= 3 { RiskRating::High } else { RiskRating::Medium } } else { estimated_rating }, + confidence, + coverage: if pass.status == PassStatus::Blocked { RiskCoverage::Unavailable } else { RiskCoverage::Partial }, + rationale: if established { "Known issue severity sets the minimum risk; source analysis may leave additional exposure.".into() } else if estimate.rating == RiskLevel::Unknown { "Insufficient measured evidence to apply a risk rule or establish a localized change.".into() } else { format!("Rule-based change-review risk under {} / {}. This prioritizes inspection; it is not a defect probability or approval.", estimate.model, profile.name) }, + evidence, + limitations: impact.iter().flat_map(|report| report.gaps.iter().cloned()).chain(estimate.facts.unknowns.iter().cloned()).chain(std::iter::once("Static review-risk estimate; runtime, security and executed-test coverage are not assessed.".into())).collect::>().into_iter().collect(), + }, if established { "findings" } else { "rule_model" }) + }; + graph.risk = Some(RiskSummary { + assessment, basis: basis.into(), findings: findings.iter().map(|finding| finding.number).collect(), + unverified_call_candidates: graph.edges.iter().filter(|edge| edge.relation == "unverified_call_candidate").count(), + unverified_import_candidates: graph.edges.iter().filter(|edge| edge.relation == "unverified_import_candidate").count(), + relationship_coverage: "Recorded before/after statically bound free-function calls via supported lexical/import/module paths; unresolved receivers/dynamic bindings are excluded, not guessed. Not compiler/type or whole-program proof.".into(), + signals: signals(&graph.nodes), + impact, + model, + }); + graph.nodes.push(atomic_canonical::review_graph::GraphNode { + id: "risk-summary".into(), + kind: "risk_summary".into(), + label: "Report-local risk assessment (not signed approval)".into(), + properties: serde_json::to_value(graph.risk.as_ref().unwrap()) + .expect("risk summary serializes"), + }); + graph.edges.push(atomic_canonical::review_graph::GraphEdge { + from: ReviewPass::BlastRadiusRisk.id().into(), + relation: "assesses_risk".into(), + to: "risk-summary".into(), + }); + if let Some(model) = &graph.risk.as_ref().unwrap().model { + for rule in &model.rules { + let id = format!("risk-rule:{}", rule.id); + graph.nodes.push(atomic_canonical::review_graph::GraphNode { + id: id.clone(), + kind: "risk_rule".into(), + label: rule.reason.clone(), + properties: serde_json::to_value(rule).expect("risk rule serializes"), + }); + graph.edges.push(atomic_canonical::review_graph::GraphEdge { + from: "risk-summary".into(), + relation: "triggered_by".into(), + to: id, + }); + } + } + for finding in findings { + graph.edges.push(atomic_canonical::review_graph::GraphEdge { + from: "risk-summary".into(), + relation: "supported_by_finding".into(), + to: finding.id.clone(), + }); + } + graph.nodes.sort_by(|left, right| left.id.cmp(&right.id)); + graph.edges.sort(); + Ok(()) +} + +pub(super) fn attach_snapshot(graph: &mut ReviewGraph) { + graph.risk = Some(RiskSummary { + assessment: RiskAssessment { + rating: RiskRating::Unknown, confidence:Confidence::Low, coverage:RiskCoverage::Unavailable, + rationale:"Whole-view snapshot audit has no change baseline; change-regression risk is not assessed. Current public-surface and dependency metrics remain available.".into(), + evidence:vec![], limitations:vec!["No before/after change or call-contract comparison is implied by a view snapshot.".into()], + }, + basis:"view_snapshot".into(),findings:vec![],unverified_call_candidates:0,unverified_import_candidates:0, + relationship_coverage:"Snapshot audit/metric scope only; change-regression relationships were not evaluated.".into(), + signals:vec![],impact:vec![],model:None, + }); + graph.nodes.push(atomic_canonical::review_graph::GraphNode { + id: "risk-summary".into(), + kind: "risk_summary".into(), + label: "Change risk not evaluated for view snapshot".into(), + properties: serde_json::to_value(graph.risk.as_ref().unwrap()) + .expect("risk summary serializes"), + }); + graph.edges.push(atomic_canonical::review_graph::GraphEdge { + from: ReviewPass::BlastRadiusRisk.id().into(), + relation: "assesses_risk".into(), + to: "risk-summary".into(), + }); +} + +pub(super) fn render(text: &mut String, stem: &str, summary: &RiskSummary) { + let assessment = &summary.assessment; + writeln!( + text, + "{stem}Risk: {:?} · Confidence: {:?} · Coverage: {:?} ({})", + assessment.rating, assessment.confidence, assessment.coverage, summary.basis + ) + .unwrap(); + writeln!(text, "{stem}{}", assessment.rationale).unwrap(); + if let Some(model) = &summary.model { + for rule in model.rules.iter().take(3) { + writeln!( + text, + "{stem}{:?} · {}: {}", + rule.level, rule.id, rule.reason + ) + .unwrap(); + } + if model.rules.len() > 3 { + writeln!( + text, + "{stem}{} further rule triggers retained in --json", + model.rules.len() - 3 + ) + .unwrap(); + } + let facts = &model.facts; + writeln!( + text, + "{stem}Scope: {} production function(s), {} test/support function(s), {} component(s)", + facts.production_functions, + facts.test_support_functions, + facts.components.len() + ) + .unwrap(); + writeln!(text, "{stem}Direct impact: {} current bound caller(s) ({} production; {} test/support); {} observed production consumers of modified existing declarations", facts.observed_production_callers + facts.observed_test_support_callers, facts.observed_production_callers, facts.observed_test_support_callers, facts.existing_production_callers).unwrap(); + let checked = summary + .impact + .iter() + .map(|report| report.checked_call_contracts) + .sum::(); + let issues = summary + .impact + .iter() + .map(|report| report.issues.len()) + .sum::(); + let preexisting = summary + .impact + .iter() + .map(|report| report.preexisting_incompatible_contracts) + .sum::(); + writeln!(text, "{stem}Source checks: {checked} call contracts · {issues} incompatible after-contract(s) · {preexisting} preexisting incompatibility(s)").unwrap(); + if summary.basis == "reviewer" { + writeln!( + text, + "{stem}Automatic estimate retained: {:?} under {} / {}", + model.rating, model.model, model.profile.name + ) + .unwrap(); + } + if assessment.coverage != RiskCoverage::Complete { + let unresolved = facts + .unresolved_references + .map(|count| count.to_string()) + .unwrap_or_else(|| "unavailable".into()); + writeln!(text, "{stem}Coverage: {unresolved} unresolved reference expression(s), excluded from callers and severity; {} scoped limits retained in --json", assessment.limitations.len()).unwrap(); + } + } + if assessment.rating != RiskRating::NotApplicable { + writeln!( + text, + "{stem}Risk findings: {}", + if summary.findings.is_empty() { + "none reported; estimated risk is not a confirmed defect".into() + } else { + summary + .findings + .iter() + .map(|number| format!("F{number}")) + .collect::>() + .join(", ") + } + ) + .unwrap(); + } + for evidence in assessment + .evidence + .iter() + .filter(|_| summary.basis == "reviewer") + .take(3) + { + writeln!( + text, + "{stem}Evidence: {} — {}", + evidence.reference, evidence.observation + ) + .unwrap(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use atomic_canonical::review_finding::{Evidence, EvidenceKind}; + + fn assessment() -> RiskAssessment { + RiskAssessment { + rating: RiskRating::Low, + confidence: Confidence::Medium, + coverage: RiskCoverage::Complete, + rationale: "Checked the selected contracts and supported consumers.".into(), + evidence: vec![Evidence { + kind: EvidenceKind::Test, + reference: "focused contract test".into(), + observation: + "Selected before/after behavior and affected supported consumers checked." + .into(), + }], + limitations: vec![], + } + } + + #[test] + fn low_requires_evidence_and_complete_scoped_coverage() { + let original = assessment(); + assert!(validate(&original, 0).is_ok()); + for mutation in [ + "rationale", + "evidence", + "reference", + "observation", + "coverage", + "limitation", + "not_applicable", + ] { + let mut changed = original.clone(); + match mutation { + "rationale" => changed.rationale.clear(), + "evidence" => changed.evidence.clear(), + "reference" => changed.evidence[0].reference.clear(), + "observation" => changed.evidence[0].observation.clear(), + "coverage" => { + changed.coverage = RiskCoverage::Partial; + changed.limitations.push("Consumers unresolved".into()); + } + "limitation" => changed.limitations.push(" ".into()), + _ => changed.rating = RiskRating::NotApplicable, + } + assert!(validate(&changed, 0).is_err(), "{mutation}"); + } + } + + #[test] + fn ratings_require_evidence_not_invented_defects_and_preserve_issue_floors() { + let mut item = assessment(); + assert!(validate(&item, 3).is_err()); + item.rating = RiskRating::High; + assert!( + validate(&item, 0).is_ok(), + "evidenced high review risk need not claim a defect" + ); + assert!(validate(&item, 3).is_ok()); + item.rating = RiskRating::Medium; + assert!(validate(&item, 3).is_err()); + assert!(validate(&item, 2).is_ok()); + item.coverage = RiskCoverage::Partial; + assert!(validate(&item, 2).is_err()); + item.limitations + .push("Dynamic consumers not resolved".into()); + assert!(validate(&item, 2).is_ok()); + item.rating = RiskRating::Unknown; + assert!(validate(&item, 0).is_ok()); + assert!(validate(&item, 2).is_err()); + item.coverage = RiskCoverage::Complete; + assert!(validate(&item, 0).is_err()); + } + + #[test] + fn metric_signals_distinguish_growth_additions_and_unavailable_baselines() { + use atomic_canonical::review_graph::GraphNode; + use serde_json::json; + let nodes = [ + json!({"metric": "public_surface", "before": {"status": "measured", "value": 42}, "after": {"status": "measured", "value": 56}}), + json!({"metric": "public_surface", "before": {"status": "not_applicable"}, "after": {"status": "measured", "value": 24}}), + json!({"metric": "public_surface", "before": {"status": "unavailable"}, "after": {"status": "measured", "value": 500}}), + json!({"metric": "dependency_fan_out", "before": {"status": "measured", "value": 3}, "after": {"status": "measured", "value": 4}}), + json!({"metric": "dependency_fan_out", "before": {"status": "measured", "value": 4}, "after": {"status": "measured", "value": 4}}), + ].into_iter().map(|observation| GraphNode { id: "metric".into(), kind: "metric".into(), label: "".into(), properties: json!({"observation": observation}) }).collect::>(); + let result = signals(&nodes); + assert_eq!(result.len(), 2); + assert!(result[0].contains("1 increased file observation(s) (+1)")); + assert!(result[1].contains( + "1 increased file observation(s) (+14); 1 added-file observation(s) (24 declared)" + )); + assert!(!result.iter().any(|signal| signal.contains("500"))); + } +} diff --git a/atomic-cli/src/commands/review/risk_facts.rs b/atomic-cli/src/commands/review/risk_facts.rs new file mode 100644 index 00000000..33c611b7 --- /dev/null +++ b/atomic-cli/src/commands/review/risk_facts.rs @@ -0,0 +1,463 @@ +//! Adapt existing semantic/metric observations, without another source scan. + +use std::collections::{BTreeMap, BTreeSet}; + +use atomic_audit::{ + impact::ImpactReport, + metrics::EXTRACTION_CONVENTION, + risk::{component, test_support, RiskFacts}, +}; +use atomic_canonical::review_graph::GraphNode; + +fn code(path: &str) -> bool { + atomic_semantic::is_supported(path) + || matches!( + std::path::Path::new(path) + .extension() + .and_then(|ext| ext.to_str()), + Some("js" | "jsx" | "mjs" | "cjs") + ) +} + +fn reference(evidence: &mut BTreeMap>, dimension: &str, value: String) { + let values = evidence.entry(dimension.into()).or_default(); + values.insert(value); + // Deterministic bounded references; full source observations remain in graph. + if values.len() > 8 { + values.pop_last(); + } +} + +pub(super) fn collect(nodes: &[GraphNode], impact: &[ImpactReport]) -> RiskFacts { + let mut facts = RiskFacts::default(); + let (mut functions, mut existing, mut signatures, mut tests) = ( + BTreeSet::new(), + BTreeSet::new(), + BTreeSet::new(), + BTreeSet::new(), + ); + let ( + mut paths, + mut non_callable, + mut prod_callers, + mut test_callers, + mut existing_callers, + mut caller_files, + mut outside, + ) = ( + BTreeSet::new(), + BTreeSet::new(), + BTreeSet::new(), + BTreeSet::new(), + BTreeSet::new(), + BTreeSet::new(), + BTreeSet::new(), + ); + let mut refs = BTreeMap::new(); + let mut recorded_paths = BTreeMap::>::new(); + for node in nodes.iter().filter(|node| node.kind == "metric") { + if let (Some(change), Some(path)) = ( + node.properties["change"].as_str(), + node.properties["path"].as_str(), + ) { + recorded_paths + .entry(change.into()) + .or_default() + .insert(path.into()); + } + } + for node in nodes.iter().filter(|node| node.kind == "finding") { + if node.properties["comparison"].is_object() + && node.properties["comparison"]["status"] != "new" + { + continue; + } + let finding = &node.properties["finding"]; + if finding["introduced_by_change"]["status"] != "no" + && matches!( + finding["requirement_or_rule"]["id"].as_str(), + Some("structural.syntax" | "anti-slop.rust-placeholder" | "anti-slop.empty-catch") + ) + { + facts.structural_alerts += 1; + facts.available = true; + reference( + &mut refs, + "alerts", + format!( + "{}:{}", + finding["change"].as_str().unwrap_or("recorded"), + finding["requirement_or_rule"]["id"].as_str().unwrap() + ), + ); + } + } + let mut unresolved = Some(0usize); + let mut selection = Some(true); + for report in impact { + reference( + &mut refs, + "change", + format!("{}:semantic-source-comparison", report.change), + ); + facts.available |= report.inspected_files_before > 0 || report.inspected_files_after > 0; + selection = match (selection, report.source_selection_complete) { + (Some(a), Some(b)) => Some(a && b), + _ => None, + }; + unresolved = unresolved + .zip(report.unresolved_references) + .map(|(a, b)| a.saturating_add(b)); + let mut old_ids = BTreeSet::new(); + let mut selected_paths = recorded_paths + .get(&report.change) + .cloned() + .unwrap_or_default(); + selected_paths.extend(report.non_callable_changes.iter().cloned()); + for function in &report.changed_functions { + let Some(location) = function.after.as_ref().or(function.before.as_ref()) else { + continue; + }; + selected_paths.insert(location.path.clone()); + if test_support(&location.path, &function.id) { + tests.insert(function.id.clone()); + continue; + } + functions.insert(function.id.clone()); + paths.insert(location.path.clone()); + if function.before.is_some() { + existing.insert(function.id.clone()); + old_ids.insert(function.id.clone()); + } + if function.signature_changed && function.before.is_some() { + signatures.insert(function.id.clone()); + } + reference( + &mut refs, + "change", + format!( + "{}:{}:{}:{}-{}", + report.change, + if function.after.is_some() { + "after" + } else { + "before" + }, + location.path, + location.start_line, + location.end_line + ), + ); + } + for path in &report.non_callable_changes { + if code(path) && !test_support(path, "") { + non_callable.insert(path.clone()); + paths.insert(path.clone()); + reference( + &mut refs, + "change", + format!("{}:module:{path}", report.change), + ); + } + } + for call in &report.callers_after { + if !call.target_present || !call.visibility_compatible { + continue; + } + if test_support(&call.location.path, &call.caller) { + test_callers.insert(call.caller.clone()); + } else { + prod_callers.insert(call.caller.clone()); + } + } + for call in report.callers_before.iter().chain(&report.callers_after) { + if !call.visibility_compatible + || test_support(&call.location.path, &call.caller) + || !old_ids.contains(&call.callee) + { + continue; + } + existing_callers.insert(call.caller.clone()); + caller_files.insert(call.location.path.clone()); + if !selected_paths.contains(&call.location.path) { + outside.insert(call.caller.clone()); + } + reference( + &mut refs, + "calls", + format!( + "{}:{}:{}-{}:{}", + report.change, + call.location.path, + call.location.start_line, + call.location.end_line, + call.caller + ), + ); + } + } + if impact.is_empty() { + selection = None; + unresolved = None; + } + let ( + mut public_seen, + mut public_complete, + mut public_growth, + mut public_added, + mut public_removed, + mut dep_seen, + mut dep_growth, + ) = (false, true, 0u64, 0u64, 0u64, false, 0u64); + let mut seen = BTreeSet::new(); + for node in nodes.iter().filter(|node| node.kind == "metric") { + if !seen.insert(&node.id) { + continue; + } + let Some(path) = node.properties["path"] + .as_str() + .filter(|path| code(path) && !test_support(path, "")) + else { + continue; + }; + let observation = &node.properties["observation"]; + let Some(metric) = observation["metric"] + .as_str() + .filter(|metric| matches!(*metric, "public_surface" | "dependency_fan_out")) + else { + continue; + }; + let before = &observation["before"]; + let after = &observation["after"]; + let measured = |value: &serde_json::Value| { + (value["status"] == "measured") + .then(|| value["value"].as_u64()) + .flatten() + }; + let supported = node.properties["convention"] == EXTRACTION_CONVENTION; + let comparable = supported + && (measured(before).is_some() || before["status"] == "not_applicable") + && (measured(after).is_some() || after["status"] == "not_applicable"); + if metric == "public_surface" { + public_seen = true; + public_complete &= comparable; + } else { + dep_seen = true; + } + if !comparable { + continue; + } + facts.available = true; + let delta = measured(before) + .zip(measured(after)) + .map(|(before, after)| after.saturating_sub(before)); + let added = if before["status"] == "not_applicable" { + measured(after) + } else { + None + }; + let removed = measured(before) + .map(|before| { + if after["status"] == "not_applicable" { + before + } else { + before.saturating_sub(measured(after).unwrap_or(before)) + } + }) + .unwrap_or(0); + if metric == "public_surface" { + public_growth = public_growth.saturating_add(delta.unwrap_or(0)); + public_added = public_added.saturating_add(added.unwrap_or(0)); + public_removed = public_removed.saturating_add(removed); + } else { + dep_growth = dep_growth.saturating_add(delta.unwrap_or(0)); + } + if delta.is_some_and(|value| value > 0) + || added.is_some_and(|value| value > 0) + || (metric == "public_surface" && removed > 0) + { + paths.insert(path.into()); + reference( + &mut refs, + if metric == "public_surface" { + "surface" + } else { + "dependency" + }, + format!( + "{}:{metric}:{path}", + node.properties["change"].as_str().unwrap_or("recorded") + ), + ); + } + } + facts.production_functions = functions.len(); + facts.existing_production_functions = existing.len(); + facts.signature_changes = signatures.len(); + facts.test_support_functions = tests.len(); + facts.components = paths + .iter() + .map(|path| component(path)) + .collect::>() + .into_iter() + .collect(); + facts.production_paths = paths.into_iter().collect(); + facts.non_callable_paths = non_callable.into_iter().collect(); + facts.observed_production_callers = prod_callers.len(); + facts.observed_test_support_callers = test_callers.len(); + facts.existing_production_callers = existing_callers.len(); + facts.existing_caller_files = caller_files.len(); + facts.outside_change_callers = outside.len(); + facts.public_growth = public_seen.then_some(public_growth); + facts.added_file_public_units = public_seen.then_some(public_added); + facts.public_removed = public_seen.then_some(public_removed); + facts.dependency_growth = dep_seen.then_some(dep_growth); + facts.source_selection_complete = selection; + facts.unresolved_references = unresolved; + facts.surface_measurements_complete = (public_seen && public_complete) + || (facts.production_functions == 0 + && facts.test_support_functions > 0 + && facts.production_paths.is_empty()); + if selection != Some(true) { + facts + .unknowns + .push("Source-selection coverage is incomplete or unavailable".into()); + } + if unresolved != Some(0) { + facts + .unknowns + .push("Unresolved reference expressions are excluded from observed callers".into()); + } + if !facts.surface_measurements_complete { + facts + .unknowns + .push("Declared public-surface measurements are incomplete or unavailable".into()); + } + facts.references = refs + .into_iter() + .map(|(key, refs)| (key, refs.into_iter().collect())) + .collect(); + facts +} + +#[cfg(test)] +mod tests { + use super::*; + use atomic_audit::impact::{ChangedFunction, DirectCall, SourceLocation}; + use serde_json::{json, Value}; + + #[test] + fn existing_or_resolved_view_observations_do_not_become_new_structural_risk_alerts() { + for status in ["existing", "resolved", "changed", "unknown"] { + let node = GraphNode { + id: "finding".into(), + kind: "finding".into(), + label: "placeholder".into(), + properties: json!({"comparison":{"status":status},"finding":{"change":"urn:comparison","introduced_by_change":{"status":"unknown"},"requirement_or_rule":{"id":"anti-slop.rust-placeholder"}}}), + }; + assert_eq!(collect(&[node], &[]).structural_alerts, 0); + } + } + + fn location(path: &str) -> SourceLocation { + SourceLocation { + path: path.into(), + start_line: 1, + end_line: 1, + } + } + fn metric(id: &str, path: &str, before: Value, after: Value) -> GraphNode { + GraphNode { + id: id.into(), + kind: "metric".into(), + label: "".into(), + properties: json!({"change":"hash","path":path,"convention":EXTRACTION_CONVENTION,"observation":{"metric":"public_surface","before":before,"after":after}}), + } + } + fn call(caller: &str, path: &str) -> DirectCall { + DirectCall { + caller: caller.into(), + callee: "src/lib.rs#work".into(), + location: location(path), + declaration: location("src/lib.rs"), + binding: "explicit binding".into(), + arguments: Some(0), + target_present: true, + visibility_compatible: true, + configuration_dependent: false, + } + } + + #[test] + fn facts_deduplicate_consumers_separate_tests_and_use_recorded_path_scope() { + let production = ChangedFunction { + id: "src/lib.rs#work".into(), + before: Some(location("src/lib.rs")), + after: Some(location("src/lib.rs")), + change: "modified".into(), + signature_changed: false, + }; + let test = ChangedFunction { + id: "src/lib.rs#tests::helper".into(), + before: None, + after: Some(location("src/lib.rs")), + change: "added".into(), + signature_changed: false, + }; + let report = ImpactReport { + change: "hash".into(), + inspected_files_after: 2, + changed_functions: vec![production, test], + callers_after: vec![ + call("consumer.rs#consumer", "consumer.rs"), + call("consumer.rs#consumer", "consumer.rs"), + call("src/lib.rs#tests::run", "src/lib.rs"), + ], + source_selection_complete: Some(true), + unresolved_references: Some(0), + ..Default::default() + }; + let measured = |value| json!({"status":"measured","value":value}); + let nodes = vec![ + metric("lib", "src/lib.rs", measured(1), measured(2)), + metric("consumer", "consumer.rs", measured(0), measured(0)), + metric("tests", "src/tests.rs", measured(0), measured(1000)), + ]; + let facts = collect(&nodes, &[report]); + assert_eq!(facts.production_functions, 1); + assert_eq!(facts.test_support_functions, 1); + assert_eq!(facts.observed_production_callers, 1); + assert_eq!(facts.observed_test_support_callers, 1); + assert_eq!(facts.existing_production_callers, 1); + assert_eq!( + facts.outside_change_callers, 0, + "consumer.rs is selected even though its functions did not change" + ); + assert_eq!(facts.public_growth, Some(1)); + } + + #[test] + fn unavailable_baselines_cannot_invent_public_growth_or_complete_measurement() { + let node = metric( + "unknown", + "src/lib.rs", + json!({"status":"unavailable","reason":"baseline unavailable"}), + json!({"status":"measured","value":500}), + ); + let facts = collect(&[node], &[]); + assert_eq!( + facts.public_growth, + Some(0), + "zero is the measured lower bound, not a replacement baseline" + ); + assert!(!facts.surface_measurements_complete); + assert!(!facts.unknowns.is_empty()); + let node = metric( + "removed", + "src/lib.rs", + json!({"status":"measured","value":5}), + json!({"status":"measured","value":3}), + ); + assert_eq!(collect(&[node], &[]).public_removed, Some(2)); + } +} diff --git a/atomic-cli/src/commands/review/scope.rs b/atomic-cli/src/commands/review/scope.rs new file mode 100644 index 00000000..8af8d5d1 --- /dev/null +++ b/atomic-cli/src/commands/review/scope.rs @@ -0,0 +1,564 @@ +//! Frozen publication subjects. Collection order never chooses a winning tree. +use std::collections::{BTreeMap, BTreeSet}; + +use atomic_core::pristine::{GraphTxnT, ViewTxnT}; +use atomic_core::types::{Base32, Hash}; +use atomic_repository::{intent_bridge, Repository, ViewEntry, ViewEntryKind}; +use serde::{Deserialize, Serialize}; + +use crate::error::{CliError, CliResult}; + +pub(super) fn invalid(message: impl Into) -> CliError { + CliError::InvalidArgument { + message: message.into(), + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(super) struct ViewPin { + pub name: String, + pub state: String, + pub members: BTreeSet, + pub roots: Vec, + pub set_id: String, + pub chain: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(super) struct SourcePin { + pub name: String, + pub state: String, + pub scope: String, + pub log: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(super) struct Scope { + pub project: String, + pub views: Vec, + pub source_session: Option, + pub source_manifest: Option, + pub roots: Vec, + pub closure: Vec, + pub intent_sources: BTreeMap, +} + +pub(super) fn view_names(value: &str) -> CliResult> { + let mut names = BTreeSet::new(); + for part in value.split(',') { + let name = part.trim(); + if name.is_empty() || name.chars().any(|c| c.is_control() || "*?[]{}".contains(c)) { + return Err(invalid( + "--view requires literal nonempty view names separated by commas", + )); + } + names.insert(name.to_string()); + if names.len() > 256 { + return Err(invalid( + "publication collection exceeds 256 views; no names were truncated", + )); + } + } + Ok(names.into_iter().collect()) +} + +pub(super) fn hashes(values: &[String]) -> CliResult> { + values + .iter() + .map(|value| { + Hash::from_base32(value.as_bytes()) + .filter(|h| h.to_base32() == *value) + .ok_or_else(|| invalid("review scope contains a noncanonical change hash")) + }) + .collect() +} + +fn frontier(repo: &Repository, members: &BTreeSet) -> CliResult> { + let mut roots = members.clone(); + for hash in hashes(&members.iter().cloned().collect::>())? { + let change = repo.load_change(&hash).map_err(CliError::Repository)?; + for dependency in change.dependencies() { + roots.remove(&dependency.to_base32()); + } + } + if roots.len() > 64 { + return Err(invalid("scope exceeds the canonical publication limit of 64 independent roots; nothing was truncated")); + } + Ok(roots.into_iter().collect()) +} + +fn projection_members(repo: &Repository, name: &str) -> CliResult> { + let txn = repo + .pristine() + .read_txn() + .map_err(|e| invalid(e.to_string()))?; + let view = txn + .get_view(name) + .map_err(|e| invalid(e.to_string()))? + .ok_or_else(|| invalid(format!("unknown publication view '{name}'")))?; + let closure = atomic_repository::repository::effective_projection_closure(&txn, &view) + .map_err(CliError::Repository)?; + closure + .iter_dependency_first() + .map(|id| { + txn.get_external(*id) + .map_err(|e| invalid(e.to_string()))? + .map(|h| h.to_base32()) + .ok_or_else(|| { + invalid("publication projection member has no external change identity") + }) + }) + .collect() +} + +pub(super) fn resolve( + repo: &Repository, + views: Option<&str>, + session: Option<&str>, +) -> CliResult { + let mut source_manifest = None; + let mut session_roots = None; + let names = if let Some(session) = session { + let (record, turns) = repo + .get_session_ledger(session) + .map_err(CliError::Repository)? + .ok_or_else(|| invalid(format!("unknown session '{session}'")))?; + if record.status.incomplete().is_some() { + return Err(invalid("source session has incomplete execution; review its recorded changes explicitly before publication")); + } + let roots: BTreeSet<_> = turns + .iter() + .flat_map(|t| &t.change_hashes) + .map(Base32::to_base32) + .collect(); + if roots.is_empty() { + return Err(invalid( + "pending: source session has no recorded changes to publish", + )); + } + session_roots = Some(roots); + source_manifest = repo + .get_session_head(session) + .map_err(CliError::Repository)? + .map(|h| h.to_base32()); + vec![record + .view_name + .ok_or_else(|| invalid("source session has no recorded view binding"))?] + } else { + view_names(views.unwrap_or(repo.current_view()))? + }; + let mut pins = Vec::new(); + let mut selected = BTreeSet::new(); + for name in names { + let info = repo.get_view_info(&name).map_err(CliError::Repository)?; + let direct: BTreeSet<_> = repo + .effective_history(Some(&name)) + .map_err(CliError::Repository)? + .into_iter() + .map(|entry| entry.hash.to_base32()) + .collect(); + let all = projection_members(repo, &name)?; + let members = session_roots.clone().unwrap_or(direct); + if !members.is_subset(&all) { + return Err(invalid( + "source session changes are not contained in its recorded source view", + )); + } + let roots = frontier(repo, &members)?; + selected.extend(members.iter().cloned()); + let mut chain = Vec::new(); + let mut next = Some(name.clone()); + while let Some(source) = next { + if chain.iter().any(|p: &SourcePin| p.name == source) || chain.len() >= 256 { + return Err(invalid("cyclic or excessive publication source chain")); + } + let source_info = repo.get_view_info(&source).map_err(CliError::Repository)?; + let manifest = repo.view_manifest(&source).map_err(CliError::Repository)?; + next = source_info.parent_name.clone(); + chain.push(SourcePin { + name: source, + state: source_info.state_base32(), + scope: source_info.kind_label().to_string(), + log: manifest.changes.iter().map(Base32::to_base32).collect(), + }); + } + let set_id = repo + .view_set_id(&name) + .map_err(CliError::Repository)? + .to_base32(); + if chain.first().map(|p| p.state.as_str()) != Some(info.state_base32().as_str()) + || repo + .get_view_info(&name) + .map_err(CliError::Repository)? + .state_base32() + != info.state_base32() + { + return Err(invalid("publication source changed while its scope was being frozen; retry without widening the original request")); + } + pins.push(ViewPin { + name, + state: info.state_base32(), + members: all, + roots, + set_id, + chain, + }); + } + if selected.is_empty() { + return Err(invalid( + "selected publication scope has no recorded changes", + )); + } + let roots = frontier(repo, &selected)?; + let closure = + atomic_repository::repository::provenance_gate::reachable_closure(repo, &hashes(&roots)?) + .map_err(CliError::Repository)?; + if closure.len() > 4096 { + return Err(invalid( + "publication dependency closure exceeds 4096 changes; nothing was truncated", + )); + } + let mut intent_sources = BTreeMap::new(); + for hash in &closure { + let change = repo.load_change(hash).map_err(CliError::Repository)?; + let graphs = repo + .find_provenance_for_change_scan(hash) + .map_err(CliError::Repository)?; + let context = repo.change_intent_context(hash, &change, &graphs); + let ids = context + .plans + .iter() + .filter_map(|p| p.intent.as_ref()) + .chain( + context + .associated_intents + .iter() + .filter_map(|p| p.intent.as_ref()), + ); + for identity in ids { + let inputs = + intent_bridge::read_intent(repo, &identity.uid).map_err(CliError::Repository)?; + let node = intent_bridge::lift(&inputs).map_err(CliError::Repository)?; + if node.kind != "review" { + intent_sources.insert(node.id, intent_bridge::source_content_hash(&inputs)); + } + } + } + Ok(Scope { + project: repo.project_id().map_err(CliError::Repository)?.to_urn(), + views: pins, + source_session: session.map(str::to_string), + source_manifest, + roots, + closure: closure + .iter() + .map(Base32::to_base32) + .collect::>() + .into_iter() + .collect(), + intent_sources, + }) +} + +/// Allow only the owned review's metadata additions, never implementation drift. +pub(super) fn recheck( + repo: &Repository, + scope: &Scope, + review_uid: Option<&str>, + reviewer_session: Option<&str>, +) -> CliResult<()> { + if repo.project_id().map_err(CliError::Repository)?.to_urn() != scope.project { + return Err(invalid("stale publication: project identity changed")); + } + for (id, expected) in &scope.intent_sources { + let inputs = intent_bridge::read_intent(repo, id).map_err(CliError::Repository)?; + if intent_bridge::source_content_hash(&inputs) != *expected { + return Err(invalid(format!( + "stale publication: reviewed intent '{id}' changed" + ))); + } + } + for pin in &scope.views { + for (index, source) in pin.chain.iter().enumerate() { + let manifest = repo + .view_manifest(&source.name) + .map_err(CliError::Repository)?; + if repo + .get_view_info(&source.name) + .map_err(CliError::Repository)? + .kind_label() + != source.scope + { + return Err(invalid("stale publication: a source view changed scope")); + } + let log: Vec<_> = manifest.changes.iter().map(Base32::to_base32).collect(); + if !log.starts_with(&source.log) + || manifest.parent.as_deref() != pin.chain.get(index + 1).map(|p| p.name.as_str()) + { + return Err(invalid( + "stale publication: source ancestry or ordered membership was rewritten", + )); + } + } + let now = projection_members(repo, &pin.name)?; + if !pin.members.is_subset(&now) { + return Err(invalid(format!( + "stale publication: '{}' lost recorded changes", + pin.name + ))); + } + for added in now.difference(&pin.members) { + let (Some(uid), Some(session)) = (review_uid, reviewer_session) else { + return Err(invalid(format!( + "stale publication: '{}' changed after it was frozen", + pin.name + ))); + }; + let hash = hashes(std::slice::from_ref(added))?[0]; + let change = repo.load_change(&hash).map_err(CliError::Repository)?; + if change.provenance().is_empty() + || change + .provenance() + .iter() + .any(|p| p.session_id.as_deref() != Some(session)) + { + return Err(invalid( + "stale publication: another execution changed the source view", + )); + } + let paths = repo + .change_modified_paths(&hash) + .map_err(CliError::Repository)?; + let intent_path = format!(".vault/intents/{uid}/intent.md"); + let attestation_path = format!( + ".vault/{}", + intent_bridge::attestation_vault_path(repo, uid).map_err(CliError::Repository)? + ); + if paths.is_empty() + || paths + .iter() + .any(|p| p != &intent_path && p != &attestation_path) + { + return Err(invalid("publisher modified implementation or unrelated evidence; review scope is stale")); + } + } + } + Ok(()) +} + +pub(super) fn check_prepared_context( + pin: &ViewPin, + subject: &atomic_canonical::publication_review::ReviewSubject, +) -> CliResult<()> { + let snapshot = subject + .snapshot + .as_ref() + .ok_or_else(|| invalid("prepared publication lacks an immutable source snapshot"))?; + if subject.effective_set_id != pin.set_id + || snapshot.membership != pin.members.iter().cloned().collect::>() + || subject.view_chain.len() != pin.chain.len() + || snapshot.view_logs.len() != pin.chain.len() + { + return Err(invalid( + "prepared publication context differs from the approved frozen view membership", + )); + } + for (index, (actual, expected)) in subject.view_chain.iter().zip(&pin.chain).enumerate() { + if actual.name != expected.name + || actual.state != expected.state + || actual.scope != expected.scope + || snapshot.view_logs[index] != expected.log + { + return Err(invalid( + "prepared publication source chain/log is not the approved frozen perspective", + )); + } + } + Ok(()) +} + +/// Conservative composition: unequal deltas at the same path require an +/// explicit integration view. Never pick a winner based on --view order. +pub(super) fn compose( + base: &BTreeMap, + inputs: &[BTreeMap], +) -> CliResult> { + let mut deltas: BTreeMap> = BTreeMap::new(); + for tree in inputs { + for path in base.keys().chain(tree.keys()).collect::>() { + let before = base.get(path); + let after = tree.get(path); + if equivalent(before, after) { + continue; + } + if let Some(existing) = deltas.get(path) { + if !equivalent(existing.as_ref(), after) { + return Err(invalid(format!("collection has incompatible deltas at '{path}'; record an explicit integration view first"))); + } + } else { + deltas.insert(path.clone(), after.cloned()); + } + } + } + let mut combined = base.clone(); + for (path, entry) in deltas { + match entry { + Some(entry) => { + combined.insert(path, entry); + } + None => { + combined.remove(&path); + } + } + } + if combined + .values() + .any(|e| e.kind == ViewEntryKind::Symlink || e.conflict_marker_line.is_some()) + { + return Err(invalid("collection composition refuses symlinks and unresolved conflicts; use an explicit integration view")); + } + Ok(combined) +} + +fn equivalent(a: Option<&ViewEntry>, b: Option<&ViewEntry>) -> bool { + match (a, b) { + (None, None) => true, + (Some(a), Some(b)) => a.kind == b.kind && a.mode == b.mode && a.content == b.content, + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn file(path: &str, bytes: &[u8]) -> ViewEntry { + ViewEntry { + path: path.into(), + inode: 0, + kind: ViewEntryKind::File, + mode: 0o644, + content: bytes.into(), + hash: Hash::of(bytes), + conflict_marker_line: None, + } + } + #[test] + fn comma_views_are_literal_sorted_and_deduplicated() { + assert_eq!(view_names(" b,a,b ").unwrap(), ["a", "b"]); + for bad in ["", "a,", ",a", "a,,b", "*", "a,?"] { + assert!(view_names(bad).is_err()); + } + } + #[test] + fn disjoint_collection_changes_compose_and_order_does_not_choose_a_winner() { + let base = BTreeMap::from([("a".into(), file("a", b"old"))]); + let a = BTreeMap::from([("a".into(), file("a", b"new"))]); + let b = BTreeMap::from([ + ("a".into(), file("a", b"old")), + ("b".into(), file("b", b"new")), + ]); + let result = compose(&base, &[a.clone(), b.clone()]).unwrap(); + assert_eq!(result["a"].content, b"new"); + assert!(result.contains_key("b")); + assert_eq!( + serde_json::to_value(&result).unwrap(), + serde_json::to_value(compose(&base, &[b, a]).unwrap()).unwrap() + ); + } + #[test] + fn conflicting_edits_or_delete_write_are_refused() { + let base = BTreeMap::from([("a".into(), file("a", b"old"))]); + let a = BTreeMap::from([("a".into(), file("a", b"one"))]); + let b = BTreeMap::from([("a".into(), file("a", b"two"))]); + assert!(compose(&base, &[a.clone(), b]).is_err()); + assert!(compose(&base, &[a, BTreeMap::new()]).is_err()); + } + #[test] + fn prepared_context_must_match_frozen_membership_and_ordered_ancestry() { + use atomic_canonical::publication_review::{ + IntentPin, ReviewSnapshot, ReviewSubject, ReviewViewPin, + }; + let pin = ViewPin { + name: "v".into(), + state: "state".into(), + members: BTreeSet::from(["original".into()]), + roots: vec!["original".into()], + set_id: "set".into(), + chain: vec![SourcePin { + name: "v".into(), + state: "state".into(), + scope: "draft".into(), + log: vec!["original".into()], + }], + }; + let mut subject = ReviewSubject { + project: "p".into(), + roots: pin.roots.clone(), + changes: vec![], + review: IntentPin { + id: "review".into(), + source_hash: "s".into(), + signed_hash: "h".into(), + public_key: "k".into(), + }, + work: vec![], + set_aside: vec![], + profile_hash: "policy".into(), + view_chain: vec![ReviewViewPin { + name: "v".into(), + state: "state".into(), + scope: "draft".into(), + }], + effective_set_id: "set".into(), + snapshot: Some(ReviewSnapshot { + version: 1, + view_logs: vec![vec!["original".into()]], + membership: vec!["original".into()], + intent_revisions: vec![], + }), + }; + assert!(check_prepared_context(&pin, &subject).is_ok()); + subject + .snapshot + .as_mut() + .unwrap() + .membership + .push("foreign".into()); + assert!(check_prepared_context(&pin, &subject).is_err()); + subject.snapshot.as_mut().unwrap().membership = vec!["original".into()]; + subject.view_chain[0].state = "other".into(); + assert!(check_prepared_context(&pin, &subject).is_err()); + } + + #[test] + fn frozen_membership_includes_dependency_only_projection_members() { + use atomic_core::change::{Change, ChangeHeader}; + use atomic_core::pristine::MutTxnT; + let dir = tempfile::tempdir().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + repo.init_vault().unwrap(); + let dependency = repo + .save_change(&Change::empty(ChangeHeader::new("dependency context"))) + .unwrap(); + let mut change = Change::empty(ChangeHeader::new("selected root")); + change.hashed.dependencies.push(dependency); + let root = repo.save_change(&change).unwrap(); + let mut txn = repo.pristine().write_txn().unwrap(); + let dependency_id = txn.register_change(&dependency).unwrap(); + let root_id = txn.register_change(&root).unwrap(); + txn.put_dep(root_id, dependency_id).unwrap(); + txn.put_change_deps(dependency_id, &[]).unwrap(); + txn.put_change_deps(root_id, &[dependency]).unwrap(); + let mut view = txn.get_view("dev").unwrap().unwrap(); + txn.put_change(&mut view, root_id, &root).unwrap(); + txn.update_view(&view).unwrap(); + txn.commit().unwrap(); + let frozen = resolve(&repo, Some("dev"), None).unwrap(); + assert_eq!(frozen.roots, vec![root.to_base32()]); + assert_eq!( + frozen.views[0].members, + BTreeSet::from([root.to_base32(), dependency.to_base32()]) + ); + recheck(&repo, &frozen, None, None).unwrap(); + } +} diff --git a/atomic-cli/src/commands/review/terminal.rs b/atomic-cli/src/commands/review/terminal.rs new file mode 100644 index 00000000..bcb37816 --- /dev/null +++ b/atomic-cli/src/commands/review/terminal.rs @@ -0,0 +1,434 @@ +//! Location-first terminal review. Card/evidence expansion is opt-in. + +use super::presentation; +use atomic_canonical::review_graph::{PassStatus, ReviewGraph, ReviewPass}; +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt::Write; + +pub(super) fn render(graph: &ReviewGraph, details: bool) -> String { + let snapshot = graph.nodes.iter().find(|node| node.kind == "view_snapshot"); + let comparison = graph + .nodes + .iter() + .find(|node| node.kind == "view_comparison"); + let mut text = format!( + "Review — {} @ {}\nLocal semantic audits and metrics · no AI execution\nNot independent signed approval · {} finding(s)\n{}\n", + graph.scope.view, + graph.scope.view_state, + graph.findings.len(), + if let Some(comparison)=comparison {format!("View comparison: BEFORE {} -> AFTER {}",comparison.properties["from"]["view"].as_str().unwrap_or("?"),comparison.properties["to"]["view"].as_str().unwrap_or("?"))} else if snapshot.is_some(){format!("Selected view snapshot: {}",graph.scope.view)}else{format!("Selected changes: {}",graph.scope.selected_roots.join(", "))} + ); + if let Some(snapshot) = snapshot { + writeln!( + text, + "Entire recorded view snapshot · {} live paths · no before/change baseline", + snapshot.properties["paths"] + .as_array() + .map(Vec::len) + .unwrap_or(0) + ) + .unwrap(); + } + if let Some(comparison) = comparison { + for side in ["from", "to"] { + writeln!( + text, + " {side}: {} · state {} · filter {}", + comparison.properties[side]["view"].as_str().unwrap_or("?"), + comparison.properties[side]["state"].as_str().unwrap_or("?"), + comparison.properties[side]["membership_hash"] + .as_str() + .unwrap_or("?") + ) + .unwrap(); + } + let mut counts = BTreeMap::<&str, usize>::new(); + for node in graph + .nodes + .iter() + .filter(|node| node.kind == "compared_file") + { + *counts + .entry(node.properties["status"].as_str().unwrap_or("unavailable")) + .or_default() += 1; + if details { + writeln!( + text, + " {}: {} -> {}", + node.properties["status"].as_str().unwrap_or("unavailable"), + node.properties["before_path"] + .as_str() + .unwrap_or("(absent)"), + node.properties["after_path"].as_str().unwrap_or("(absent)") + ) + .unwrap(); + } + } + writeln!( + text, + "Recorded file states: {}", + counts + .into_iter() + .map(|(status, count)| format!("{count} {status}")) + .collect::>() + .join(" · ") + ) + .unwrap(); + } + let regions = presentation::regions(graph); + for node in graph + .nodes + .iter() + .filter(|node| node.kind == "analysis_exclusion") + { + writeln!( + text, + "Excluded from code analysis: {} .vault metadata path(s), retained as evidence", + node.properties["paths"] + .as_array() + .map(Vec::len) + .unwrap_or(0) + ) + .unwrap(); + } + let nodes: BTreeMap<_, _> = graph + .nodes + .iter() + .map(|node| (node.id.as_str(), node)) + .collect(); + for pass in &graph.passes { + writeln!(text, "\n{} [{:?}]", pass.pass.label(), pass.status).unwrap(); + if pass.status == PassStatus::NotApplicable { + writeln!(text, "{}", pass.detail).unwrap(); + continue; + } + if pass.pass == ReviewPass::BlastRadiusRisk { + if let Some(risk) = &graph.risk { + super::risk::render(&mut text, "", risk); + } + } + let findings: BTreeMap<_, _> = graph + .findings + .iter() + .filter(|finding| finding.passes.contains(&pass.pass)) + .map(|finding| (finding.number, finding)) + .collect(); + let mut previous = None; + let mut printed = BTreeSet::new(); + for region in ®ions { + let relevant: Vec<_> = region + .findings + .iter() + .filter_map(|number| findings.get(number)) + .collect(); + if relevant.is_empty() { + continue; + } + let file = (®ion.change, ®ion.path); + if previous != Some(file) { + writeln!( + text, + "\n{} [{} {}]", + region.path, + if comparison.is_some() { + "view comparison" + } else if snapshot.is_some() { + "view snapshot" + } else { + "change" + }, + if comparison.is_some() || snapshot.is_some() { + graph.scope.view.clone() + } else { + region.change.chars().take(12).collect::() + } + ) + .unwrap(); + previous = Some(file); + } + let range = region + .start_line + .zip(region.end_line) + .map(|(lo, hi)| format!("{lo}–{hi}")) + .unwrap_or_else(|| "unavailable range".into()); + let subjects = region + .subjects + .iter() + .filter(|subject| **subject != region.path) + .collect::>(); + let name = match subjects.as_slice() { + [subject] => (*subject).clone(), + [] => "source region".into(), + many => format!("{} source subjects", many.len()), + }; + writeln!(text, " {range} ({}) {name}", region.side).unwrap(); + for finding in relevant { + printed.insert(finding.number); + if let Some(state) = &finding.comparison { + writeln!( + text, + " Comparison observation: {} — {}", + state.status, state.rationale + ) + .unwrap(); + } + writeln!( + text, + " F{} · {:?} / {:?}: {}", + finding.number, + finding.finding.severity, + finding.finding.confidence, + finding.finding.summary + ) + .unwrap(); + writeln!( + text, + " Audit/rule: {} · introduced: {:?}", + finding.finding.requirement_or_rule.id, + finding.finding.introduced_by_change.status + ) + .unwrap(); + if details { + writeln!( + text, + " Attribution: {}", + finding.finding.introduced_by_change.rationale + ) + .unwrap(); + for evidence in &finding.finding.evidence { + writeln!( + text, + " Evidence {}: {}", + evidence.reference, evidence.observation + ) + .unwrap(); + } + writeln!( + text, + " Correction: {}", + finding.finding.proposed_correction + ) + .unwrap(); + for criterion in &finding.finding.acceptance_criteria { + writeln!( + text, + " AC {} → {:?}: {}", + criterion.criterion, criterion.assessment, criterion.rationale + ) + .unwrap(); + } + if finding.finding.acceptance_criteria.is_empty() { + writeln!(text," AC mapping: unresolved (engineering rule only; no unmet criterion inferred)").unwrap(); + } + } + } + let metrics = if region.metrics.is_empty() { + ®ion.context_metrics + } else { + ®ion.metrics + }; + let has_functions = metrics.iter().any(|id| { + nodes + .get(id.as_str()) + .is_some_and(|node| node.properties["scope"] == "function") + }); + for id in metrics { + if let Some(node) = nodes.get(id.as_str()) { + if has_functions && node.properties["scope"] != "function" && !details { + continue; + } + if presentation::metric_id(node) == "metric.parameter-count" && !details { + continue; + } + let subject = if subjects.len() > 1 { + node.properties["observation"]["subject"] + .as_str() + .map(|name| format!(" [{}]", presentation::subject_label(name))) + .unwrap_or_default() + } else { + String::new() + }; + writeln!( + text, + " {}{subject}: {}{}", + presentation::metric_id(node), + presentation::metric_value(node), + if region.context_metrics.contains(id) { + " (enclosing function)" + } else { + "" + } + ) + .unwrap(); + } + } + } + // Findings without coordinates still remain visible; never drop an + // imported judgment just because file navigation cannot locate it. + for finding in findings + .values() + .filter(|finding| !printed.contains(&finding.number)) + { + writeln!( + text, + "F{} · {:?}: {} [{}]", + finding.number, + finding.finding.severity, + finding.finding.summary, + finding.finding.requirement_or_rule.id + ) + .unwrap(); + } + if pass.pass == ReviewPass::IntentConformance { + if let Some(view) = comparison.or(snapshot) { + let context = &view.properties["conformance"]; + if let Some(intents) = context["intents"].as_array() { + writeln!( + text, + "View-scoped intents: {} ({}); assignment is context, not acceptance proof", + intents.len(), + context["scope"]["view"].as_str().unwrap_or("?") + ) + .unwrap(); + for intent in intents { + writeln!( + text, + " {} · {} [{}; {}]", + intent["human_key"].as_str().unwrap_or("?"), + intent["title"].as_str().unwrap_or("?"), + intent["status"].as_str().unwrap_or("unknown"), + intent["source_kind"].as_str().unwrap_or("unavailable") + ) + .unwrap(); + } + } + if let Some(changes) = context["changes"] + .as_array() + .filter(|_| comparison.is_some()) + { + writeln!( + text, + "Recorded membership delta: {} change(s) added to To, {} only in From", + changes + .iter() + .filter(|change| change["direction"] == "added_to_after") + .count(), + changes + .iter() + .filter(|change| change["direction"] == "removed_from_after") + .count() + ) + .unwrap(); + } + if let Some(criteria) = context["criteria"].as_array() { + for criterion in criteria { + writeln!( + text, + " {}: before declared={} -> after declared={}{}", + criterion["id"].as_str().unwrap_or("?"), + criterion["before"]["status"] + .as_str() + .unwrap_or("unavailable"), + criterion["after"]["status"] + .as_str() + .unwrap_or("unavailable"), + if criterion["current_context"].is_object() { + "; current vault fallback is context only" + } else { + "; pinned recorded definitions" + } + ) + .unwrap(); + } + } + } + if graph.criteria.is_empty() { + writeln!(text, "{}", pass.detail).unwrap(); + } + for criterion in &graph.criteria { + writeln!( + text, + "AC {} · review={:?} · declared={} · findings={}\n {}", + criterion.id, + criterion.review_assessment, + criterion.declared_status, + criterion + .findings + .iter() + .map(|n| format!("F{n}")) + .collect::>() + .join(", "), + criterion.text + ) + .unwrap(); + } + } else if pass.pass == ReviewPass::AntiSlop { + if findings.is_empty() { + writeln!( + text, + "No numbered audit findings in the supported checks; not a clean-code verdict." + ) + .unwrap(); + } + let count = |status: &str| { + graph + .nodes + .iter() + .filter(|node| node.kind == "check" && node.properties["status"] == status) + .count() + }; + writeln!( + text, + "\nChecks: {} completed · {} skipped · {} errors", + count("completed"), + count("skipped"), + count("error") + ) + .unwrap(); + if details { + render_details(&mut text, graph); + } else if snapshot.is_some() || comparison.is_some() { + let metrics = graph + .nodes + .iter() + .filter(|node| node.kind == "metric") + .collect::>(); + super::metric_output::render_metrics(&mut text, "", &metrics, false); + } + } + } + for diagnostic in &graph.diagnostics { + writeln!(text, "Note: {diagnostic}").unwrap(); + } + writeln!(text,"\nBrowse files, recorded source and audit/metric cards: --html\nFull measurements and evidence: --details or --json").unwrap(); + text +} + +fn render_details(text: &mut String, graph: &ReviewGraph) { + for card in atomic_audit::AUDIT_CARDS { + let count = |status: &str| { + graph + .nodes + .iter() + .filter(|node| { + node.kind == "check" + && node.properties["rule"] == card.id + && node.properties["status"] == status + }) + .count() + }; + let findings = graph + .findings + .iter() + .filter(|finding| finding.finding.requirement_or_rule.id == card.id) + .count(); + writeln!(text,"Audit {}: {} finding(s) · {} completed · {} skipped · {} errors\n Card {}: {}\n Evidence: {}\n Exceptions: {}",card.title,findings,count("completed"),count("skipped"),count("error"),card.id,card.question,card.evidence,card.exceptions).unwrap(); + } + let metrics = graph + .nodes + .iter() + .filter(|node| node.kind == "metric") + .collect::>(); + super::metric_output::render_metrics(text, "", &metrics, true); + super::metric_output::render_coverage(text, &graph.nodes); +} diff --git a/atomic-cli/src/commands/review/view_comparison.rs b/atomic-cli/src/commands/review/view_comparison.rs new file mode 100644 index 00000000..352d27dd --- /dev/null +++ b/atomic-cli/src/commands/review/view_comparison.rs @@ -0,0 +1,501 @@ +//! Two pinned recorded view states, compared locally without switching either. + +mod conformance; +pub(super) use conformance::{collect_view, Conformance}; +mod findings; +mod impact; +mod metrics; + +pub(super) use impact::{changed_paths, inspect as inspect_impact}; + +use super::incremental::{IncrementalArgs, IncrementalReport, Selection, ViewInspection}; +use crate::error::{CliError, CliResult}; +use atomic_canonical::{review_finding::AnalysisReport, review_graph::FindingComparison}; +use atomic_core::types::{Base32, Hash}; +use atomic_repository::Repository; +use serde::Serialize; +use serde_json::json; +use std::collections::{BTreeMap, BTreeSet}; + +struct SideIndex<'a> { + view: &'a ViewInspection, + metrics: BTreeMap<&'a str, Vec<&'a atomic_audit::metrics::ExtractedMetric>>, + checks: BTreeMap<&'a str, Vec<&'a atomic_canonical::review_finding::Check>>, + findings: BTreeMap<&'a str, Vec<&'a atomic_canonical::review_finding::ReviewFinding>>, +} + +impl<'a> SideIndex<'a> { + fn new(view: &'a ViewInspection) -> Self { + let mut index = Self { + view, + metrics: BTreeMap::new(), + checks: BTreeMap::new(), + findings: BTreeMap::new(), + }; + for metric in &view.analysis.metrics { + index.metrics.entry(&metric.path).or_default().push(metric); + } + for check in &view.analysis.checks { + index.checks.entry(&check.path).or_default().push(check); + } + for finding in &view.analysis.findings { + for path in finding + .locations + .iter() + .map(|location| location.path.as_str()) + .collect::>() + { + index.findings.entry(path).or_default().push(finding); + } + } + index + } + fn metrics(&self, path: Option<&str>) -> &[&'a atomic_audit::metrics::ExtractedMetric] { + path.and_then(|path| self.metrics.get(path)) + .map(Vec::as_slice) + .unwrap_or(&[]) + } + fn checks(&self, path: Option<&str>) -> &[&'a atomic_canonical::review_finding::Check] { + path.and_then(|path| self.checks.get(path)) + .map(Vec::as_slice) + .unwrap_or(&[]) + } + fn findings( + &self, + path: Option<&str>, + ) -> &[&'a atomic_canonical::review_finding::ReviewFinding] { + path.and_then(|path| self.findings.get(path)) + .map(Vec::as_slice) + .unwrap_or(&[]) + } +} + +fn invalid(message: impl Into) -> CliError { + CliError::InvalidArgument { + message: message.into(), + } +} + +#[derive(Clone, Debug, Serialize)] +pub struct ViewPin { + pub view: String, + pub state: String, + pub membership_hash: String, + pub source_ref: String, +} +impl From<&ViewInspection> for ViewPin { + fn from(view: &ViewInspection) -> Self { + Self { + view: view.view.clone(), + state: view.state.clone(), + membership_hash: view.membership_hash.clone(), + source_ref: view.source_ref.clone(), + } + } +} + +#[derive(Debug, Serialize)] +pub struct ComparedFile { + pub source_ref: String, + pub path: String, + pub before_path: Option, + pub after_path: Option, + pub before_inode: Option, + pub after_inode: Option, + pub before_hash: Option, + pub after_hash: Option, + pub status: String, + pub content_status: String, + pub analysis: AnalysisReport, + /// Keys are report-local finding IDs, not persistent KG assertions. + pub finding_states: BTreeMap, +} + +#[derive(Debug, Serialize)] +pub struct ViewComparison { + pub source_ref: String, + pub from: ViewPin, + pub to: ViewPin, + pub files: Vec, + pub diagnostics: Vec, + pub conformance: conformance::Conformance, +} +impl ViewComparison { + pub(super) fn file(&self, reference: &str) -> Option<&ComparedFile> { + self.files.iter().find(|file| file.source_ref == reference) + } +} + +pub(super) fn resolve(repo: &Repository, args: &IncrementalArgs) -> CliResult { + let from = args + .from + .as_deref() + .ok_or_else(|| invalid("--from requires --to and vice versa"))?; + let to = args + .to + .as_deref() + .ok_or_else(|| invalid("--from requires --to and vice versa"))?; + if [from, to] + .iter() + .any(|name| name.is_empty() || name.trim() != *name) + { + return Err(invalid("Comparison view names must be exact and nonempty")); + } + if args.view.is_some() + || args.change.is_some() + || args.turn.is_some() + || args.intent.is_some() + || args.findings.is_some() + || args.risk_profile.is_some() + { + return Err(invalid("--from/--to cannot be combined with snapshot/change/turn/intent selectors, supplied change findings or a change-risk profile")); + } + let mut before = super::view_snapshot::collect(repo, from)?; + let mut after = super::view_snapshot::collect(repo, to)?; + let before_view = before.view_snapshot.take().unwrap(); + let after_view = after.view_snapshot.take().unwrap(); + let from_pin = ViewPin::from(&before_view); + let to_pin = ViewPin::from(&after_view); + let source_ref = format!( + "urn:atomic:view-comparison:{}", + Hash::of( + &serde_json::to_vec(&json!({"from":from_pin,"to":to_pin})) + .map_err(|error| CliError::Internal(error.into()))? + ) + .to_base32() + ); + let before_ids = identities(repo, &before_view)?; + let after_ids = identities(repo, &after_view)?; + let pairs = pair_paths(&before_ids, &after_ids); + let before_index = SideIndex::new(&before_view); + let after_index = SideIndex::new(&after_view); + let mut files = Vec::new(); + for (old, new) in pairs { + let old_id = old.as_ref().and_then(|path| before_ids.get(path)).cloned(); + let new_id = new.as_ref().and_then(|path| after_ids.get(path)).cloned(); + let old_hash = old + .as_ref() + .and_then(|path| before_view.content_hashes.get(path)) + .cloned(); + let new_hash = new + .as_ref() + .and_then(|path| after_view.content_hashes.get(path)) + .cloned(); + let content_status = match (&old_hash, &new_hash) { + (Some(a), Some(b)) => { + if a == b { + "unchanged" + } else { + "modified" + } + } + _ => "unavailable", + } + .to_string(); + let status = match (&old, &new) { + (None, Some(_)) => "added", + (Some(_), None) => "removed", + (Some(a), Some(b)) if a != b => "renamed", + _ if old_id != new_id => "replaced", + _ => content_status.as_str(), + } + .to_string(); + let path = new.as_ref().or(old.as_ref()).unwrap().clone(); + let file_ref = format!( + "{source_ref}:file:{}", + Hash::of( + &serde_json::to_vec(&json!([old, new, old_id, new_id])) + .map_err(|error| CliError::Internal(error.into()))? + ) + .to_base32() + ); + let mut analysis = metrics::analysis( + &before_index, + &after_index, + &path, + old.as_deref(), + new.as_deref(), + old_id == new_id, + ); + let (local_findings, states) = findings::compare( + &before_index, + &after_index, + &file_ref, + old.as_deref(), + new.as_deref(), + old_id == new_id, + ); + analysis.findings = local_findings; + files.push(ComparedFile { + source_ref: file_ref, + path, + before_path: old, + after_path: new, + before_inode: old_id, + after_inode: new_id, + before_hash: old_hash, + after_hash: new_hash, + status, + content_status, + analysis, + finding_states: states, + }); + } + files.sort_by(|a, b| a.path.cmp(&b.path).then(a.source_ref.cmp(&b.source_ref))); + let diagnostics = before_view + .analysis + .metric_diagnostics + .iter() + .filter(|line| !line.contains(super::analysis::SNAPSHOT_BASELINE)) + .map(|line| format!("Before {from}: {line}")) + .chain( + after_view + .analysis + .metric_diagnostics + .iter() + .filter(|line| !line.contains(super::analysis::SNAPSHOT_BASELINE)) + .map(|line| format!("After {to}: {line}")), + ) + .collect(); + let mut comparison = ViewComparison { + source_ref, + from: from_pin, + to: to_pin, + files, + diagnostics, + conformance: Default::default(), + }; + comparison.conformance = conformance::collect( + repo, + &comparison, + &before.dependency_closure, + &after.dependency_closure, + )?; + verify(repo, &comparison)?; + after.schema_version = 4; + after.purpose = "local_view_comparison_review"; + after.selection=Selection { kind:"view_comparison".into(),value:Some(format!("{from} -> {to}")),reason:"From is the recorded before state; To is the recorded after state. Both complete view corpora are inspected locally.".into() }; + after.source["from_view"] = json!(from); + after.source["from_state"] = json!(comparison.from.state); + let mut refs = BTreeMap::new(); + for reference in before + .dependency_references + .into_iter() + .chain(after.dependency_references) + { + refs.insert(reference.hash.clone(), reference); + } + after.dependency_references = refs.into_values().collect(); + let members: BTreeSet<_> = before + .dependency_closure + .into_iter() + .chain(after.dependency_closure) + .collect(); + after.dependency_closure = members.into_iter().collect(); + after.dependency_only = after.dependency_closure.clone(); + after.warnings=vec![ + format!("Local recorded-view comparison: BEFORE {from} -> AFTER {to}. No view switch, working-copy bytes, model or network calls."), + "Audit lifecycles compare local rule/AST observations within recorded file identities and qualified metric owners. Changed/unknown observations are not fabricated resolutions or proof of behavioral equivalence.".into(), + "Each side uses the same explicit semantic/metric bounds as --view. Unsupported, unavailable and over-budget data stay unknown, not absent or zero.".into(), + "Metric comparisons use the complete supplied corpus on each side. Renames are based on canonical recorded inode identity, never filename/content similarity.".into(), + "Conformance includes actual membership-delta governance and recorded criteria where available; current vault fallback is labelled context, never historical approval. Blast radius uses the shared named-view semantic selector, direct-call contracts and local risk model; compiler/type/runtime behavior is not proven.".into(), + ]; + after.view_comparison = Some(comparison); + after.graph = Some(super::graph::build(repo, &after, None, None)?); + super::view_snapshot::verify(repo, &after)?; + Ok(after) +} + +fn identities(repo: &Repository, view: &ViewInspection) -> CliResult> { + let ids = repo + .recorded_file_inodes_on_view(&view.paths, &view.view) + .map_err(CliError::Repository)?; + view.paths + .iter() + .zip(ids) + .map(|(path, inode)| { + Ok(( + path.clone(), + inode + .ok_or_else(|| { + invalid("Visible recorded file lost its inode identity during comparison") + })? + .get() + .to_string(), + )) + }) + .collect() +} + +fn pair_paths( + before: &BTreeMap, + after: &BTreeMap, +) -> Vec<(Option, Option)> { + let mut old: BTreeSet<_> = before.keys().cloned().collect(); + let mut new: BTreeSet<_> = after.keys().cloned().collect(); + let mut pairs = Vec::new(); + for path in before + .keys() + .filter(|path| after.get(*path) == before.get(*path)) + { + old.remove(path); + new.remove(path); + pairs.push((Some(path.clone()), Some(path.clone()))); + } + let mut old_ids = BTreeMap::<&str, Vec>::new(); + let mut new_ids = BTreeMap::<&str, Vec>::new(); + for path in &old { + old_ids.entry(&before[path]).or_default().push(path.clone()); + } + for path in &new { + new_ids.entry(&after[path]).or_default().push(path.clone()); + } + for (inode, paths) in old_ids { + if paths.len() == 1 { + if let Some(targets) = new_ids.get(inode).filter(|paths| paths.len() == 1) { + let a = paths[0].clone(); + let b = targets[0].clone(); + old.remove(&a); + new.remove(&b); + pairs.push((Some(a), Some(b))); + } + } + } + let replacements = old + .iter() + .filter(|path| new.contains(*path)) + .cloned() + .collect::>(); + for path in replacements { + old.remove(&path); + new.remove(&path); + pairs.push((Some(path.clone()), Some(path))); + } + pairs.extend(old.into_iter().map(|path| (Some(path), None))); + pairs.extend(new.into_iter().map(|path| (None, Some(path)))); + pairs +} + +pub(super) fn verify(repo: &Repository, comparison: &ViewComparison) -> CliResult<()> { + comparison.conformance.verify(repo)?; + for pin in [&comparison.from, &comparison.to] { + if repo + .get_view_info(&pin.view) + .map_err(CliError::Repository)? + .state + .to_base32() + != pin.state + || super::graph::membership_hash(repo, &pin.view)? != pin.membership_hash + { + return Err(invalid(format!( + "Recorded comparison view '{}' changed during audit/export; retry both views", + pin.view + ))); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use atomic_core::change::ChangeHeader; + use atomic_repository::{record::RecordOptions, tracking::TrackingOptions}; + + fn map(entries: &[(&str, &str)]) -> BTreeMap { + entries + .iter() + .map(|(path, inode)| (path.to_string(), inode.to_string())) + .collect() + } + #[test] + fn pair_canonical_identities_before_path_replacements_or_similarity() { + for (old, new, expected) in [ + ( + map(&[("a", "1"), ("b", "2")]), + map(&[("a", "2"), ("b", "1")]), + vec![(Some("a"), Some("b")), (Some("b"), Some("a"))], + ), + ( + map(&[("a", "1"), ("b", "2")]), + map(&[("b", "1")]), + vec![(Some("a"), Some("b")), (Some("b"), None)], + ), + ( + map(&[("a", "1")]), + map(&[("a", "3")]), + vec![(Some("a"), Some("a"))], + ), + ( + map(&[("a", "1")]), + map(&[("similar-a", "3")]), + vec![(Some("a"), None), (None, Some("similar-a"))], + ), + // An ambiguous alias is not a guessed rename. + ( + map(&[("a", "1"), ("alias", "1")]), + map(&[("b", "1")]), + vec![(Some("a"), None), (Some("alias"), None), (None, Some("b"))], + ), + ] { + let actual: BTreeSet<_> = pair_paths(&old, &new).into_iter().collect(); + let expected: BTreeSet<_> = expected + .into_iter() + .map(|(a, b)| (a.map(str::to_owned), b.map(str::to_owned))) + .collect(); + assert_eq!(actual, expected); + } + } + #[test] + fn comparison_checks_both_effective_parent_memberships_without_switching() { + let directory = tempfile::tempdir().unwrap(); + let mut repo = Repository::init(directory.path()).unwrap(); + let wc = repo.require_working_copy_id().unwrap(); + let parent = repo.current_view().to_owned(); + std::fs::write( + directory.path().join("file.rs"), + "fn before() { todo!(); }\n", + ) + .unwrap(); + repo.add(wc, "file.rs", TrackingOptions::default()).unwrap(); + let record = |repo: &Repository| { + repo.record( + wc, + ChangeHeader::new("pin fixture"), + RecordOptions::new() + .with_all(true) + .save_to_store(true) + .apply_after_record(true) + .enrich_kg(false), + ) + .unwrap() + }; + record(&repo); + repo.create_draft_view("left", &parent).unwrap(); + repo.create_draft_view("right", &parent).unwrap(); + let report = resolve( + &repo, + &IncrementalArgs { + from: Some("left".into()), + to: Some("right".into()), + ..Default::default() + }, + ) + .unwrap(); + let comparison = report.view_comparison.as_ref().unwrap(); + verify(&repo, comparison).unwrap(); + std::fs::write(directory.path().join("file.rs"), "fn after() {}\n").unwrap(); + record(&repo); + assert_eq!( + repo.get_view_info("left").unwrap().state.to_base32(), + comparison.from.state + ); + assert_eq!( + repo.get_view_info("right").unwrap().state.to_base32(), + comparison.to.state + ); + assert!(verify(&repo, comparison).is_err()); + assert!(super::super::html::render(&repo, &report).is_err()); + assert_eq!(repo.current_view(), parent); + } +} diff --git a/atomic-cli/src/commands/review/view_comparison/conformance.rs b/atomic-cli/src/commands/review/view_comparison/conformance.rs new file mode 100644 index 00000000..8f6dfadd --- /dev/null +++ b/atomic-cli/src/commands/review/view_comparison/conformance.rs @@ -0,0 +1,726 @@ +//! Recorded governing declarations and criterion evidence, not inferred approval. +use std::collections::{BTreeMap, BTreeSet}; + +use atomic_canonical::{ + review_finding::CriterionOutcome, review_graph::CriterionReview, CanonicalNode, +}; +use atomic_core::types::{Base32, Hash}; +use atomic_repository::{intent_bridge as bridge, Repository}; +use serde::Serialize; +use serde_json::{json, Value}; + +use super::ViewComparison; +use crate::error::{CliError, CliResult}; + +#[derive(Debug, Default, Serialize)] +pub struct Conformance { + pub scope: Option, + pub intents: Vec, + pub changes: Vec, + pub criteria: Vec, + pub diagnostics: Vec, + #[serde(skip)] + current_sources: BTreeMap, +} + +#[derive(Debug, Serialize)] +pub struct IntentScope { + pub view: String, + pub current_inventory_hash: String, +} + +#[derive(Debug, Serialize)] +pub struct ScopedIntent { + pub id: String, + pub human_key: String, + pub title: String, + pub status: String, + pub view: String, + pub source_kind: String, + pub path: String, + pub source_hash: String, + pub definition_error: Option, +} + +#[derive(Debug, Serialize)] +pub struct GovernanceChange { + pub hash: String, + /// added_to_after / removed_from_after; neither implies patch replay. + pub direction: String, + pub paths: Vec, + pub intent_context: Value, +} + +#[derive(Debug, Serialize)] +pub struct ComparedCriterion { + pub id: String, + pub intent: String, + pub governing_changes: Vec, + pub before: Option, + pub after: Option, + pub current_context: Option, +} + +#[derive(Debug, Serialize)] +pub struct Declaration { + pub text: String, + pub status: String, + pub source_kind: String, + pub view: Option, + pub path: String, + pub source_hash: String, + pub verified_by: Option, + pub evidence: Option, + pub verifications: Vec, + pub required_kinds: Vec, + pub tasks: Vec, +} + +#[derive(Debug, Serialize)] +pub struct TaskEvidence { + pub id: String, + pub text: String, + pub status: String, + /// Navigation hints only; touching a task file does not prove conformance. + pub files: Vec, +} + +#[derive(Clone)] +struct Definition { + node: CanonicalNode, + kind: &'static str, + view: Option, + path: String, + hash: String, +} + +struct CurrentIntent { + row: ScopedIntent, + definition: Option, +} + +struct CurrentScope { + intents: Vec, + hash: String, + diagnostics: Vec, +} + +fn vault_path(path: &str) -> String { + if path.starts_with(".vault/") { + path.into() + } else { + format!(".vault/{path}") + } +} + +fn current_scope(repo: &Repository, view: &str) -> CliResult { + let manifest = if repo.has_vault().map_err(CliError::Repository)? { + repo.vault_manifest().map_err(CliError::Repository)? + } else { + Default::default() + }; + let mut intents = Vec::new(); + let mut inventory = BTreeMap::new(); + let mut diagnostics = Vec::new(); + for (key, summary) in manifest.intents { + let inputs = if summary.vault_path.is_empty() { + bridge::read_intent(repo, &key).map_err(CliError::Repository)? + } else { + let Some(entry) = repo + .vault_retrieve(summary.vault_path.trim_start_matches(".vault/")) + .map_err(CliError::Repository)? + else { + inventory.insert(key.clone(), "missing_definition".into()); + diagnostics.push(format!( + "{key}: vault definition missing; view assignment unavailable" + )); + continue; + }; + bridge::inputs_from_entry(&entry).map_err(CliError::Repository)? + }; + if inputs.frontmatter.get("view").and_then(Value::as_str) != Some(view) { + continue; + } + let hash = bridge::source_content_hash(&inputs); + inventory.insert(key.clone(), hash.clone()); + let path = vault_path(&summary.vault_path); + let lifted = bridge::lift(&inputs); + let (node, error) = match lifted { + Ok(node) => (Some(node), None), + Err(error) => { + let error = error.to_string(); + diagnostics.push(format!( + "{key}: view-scoped intent definition unavailable: {error}" + )); + (None, Some(error)) + } + }; + let row = ScopedIntent { + id: node + .as_ref() + .map(|node| node.id.clone()) + .unwrap_or_else(|| key.clone()), + human_key: node + .as_ref() + .map(|node| node.human_key.clone()) + .unwrap_or_else(|| key.clone()), + title: inputs + .frontmatter + .get("title") + .and_then(Value::as_str) + .unwrap_or(&summary.title) + .into(), + status: inputs + .frontmatter + .get("status") + .and_then(Value::as_str) + .unwrap_or(&summary.status) + .into(), + view: view.into(), + source_kind: "current_vault_context".into(), + path: path.clone(), + source_hash: hash.clone(), + definition_error: error, + }; + let definition = node.map(|node| Definition { + node, + kind: "current_vault_context", + view: None, + path, + hash, + }); + intents.push(CurrentIntent { row, definition }); + } + let hash = Hash::of( + &serde_json::to_vec(&inventory).map_err(|error| CliError::Internal(error.into()))?, + ) + .to_base32(); + Ok(CurrentScope { + intents, + hash, + diagnostics, + }) +} + +struct Sources<'a> { + before: Option<&'a str>, + after: &'a str, + paths: BTreeSet, + files: BTreeMap>, +} + +fn recorded(bytes: &[u8], view: &str, path: &str) -> Result { + if bytes.len() > 1024 * 1024 { + return Err("Recorded intent exceeds the 1 MiB definition budget".into()); + } + let hash = Hash::of(bytes).to_base32(); + let text = std::str::from_utf8(bytes) + .map_err(|error| error.to_string())? + .replace("\r\n", "\n"); + let (front, body) = text + .strip_prefix("---\n") + .and_then(|text| text.split_once("\n---\n")) + .ok_or("Recorded intent has no delimited YAML frontmatter")?; + let inputs = bridge::LiftInputs { + frontmatter: serde_yaml_ng::from_str(front).map_err(|error| error.to_string())?, + body: body.into(), + }; + let node = bridge::lift(&inputs).map_err(|error| error.to_string())?; + Ok(Definition { + node, + kind: "recorded_view", + view: Some(view.into()), + path: path.into(), + hash, + }) +} + +fn matches(node: &CanonicalNode, reference: &str) -> bool { + node.id == reference + || node.human_key == reference + || node.id.rsplit(':').next() == Some(reference) +} + +fn declaration( + definition: &Definition, + id: &str, + files: &BTreeMap>, +) -> Option { + let criterion = definition + .node + .has_acceptance_criterion + .iter() + .find(|criterion| criterion.id == id)?; + let tasks = definition.node.has_task.iter().filter(|task|task.satisfies.as_slice().contains(&id.to_string())).map(|task|TaskEvidence { + id:task.id.clone(),text:task.text.clone(),status:task.task_status.clone(), + files:task.touches_file.iter().map(|path| { + let references = files.get(path).cloned().unwrap_or_default(); + json!({"path":path,"comparisons":references,"coverage":if references.is_empty(){"not_present_in_recorded_comparison"}else{"recorded_file_reference_only"}}) + }).collect(), + }).collect(); + Some(Declaration { + text: criterion.text.clone(), + status: criterion.ac_status.clone(), + source_kind: definition.kind.into(), + view: definition.view.clone(), + path: definition.path.clone(), + source_hash: definition.hash.clone(), + verified_by: criterion.verified_by.clone(), + evidence: criterion.evidence.clone(), + verifications: criterion.verifications.clone(), + required_kinds: criterion.required_kinds.clone(), + tasks, + }) +} + +pub(super) fn collect( + repo: &Repository, + comparison: &ViewComparison, + before: &[String], + after: &[String], +) -> CliResult { + let mut files = BTreeMap::>::new(); + for file in &comparison.files { + for path in file + .before_path + .iter() + .chain(&file.after_path) + .collect::>() + { + files.entry(path.clone()).or_default().push(json!({"source_ref":file.source_ref,"before_path":file.before_path,"after_path":file.after_path,"status":file.status})); + } + } + let sources = Sources { + before: Some(&comparison.from.view), + after: &comparison.to.view, + paths: files.keys().cloned().collect(), + files, + }; + collect_sources(repo, &sources, before, after) +} + +pub(in super::super) fn collect_view( + repo: &Repository, + snapshot: &super::super::incremental::ViewInspection, +) -> CliResult { + let files=snapshot.paths.iter().map(|path|(path.clone(),vec![json!({"source_ref":snapshot.source_ref,"before_path":Value::Null,"after_path":path,"status":"snapshot"})])).collect(); + let sources = Sources { + before: None, + after: &snapshot.view, + paths: snapshot.paths.iter().cloned().collect(), + files, + }; + collect_sources(repo, &sources, &[], &[]) +} + +fn collect_sources( + repo: &Repository, + sources: &Sources<'_>, + before: &[String], + after: &[String], +) -> CliResult { + let old: BTreeSet<_> = before.iter().collect(); + let new: BTreeSet<_> = after.iter().collect(); + let mut result = Conformance::default(); + let current = current_scope(repo, sources.after)?; + result.scope = Some(IntentScope { + view: sources.after.into(), + current_inventory_hash: current.hash, + }); + result.diagnostics.extend(current.diagnostics); + let mut current_definitions = Vec::new(); + let mut plans = BTreeMap::>::new(); + let mut candidates = BTreeSet::new(); + for intent in current.intents { + candidates.insert(intent.row.path.clone()); + if let Some(definition) = intent.definition { + plans.entry(definition.node.id.clone()).or_default(); + current_definitions.push(definition); + } + result.intents.push(intent.row); + } + for (hash, direction) in new + .difference(&old) + .map(|hash| (*hash, "added_to_after")) + .chain( + old.difference(&new) + .map(|hash| (*hash, "removed_from_after")), + ) + { + let parsed = Hash::from_base32(hash.as_bytes()).expect("recorded membership hash"); + let change = repo.load_change(&parsed).map_err(CliError::Repository)?; + let graphs = repo + .find_provenance_for_change(&parsed) + .map_err(CliError::Repository)?; + let context = repo.change_intent_context(&parsed, &change, &graphs); + if context.status == "recorded" { + for plan in &context.plans { + let reference = plan + .intent + .as_ref() + .map(|intent| { + if intent.uid.is_empty() { + intent.id.as_str() + } else { + intent.uid.as_str() + } + }) + .unwrap_or(&plan.plan_id); + plans + .entry(reference.into()) + .or_default() + .insert(hash.clone()); + if let Some(intent) = &plan.intent { + candidates.insert(intent.path.clone()); + } + if let Ok(Some(path)) = bridge::vault_path_for(repo, reference) { + candidates.insert(if path.starts_with(".vault/") { + path + } else { + format!(".vault/{path}") + }); + } + } + } else { + result.diagnostics.push(format!( + "{hash} ({direction}): {} governing intent; file overlap is not a declaration", + context.status + )); + } + let mut paths = repo + .change_modified_paths(&parsed) + .map_err(CliError::Repository)?; + paths.sort(); + paths.dedup(); + result.changes.push(GovernanceChange { + hash: hash.clone(), + direction: direction.into(), + paths, + intent_context: serde_json::to_value(context) + .map_err(|error| CliError::Internal(error.into()))?, + }); + } + result.changes.sort_by(|a, b| a.hash.cmp(&b.hash)); + // Recorded definitions can survive deletion of their current vault entry. + // Inspect only intent documents, never unrelated history or code payloads. + for path in &sources.paths { + if path.starts_with(".vault/intents/") && path.ends_with("/intent.md") { + candidates.insert(path.clone()); + } + } + let mut before_definitions = Vec::new(); + let mut after_definitions = Vec::new(); + if !candidates.is_empty() { + let candidates: Vec<_> = candidates.into_iter().collect(); + for (view, definitions) in [ + (sources.before, &mut before_definitions), + (Some(sources.after), &mut after_definitions), + ] { + let Some(view) = view else { + continue; + }; + // One canonical tree projection and span context per side, not one + // full repository projection for every intent document. + let mut remaining = 16 * 1024 * 1024usize; + repo.for_each_file_content_and_kind_on_view(&candidates,view,|path,bytes,kind| { + let Some(bytes)=bytes else {return Ok(());}; + if kind!=Some(atomic_core::change::InodeKind::Regular) || bytes.len()>remaining { + result.diagnostics.push(format!("{view}:{path}: recorded definition unavailable (non-regular source or 16 MiB intent-source budget); no acceptance claim inferred")); + return Ok(()); + } + remaining -= bytes.len(); + match recorded(&bytes, view, path) { + Ok(definition) + if definition.node.view.as_deref()==Some(sources.after) || plans + .keys() + .any(|reference| matches(&definition.node, reference)) => + { + definitions.push(definition) + } + Ok(_) => {} + Err(error) => result + .diagnostics + .push(format!("{view}:{path}: {error}")), + } + Ok(()) + }).map_err(CliError::Repository)?; + } + } + for definition in &after_definitions { + if definition.node.view.as_deref() != Some(sources.after) { + continue; + } + plans.entry(definition.node.id.clone()).or_default(); + let row = ScopedIntent { + id: definition.node.id.clone(), + human_key: definition.node.human_key.clone(), + title: definition.node.title.clone(), + status: definition.node.status.clone(), + view: sources.after.into(), + source_kind: definition.kind.into(), + path: definition.path.clone(), + source_hash: definition.hash.clone(), + definition_error: None, + }; + if let Some(existing) = result.intents.iter_mut().find(|intent| { + intent.id == row.id + || (intent.definition_error.is_some() && intent.human_key == row.human_key) + }) { + *existing = row; + } else { + result.intents.push(row); + } + } + let mut seen = BTreeSet::new(); + for (reference, changes) in plans { + let old: Vec<_> = before_definitions + .iter() + .filter(|definition| matches(&definition.node, &reference)) + .collect(); + let new: Vec<_> = after_definitions + .iter() + .filter(|definition| matches(&definition.node, &reference)) + .collect(); + if old.len() > 1 || new.len() > 1 { + result.diagnostics.push(format!( + "{reference}: ambiguous recorded intent definitions; no criteria guessed" + )); + continue; + } + let old = old.first().copied(); + let new = new.first().copied(); + let scoped_current = current_definitions + .iter() + .find(|definition| matches(&definition.node, &reference)); + let current = if old.is_none() && new.is_none() { + if let Some(definition) = scoped_current { + Some(definition.clone()) + } else { + match bridge::read_intent(repo, &reference).and_then(|inputs| { + bridge::lift(&inputs).map(|node| (node, bridge::source_content_hash(&inputs))) + }) { + Ok((node, hash)) => { + result + .current_sources + .insert(reference.clone(), hash.clone()); + result.diagnostics.push(format!("{reference}: recorded intent source unavailable; current vault definition is labelled context only, not historical acceptance evidence")); + Some(Definition { + node, + hash, + kind: "current_vault_context", + view: None, + path: reference.clone(), + }) + } + Err(error) => { + result.diagnostics.push(format!( + "{reference}: governing intent definition unavailable: {error}" + )); + None + } + } + } + } else { + None + }; + let ids: BTreeSet<_> = old + .into_iter() + .chain(new) + .chain(current.as_ref()) + .flat_map(|definition| { + definition + .node + .has_acceptance_criterion + .iter() + .map(|criterion| criterion.id.clone()) + }) + .collect(); + if ids.is_empty() { + result.diagnostics.push(format!( + "{reference}: no acceptance criteria available in this intent definition" + )); + } + for id in ids { + if !seen.insert(id.clone()) { + let existing = result + .criteria + .iter_mut() + .find(|criterion| criterion.id == id) + .unwrap(); + if existing.intent != new.or(old).or(current.as_ref()).unwrap().node.id { + return Err(CliError::InvalidArgument { + message: format!( + "Ambiguous criterion identity {id} in comparison governance" + ), + }); + } + existing.governing_changes = existing + .governing_changes + .iter() + .chain(&changes) + .cloned() + .collect::>() + .into_iter() + .collect(); + continue; + } + result.criteria.push(ComparedCriterion { + id: id.clone(), + intent: new.or(old).or(current.as_ref()).unwrap().node.id.clone(), + governing_changes: changes.iter().cloned().collect(), + before: old.and_then(|definition| declaration(definition, &id, &sources.files)), + after: new.and_then(|definition| declaration(definition, &id, &sources.files)), + current_context: current + .as_ref() + .and_then(|definition| declaration(definition, &id, &sources.files)), + }); + } + } + result.criteria.sort_by(|a, b| a.id.cmp(&b.id)); + // Native change context resolves display identities through the live vault. + // Do not let a later title edit overwrite identity context for a definition + // we actually have pinned in one of the recorded views. + for change in &mut result.changes { + for field in ["plans", "associated_intents"] { + for item in change.intent_context[field] + .as_array_mut() + .into_iter() + .flatten() + { + let Some(identity) = item["intent"].as_object_mut() else { + continue; + }; + let reference = identity + .get("uid") + .filter(|value| value.as_str().is_some_and(|value| !value.is_empty())) + .or_else(|| identity.get("id")) + .and_then(Value::as_str) + .unwrap_or_default(); + let preferred: Vec<_> = after_definitions + .iter() + .filter(|definition| matches(&definition.node, reference)) + .collect(); + let preferred = if preferred.is_empty() { + before_definitions + .iter() + .filter(|definition| matches(&definition.node, reference)) + .collect() + } else { + preferred + }; + if let [definition] = preferred.as_slice() { + identity.insert("title".into(), json!(definition.node.title)); + identity.insert("source_kind".into(), json!("recorded_view")); + identity.insert("source_view".into(), json!(definition.view)); + identity.insert("source_hash".into(), json!(definition.hash)); + } else { + identity.insert("source_kind".into(), json!("current_vault_context")); + } + } + } + } + result + .intents + .sort_by(|a, b| a.human_key.cmp(&b.human_key).then(a.id.cmp(&b.id))); + result.diagnostics.sort(); + result.diagnostics.dedup(); + Ok(result) +} + +impl Conformance { + pub(crate) fn reviews(&self) -> Vec { + self.criteria + .iter() + .map(|criterion| { + let declaration = criterion + .after + .as_ref() + .or(criterion.before.as_ref()) + .or(criterion.current_context.as_ref()) + .unwrap(); + CriterionReview { + id: criterion.id.clone(), + intent: criterion.intent.clone(), + text: declaration.text.clone(), + declared_status: declaration.status.clone(), + review_assessment: CriterionOutcome::Unknown, + findings: vec![], + source_hash: declaration.source_hash.clone(), + } + }) + .collect() + } + pub(crate) fn verify(&self, repo: &Repository) -> CliResult<()> { + if let Some(scope) = &self.scope { + if current_scope(repo, &scope.view)?.hash != scope.current_inventory_hash { + return Err(CliError::InvalidArgument {message:"View-scoped intent catalogue changed during review/export; retry without stale context".into()}); + } + } + for (reference, hash) in &self.current_sources { + let inputs = bridge::read_intent(repo, reference).map_err(CliError::Repository)?; + if bridge::source_content_hash(&inputs) != *hash { + return Err(CliError::InvalidArgument { + message: + "Current-vault conformance context changed during export; retry review" + .into(), + }); + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use atomic_repository::{IntentCreateOptions, IntentUpdateOptions}; + + fn create(repo: &Repository, title: &str) -> atomic_repository::IntentCreateResult { + repo.vault_intent_create(IntentCreateOptions { + title: title.into(), + priority: None, + assignee: None, + labels: vec![], + session_id: None, + turn_id: None, + kind: None, + }) + .unwrap() + } + fn pin(repo: &Repository, view: &str) -> Conformance { + Conformance { + scope: Some(IntentScope { + view: view.into(), + current_inventory_hash: current_scope(repo, view).unwrap().hash, + }), + ..Default::default() + } + } + #[test] + fn scope_inventory_detects_new_intents_and_definition_drift_but_not_unrelated_views() { + let dir = tempfile::tempdir().unwrap(); + let mut repo = Repository::init(dir.path()).unwrap(); + repo.init_vault().unwrap(); + let wc = repo.require_working_copy_id().unwrap(); + let view = repo.current_view().to_owned(); + let first = pin(&repo, &view); + repo.create_draft_view("other", &view).unwrap(); + repo.switch_view(wc, "other").unwrap(); + create(&repo, "Unrelated scope"); + first.verify(&repo).unwrap(); + repo.switch_view(wc, &view).unwrap(); + let work = create(&repo, "New view-scoped intent"); + assert!(first.verify(&repo).is_err()); + let second = pin(&repo, &view); + second.verify(&repo).unwrap(); + repo.vault_intent_update( + &work.id, + IntentUpdateOptions { + content: Some(":::why\nChanged after selection.\n:::\n".into()), + ..Default::default() + }, + ) + .unwrap(); + assert!(second.verify(&repo).is_err()); + } +} diff --git a/atomic-cli/src/commands/review/view_comparison/findings.rs b/atomic-cli/src/commands/review/view_comparison/findings.rs new file mode 100644 index 00000000..8d286431 --- /dev/null +++ b/atomic-cli/src/commands/review/view_comparison/findings.rs @@ -0,0 +1,187 @@ +use super::SideIndex; +use atomic_canonical::{ + review_finding::{CheckStatus, ReviewFinding, SourceSide}, + review_graph::FindingComparison, +}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; + +fn owner(view: &SideIndex<'_>, finding: &ReviewFinding, path: &str) -> String { + let line = &finding.locations[0]; + view.metrics(Some(path)) + .iter() + .filter(|metric| { + !metric.subject_identity_ambiguous + && metric.path == path + && matches!( + metric.scope, + atomic_audit::catalog::MetricScope::Function + | atomic_audit::catalog::MetricScope::Class + ) + }) + .filter_map(|metric| { + metric + .after_location + .as_ref() + .filter(|span| span.start_line <= line.start_line && span.end_line >= line.end_line) + .map(|span| { + ( + span.end_line - span.start_line, + metric.observation.subject.as_str(), + ) + }) + }) + .min_by_key(|(size, _)| *size) + .map(|(_, subject)| super::metrics::subject(subject, path, "")) + .unwrap_or_else(|| "".into()) +} +fn fingerprint(finding: &ReviewFinding) -> String { + finding + .evidence + .iter() + .find(|item| item.reference.starts_with("urn:atomic:audit-observation:")) + .map(|item| item.reference.clone()) + .unwrap_or_default() +} +fn checked(view: &SideIndex<'_>, path: Option<&str>, rule: &str) -> bool { + path.is_none() + || view.checks(path).iter().any(|check| { + Some(check.path.as_str()) == path + && check.rule == rule + && check.status == CheckStatus::Completed + }) +} +fn side( + finding: &ReviewFinding, + side: SourceSide, +) -> Vec { + finding + .locations + .iter() + .map(|location| { + let mut location = location.clone(); + location.side = side.clone(); + location + }) + .collect() +} + +pub(super) fn compare( + before: &SideIndex<'_>, + after: &SideIndex<'_>, + reference: &str, + old: Option<&str>, + new: Option<&str>, + same_identity: bool, +) -> (Vec, BTreeMap) { + let first = before.findings(old); + let last = after.findings(new); + let key = |view: &SideIndex<'_>, finding: &ReviewFinding, path: &str| { + ( + finding.requirement_or_rule.id.clone(), + owner(view, finding, path), + ) + }; + let mut used = BTreeSet::new(); + let first_keys: Vec<_> = first + .iter() + .map(|finding| key(before, finding, old.unwrap())) + .collect(); + let last_keys: Vec<_> = last + .iter() + .map(|finding| key(after, finding, new.unwrap())) + .collect(); + let exact_key = |group: &(String, String), finding: &ReviewFinding| { + let fingerprint = if group.0 == "anti-slop.manageability" + && group.1 != "" + { + "qualified-manageability-owner".into() + } else { + fingerprint(finding) + }; + (!fingerprint.is_empty()).then(|| (group.clone(), fingerprint)) + }; + // Reserve exact continuations before pairing edited constructs. Otherwise + // an edited first occurrence could consume a later unchanged observation. + let mut exact_matches = BTreeMap::new(); + let mut edited_candidates = BTreeMap::<_, VecDeque>::new(); + if same_identity { + let mut candidates = BTreeMap::<_, VecDeque>::new(); + for (index, previous) in first.iter().enumerate() { + if let Some(key) = exact_key(&first_keys[index], previous) { + candidates.entry(key).or_default().push_back(index); + } + } + for (current_index, current) in last.iter().enumerate() { + if let Some(index) = exact_key(&last_keys[current_index], current) + .and_then(|key| candidates.get_mut(&key)) + .and_then(VecDeque::pop_front) + { + used.insert(index); + exact_matches.insert(current_index, index); + } + } + for (index, group) in first_keys.into_iter().enumerate() { + if !used.contains(&index) { + edited_candidates.entry(group).or_default().push_back(index); + } + } + } + let mut findings = Vec::new(); + let mut states = BTreeMap::new(); + let mut emit = |first: Option<&ReviewFinding>, + last: Option<&ReviewFinding>, + status: &str, + reason: &str| { + let mut finding = last.or(first).unwrap().clone(); + finding.change = reference.into(); + if last.is_none() { + for location in &mut finding.locations { + location.side = SourceSide::Before; + } + } + finding.introduced_by_change.status = + atomic_canonical::review_finding::IntroductionStatus::Unknown; + finding.introduced_by_change.rationale="Local comparison of two recorded view states; this is not attribution to an authored change".into(); + let state = FindingComparison { + status: status.into(), + before: first + .map(|f| side(f, SourceSide::Before)) + .unwrap_or_default(), + after: last.map(|f| side(f, SourceSide::After)).unwrap_or_default(), + rationale: reason.into(), + }; + states.insert(super::super::graph::finding_id(&finding), state); + findings.push(finding); + }; + for (current_index, current) in last.iter().copied().enumerate() { + let group = &last_keys[current_index]; + if let Some(index) = exact_matches.get(¤t_index) { + let previous = first[*index]; + emit(Some(previous),Some(current),"existing","The same local rule/AST observation remains in the same recorded file identity and qualified metric owner; line shifts and file renames are not new findings."); + continue; + } + let edited = edited_candidates + .get_mut(group) + .and_then(VecDeque::pop_front); + if let Some(index) = edited { + let previous = first[index]; + used.insert(index); + emit(Some(previous),Some(current),"changed","The same local rule/owner still matches different AST bytes. Equivalence, introduction and resolution are not guessed."); + } else if checked(before, old, &group.0) { + emit(None,Some(current),"new","Additional local rule observation relative to a successfully checked before side or a proven absent file; not a whole-program defect verdict."); + } else { + emit(None,Some(current),"unknown","Before-side rule coverage is unavailable/skipped; a missing observation is not proof of a new issue."); + } + } + for (index, previous) in first.iter().enumerate() { + if used.contains(&index) { + continue; + } + if checked(after, new, &previous.requirement_or_rule.id) { + emit(Some(previous),None,"resolved","The before-side local observation is absent in a successfully checked after side or a proven removed file; not proof of behavioral correctness."); + } else { + emit(Some(previous),None,"unknown","After-side rule coverage is unavailable/skipped; a missing observation is not a resolution."); + } + } + (findings, states) +} diff --git a/atomic-cli/src/commands/review/view_comparison/impact.rs b/atomic-cli/src/commands/review/view_comparison/impact.rs new file mode 100644 index 00000000..aa7a52ae --- /dev/null +++ b/atomic-cli/src/commands/review/view_comparison/impact.rs @@ -0,0 +1,87 @@ +use atomic_audit::impact::ImpactReport; +use atomic_canonical::review_graph::SubmittedFinding; +use atomic_repository::Repository; +use atomic_semantic::ParserRegistry; +use std::collections::BTreeSet; + +use super::ViewComparison; + +pub(in super::super) fn changed_paths(comparison: &ViewComparison) -> Vec { + if comparison.from.state == comparison.to.state + && comparison.from.membership_hash == comparison.to.membership_hash + { + return vec![]; + } + let recorded_changes: BTreeSet<_> = comparison + .conformance + .changes + .iter() + .flat_map(|change| change.paths.iter()) + .collect(); + comparison + .files + .iter() + .filter(|file| { + file.status != "unchanged" + && (file.status != "unavailable" + || file + .before_path + .iter() + .chain(&file.after_path) + .any(|path| recorded_changes.contains(path))) + }) + .flat_map(|file| file.before_path.iter().chain(&file.after_path)) + .filter(|path| !atomic_repository::is_vault_path(path)) + .cloned() + .collect::>() + .into_iter() + .collect() +} + +pub(in super::super) fn inspect( + repo: &Repository, + comparison: &ViewComparison, +) -> (Vec, Vec) { + let paths = changed_paths(comparison); + let mut result = ImpactReport { + change: comparison.source_ref.clone(), + code_changed: !paths.is_empty(), + ..Default::default() + }; + if paths.is_empty() { + result.source_selection_complete = Some(true); + result.unresolved_references = Some(0); + } else if !paths.iter().any(|path| atomic_semantic::is_supported(path)) { + result.gaps.push("Changed paths have no supported semantic source; configuration/non-code runtime effects are not inferred".into()); + } else { + match ( + repo.semantic_view_on_view(&comparison.from.view), + repo.semantic_view_on_view(&comparison.to.view), + ) { + (Ok(before), Ok(after)) => { + result = super::super::impact::inspect_views( + &before, + &after, + &paths, + &mut ParserRegistry::new(), + ); + result.change = comparison.source_ref.clone(); + } + (before, after) => { + if let Err(error) = before { + result.gaps.push(format!( + "Before named-view semantic source unavailable: {error}" + )); + } + if let Err(error) = after { + result.gaps.push(format!( + "After named-view semantic source unavailable: {error}" + )); + } + } + } + } + let findings = super::super::impact::contract_findings(&result); + result.gaps.push("Compared the complete effective named-view states, not intermediate authored patches. Semantic callable IDs are path/module-addressed; a recorded file rename can change bindings. Caller context is bounded by the existing semantic selector; compiler/type/runtime/test execution is not performed.".into()); + (vec![result], findings) +} diff --git a/atomic-cli/src/commands/review/view_comparison/metrics.rs b/atomic-cli/src/commands/review/view_comparison/metrics.rs new file mode 100644 index 00000000..254b0490 --- /dev/null +++ b/atomic-cli/src/commands/review/view_comparison/metrics.rs @@ -0,0 +1,274 @@ +use super::SideIndex; +use atomic_audit::{metrics::ExtractedMetric, Measurement, Metric}; +use atomic_canonical::review_finding::AnalysisReport; +use std::collections::{BTreeMap, BTreeSet}; + +pub(super) fn subject(subject: &str, actual: &str, logical: &str) -> String { + match subject.strip_prefix(actual) { + Some(tail) if tail.is_empty() || tail.starts_with('#') => format!("{logical}{tail}"), + _ => subject.into(), + } +} + +fn inventory<'a>( + view: &SideIndex<'a>, + path: Option<&str>, + logical: &str, +) -> BTreeMap<(Metric, String), &'a ExtractedMetric> { + view.metrics(path) + .iter() + .copied() + .map(|metric| { + ( + ( + metric.observation.metric, + subject(&metric.observation.subject, &metric.path, logical), + ), + metric, + ) + }) + .collect() +} + +fn missing(view: &SideIndex<'_>, path: Option<&str>, metric: Metric) -> Measurement { + let Some(path) = path else { + return Measurement::NotApplicable { + reason: "File is absent in this revision".into(), + }; + }; + let records: Vec<_> = view + .metrics(Some(path)) + .iter() + .filter(|record| record.observation.metric == metric) + .collect(); + if records.is_empty() + || view.view.analysis.metric_diagnostics.iter().any(|line| { + !line.contains(super::super::analysis::SNAPSHOT_BASELINE) + && (line.contains(path) || line.to_ascii_lowercase().contains("budget")) + }) + { + return Measurement::Unavailable { reason:"No reliable subject baseline was supplied for this metric; missing/unsupported/budget-limited data is not an absent subject".into() }; + } + if let Some(reason) = records + .iter() + .find_map(|record| match &record.observation.after { + Measurement::Unavailable { reason } => Some(reason.clone()), + _ => None, + }) + { + return Measurement::Unavailable { reason }; + } + Measurement::NotApplicable { + reason: "Subject is not present in this revision".into(), + } +} + +pub(super) fn analysis( + before: &SideIndex<'_>, + after: &SideIndex<'_>, + logical: &str, + old: Option<&str>, + new: Option<&str>, + same_identity: bool, +) -> AnalysisReport { + let before_metrics = inventory(before, old, logical); + let after_metrics = inventory(after, new, logical); + let keys: BTreeSet<_> = before_metrics + .keys() + .chain(after_metrics.keys()) + .cloned() + .collect(); + let mut metrics = Vec::new(); + for key in keys { + let first = before_metrics.get(&key).copied(); + let last = after_metrics.get(&key).copied(); + let mut metric = last.or(first).unwrap().clone(); + metric.path = logical.into(); + metric.observation.subject = key.1; + metric.observation.before = first + .map(|record| record.observation.after.clone()) + .unwrap_or_else(|| missing(before, old, key.0)); + metric.observation.after = last + .map(|record| record.observation.after.clone()) + .unwrap_or_else(|| missing(after, new, key.0)); + metric.before_location = first.and_then(|record| record.after_location.clone()); + metric.after_location = last.and_then(|record| record.after_location.clone()); + if !same_identity + && old.is_some() + && new.is_some() + && matches!( + metric.scope, + atomic_audit::catalog::MetricScope::Function + | atomic_audit::catalog::MetricScope::Class + ) + { + metric.observation.before = Measurement::Unavailable { reason: "Recorded inode was replaced; a same-named subject is not an established identity baseline".into() }; + metric.before_location = None; + } + metric.subject_identity_ambiguous = first + .into_iter() + .chain(last) + .any(|record| record.subject_identity_ambiguous); + if metric.subject_identity_ambiguous { + metric.observation.before = Measurement::Unavailable { reason: "Anonymous/overloaded subject identity is ambiguous between independently extracted views; no ordinal-based delta inferred".into() }; + metric.before_location = None; + } + if first + .zip(last) + .is_some_and(|(a, b)| a.convention != b.convention) + { + metric.observation.before = Measurement::Unavailable { + reason: "Measurement conventions differ between the supplied views".into(), + }; + } + metric.delta = metric.observation.delta(); + metric.detail=format!("{}; local measurements from two pinned recorded view corpora; renames use recorded file identity, not inferred similarity",metric.detail); + metrics.push(metric); + } + let mut checks = Vec::new(); + for (side, view, path) in [("Before", before, old), ("After", after, new)] { + for check in view.checks(path) { + let mut check = (*check).clone(); + check.detail = format!("{side} view {}: {}", view.view.view, check.detail); + checks.push(check); + } + } + let excluded = before + .view + .analysis + .excluded_metadata_paths + .iter() + .chain(&after.view.analysis.excluded_metadata_paths) + .filter(|path| Some(path.as_str()) == old || Some(path.as_str()) == new) + .cloned() + .collect::>() + .into_iter() + .collect(); + AnalysisReport { + schema: before.view.analysis.schema.clone(), + analyzer: before.view.analysis.analyzer.clone(), + analyzer_version: before.view.analysis.analyzer_version.clone(), + checks, + findings: vec![], + metrics, + metric_diagnostics: vec![], + metric_comparison_scope: vec![logical.into()], + excluded_metadata_paths: excluded, + } +} + +#[cfg(test)] +mod tests { + use super::super::super::incremental::ViewInspection; + use super::*; + + fn snapshot(path: &str, source: &str) -> ViewInspection { + let extracted = atomic_audit::extract::extract_changes( + &[atomic_audit::extract::FileChange { + path: path.into(), + before: atomic_audit::extract::Source::Absent, + after: atomic_audit::extract::Source::Text(source.into()), + }], + &mut atomic_semantic::ParserRegistry::new(), + &Default::default(), + ) + .unwrap(); + ViewInspection { + conformance: None, + source_ref: "urn:snapshot:test".into(), + view: "test".into(), + state: "test".into(), + membership_hash: "test".into(), + paths: vec![path.into()], + content_hashes: BTreeMap::new(), + analysis: AnalysisReport { + schema: "test".into(), + analyzer: "test".into(), + analyzer_version: "test".into(), + checks: vec![], + findings: vec![], + metrics: extracted.metrics, + metric_diagnostics: extracted.diagnostics, + metric_comparison_scope: extracted.comparison_paths, + excluded_metadata_paths: vec![], + }, + } + } + + #[test] + fn missing_data_and_anonymous_or_overloaded_subjects_never_make_numeric_baselines() { + let mut before = snapshot("code.rs", "fn keep() {}\n"); + let after = snapshot("code.rs", "fn keep() {}\nfn added() { if true {} }\n"); + before + .analysis + .metric_diagnostics + .push("code.rs (after): Subject inventory budget exceeded".into()); + let report = analysis( + &SideIndex::new(&before), + &SideIndex::new(&after), + "code.rs", + Some("code.rs"), + Some("code.rs"), + true, + ); + for metric in report + .metrics + .iter() + .filter(|m| m.observation.subject.contains("added")) + { + assert!(matches!( + metric.observation.before, + Measurement::Unavailable { .. } + )); + assert!(metric.delta.is_none()); + } + let before = snapshot( + "code.ts", + "function f(a: string) { return a; }\nfunction f(a: number) { return a; }\n", + ); + let report = analysis( + &SideIndex::new(&before), + &SideIndex::new(&before), + "code.ts", + Some("code.ts"), + Some("code.ts"), + true, + ); + let ambiguous: Vec<_> = report + .metrics + .iter() + .filter(|m| m.subject_identity_ambiguous) + .collect(); + assert!(!ambiguous.is_empty()); + assert!(ambiguous.iter().all(|m| m.delta.is_none() + && matches!(m.observation.before, Measurement::Unavailable { .. }))); + } + + #[test] + fn replacement_does_not_infer_named_subject_continuity_from_the_path() { + let before = snapshot("code.rs", "fn same_name() {}\n"); + let after = snapshot("code.rs", "fn same_name() { if true {} }\n"); + let report = analysis( + &SideIndex::new(&before), + &SideIndex::new(&after), + "code.rs", + Some("code.rs"), + Some("code.rs"), + false, + ); + let metric = report + .metrics + .iter() + .find(|m| m.observation.metric == Metric::CyclomaticComplexity) + .unwrap(); + assert!(metric.delta.is_none()); + assert!(matches!( + metric.observation.before, + Measurement::Unavailable { .. } + )); + assert!(matches!( + metric.observation.after, + Measurement::Measured { value: 2 } + )); + } +} diff --git a/atomic-cli/src/commands/review/view_snapshot.rs b/atomic-cli/src/commands/review/view_snapshot.rs new file mode 100644 index 00000000..b35df640 --- /dev/null +++ b/atomic-cli/src/commands/review/view_snapshot.rs @@ -0,0 +1,313 @@ +//! Entire recorded view inspection. No history replay or working-copy switch. + +use std::collections::BTreeSet; + +use atomic_core::{ + pristine::{GraphTxnT, ViewTxnT}, + types::{Base32, Hash}, +}; +use atomic_repository::{graph_visibility_closure, Repository}; +use serde_json::json; + +use super::incremental::{ + DependencyReference, IncrementalArgs, IncrementalReport, Selection, ViewInspection, +}; +use crate::error::{CliError, CliResult}; + +fn invalid(message: impl Into) -> CliError { + CliError::InvalidArgument { + message: message.into(), + } +} + +pub(super) fn resolve(repo: &Repository, args: &IncrementalArgs) -> CliResult { + let name = args + .view + .as_deref() + .ok_or_else(|| invalid("Missing --view name"))?; + if name.is_empty() || name.trim() != name { + return Err(invalid("--view requires an exact nonempty view name")); + } + if args.change.is_some() + || args.turn.is_some() + || args.intent.is_some() + || args.findings.is_some() + || args.risk_profile.is_some() + || args.from.is_some() + || args.to.is_some() + { + return Err(invalid("--view is a snapshot selector; it cannot be combined with change/turn/intent selectors, supplied change findings or a change-risk profile")); + } + let mut report = collect(repo, name)?; + let snapshot = report.view_snapshot.as_mut().expect("resolved snapshot"); + snapshot.conformance = Some(super::view_comparison::collect_view(repo, snapshot)?); + report.graph = Some(super::graph::build(repo, &report, None, None)?); + verify(repo, &report)?; + Ok(report) +} + +pub(super) fn collect(repo: &Repository, name: &str) -> CliResult { + let info = repo.get_view_info(name).map_err(CliError::Repository)?; + let membership_hash = super::graph::membership_hash(repo, name)?; + let mut paths: Vec<_> = repo + .recorded_file_identities_on_view(name) + .map_err(CliError::Repository)? + .into_keys() + .collect(); + paths.sort(); + let descriptor = json!({"project":repo.project_id().map_err(CliError::Repository)?.to_urn(),"view":name,"state":info.state.to_base32(),"membership_hash":membership_hash}); + let source_ref = format!( + "urn:atomic:view-snapshot:{}", + Hash::of( + &serde_json::to_vec(&descriptor).map_err(|error| CliError::Internal(error.into()))? + ) + .to_base32() + ); + let current: BTreeSet<_> = repo + .effective_history(None) + .map_err(CliError::Repository)? + .iter() + .map(|entry| entry.hash.to_base32()) + .collect(); + let members = { + let txn = repo + .pristine() + .read_txn() + .map_err(|error| CliError::Internal(error.into()))?; + let view = txn + .get_view(name) + .map_err(|error| CliError::Internal(error.into()))? + .ok_or_else(|| invalid("View disappeared during snapshot resolution"))?; + let closure = graph_visibility_closure(&txn, &view).map_err(CliError::Repository)?; + closure + .iter_dependency_first() + .filter(|id| !id.is_root()) + .map(|id| { + txn.get_external(*id) + .map_err(|error| CliError::Internal(error.into()))? + .ok_or_else(|| invalid("View membership has no external change hash")) + }) + .collect::>>()? + }; + let mut references = Vec::new(); + for hash in &members { + let change = repo.load_change(hash).map_err(CliError::Repository)?; + let mut dependencies: Vec<_> = change + .hashed + .dependencies + .iter() + .map(Hash::to_base32) + .collect(); + dependencies.sort(); + dependencies.dedup(); + references.push(DependencyReference { + hash: hash.to_base32(), + direct: false, + on_current_view: current.contains(&hash.to_base32()), + summary: change + .hashed + .header + .message + .lines() + .next() + .unwrap_or_default() + .chars() + .take(240) + .collect(), + dependencies, + }); + } + let (analysis, content_hashes) = + super::analysis::analyze_snapshot(repo, name, &source_ref, &paths) + .map_err(CliError::Repository)?; + let report = IncrementalReport { + schema_version:3, purpose:"local_view_snapshot_review", independent_approval:false, + selection:Selection { kind:"view".into(),value:Some(name.into()),reason:"Entire recorded view snapshot, once per live file; history is references only".into() }, + source:json!({"repository_root":repo.root(),"atomic_directory":repo.dot_dir(),"project_identity":repo.project_identity().map_err(CliError::Repository)?,"view":name,"view_state":info.state.to_base32(),"view_scope":info.kind_label(),"parent_view":info.parent_name,"view_change_count":info.change_count,"working_copy_view":repo.current_view(),"working_copy_status":"not_scanned"}), + selected_roots:vec![],dependency_closure:members.iter().map(Hash::to_base32).collect(),dependency_only:members.iter().map(Hash::to_base32).collect(),dependency_references:references, + changes:vec![],view_snapshot:Some(ViewInspection { source_ref, view:name.into(),state:info.state.to_base32(),membership_hash,paths,analysis,content_hashes,conformance:None }),view_comparison:None, + turns:vec![],pending_work_outside_selection:vec![],intents:vec![],warnings:vec![ + "Local-only recorded view snapshot: no working-copy bytes, model calls or view switch.".into(), + "Snapshot findings describe current source, not introduction by an authored change. There is no before revision or metric delta.".into(), + "Snapshot conformance includes explicit view-assigned intents and declared criteria, not inferred change governance or acceptance approval. Change-regression risk still has no before baseline.".into(), + "Metrics cover the full supplied live-file set subject to explicit limits: 1 MiB per source, 128 MiB total, 2M tokens, 65536 subjects and 2M clone comparisons. Omissions remain unavailable/skipped.".into(), + ],graph:None, + }; + verify(repo, &report)?; + Ok(report) +} + +pub(super) fn verify(repo: &Repository, report: &IncrementalReport) -> CliResult<()> { + if let Some(comparison) = &report.view_comparison { + super::view_comparison::verify(repo, comparison)?; + } + if let Some(snapshot) = &report.view_snapshot { + if let Some(conformance) = &snapshot.conformance { + conformance.verify(repo)?; + } + if repo + .get_view_info(&snapshot.view) + .map_err(CliError::Repository)? + .state + .to_base32() + != snapshot.state + || super::graph::membership_hash(repo, &snapshot.view)? != snapshot.membership_hash + { + return Err(invalid( + "Recorded view snapshot changed during audit/export; retry the selected view", + )); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use atomic_core::change::ChangeHeader; + use atomic_repository::{record::RecordOptions, tracking::TrackingOptions}; + + fn record(repo: &Repository) { + repo.record( + repo.require_working_copy_id().unwrap(), + ChangeHeader::new("snapshot fixture"), + RecordOptions::new() + .with_all(true) + .save_to_store(true) + .apply_after_record(true) + .enrich_kg(false), + ) + .unwrap(); + } + + #[test] + fn inherited_parent_changes_invalidate_snapshot_even_when_child_state_is_unchanged() { + let directory = tempfile::tempdir().unwrap(); + let mut repo = Repository::init(directory.path()).unwrap(); + std::fs::write( + directory.path().join("source.rs"), + "fn old() { todo!(); }\n", + ) + .unwrap(); + repo.add( + repo.require_working_copy_id().unwrap(), + "source.rs", + TrackingOptions::default(), + ) + .unwrap(); + record(&repo); + let parent = repo.current_view().to_owned(); + repo.create_draft_view("child", &parent).unwrap(); + let args = IncrementalArgs { + view: Some("child".into()), + ..Default::default() + }; + let first = resolve(&repo, &args).unwrap(); + let child_state = first.view_snapshot.as_ref().unwrap().state.clone(); + std::fs::write(directory.path().join("source.rs"), "fn current() {}\n").unwrap(); + record(&repo); + assert_eq!( + repo.get_view_info("child").unwrap().state.to_base32(), + child_state + ); + assert!(verify(&repo, &first).is_err()); + let second = resolve(&repo, &args).unwrap(); + assert_ne!( + first.view_snapshot.unwrap().source_ref, + second.view_snapshot.unwrap().source_ref + ); + assert_eq!(repo.current_view(), parent); + } + + #[test] + fn whole_view_metrics_do_not_stop_at_the_change_file_budget() { + let directory = tempfile::tempdir().unwrap(); + let repo = Repository::init(directory.path()).unwrap(); + repo.init_vault().unwrap(); + for index in 0..134 { + let path = format!("file_{index:03}.rs"); + std::fs::write( + directory.path().join(&path), + format!("fn function_{index}() {{}}\n"), + ) + .unwrap(); + repo.add( + repo.require_working_copy_id().unwrap(), + &path, + TrackingOptions::default(), + ) + .unwrap(); + } + record(&repo); + let report = resolve( + &repo, + &IncrementalArgs { + view: Some(repo.current_view().into()), + ..Default::default() + }, + ) + .unwrap(); + let snapshot = report.view_snapshot.unwrap(); + assert_eq!(snapshot.paths.len(), 134); + assert_eq!( + snapshot + .analysis + .checks + .iter() + .filter(|check| check.rule == "structural.syntax" + && check.status == atomic_canonical::review_finding::CheckStatus::Completed) + .count(), + 134 + ); + let measured: BTreeSet<_> = snapshot + .analysis + .metrics + .iter() + .filter(|metric| { + matches!( + metric.observation.after, + atomic_audit::Measurement::Measured { .. } + ) + }) + .map(|metric| metric.path.as_str()) + .collect(); + assert_eq!(measured.len(), 134); + assert!(measured.contains("file_133.rs")); + } + + #[test] + fn snapshot_clones_cover_the_whole_current_corpus_without_an_invented_baseline() { + let directory = tempfile::tempdir().unwrap(); + let repo = Repository::init(directory.path()).unwrap(); + repo.init_vault().unwrap(); + for path in ["a.rs", "b.rs"] { + std::fs::write(directory.path().join(path),"pub fn clone(value: i32) -> i32 { let a = value + 1; let b = a * 2; let c = b - value; if c > 0 { c + a } else { value - c } }\n").unwrap(); + repo.add( + repo.require_working_copy_id().unwrap(), + path, + TrackingOptions::default(), + ) + .unwrap(); + } + record(&repo); + let report = collect(&repo, repo.current_view()).unwrap(); + let snapshot = report.view_snapshot.unwrap(); + let clones: Vec<_> = snapshot + .analysis + .metrics + .iter() + .filter(|m| m.observation.metric == atomic_audit::Metric::DuplicatedTokens) + .collect(); + assert_eq!(clones.len(), 2); + for metric in clones { + assert!( + matches!(metric.observation.after,atomic_audit::Measurement::Measured { value } if value > 0) + ); + assert!(matches!( + metric.observation.before, + atomic_audit::Measurement::Unavailable { .. } + )); + assert!(metric.delta.is_none()); + } + } +} diff --git a/atomic-cli/src/commands/review/viewer.css b/atomic-cli/src/commands/review/viewer.css new file mode 100644 index 00000000..c1c0741d --- /dev/null +++ b/atomic-cli/src/commands/review/viewer.css @@ -0,0 +1,59 @@ +/* Atomic palette: atomic.dev. Offline assets/provenance: assets/README.md. */ +:root{color-scheme:dark;--canvas:#07041a;--paper:#0c0726;--raised:#130a36;--ink:#f4eefe;--accent:#ff0a8c;--violet:#8c2eff;--green:#4ade80;--amber:#ffd166;--danger:#ff4ea8;--line:#ffffff24;--muted:#f4eefea8;--code:"GT America Mono","SFMono-Regular",Menlo,Consolas,monospace;font-family:"GT America","Helvetica Neue",system-ui,sans-serif;color:var(--ink);background:var(--canvas)} +*{box-sizing:border-box}body{margin:0}button,input,select{font:inherit} +button,select,input{border:1px solid var(--line);border-radius:4px;background:var(--paper);color:var(--ink)} +button{cursor:pointer;padding:.45rem .7rem}button:hover{border-color:var(--accent);background:var(--raised)} +button:disabled{cursor:default;opacity:.65}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible{outline:3px solid var(--accent);outline-offset:3px} +a{color:var(--accent)}[hidden]{display:none!important}h1,h2,h3,p{margin:0} +h1{font-size:1.35rem;font-weight:600;letter-spacing:-.025em;overflow-wrap:anywhere}h2{font-size:1.1rem;line-height:1.4}h3{font-size:.98rem} +p{line-height:1.6;max-width:76ch;overflow-wrap:anywhere}code,pre,.source-path{font-family:var(--code)}code{font-size:.86em;overflow-wrap:anywhere} +pre{white-space:pre-wrap;overflow-wrap:anywhere;font-size:.8rem;line-height:1.7}summary{cursor:pointer}details>summary{padding:.45rem 0}details[open]>summary{margin-bottom:.5rem} +dl{margin:.6rem 0}dt{font-weight:600;font-size:.85rem;margin-top:.7rem}dd{margin:.2rem 0;line-height:1.55;overflow-wrap:anywhere} +table{border-collapse:collapse;width:100%;font-size:.84rem}th,td{text-align:left;padding:.6rem .5rem;vertical-align:top;border-bottom:1px solid var(--line)}th{font-weight:600} +ul{padding-left:1.25rem;line-height:1.7}footer{padding:1.1rem 1.5rem;font-size:.78rem;color:var(--muted);border-top:1px solid var(--line)} +.skip{position:absolute;left:1rem;top:-5rem;z-index:9;padding:.6rem;background:var(--paper)}.skip:focus{top:.6rem} +.report-header{display:flex;align-items:center;justify-content:space-between;gap:1.5rem;padding:1.15rem 1.5rem;background:var(--paper);border-bottom:1px solid var(--line)} +.identity{display:flex;align-items:center;gap:1.2rem;min-width:0}.identity>div{min-width:0}.atomic-logo{display:block;width:140px;height:40px;object-fit:contain;flex:none} +#report-scope{color:var(--muted);font-size:.8rem;margin-top:.2rem;overflow-wrap:anywhere}.report-actions{display:flex;align-items:center;gap:1rem;flex:none} +.scope-details{position:relative;font-size:.85rem}.scope-details[open]>div{position:absolute;right:0;top:2rem;width:min(600px,90vw);max-height:70vh;overflow:auto;padding:1.2rem;background:var(--paper);border:1px solid var(--line);box-shadow:0 12px 35px #0008;z-index:8} +.pass-tabs{display:flex;gap:.3rem;padding:.65rem 1.5rem 0;background:var(--paper);border-bottom:1px solid var(--line)} +.pass-tabs>button{display:flex;gap:.65rem;align-items:center;border:0;border-bottom:3px solid transparent;border-radius:0;padding:.7rem .9rem;color:var(--muted);background:transparent} +.pass-tabs>button[aria-selected=true]{border-bottom-color:var(--accent);color:var(--accent);font-weight:600}.pass-tabs span{font-size:.76rem;font-weight:500} +.toolbar{display:flex;align-items:center;gap:1.5rem;flex-wrap:wrap;padding:.8rem 1.5rem;font-size:.82rem;border-bottom:1px solid var(--line)} +.toolbar label{display:flex;align-items:center;gap:.6rem}.toolbar input{padding:.45rem .65rem;width:min(32vw,340px)}.toolbar select{padding:.45rem}.toolbar #result-count{margin-left:auto;color:var(--muted)} +#workspace{display:grid;grid-template-columns:260px minmax(0,1fr) 300px;min-height:calc(100vh - 240px)} +#workspace[data-summary=true]{grid-template-columns:minmax(0,1fr);min-height:calc(100vh - 200px)} +#panel-summary{max-width:1100px}#panel-summary>h2{margin-bottom:.8rem}.summary-actions{display:flex;gap:.6rem;flex-wrap:wrap;margin:0 0 1.6rem}.summary-actions button{font-size:.85rem} +.file-navigation{padding:1rem .7rem;min-width:0;border-right:1px solid var(--line);background:var(--canvas)}.file-navigation>h2{padding:0 .5rem .8rem;font-size:.9rem;color:var(--muted)} +.file-group{margin-bottom:.7rem}.file-title{font-size:.78rem;line-height:1.5;overflow-wrap:anywhere;padding:.55rem .5rem;color:var(--muted)} +.region-button{display:block;width:100%;text-align:left;border-color:transparent;border-radius:4px;margin:.15rem 0;padding:.65rem .6rem;background:transparent;font-size:.8rem} +.region-button[aria-current=true]{background:var(--raised);border-color:var(--line);border-left:3px solid var(--accent)}.region-button strong{display:block;font-weight:600;overflow-wrap:anywhere}.region-button small{display:block;margin-top:.2rem;color:var(--muted);line-height:1.5} +.intent-group{margin-bottom:.9rem}.intent-button .intent-name{display:block;margin-top:.25rem;line-height:1.5;overflow-wrap:anywhere}.intent-button[data-active=true] strong{color:var(--accent)}.intent-criteria{margin-left:.55rem;padding-left:.4rem;border-left:1px solid var(--line)}.intent-criteria:empty{display:none}.criterion-button{font-size:.76rem} +@media(max-width:700px){.file-navigation{overflow:auto}} +.review-content{padding:1.4rem 1.6rem;min-width:0;background:var(--paper)}.card-inspector{padding:1.2rem;border-left:1px solid var(--line);min-width:0} +.card-inspector>label{font-size:.8rem;color:var(--muted)}#card-picker{width:100%;padding:.5rem;margin:.35rem 0 1.2rem;font-size:.8rem} +#card-content{font-size:.85rem}#card-content h2{margin-bottom:.65rem}#card-content p{margin:.5rem 0}#card-content .card-id{color:var(--accent);font-size:.73rem;margin-bottom:.6rem}#card-content dl dd{color:var(--muted)} +.overview{padding:0 0 1.2rem;margin-bottom:1.3rem;border-bottom:1px solid var(--line)}.overview p{font-size:.85rem;color:var(--muted);margin:.55rem 0}.overview .outcome{font-size:1.35rem;letter-spacing:-.02em}.overview>.coverage{margin-bottom:0}.overview>h2{margin-bottom:.6rem} +.region-heading{display:flex;gap:.7rem;flex-wrap:wrap;align-items:baseline;margin-bottom:.4rem}.source-path{font-size:.85rem;overflow-wrap:anywhere}.region-meta{font-size:.78rem;color:var(--muted);margin:.3rem 0 .9rem} +.finding{padding:.85rem 0;border-bottom:1px solid var(--line)}.finding h3{display:flex;gap:.5rem;align-items:baseline;line-height:1.6;flex-wrap:wrap}.finding p{font-size:.88rem;margin-top:.5rem}.finding .finding-number{color:var(--accent);font-size:.85rem;flex:none} +.badge{display:inline-block;font-size:.72rem;line-height:1.4;border:1px solid var(--line);padding:.12rem .4rem;border-radius:4px;white-space:nowrap} +.badge.low,.badge.met,.badge.existing{color:var(--ink);background:#23143e}.badge.medium,.badge.blocked,.badge.unknown,.badge.pending,.badge.changed{color:var(--amber);background:#34251b;border-color:#765132} +.badge.high,.badge.critical,.badge.unmet{color:var(--danger);background:#2c1028;border-color:#8c2558}.badge.new,.badge.resolved{color:var(--green);background:#0b2820;border-color:#265d4a} +.callouts{display:flex;gap:.4rem;flex-wrap:wrap;margin:.65rem 0}.card-callout{font-size:.76rem;color:var(--accent);background:var(--raised);border-color:var(--line);text-align:left;overflow-wrap:anywhere} +.evidence{margin:.7rem 0;font-size:.82rem}.evidence pre{background:var(--canvas);padding:.8rem;border-radius:4px;margin:.5rem 0}.evidence p{font-size:.8rem;color:var(--muted)} +.metrics-block{margin:1.2rem 0;overflow-x:auto}.metrics-block h3{margin-bottom:.5rem}.metric-value{white-space:nowrap}.unknown-text{color:var(--muted);font-size:.78rem} +.source-toolbar{display:flex;align-items:center;gap:.4rem;flex-wrap:wrap;margin:1.4rem 0 .6rem;font-size:.8rem}.source-toolbar button[aria-pressed=true]{background:var(--accent);border-color:var(--accent);color:var(--canvas);font-weight:600}.source-toolbar .source-note{color:var(--muted);margin-left:auto;font-size:.75rem} +.source-code{overflow:auto;border:1px solid var(--line);border-radius:5px;background:var(--canvas);max-height:650px;padding:.5rem 0;line-height:1.7}.source-line{display:flex;min-width:max-content;font-family:var(--code);font-size:.76rem;min-height:1.7em}.source-line.highlight{background:#28194d} +.line-number{display:inline-block;position:sticky;left:0;text-align:right;padding:0 .75rem;width:4.4rem;color:var(--muted);background:inherit;user-select:none;flex:none}.line-text{white-space:pre;padding-right:1rem}.source-caption{font-size:.75rem;color:var(--muted);margin:.45rem 0} +.empty{padding:1.2rem 0;color:var(--muted);line-height:1.7}.empty button{display:block;margin-top:.8rem}.criterion{padding:1rem 0;border-bottom:1px solid var(--line)}.criterion .criterion-title{display:flex;gap:.6rem;align-items:center;flex-wrap:wrap}.criterion p{font-size:.9rem;margin-top:.6rem}.criterion small{display:block;color:var(--muted);margin:.5rem 0;overflow-wrap:anywhere} +.risk-rule{padding:.65rem 0;border-bottom:1px solid var(--line);font-size:.87rem;line-height:1.6}.risk-rule code{display:block;color:var(--accent);margin:.2rem 0}.coverage{font-size:.8rem;margin:.7rem 0}.coverage>div{overflow:auto} +.impact-reference{padding:.7rem 0;border-bottom:1px solid var(--line);font-size:.82rem}.impact-reference p{font-size:.82rem;overflow-wrap:anywhere}.impact-reference code{font-size:.78rem}.muted{color:var(--muted)} +.card-coverage{overflow-x:auto}.card-coverage section+section{margin-top:1rem}.card-coverage .card-callout{text-align:left;white-space:normal} +#file-drawer>summary{display:none}#file-drawer>summary:focus-visible{outline:3px solid var(--accent)} +.comparison-direction{display:grid;grid-template-columns:1fr auto 1fr;gap:1rem;align-items:center;padding:.9rem 0;border-top:1px solid var(--line);border-bottom:1px solid var(--line);margin:.8rem 0} +.comparison-direction strong{display:block;overflow-wrap:anywhere}.comparison-direction small{display:block;color:var(--muted);font-size:.75rem;overflow-wrap:anywhere}.comparison-direction .direction-arrow{color:var(--accent);font-size:1.35rem}.file-comparisons{overflow-x:auto} +@media(min-width:1500px){#workspace{grid-template-columns:290px minmax(0,1fr) 340px}.review-content{padding:1.7rem 2.2rem}.card-inspector{padding:1.5rem}} +@media(max-width:1120px){#workspace{grid-template-columns:230px minmax(0,1fr)}.card-inspector{grid-column:1/-1;border-left:0;border-top:1px solid var(--line);display:grid;grid-template-columns:220px 1fr;column-gap:1.5rem}.card-inspector>label,.card-inspector>select{grid-column:1}.card-inspector>div{grid-column:2;grid-row:1/4}.report-actions{gap:.6rem}} +@media(max-width:700px){.report-header{padding:1rem;align-items:flex-start}.identity{gap:.55rem;flex-direction:column;align-items:flex-start}.atomic-logo{width:112px;height:32px}.report-actions{flex-direction:column;align-items:flex-end;font-size:.75rem}.report-actions>button{font-size:.75rem}h1{font-size:1.1rem}.pass-tabs{padding:0 .5rem;gap:0}.pass-tabs>button{font-size:.85rem;padding:.75rem .6rem;display:block}.pass-tabs span{display:block;margin-top:.2rem}.toolbar{gap:.7rem;padding:.7rem 1rem}.toolbar .search-label{width:100%;display:block}.toolbar input{display:block;width:100%;margin-top:.3rem}#workspace{display:block}.file-navigation{border-right:0;border-bottom:1px solid var(--line);max-height:270px;padding:.7rem}.file-navigation>h2{padding-bottom:.5rem;font-size:.78rem}.review-content{padding:1.1rem 1rem}.card-inspector{display:block;padding:1rem}.source-path{font-size:.77rem}.scope-details[open]>div{right:0;max-width:85vw}table{font-size:.75rem}th,td{padding:.5rem .25rem}.line-number{width:3.2rem;padding:0 .4rem}.source-line{font-size:.7rem}footer{padding:1rem}.region-meta{overflow-wrap:anywhere}.scope-state{display:none}#file-drawer>summary{display:block;padding:.45rem .5rem;border:1px solid var(--line);border-radius:4px;background:var(--paper);font-size:.8rem}#file-drawer>summary::before{content:'▸ ';color:var(--accent)}#file-drawer[open]>summary::before{content:'▾ '}.comparison-direction{grid-template-columns:1fr;gap:.5rem}.comparison-direction .direction-arrow{display:none}} +@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important}} +@media print{:root{color-scheme:light;--canvas:#fff;--paper:#fff;--ink:#1b1833;--muted:#514c63;--line:#b9b1c9;--accent:#8c0051}.pass-tabs,.toolbar,.report-actions,.file-navigation,.card-inspector{display:none}.atomic-logo{background:#07041a;padding:.25rem}#workspace{display:block}.source-code{max-height:none;overflow:visible}.review-content{padding:0}footer{margin-top:1rem}} diff --git a/atomic-cli/src/commands/review/viewer.html b/atomic-cli/src/commands/review/viewer.html new file mode 100644 index 00000000..8038874a --- /dev/null +++ b/atomic-cli/src/commands/review/viewer.html @@ -0,0 +1,38 @@ + + + + + + +Atomic review + + + + +
+

Atomic review

+
Scope & provenance
+
+ + +
+ +
+

Review summary

+ + + +
+ +
+
Local-only semantic audit and metrics. No model calls or network requests. Findings, metric observations and estimated risk are distinct. This report is not independent signed approval.
+ + + + + diff --git a/atomic-cli/src/commands/review/viewer.js b/atomic-cli/src/commands/review/viewer.js new file mode 100644 index 00000000..d681aaea --- /dev/null +++ b/atomic-cli/src/commands/review/viewer.js @@ -0,0 +1,702 @@ +(() => { + 'use strict'; + const data = JSON.parse(document.getElementById('review-data').textContent); + const report = data.view; + const graph = report.graph; + const viewSnapshot = report.view_snapshot; + const viewComparison = report.view_comparison; + const viewConformance = viewComparison?.conformance || viewSnapshot?.conformance; + const comparedFiles = new Map((viewComparison?.files || []).map(file=>[file.source_ref,file])); + const regions = data.regions; + const byId = new Map(graph.nodes.map(node => [node.id, node])); + const findings = new Map(graph.findings.map(finding => [finding.number, finding])); + const snapshots = new Map(data.sources.map(source => [source.change + '\0' + source.path, source])); + const passes = new Map(graph.passes.map(pass => [pass.pass, pass])); + const metricId = node => 'metric.' + node.properties.observation.metric.replaceAll('_', '-'); + const metricCards = new Map(data.metric_cards.map(card => ['metric.' + card.metric.replaceAll('_', '-'), card])); + const auditCards = new Map(data.audit_cards.map(card => [card.id, card])); + const risk = graph.risk; + const riskRules = new Map((risk?.model?.rules || []).map(rule => [rule.id, rule])); + const sections = ['summary', 'slop', 'conformance', 'risk']; + const rememberedRegions = { slop: null, risk: null }; + const state = { pass: 'summary', region: null, intent: null, criterion: null, criterionRegion: null, query: '', filter: viewSnapshot ? 'all' : 'concerns' }; + const criterionFindings=new Map(); + for(const finding of graph.findings)for(const id of finding.related_criteria) { + if(!criterionFindings.has(id))criterionFindings.set(id,new Set()); + criterionFindings.get(id).add(finding.number); + } + const intentCatalog = new Map((viewConformance?.intents || []).map(intent=>[intent.id,{...intent,scoped:true,criteria:[]}])); + for(const criterion of graph.criteria) { + if(!intentCatalog.has(criterion.intent)) { + const linked=(viewConformance?.changes || []).flatMap(change=>change.intent_context.plans || []).map(plan=>plan.intent).find(intent=>intent && (criterion.intent===intent.id || criterion.intent.endsWith(':'+intent.uid))); + intentCatalog.set(criterion.intent,{id:criterion.intent,human_key:linked?.id || criterion.intent,title:linked?.title || 'Change-linked intent',status:'',view:null,scoped:false,criteria:[]}); + } + intentCatalog.get(criterion.intent).criteria.push({...criterion,navigation_findings:[...new Set([...criterion.findings,...(criterionFindings.get(criterion.id) || [])])]}); + } + const $ = id => document.getElementById(id); + const el = (tag, className, text) => { + const node = document.createElement(tag); + if (className) node.className = className; + if (text !== undefined && text !== null) node.textContent = String(text); + return node; + }; + const button = (text, action, className = '') => { + const node = el('button', className, text); + node.type = 'button'; + node.addEventListener('click', action); + return node; + }; + const title = text => String(text || '').replaceAll('_', ' ').replace(/^./, c => c.toUpperCase()); + const shown = value => value === null || value === undefined ? 'unavailable' : String(value); + const badge = (text, value = text) => el('span', 'badge ' + String(value).toLowerCase().replace(/[^a-z]/g, ''), text); + const detail = (label, content) => { + const node = el('details', 'coverage'); + node.append(el('summary', '', label), content); + return node; + }; + const definition = (entries) => { + const list = el('dl'); + for (const [name, value] of entries) list.append(el('dt', '', name), el('dd', '', value)); + return list; + }; + const cardCallout = (id, text) => button(text || id, () => showCard(id, true), 'card-callout'); + const location = region => region.start_line ? `Lines ${region.start_line}–${region.end_line} · ${viewSnapshot ? 'snapshot' : region.side}` : 'File-level observation · range unavailable'; + const regionName = region => { + const subjects = region.subjects.filter(subject => subject !== region.path); + return subjects.length > 1 ? subjects.length + ' source subjects' : subjects[0] || 'File-level facts'; + }; + const inPass = (finding, pass) => finding.passes.includes(pass === 'slop' ? 'anti_slop' : pass === 'risk' ? 'blast_radius_risk' : 'intent_conformance'); + const regionFindings = region => region.findings.map(number => findings.get(number)).filter(Boolean); + const numberText = region => region.findings.map(number => 'F' + number).join(', '); + const changes = new Map(report.changes.map(change => [change.hash, change])); + + function describeValue(value) { + if (value.status === 'measured') return shown(value.value); + return value.status === 'not_applicable' ? 'N/A' : 'Unavailable'; + } + function isAbsent(value) { + return value.status === 'not_applicable' && ['File is absent in this revision', 'Subject is not present in this revision'].includes(value.reason); + } + function changeText(node) { + if (viewSnapshot) return 'Snapshot value; no comparison'; + const observation = node.properties.observation; + if (typeof node.properties.delta === 'number') return (node.properties.delta > 0 ? '+' : '') + node.properties.delta; + if (isAbsent(observation.before) && observation.after.status === 'measured') return 'New subject'; + if (isAbsent(observation.after) && observation.before.status === 'measured') return 'Removed subject'; + return 'Not comparable'; + } + function changed(node) { + if (!node) return false; + const value = node.properties.observation; + return typeof node.properties.delta === 'number' ? node.properties.delta !== 0 : + (isAbsent(value.before) && value.after.status === 'measured') || (isAbsent(value.after) && value.before.status === 'measured'); + } + + function showCard(id, focus = false) { + if (state.pass === 'summary') activate(riskRules.has(id) ? 'risk' : 'slop'); + const host = $('card-content'); + host.replaceChildren(); + if (!Array.from($('card-picker').options).some(option => option.value === id)) { + const option = el('option', '', id); + option.value = id; + $('card-picker').append(option); + } + $('card-picker').value = id; + const audit = auditCards.get(id), metric = metricCards.get(id), rule = riskRules.get(id); + const heading = el('h2', '', audit?.title || metric?.title || (rule ? 'Change-risk rule' : 'Engineering rule')); + heading.tabIndex = -1; + host.append(el('p', 'card-id', id), heading); + if (audit) { + host.append(el('p', '', audit.question), definition([ + ['Supported patterns', data.patterns[id] || 'See the finding evidence'], + ['Evidence to inspect', audit.evidence], ['Exceptions and limits', audit.exceptions] + ])); + const checks = graph.nodes.filter(node => node.kind === 'check' && node.properties.rule === id); + const count = status => checks.filter(node => node.properties.status === status).length; + host.append(el('p', 'muted', `${count('completed')} completed · ${count('skipped')} skipped · ${count('error')} errors`)); + host.append(detail('Exact check coverage', el('pre', '', checks.map(node => `${node.properties.path}: ${node.properties.status}\n${node.properties.detail}`).join('\n\n')))); + } else if (metric) { + host.append(definition([ + ['Definition', metric.definition], ['Scope and unit', `${metric.scope} · ${metric.unit}`], + ['How to interpret it', metric.interpretation], ['Exceptions', metric.exceptions] + ])); + const nodes = graph.nodes.filter(node => node.kind === 'metric' && metricId(node) === id); + const measured = nodes.filter(node => ['before', 'after'].some(side => node.properties.observation[side].status === 'measured')).length; + host.append(el('p', 'muted', `${nodes.length} observations; ${measured} have a numeric value. These are measurements, not findings.`)); + const conventions = [...new Set(nodes.map(node => node.properties.convention).filter(Boolean))]; + host.append(el('p', 'muted', `Counting convention: ${conventions.join(', ') || 'not reported'}. Unavailable values are never zero baselines.`)); + const samples = nodes.map(node => { + const item = node.properties, sample = item.observation; + const value = side => describeValue(sample[side]) + (sample[side].reason ? ' — ' + sample[side].reason : ''); + const location = side => item[side + '_location'] ? `${item[side + '_location'].start_line}–${item[side + '_location'].end_line}` : 'no recorded range'; + return viewSnapshot ? `${viewSnapshot.view} @ ${viewSnapshot.state} · ${item.path}\n${sample.subject}\nSnapshot (${location('after')}): ${value('after')}` : `${item.change} · ${item.path}\n${sample.subject}\nBefore (${location('before')}): ${value('before')}\nAfter (${location('after')}): ${value('after')}\n${changeText(node)}`; + }); + host.append(detail('All recorded observations', el('pre', '', samples.join('\n\n') || 'No recorded observations for this metric in the selected scope.'))); + } else if (rule) { + host.append(badge(title(rule.level), rule.level), el('p', '', rule.reason)); + host.append(el('p', 'muted', `${risk.model.model}: Atomic review-priority policy, not defect probability or a confirmed bug.`)); + host.append(detail('Expanded threshold profile', el('pre', '', data.profile_json || 'Profile not exported'))); + host.append(detail('Recorded references', el('pre', '', rule.references.join('\n')))); + } else { + const finding = graph.findings.find(item => item.finding.requirement_or_rule.id === id); + host.append(el('p', '', finding?.finding.requirement_or_rule.explanation || 'No definition was supplied for this rule.')); + } + if (focus) heading.focus(); + } + + function findingBlock(number) { + const item = findings.get(number), finding = item.finding; + const host = el('article', 'finding'); + host.dataset.finding=String(number); + const heading = el('h3'); + heading.append(el('span', 'finding-number', 'F' + number), el('span', '', finding.summary), badge(title(finding.severity), finding.severity)); + if (item.comparison) heading.append(badge(title(item.comparison.status),item.comparison.status)); + host.append(heading); + const links = el('div', 'callouts'); + links.append(cardCallout(finding.requirement_or_rule.id, 'Audit: ' + (auditCards.get(finding.requirement_or_rule.id)?.title || finding.requirement_or_rule.id))); + host.append(links, el('p', 'region-meta', viewComparison ? `Confidence: ${title(finding.confidence)} · ${title(item.comparison?.status || 'unknown')} local observation between the selected views` : `Confidence: ${title(finding.confidence)} · Introduced by this change: ${finding.introduced_by_change.status}`)); + const evidence = el('div', 'evidence'); + if (item.comparison) evidence.append(el('p','',item.comparison.rationale)); + evidence.append(el('p', '', finding.introduced_by_change.rationale)); + for (const entry of finding.evidence) { + evidence.append(el('p', 'source-path', entry.reference), el('pre', '', entry.observation)); + } + evidence.append(el('h3', '', 'Proposed correction'), el('p', '', finding.proposed_correction)); + for (const criterion of finding.acceptance_criteria || []) evidence.append(el('p', '', `${criterion.criterion}: ${criterion.assessment} — ${criterion.rationale}`)); + if (!(finding.acceptance_criteria || []).length) evidence.append(el('p', 'muted', 'Engineering-rule concern; no unmet acceptance criterion was inferred.')); + host.append(detail('Evidence, attribution & correction', evidence)); + return host; + } + + function metricTable(region) { + const host = el('section', 'metrics-block'); + const own = region.metrics.length ? region.metrics : region.context_metrics; + if (!own.length) return host; + host.append(el('h3', '', region.metrics.length ? 'Region measurements' : 'Enclosing function measurements')); + const table = el('table'); + const head = el('thead'), row = el('tr'); + for (const name of viewSnapshot ? ['Metric card', 'Snapshot value'] : ['Metric card', 'Before', 'After', 'Change']) { const cell = el('th', '', name); cell.scope = 'col'; row.append(cell); } + head.append(row); table.append(head); + let body = el('tbody'); + const nodes = own.map(id => byId.get(id)).filter(Boolean).sort((left, right) => + left.properties.observation.subject.localeCompare(right.properties.observation.subject) || metricId(left).localeCompare(metricId(right))); + const subjects = new Set(nodes.map(node => node.properties.observation.subject)); + let previousSubject = null; + for (const node of nodes) { + if (subjects.size > 1 && node.properties.observation.subject !== previousSubject) { + if (body.childElementCount) table.append(body); + body = el('tbody'); + const group = el('tr'), heading = el('th', '', node.properties.observation.subject); + heading.colSpan = viewSnapshot ? 2 : 4; heading.scope = 'rowgroup'; group.append(heading); body.append(group); + previousSubject = node.properties.observation.subject; + } + const metric = metricId(node), observation = node.properties.observation; + const row = el('tr'), label = el('td'); + label.append(cardCallout(metric, metricCards.get(metric)?.title || metric)); + row.append(label); + for (const side of viewSnapshot ? ['after'] : ['before', 'after']) { + const sample = observation[side], cell = el('td', 'metric-value'); + cell.append(el('span', '', describeValue(sample))); + if (sample.reason) cell.append(detail('Reason', el('p', 'unknown-text', sample.reason))); + row.append(cell); + } + if (!viewSnapshot) row.append(el('td', '', changeText(node))); + body.append(row); + } + table.append(body); host.append(table); + return host; + } + + function counterpart(region, side) { + if (side === region.side) return { start: region.start_line, end: region.end_line, note: region.start_line ? 'Selected recorded region' : 'File-level context; no source range was reported' }; + if (viewComparison) { + for (const item of regionFindings(region)) { + const location=item.comparison?.[side]?.[0]; + if (location) return {start:location.start_line,end:location.end_line,note:'Matched local observation in the other recorded view'}; + } + } + for (const id of [...region.metrics, ...region.context_metrics]) { + const node = byId.get(id), value = node?.properties.observation; + const location = node?.properties[side + '_location']; + if (location && value.before.status === 'measured' && value.after.status === 'measured') { + return { start: location.start_line, end: location.end_line, note: region.metrics.length ? 'Matched recorded subject' : 'Matched enclosing function; not an exact branch mapping' }; + } + } + for (const impact of region.impact) { + if (impact.kind === 'changed_function' && impact.function[side]) { + return { start: impact.function[side].start_line, end: impact.function[side].end_line, note: 'Matched function from recorded impact analysis' }; + } + } + return { start: null, end: null, note: 'Opposite revision; no reliable matching region was established' }; + } + + function sourceViewer(region) { + const host = el('section'); + const toolbar = el('div', 'source-toolbar'), body = el('div'), caption = el('p', 'source-caption'); + let side = region.side, full = false; + const before = button('Before', () => { side = 'before'; full = false; update(); }); + const after = button('After', () => { side = 'after'; full = false; update(); }); + const diff = button('Recorded change diff', () => { side = 'diff'; update(); }); + const expand = button('Show full file', () => { full = !full; update(); }); + if (viewSnapshot) { before.hidden = true; diff.hidden = true; after.textContent = 'View snapshot'; side = 'after'; } + if (viewComparison) { diff.hidden=true;before.textContent='Before: '+viewComparison.from.view;after.textContent='After: '+viewComparison.to.view; } + toolbar.append(before, after, diff, expand); + host.append(toolbar, body, caption); + function update() { + before.setAttribute('aria-pressed', String(side === 'before')); + after.setAttribute('aria-pressed', String(side === 'after')); + diff.setAttribute('aria-pressed', String(side === 'diff')); + body.replaceChildren(); + expand.hidden = side === 'diff'; + if (side === 'diff') { + const change = changes.get(region.change); + body.append(el('pre', 'source-code', change?.diff ? change.diff.replace(/\x1b\[[0-9;]*m/g, '') : 'Recorded diff unavailable: ' + (change?.diff_status || 'not supplied'))); + caption.textContent = 'Entire selected change diff, not limited to this region. Unchanged caller context may have no hunk.'; + return; + } + const snapshot = snapshots.get(region.change + '\0' + region.path); + const source = snapshot?.[side]; + if (!source || source.status !== 'present') { + body.append(el('p', 'empty', source?.status === 'absent' ? 'This file is absent in this recorded revision.' : source?.reason || 'Recorded source was not exported. No working-copy bytes are substituted.')); + expand.hidden = true; + caption.textContent = viewComparison ? `${side==='before'?'Before':'After'} view ${viewComparison[side==='before'?'from':'to'].view}` : viewSnapshot ? `Recorded view ${viewSnapshot.view} @ ${viewSnapshot.state}` : `${side} snapshot · change ${region.change}`; + return; + } + const range = counterpart(region, side); + const lines = source.text.split('\n'); + const start = full || !range.start ? 1 : Math.max(1, range.start - 6); + const end = full ? lines.length : Math.min(lines.length, Math.max(start + 30, Math.min((range.end || start) + 6, start + 399))); + const code = el('div', 'source-code'); + code.setAttribute('aria-label', `${side} recorded source, lines ${start} through ${end}`); + for (let i = start; i <= end; i++) { + const line = el('div', 'source-line' + (range.start && i >= range.start && i <= range.end ? ' highlight' : '')); + const number = el('span', 'line-number', i); number.setAttribute('aria-hidden', 'true'); + line.append(number, el('span', 'line-text', lines[i - 1] || ' ')); code.append(line); + } + body.append(code); + expand.textContent = full ? 'Show region context' : 'Show full file'; + const compared=comparedFiles.get(region.change), pin=viewComparison?.[side==='before'?'from':'to']; + caption.textContent = viewComparison ? `${side==='before'?'Before':'After'} ${pin.view}: ${compared?.[side+'_path'] || region.path}, lines ${start}–${end} of ${lines.length}. State ${pin.state}. ${range.note}.` : viewSnapshot ? `Recorded view ${viewSnapshot.view}: lines ${start}–${end} of ${lines.length}. State ${viewSnapshot.state}. No working-copy bytes or before revision.` : `Recorded ${side}: lines ${start}–${end} of ${lines.length}. ${range.note}. ${snapshot.reviewed_root ? 'Selected source file.' : 'Caller context only, not an additional reviewed root.'}`; + } + update(); + return host; + } + + function impactEvidence(region) { + const host = el('section'); + for (const item of region.impact) { + const row = el('article', 'impact-reference'); + if (item.kind === 'changed_function') { + row.append(el('h3', '', title(item.function.change) + ' function'), el('code', '', item.function.id)); + row.append(el('p', '', item.function.signature_changed ? 'Declared signature changed.' : 'No declared signature change recorded.')); + } else { + const call = item.call; + row.append(el('h3', '', title(item.kind)), el('code', '', call.caller + ' → ' + call.callee)); + const binding = call.target_present ? (call.visibility_compatible ? 'Bound direct source reference' : 'Access-incompatible reference') : 'Reference to a removed target'; + row.append(el('p', '', `${binding}. ${call.binding}.`)); + row.append(el('p', 'muted', `${call.location.path}:${call.location.start_line} · declaration ${call.declaration.path}:${call.declaration.start_line}`)); + if (call.configuration_dependent) row.append(el('p', 'muted', 'Configuration-dependent source evidence; active compiler configuration is not established.')); + } + host.append(row); + } + return host; + } + + function selection(region, pass) { + const host = el('div'); + host.append(el('h2', 'source-path', region.path), el('p', 'region-meta', `${location(region)} · ${regionName(region)} · ${viewComparison ? viewComparison.from.view+' → '+viewComparison.to.view : viewSnapshot ? 'view ' + viewSnapshot.view : 'change ' + region.change.slice(0, 12)}`)); + const relevant = regionFindings(region).filter(finding => inPass(finding, pass) && (pass !== 'slop' || lifecycleMatches(finding))); + for (const finding of relevant) host.append(findingBlock(finding.number)); + if (pass === 'risk') host.append(impactEvidence(region)); + const measurements = metricTable(region); + const metricCount = region.metrics.length || region.context_metrics.length; + if (metricCount) { + if (pass === 'slop' && state.filter !== 'concerns') host.append(measurements); + else host.append(detail(`${metricCount} measurements & metric cards`, measurements)); + } + host.append(sourceViewer(region)); + if (relevant.length) showCard(relevant[0].finding.requirement_or_rule.id); + return host; + } + + function lifecycleMatches(item) { + if (!viewComparison || !['new','existing','resolved','uncertain'].includes(state.filter)) return true; + return state.filter === 'uncertain' ? ['changed','unknown'].includes(item.comparison?.status) : item.comparison?.status === state.filter; + } + function eligible(region) { + if (state.pass === 'risk') return region.impact.length || regionFindings(region).some(finding => inPass(finding, 'risk')); + if (viewComparison && ['new','existing','resolved','uncertain'].includes(state.filter)) return regionFindings(region).some(lifecycleMatches); + if (state.filter === 'concerns') return regionFindings(region).some(finding => inPass(finding, 'slop')); + if (state.filter === 'changed') return region.metrics.some(id => changed(byId.get(id))); + return region.metrics.length > 0 || region.findings.length > 0; + } + function matches(region) { + if (!state.query) return true; + const metrics = [...region.metrics, ...region.context_metrics].map(id => byId.get(id)).filter(Boolean).map(node => metricId(node) + ' ' + (metricCards.get(metricId(node))?.title || '')); + const text = [region.path, ...region.subjects, ...metrics, numberText(region), ...regionFindings(region).map(item => item.finding.summary + ' ' + item.finding.requirement_or_rule.id), ...region.impact.map(item => item.function?.id || (item.call.caller + ' ' + item.call.callee))].join(' ').toLowerCase(); + return text.includes(state.query.toLowerCase()); + } + function renderNavigation() { + const host = $('files'); host.replaceChildren(); + if (state.pass === 'conformance') { + $('navigation-title').textContent = viewConformance?.scope ? 'View intents' : 'Intents and criteria'; + const query=state.query.toLowerCase(); + const groups=Array.from(intentCatalog.values()).map(intent=>{ + const ownMatch=!query || [intent.id,intent.human_key,intent.title,intent.status,intent.view].join(' ').toLowerCase().includes(query); + const criteria=intent.criteria.filter(item=>ownMatch || (item.text+' '+item.id+' '+item.navigation_findings.map(number=>'F'+number).join(' ')).toLowerCase().includes(query)); + return {...intent,criteria,visible:ownMatch || criteria.length>0}; + }).filter(intent=>intent.visible).sort((a,b)=>Number(b.scoped)-Number(a.scoped) || a.human_key.localeCompare(b.human_key,undefined,{numeric:true})); + const selected=groups.find(intent=>intent.id===state.intent) || groups.find(intent=>intent.criteria.some(item=>item.id===state.criterion)) || groups[0]; + state.intent=selected?.id || null; + if(!selected?.criteria.some(item=>item.id===state.criterion))state.criterion=selected?.criteria[0]?.id || null; + let contextHeading=false; + for (const intent of groups) { + if(viewConformance?.scope && !intent.scoped && !contextHeading) {host.append(el('h3','file-title','Change-linked context (not view assignment)'));contextHeading=true;} + const group=el('section','intent-group');group.dataset.intentGroup=intent.id; + const own=button('',()=>{state.intent=intent.id;state.criterion=intent.criteria[0]?.id || null;state.criterionRegion=null;closeMobileFiles();render();},'region-button intent-button'); + own.dataset.intent=intent.id;own.dataset.active=String(intent.id===state.intent); + own.setAttribute('aria-current',String(intent.id===state.intent && !state.criterion)); + own.append(el('strong','',intent.human_key),el('span','intent-name',intent.title),el('small','',`${intent.status || 'recorded context'} · ${intent.criteria.length} criteria${intent.scoped?' · view '+intent.view:' · change-linked only'}`)); + group.append(own); + const children=el('div','intent-criteria'); + for (const item of intent.criteria) { + const control = button('', () => { state.intent=intent.id;state.criterion = item.id; state.criterionRegion = null; closeMobileFiles(); render(); }, 'region-button criterion-button'); + control.dataset.criterion=item.id; + control.setAttribute('aria-current', String(item.id === state.criterion)); + control.append(el('strong', '', item.text), el('small', '', `Review: ${item.review_assessment} · ${item.navigation_findings.length} related findings`)); + children.append(control); + } + group.append(children);host.append(group); + } + if (!groups.length) host.append(el('p', 'empty', intentCatalog.size ? 'No intents or criteria match this search.' : viewConformance?.scope ? 'No intents scoped to view '+viewConformance.scope.view+'.' : 'No governing intents resolved.')); + const criteria=groups.reduce((count,intent)=>count+intent.criteria.length,0); + $('result-count').textContent = `${groups.length} intents · ${criteria} criteria`; + return; + } + $('navigation-title').textContent = 'Files & regions'; + const visible = regions.filter(region => eligible(region) && matches(region)); + if (!visible.some(region => region.id === state.region)) state.region = visible.find(region => region.findings.length)?.id || visible[0]?.id || null; + const files = new Map(); + for (const region of visible) { + const key = region.path + '\0' + region.change; + if (!files.has(key)) files.set(key, []); + files.get(key).push(region); + } + for (const items of files.values()) { + const group = el('div', 'file-group'); + const compared=comparedFiles.get(items[0].change); + group.append(el('h3', 'file-title', compared ? `${compared.before_path || '(absent)'} → ${compared.after_path || '(absent)'} · ${title(compared.status)}` : items[0].path + (report.selected_roots.length > 1 ? ' · ' + items[0].change.slice(0, 8) : ''))); + for (const region of items) { + const control = button('', () => { state.region = region.id; closeMobileFiles(); render(); }, 'region-button'); + control.dataset.region = region.id; + control.setAttribute('aria-current', String(region.id === state.region)); + control.append(el('strong', '', regionName(region)), el('small', '', location(region) + (region.findings.length ? ' · ' + numberText(region) : ''))); + group.append(control); + } + host.append(group); + } + if (!visible.length) host.append(el('p', 'empty', state.query ? 'No regions match this search.' : 'No regions in this view.')); + const fileLabel = report.selected_roots.length > 1 ? (files.size === 1 ? 'file snapshot' : 'file snapshots') : (files.size === 1 ? 'file' : 'files'); + $('result-count').textContent = `${files.size} ${fileLabel} · ${visible.length} ${visible.length === 1 ? 'region' : 'regions'}`; + } + + function renderAuditOverview() { + const pass = passes.get('anti_slop'); + const overview = $('audit-overview'); overview.replaceChildren(); overview.className = 'overview'; + const count = graph.findings.filter(finding => inPass(finding, 'slop')).length; + const resolved=graph.findings.filter(item=>inPass(item,'slop') && item.comparison?.status==='resolved').length; + overview.append(el('h2', '', viewComparison ? `${count-resolved} current audit observation(s) · ${resolved} resolved` : `${count} audit finding${count === 1 ? '' : 's'}`)); + if (viewComparison) overview.append(comparisonOverview()); + overview.append(el('p', 'region-meta', 'Local analysis: atomic-semantic + atomic-audit. No AI execution or network requests.')); + overview.append(cardCoverage()); + const checks = graph.nodes.filter(node => node.kind === 'check'); + const completed = checks.filter(node => node.properties.status === 'completed').length; + const skipped = checks.filter(node => node.properties.status === 'skipped').length; + const errors = checks.filter(node => node.properties.status === 'error').length; + const coverage = el('div'); coverage.append(el('p', '', pass.detail), el('pre', '', data.audit_cards.map(card => { + const own = checks.filter(node => node.properties.rule === card.id); + return `${card.title}\n${own.filter(node => node.properties.status === 'completed').length} completed; ${own.filter(node => node.properties.status === 'skipped').length} skipped; ${own.filter(node => node.properties.status === 'error').length} errors\n${data.patterns[card.id]}`; + }).join('\n\n'))); + overview.append(detail(`Audit coverage: ${completed} completed · ${skipped} skipped · ${errors} errors`, coverage)); + } + + function renderSlop() { + const pass = passes.get('anti_slop'); + const host = $('slop-selection'); host.replaceChildren(); + const region = regions.find(region => region.id === state.region); + if (region) host.append(selection(region, 'slop')); + else { + const empty = el('div', 'empty', state.query ? 'No matching source region. Clear the search to return to the review.' : pass.status === 'not_applicable' ? pass.detail : 'No numbered findings in this view. That does not establish a clean-code verdict.'); + empty.append(button('Browse changed metrics', () => { state.query = ''; $('search').value = ''; state.filter = 'changed'; $('region-filter').value = 'changed'; render(); })); + host.append(empty); + } + } + + function comparisonOverview() { + const host=el('div'), direction=el('div','comparison-direction'); + for (const [index,[label,pin]] of [['From · before',viewComparison.from],['To · after',viewComparison.to]].entries()) { + if (index) direction.append(el('span','direction-arrow','→')); + const side=el('div');side.append(el('small','',label),el('strong','',pin.view),el('small','',`state ${pin.state.slice(0,12)} · filter ${pin.membership_hash.slice(0,12)}`));direction.append(side); + } + host.append(direction); + const files=el('div','file-comparisons'), table=el('table'), head=el('thead'), heading=el('tr'),body=el('tbody'); + for (const title of ['File state','Before path','After path','Content']) { const th=el('th','',title);th.scope='col';heading.append(th); } + head.append(heading);table.append(head,body); + for (const file of viewComparison.files) { const row=el('tr');row.dataset.fileComparison=file.source_ref;row.append(el('td','',title(file.status)),el('td','source-path',file.before_path || '(absent)'),el('td','source-path',file.after_path || '(absent)'),el('td','',title(file.content_status)));body.append(row); } + files.append(table);host.append(detail(`Recorded file comparison (${viewComparison.files.length})`,files)); + host.append(el('p','muted','New/existing/resolved/changed/unknown describe local rule observations, not whole-program behavioral proof. Missing source coverage is never a resolution.')); + return host; + } + + function cardCoverage() { + const host = el('div', 'card-coverage'); + const table = (label, headings) => { + const section = el('section'); section.append(el('h3', '', label)); + const grid = el('table'), head = el('thead'), row = el('tr'), body = el('tbody'); + for (const heading of headings) { const cell = el('th', '', heading); cell.scope = 'col'; row.append(cell); } + head.append(row); grid.append(head, body); section.append(grid); host.append(section); + return body; + }; + const auditBody = table('Audit cards — local rule coverage', ['Card', 'Coverage', 'Checks', viewComparison ? 'New / existing / resolved / other' : 'Findings']); + for (const card of data.audit_cards) { + const checks = graph.nodes.filter(node => node.kind === 'check' && node.properties.rule === card.id); + const completed = checks.filter(node => node.properties.status === 'completed').length; + const skipped = checks.filter(node => node.properties.status === 'skipped').length; + const errors = checks.filter(node => node.properties.status === 'error').length; + const status = errors ? 'Error' : completed ? (skipped ? 'Partial' : 'Checked') : skipped ? 'Skipped' : 'Not evaluated'; + const findings = graph.findings.filter(item => item.finding.requirement_or_rule.id === card.id).length; + const row = el('tr'); row.dataset.cardId = card.id; row.dataset.kind = 'audit'; + const name = el('td'); name.append(cardCallout(card.id, card.title)); + const own=graph.findings.filter(item=>item.finding.requirement_or_rule.id===card.id); + const totals=viewComparison ? ['new','existing','resolved','other'].map(status=>own.filter(item=>status==='other' ? !['new','existing','resolved'].includes(item.comparison?.status) : item.comparison?.status===status).length).join(' / ') : String(findings); + row.append(name, el('td', '', status), el('td', '', `${completed} completed · ${skipped} skipped · ${errors} errors`), el('td', '', totals)); + auditBody.append(row); + } + const metricBody = table('Metric cards — all recorded observations', ['Card', 'Coverage', viewSnapshot ? 'Recorded snapshot' : 'Before / after', 'Observations']); + for (const [id, card] of metricCards) { + const nodes = graph.nodes.filter(node => node.kind === 'metric' && metricId(node) === id); + const sides = (viewSnapshot ? ['after'] : ['before', 'after']).map(side => { + const measured = nodes.filter(node => node.properties.observation[side]?.status === 'measured').length; + const absent = nodes.filter(node => node.properties.observation[side]?.status === 'not_applicable').length; + return { measured, absent, unavailable: nodes.length - measured - absent }; + }); + const measured = sides.some(side => side.measured), unavailable = sides.some(side => side.unavailable); + const status = !nodes.length ? 'Not evaluated' : unavailable ? (measured ? 'Partial' : 'Unavailable') : measured ? 'Measured' : 'Not applicable'; + const row = el('tr'); row.dataset.cardId = id; row.dataset.kind = 'metric'; + const name = el('td'); name.append(cardCallout(id, card.title)); + row.append(name, el('td', '', status), el('td', '', sides.map(side => `${side.measured} measured · ${side.absent} N/A · ${side.unavailable} unavailable`).join(' / ')), el('td', '', String(nodes.length))); + metricBody.append(row); + } + host.append(el('p', 'muted', 'Checked means the registered local rules ran, not that the code is defect-free. Unsupported and unavailable cases are never passing results. Counts cover the exact ' + (viewSnapshot ? 'recorded view snapshot.' : 'selected recorded changes.'))); + const panel = detail(`All cards: ${data.audit_cards.length} audits · ${data.metric_cards.length} metrics`, host); + panel.id = 'card-coverage'; + return panel; + } + + function renderConformanceOverview() { + const host = $('conformance-overview'); host.replaceChildren(); host.className = 'overview'; + const pass = passes.get('intent_conformance'); + const heading = el('h2', '', 'Intent conformance '); heading.append(badge(title(pass.status), pass.status)); + host.append(heading, el('p', 'region-meta', pass.detail), el('p', '', `${graph.criteria.length} scoped acceptance criterion/criteria`)); + if(viewConformance?.scope)host.append(el('p','',`${viewConformance.intents.length} intents explicitly scoped to view ${viewConformance.scope.view}. Scope assignment is not change governance or acceptance approval.`)); + if (viewComparison) { + const conformance=viewComparison.conformance; + const changes=conformance?.changes || []; + host.append(el('p','',`${changes.filter(change=>change.direction==='added_to_after').length} recorded change(s) added to To · ${changes.filter(change=>change.direction==='removed_from_after').length} removed from From · ${(conformance?.criteria || []).length} criterion/criteria in scope`)); + const evidence=el('div'); + for(const change of changes) evidence.append(el('p','',`${title(change.direction)} · ${change.hash} · governing intent: ${change.intent_context.status}`)); + for(const note of conformance?.diagnostics || []) evidence.append(el('p','muted',note)); + if(evidence.childElementCount)host.append(detail('Recorded membership and governance evidence',evidence)); + } + else if(viewConformance?.diagnostics.length)host.append(detail('View intent scope notes',el('pre','',viewConformance.diagnostics.join('\n')))); + } + + function renderCriteria() { + const host = $('criteria'); host.replaceChildren(); + const intent=intentCatalog.get(state.intent); + const criterion = graph.criteria.find(item => item.id === state.criterion); + if(intent) { + host.append(el(criterion?'p':'h2',criterion?'region-meta':'',`${intent.human_key} · ${intent.title}`)); + host.append(el('p','region-meta',intent.scoped?`View-scoped intent · ${intent.view} · ${intent.status} · ${intent.source_kind}`:'Recorded change-linked context; no explicit target-view assignment is implied.')); + if(intent.definition_error)host.append(el('p','empty',intent.definition_error)); + if(!criterion) {host.append(el('p','empty','No acceptance criteria are available for this scoped intent. Define criteria on the intent to review them here; no acceptance verdict is inferred.'));return;} + } + if (!criterion) { host.append(el('p', 'empty', 'No scoped criterion assessment is available. File overlap and author completion claims are not acceptance evidence.')); return; } + const article = el('article', 'criterion'), heading = el('div', 'criterion-title'); + heading.append(badge('Review: ' + title(criterion.review_assessment), criterion.review_assessment), badge('Author declared: ' + criterion.declared_status, 'declared')); + article.append(heading, el('h2', '', criterion.text), el('small', '', `Criterion ${criterion.id}`), el('small', '', `Intent ${criterion.intent}`)); + article.append(detail('Criteria source and authentication', el('pre', '', viewConformance ? `Definition hash: ${criterion.source_hash}\nRecorded view definitions are preferred; any current-vault fallback is labelled context only. Recorded author verification claims are not independently re-executed or authenticated acceptance proof.` : `Current source hash: ${criterion.source_hash}\nCurrent intent definitions are source-hashed context, not authenticated historical criteria. A report-local judgment is not independent signed approval.`))); + if(viewConformance) { + const compared=viewConformance.criteria.find(item=>item.id===criterion.id); + for(const [label,declaration] of [['From · before',compared?.before],[viewSnapshot?'Recorded view · '+viewSnapshot.view:'To · after',compared?.after],['Current vault · context only',compared?.current_context]]) { + if(!declaration)continue; + const section=el('section','criterion-declaration'); + section.append(el('h3','',label),el('p','',declaration.text),el('p','region-meta',`Author declared: ${declaration.status} · ${declaration.source_kind} · ${declaration.view || 'not a pinned historical view'} · ${declaration.path} · ${declaration.source_hash}`)); + if(declaration.verified_by || declaration.evidence)section.append(el('p','',`Declared verifier: ${declaration.verified_by || 'not supplied'} · Evidence claim (not executed): ${declaration.evidence || 'not supplied'}`)); + if(declaration.verifications?.length || declaration.required_kinds?.length)section.append(detail('Recorded verification claims — not independently authenticated or executed',el('pre','',JSON.stringify({required_kinds:declaration.required_kinds,verifications:declaration.verifications},null,2)))); + for(const task of declaration.tasks) { + section.append(el('p','',`Task ${task.id} · ${task.status}: ${task.text}`)); + const links=el('div','callouts'); + for(const file of task.files) { + const references=file.comparisons.flatMap(file=>regions.filter(region=>region.change===file.source_ref)); + if(!references.length)links.append(el('span','muted',`${file.path}: ${title(file.coverage)}`)); + else links.append(button(file.path+' · recorded file evidence',()=>{state.criterionRegion=references[0].id;renderCriteria();},'card-callout')); + } + section.append(links); + } + article.append(section); + } + } + host.append(article); + for (const number of criterion.findings) { + host.append(findingBlock(number)); + const links = el('div', 'callouts'); + for (const region of regions.filter(region => region.findings.includes(number))) links.append(button(region.path + ' · ' + location(region), () => { state.criterionRegion = region.id; renderCriteria(); }, 'card-callout')); + host.append(links); + } + if (!criterion.findings.length) host.append(el('p', 'empty', 'No numbered findings are mapped to this criterion. This is not an automatic passing assessment.')); + if(viewConformance) { + const related=graph.findings.filter(finding=>finding.related_criteria.includes(criterion.id) && !criterion.findings.includes(finding.number)); + if(related.length) { + const body=el('div');body.append(el('p','muted','Engineering findings in declared task files are review context, not inferred criterion failures.')); + for(const finding of related) body.append(findingBlock(finding.number)); + host.append(detail(`Related engineering findings (${related.length}) — not acceptance verdicts`,body)); + } + } + const source = regions.find(region => region.id === state.criterionRegion); + if (source) host.append(detail('Source-region measurements & cards', metricTable(source)), sourceViewer(source)); + } + + function renderRiskOverview() { + const host = $('risk-overview'); host.replaceChildren(); host.className = 'overview'; + if (!risk) { host.append(el('p', 'empty', 'No risk assessment was supplied for this scope.')); return; } + const assessment = risk.assessment; + const heading = el('h2', 'outcome'); heading.append(el('span', '', viewSnapshot ? 'Change risk not assessed — view snapshot' : assessment.rating === 'not_applicable' ? 'Code risk not applicable' : title(assessment.rating) + ' estimated review risk'), document.createTextNode(' '), badge(title(assessment.coverage) + ' coverage', assessment.coverage)); + host.append(heading, el('p', '', `Confidence: ${title(assessment.confidence)}. ${assessment.rationale}`)); + const rules = el('div'); + for (const rule of risk.model?.rules || []) { + const row = el('div', 'risk-rule'); row.append(badge(title(rule.level), rule.level), document.createTextNode(' ' + rule.reason), cardCallout(rule.id, rule.id)); + rules.append(row); + } + const lead = risk.model?.rules[0]; + if (lead) host.append(el('p', '', lead.reason)); + if (rules.childElementCount) host.append(detail(`Triggered risk rules (${rules.childElementCount})`, rules)); + const facts = risk.model?.facts; + if (facts) host.append(definition([ + ['Changed functions', `${shown(facts.production_functions)} production; ${shown(facts.test_support_functions)} test/support`], + ['Observed current bound consumers', `${shown(facts.observed_production_callers)} production; ${shown(facts.observed_test_support_callers)} test/support`], + ['Production consumers of modified existing declarations', shown(facts.existing_production_callers)], + ['Unresolved expressions', `${shown(facts.unresolved_references)} — excluded from bound-caller counts`] + ])); + const checks = risk.impact.reduce((count, report) => count + report.checked_call_contracts, 0); + host.append(el('p', 'muted', `${checks} source call-contract checks. Availability/access/arity checks do not prove type, runtime or executed-test correctness.`)); + host.append(detail(`Coverage limits (${assessment.limitations.length})`, el('pre', '', assessment.limitations.join('\n')))); + } + + function renderRisk() { + const selected = $('risk-selection'); selected.replaceChildren(); + const region = regions.find(region => region.id === state.region); + if (region) selected.append(selection(region, 'risk')); + else selected.append(el('p', 'empty', 'No located impact evidence in this selection. Missing or unresolved relationships are not fabricated callers.')); + } + + function renderSummary() { + const actions = $('summary-actions'); + for (const [section, label] of [['slop', 'Review audit findings'], ['conformance', 'Review conformance'], ['risk', 'Review blast radius']]) { + const control = button(label, () => { activate(section); $('tab-' + section).focus(); }); + control.dataset.section = section; actions.append(control); + } + // The report is immutable. Build report-wide tables once instead of + // rebuilding them whenever a different file or region is selected. + renderAuditOverview(); + renderConformanceOverview(); + renderRiskOverview(); + } + + function render() { + for (const name of sections) { + const active = state.pass === name; + $('tab-' + name).setAttribute('aria-selected', String(active)); + $('tab-' + name).tabIndex = active ? 0 : -1; + $('panel-' + name).hidden = !active; + } + const summary = state.pass === 'summary'; + $('workspace').dataset.summary = String(summary); + $('review-toolbar').hidden = summary; + $('file-navigation').hidden = summary; + $('card-inspector').hidden = summary; + if (summary) return; + $('region-filter').parentElement.hidden = state.pass !== 'slop'; + $('search-title').textContent = state.pass === 'conformance' ? 'Find an intent or criterion' : 'Find a file or region'; + $('search').placeholder = state.pass === 'conformance' ? 'Intent title, ID, criterion or F-number' : state.pass === 'risk' ? 'Caller, callee, file or F-number' : 'Path, function, metric, audit or F-number'; + $('file-navigation').setAttribute('aria-label',state.pass==='conformance'?'View intents and acceptance criteria':'Files and source regions'); + $('file-drawer-label').textContent=state.pass==='conformance'?'Choose an intent or criterion':'Choose a file or region'; + renderNavigation(); + if (state.pass === 'slop') renderSlop(); + else if (state.pass === 'conformance') renderCriteria(); + else renderRisk(); + } + const mobileFiles = matchMedia('(max-width:700px)'); + function closeMobileFiles() { if (mobileFiles.matches) $('file-drawer').open = false; } + function resizeNavigation() { $('file-drawer').open = !mobileFiles.matches; } + mobileFiles.addEventListener('change', resizeNavigation); + resizeNavigation(); + function activate(name) { + if (state.pass in rememberedRegions) rememberedRegions[state.pass] = state.region; + state.pass = name; state.region = rememberedRegions[name] || null; render(); window.scrollTo(0, 0); + } + for (const name of sections) $('tab-' + name).addEventListener('click', () => activate(name)); + document.querySelector('.pass-tabs').addEventListener('keydown', event => { + const index = sections.indexOf(state.pass); + const next = event.key === 'ArrowRight' ? (index + 1) % sections.length : event.key === 'ArrowLeft' ? (index + sections.length - 1) % sections.length : event.key === 'Home' ? 0 : event.key === 'End' ? sections.length - 1 : null; + if (next === null) return; + event.preventDefault(); activate(sections[next]); $('tab-' + sections[next]).focus(); + }); + $('search').addEventListener('input', event => { state.query = event.target.value; render(); }); + $('region-filter').addEventListener('change', event => { state.filter = event.target.value; state.region = null; render(); }); + $('card-picker').addEventListener('change', event => { if (event.target.value) showCard(event.target.value); }); + for (const [label, cards] of [['Audit cards', auditCards], ['Metric cards', metricCards], ['Triggered risk rules', riskRules]]) { + const group = el('optgroup'); group.label = label; + for (const [id, card] of cards) { const option = el('option', '', card.title || id); option.value = id; group.append(option); } + $('card-picker').append(group); + } + const root = viewComparison ? viewComparison.source_ref.split(':').pop() : viewSnapshot ? viewSnapshot.source_ref.split(':').pop() : report.selected_roots[0] || ''; + $('report-title').textContent = viewComparison ? viewComparison.from.view+' → '+viewComparison.to.view : viewSnapshot ? 'View review · ' + viewSnapshot.view : report.selected_roots.length === 1 ? 'Review ' + root.slice(0, 12) : `Review ${report.selected_roots.length} selected changes`; + if (viewComparison) for (const [value,label] of [['new','New audit findings'],['existing','Existing audit findings'],['resolved','Resolved audit findings'],['uncertain','Changed / unknown findings']]) { const option=el('option','',label);option.value=value;$('region-filter').append(option); } + if (viewSnapshot) { + $('region-filter').value = 'all'; + $('region-filter').querySelector('option[value="changed"]').disabled = true; + } + document.title = $('report-title').textContent + ' · Atomic'; + $('report-scope').append(document.createTextNode(graph.scope.view + ' · '), el('span', 'scope-state', `state ${graph.scope.view_state.slice(0, 12)} · `), document.createTextNode('not signed approval')); + if (viewSnapshot) $('report-scope').append(document.createTextNode(` · filter ${viewSnapshot.membership_hash.slice(0,12)} · ${viewSnapshot.file_count} live recorded paths`)); + const slopCount = graph.findings.filter(item => inPass(item, 'slop')).length; + $('slop-status').textContent = `${slopCount} ${slopCount === 1 ? 'finding' : 'findings'} · ${title(passes.get('anti_slop').status)}`; + $('conformance-status').textContent = title(passes.get('intent_conformance').status); + $('risk-status').textContent = risk ? `${title(risk.assessment.rating)} · ${title(risk.assessment.coverage)}` : 'Unavailable'; + $('provenance').append(el('h2', '', 'Recorded review scope'), el('pre', '', JSON.stringify(graph.scope, null, 2)), el('h3', '', 'Scope notes'), el('pre', '', [...graph.diagnostics, ...report.warnings].join('\n')), el('p', '', 'Additional source snapshots are bounded exports from this recorded scope. Working-copy bytes are never substituted. Keep this artifact private if its source/evidence is sensitive.')); + if (typeof DecompressionStream !== 'function') $('download').textContent = 'Download JSON.gz'; + $('download').addEventListener('click', async () => { + const control = $('download'), label = control.textContent; + control.disabled = true; control.textContent = 'Preparing JSON…'; + try { + const bytes = Uint8Array.from(atob(data.report_archive.data), character => character.charCodeAt(0)); + let blob = new Blob([bytes], { type: 'application/gzip' }), extension = '.json.gz'; + if (typeof DecompressionStream === 'function') { + blob = await new Response(blob.stream().pipeThrough(new DecompressionStream('gzip'))).blob(); + extension = '.json'; + } + const url = URL.createObjectURL(blob); + const link = el('a'); link.href = url; link.download = 'atomic-review-' + (root.slice(0, 12).replace(/[^a-z0-9]/gi, '') || 'report') + extension; + document.body.append(link); link.click(); link.remove(); setTimeout(() => URL.revokeObjectURL(url), 0); + } catch (error) { + control.title = 'Could not restore JSON archive: ' + error.message; + control.textContent = 'Download failed'; + control.disabled = false; + return; + } + control.disabled = false; control.textContent = label; + }); + renderSummary(); + render(); +})(); diff --git a/atomic-cli/src/commands/triage/mod.rs b/atomic-cli/src/commands/triage/mod.rs index 330b0f3c..a794f927 100644 --- a/atomic-cli/src/commands/triage/mod.rs +++ b/atomic-cli/src/commands/triage/mod.rs @@ -24,7 +24,7 @@ pub mod model { pub use atomic_repository::triage::model::*; } pub mod output; -mod publication_review; +pub(crate) mod publication_review; pub(crate) use publication_review::read as read_publication_review; pub mod project { pub use atomic_repository::triage::report::{build_report, build_walkthrough, TaskFact}; diff --git a/atomic-cli/src/commands/triage/publication_review.rs b/atomic-cli/src/commands/triage/publication_review.rs index b77e49e3..2d8c04e2 100644 --- a/atomic-cli/src/commands/triage/publication_review.rs +++ b/atomic-cli/src/commands/triage/publication_review.rs @@ -14,14 +14,14 @@ use atomic_repository::{ use clap::{Parser, Subcommand}; use std::path::{Path, PathBuf}; -#[derive(Debug, Parser)] +#[derive(Debug, Clone, Parser)] pub struct PublicationReviewCommand { #[command(subcommand)] - action: Action, + pub(crate) action: Action, } -#[derive(Debug, Subcommand)] -enum Action { +#[derive(Debug, Clone, Subcommand)] +pub(crate) enum Action { /// Print the pinned review document and exact bytes for external signing. Prepare { #[arg(long)] diff --git a/atomic-cli/src/main.rs b/atomic-cli/src/main.rs index 50f20b2b..45938d83 100644 --- a/atomic-cli/src/main.rs +++ b/atomic-cli/src/main.rs @@ -97,6 +97,7 @@ use commands::{ Remove, Repo, Restore, + Review, Revise, Sandbox, ServerCmd, @@ -934,6 +935,9 @@ enum Commands { /// with no arguments asks whether the current view is ready to promote. Triage(Triage), + /// Inspect a recorded turn/intent/change, or independently publish view reviews. + Review(Review), + /// Generate a shell completion script. /// /// Emits a static completion script for the given shell. For live @@ -1114,6 +1118,7 @@ fn main() { Commands::Provenance(provenance) => provenance.run(), Commands::Triage(triage) => triage.run(), + Commands::Review(review) => review.run(), }; // Handle errors with user-friendly output diff --git a/atomic-cli/src/output/html.rs b/atomic-cli/src/output/html.rs new file mode 100644 index 00000000..05f8fe32 --- /dev/null +++ b/atomic-cli/src/output/html.rs @@ -0,0 +1,38 @@ +//! Shared HTML artifact writing and browser handoff. + +use crate::error::{CliError, CliResult}; + +/// Finish writing before handing the file URL to an asynchronous browser. The +/// unique automatic file survives process exit and browser-launch failure. +pub(crate) fn write_and_open_html( + html: &str, + output: Option<&std::path::Path>, + open_browser: impl FnOnce(&str) -> std::io::Result<()>, +) -> CliResult { + use std::io::Write; + let path = match output { + Some(path) => { + std::fs::write(path, html)?; + path.to_path_buf() + } + None => { + let path = + std::env::temp_dir().join(format!("atomic-report-{}.html", uuid::Uuid::new_v4())); + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path)?; + file.write_all(html.as_bytes())?; + path + } + }; + let path = std::fs::canonicalize(path)?; + let url = url::Url::from_file_path(&path).map_err(|_| CliError::InvalidArgument { + message: format!("cannot convert HTML path to a file URL: {}", path.display()), + })?; + println!("Wrote HTML report to {}", path.display()); + if let Err(error) = open_browser(url.as_str()) { + eprintln!("Could not open a browser: {error}. Open {url} manually."); + } + Ok(path) +} diff --git a/atomic-cli/src/output/mod.rs b/atomic-cli/src/output/mod.rs index c5f94ec9..91ba6a48 100644 --- a/atomic-cli/src/output/mod.rs +++ b/atomic-cli/src/output/mod.rs @@ -53,6 +53,7 @@ //! ``` pub mod colors; +pub(crate) mod html; pub(crate) mod live; pub mod progress; pub mod table; diff --git a/atomic-cli/tests/review_audits.rs b/atomic-cli/tests/review_audits.rs new file mode 100644 index 00000000..436f1bee --- /dev/null +++ b/atomic-cli/tests/review_audits.rs @@ -0,0 +1,370 @@ +//! Verify executable audit coverage through the real CLI, not just catalog flags. + +use atomic_core::{change::ChangeHeader, types::Base32}; +use atomic_repository::{record::RecordOptions, tracking::TrackingOptions, Repository}; +use std::collections::BTreeSet; +use std::process::Command; + +#[test] +fn repository_wide_ancestor_is_reference_only_in_json_and_html() { + let directory = tempfile::tempdir().unwrap(); + let repo = Repository::init(directory.path()).unwrap(); + repo.init_vault().unwrap(); + let wc = repo.require_working_copy_id().unwrap(); + std::fs::create_dir_all(directory.path().join("src")).unwrap(); + // One ancestor spans the repository and holds payload that the selected + // single-file change must never drag into either export, even compressed. + let payload = "ANCESTOR_ONLY_FILE_TOKEN_PAYLOAD ".repeat(512); + for index in 0..32 { + let path = format!("ancestor-only-{index}.txt"); + std::fs::write(directory.path().join(&path), &payload).unwrap(); + repo.add(wc, &path, TrackingOptions::default()).unwrap(); + } + let path = directory.path().join("src/lib.rs"); + std::fs::write(&path, "pub fn selected() {}\n").unwrap(); + repo.add(wc, "src/lib.rs", TrackingOptions::default()) + .unwrap(); + let options = || { + RecordOptions::new() + .with_all(true) + .save_to_store(true) + .apply_after_record(true) + .enrich_kg(false) + }; + let ancestor = repo + .record( + wc, + ChangeHeader::new(format!("{}\nANCESTOR_ONLY_MESSAGE_BODY", "🦀".repeat(300))), + options(), + ) + .unwrap() + .hash() + .to_base32(); + let source = "pub fn selected() { todo!(); }\n"; + std::fs::write(&path, source).unwrap(); + let selected = repo + .record(wc, ChangeHeader::new("selected change"), options()) + .unwrap() + .hash() + .to_base32(); + std::fs::write(&path, "fn DIRTY_EXPORT_PAYLOAD() {}\n").unwrap(); + let database = repo.dot_dir().join("atomic.redb"); + drop(repo); + let before = std::fs::read(&database).unwrap(); + let export = |flags: &[&str]| { + let output = Command::new(env!("CARGO_BIN_EXE_atomic")) + .current_dir(directory.path()) + .env_remove("ATOMIC_SESSION_ID") + .env("PATH", directory.path().join("no-external-executables")) + .env("OPENAI_API_KEY", "must-not-be-used") + .env("ANTHROPIC_API_KEY", "must-not-be-used") + .env("OPENAI_BASE_URL", "http://127.0.0.1:1") + .env("ANTHROPIC_BASE_URL", "http://127.0.0.1:1") + .env("LLM_MODEL", "must-not-be-used") + .args(["review", "--change", &selected]) + .args(flags) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() + }; + let json = export(&["--json"]); + let report: serde_json::Value = serde_json::from_str(&json).unwrap(); + assert_eq!(report["schema_version"], 2); + assert_eq!(report["selected_roots"], serde_json::json!([selected])); + assert_eq!(report["dependency_only"], serde_json::json!([ancestor])); + assert_eq!( + report["dependency_closure"], + serde_json::json!([ancestor, selected]) + ); + let references = report["dependency_references"].as_array().unwrap(); + assert_eq!(references.len(), 1); + let reference = &references[0]; + assert_eq!(reference["hash"], ancestor); + assert_eq!(reference["direct"], true); + assert_eq!(reference["on_current_view"], true); + assert_eq!(reference["summary"].as_str().unwrap(), "🦀".repeat(240)); + assert_eq!( + reference + .as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect::>(), + [ + "hash", + "direct", + "on_current_view", + "summary", + "dependencies" + ] + .into_iter() + .collect() + ); + let changes = report["changes"].as_array().unwrap(); + assert_eq!(changes.len(), 1); + assert_eq!(changes[0]["hash"], selected); + assert_eq!(changes[0]["paths"], serde_json::json!(["src/lib.rs"])); + assert_eq!(changes[0]["dependencies"], serde_json::json!([ancestor])); + assert!(changes[0]["recorded_patch"].is_object()); + assert!(changes[0]["diff"].as_str().unwrap().contains("todo!()")); + assert!(!report["graph"]["findings"].as_array().unwrap().is_empty()); + assert!(report["graph"]["nodes"] + .as_array() + .unwrap() + .iter() + .any(|node| node["kind"] == "metric")); + for excluded in [ + "ANCESTOR_ONLY_FILE_TOKEN_PAYLOAD", + "ANCESTOR_ONLY_MESSAGE_BODY", + "ancestor-only-", + "DIRTY_EXPORT_PAYLOAD", + ] { + assert!( + !json.contains(excluded), + "unexpected ancestor/dirty payload: {excluded}" + ); + } + let html = export(&["--html", "--no-open"]); + // A generous bound detects repository-payload inclusion, not compression + // efficiency. The decoded archive must also pass the exact JSON boundary. + assert!( + json.len() < payload.len() * 16, + "{} bytes of JSON", + json.len() + ); + assert!( + html.len() < payload.len() * 16, + "{} bytes of HTML", + html.len() + ); + let data = html + .split("id=\"review-data\"") + .nth(1) + .unwrap() + .split_once('>') + .unwrap() + .1 + .split("") + .next() + .unwrap(); + let document: serde_json::Value = serde_json::from_str(data).unwrap(); + assert_eq!(document["local_only"], true); + assert_eq!(document["audit_cards"].as_array().unwrap().len(), 10); + assert_eq!(document["metric_cards"].as_array().unwrap().len(), 10); + assert!(document["view"]["graph"]["nodes"] + .as_array() + .unwrap() + .iter() + .all(|node| node["kind"] != "review_execution")); + let compressed = data_encoding::BASE64 + .decode( + document["report_archive"]["data"] + .as_str() + .unwrap() + .as_bytes(), + ) + .unwrap(); + let embedded: serde_json::Value = + serde_json::from_reader(flate2::read::GzDecoder::new(compressed.as_slice())).unwrap(); + assert_eq!( + embedded, report, + "HTML download must have exactly the JSON boundary" + ); + let snapshots = document["sources"].as_array().unwrap(); + assert!(snapshots + .iter() + .all(|snapshot| snapshot["path"] == "src/lib.rs" && snapshot["reviewed_root"] == true)); + assert_eq!(snapshots[0]["after"]["text"], source); + assert_eq!(before, std::fs::read(database).unwrap()); +} + +#[test] +fn all_seven_substantive_audits_run_without_supplied_findings() { + let directory = tempfile::tempdir().unwrap(); + let repo = Repository::init(directory.path()).unwrap(); + repo.init_vault().unwrap(); + let wc = repo.require_working_copy_id().unwrap(); + std::fs::create_dir_all(directory.path().join("src")).unwrap(); + let path = directory.path().join("src/lib.rs"); + let mut source = String::from( + r#" +fn masked() -> Result<(),()> { match work() { Ok(())=>Ok(()), Err(_)=>Ok(()) } } +fn duplicate(b:bool) { if b { work(1); } else { work(1); } } +fn implementation(x:i32)->i32 { x+1 } +fn middle(x:i32)->i32 { implementation(x) } +fn outer(x:i32)->i32 { middle(x) } +async fn locked() { let m=std::sync::Mutex::new(0); let guard=m.lock().unwrap(); work().await; drop(guard); } +#[test] fn weak_test() { let result=work(); assert_eq!(result,result); } +fn cast(bits:u32)->f32 { unsafe { std::mem::transmute::(bits) } } +fn large(x:i32) { +"#, + ); + for i in 0..15 { + source.push_str(&format!("if x == {i} {{ work(); }}\n")); + } + for _ in 0..100 { + source.push_str("work();\n"); + } + source.push_str("}\n"); + std::fs::write(&path, &source).unwrap(); + repo.add(wc, "src/lib.rs", TrackingOptions::default()) + .unwrap(); + let hash = repo + .record( + wc, + ChangeHeader::new("audit fixture"), + RecordOptions::new() + .with_all(true) + .save_to_store(true) + .apply_after_record(true) + .enrich_kg(false), + ) + .unwrap() + .hash() + .to_base32(); + std::fs::write(&path, "fn unrelated_dirty_bytes() {}\n").unwrap(); + let database = repo.dot_dir().join("atomic.redb"); + drop(repo); + let before = std::fs::read(&database).unwrap(); + let mut original_report = None; + for json in [true, false] { + let mut command = Command::new(env!("CARGO_BIN_EXE_atomic")); + command + .current_dir(directory.path()) + .env_remove("ATOMIC_SESSION_ID") + .args(["review", "--change", &hash]); + if json { + command.arg("--json"); + } + let output = command.output().unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let text = String::from_utf8(output.stdout).unwrap(); + if json { + let report: serde_json::Value = serde_json::from_str(&text).unwrap(); + let findings = report["graph"]["findings"].as_array().unwrap(); + let checks = report["changes"] + .as_array() + .unwrap() + .iter() + .flat_map(|change| change["analysis"]["checks"].as_array().unwrap()) + .collect::>(); + for card in atomic_audit::AUDIT_CARDS { + assert!( + checks.iter().any(|check| check["rule"] == card.id), + "Missing local coverage for {}", + card.id + ); + } + let rules: BTreeSet<_> = findings + .iter() + .map(|finding| { + finding["finding"]["requirement_or_rule"]["id"] + .as_str() + .unwrap() + }) + .collect(); + assert_eq!( + rules, + [ + "anti-slop.failure-masking", + "anti-slop.duplicated-behavior", + "anti-slop.unnecessary-machinery", + "anti-slop.manageability", + "anti-slop.async-resource-safety", + "anti-slop.weak-verification", + "anti-slop.unsafe-shortcuts" + ] + .into_iter() + .collect() + ); + assert_eq!(findings.len(), 7); + for finding in findings { + assert_eq!(finding["finding"]["change"], hash); + assert_eq!(finding["finding"]["introduced_by_change"]["status"], "yes"); + assert!(!finding["finding"]["evidence"] + .as_array() + .unwrap() + .is_empty()); + } + original_report = Some(report); + } else { + for number in 1..=7 { + assert!(text.contains(&format!("F{number} ·"))); + } + assert!(text.contains("Audit/rule: anti-slop.failure-masking")); + assert!(!text.contains("Not automatically audited:")); + } + } + let destination = directory.path().join("review #1 100%.html"); + for to_file in [false, true] { + let mut command = Command::new(env!("CARGO_BIN_EXE_atomic")); + command + .current_dir(directory.path()) + .env_remove("ATOMIC_SESSION_ID") + .args(["review", "--change", &hash, "--html", "--no-open"]); + if to_file { + command.arg("--output").arg(&destination); + } + let output = command.output().unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let html = if to_file { + assert!(output.stdout.is_empty()); + if let Some(artifact) = std::env::var_os("ATOMIC_REVIEW_HTML_ARTIFACT") { + std::fs::copy(&destination, artifact).unwrap(); + } + std::fs::read_to_string(&destination).unwrap() + } else { + String::from_utf8(output.stdout).unwrap() + }; + assert!(html.starts_with("")); + assert!(!html.contains("unrelated_dirty_bytes")); + let encoded = html + .split("id=\"review-data\"") + .nth(1) + .unwrap() + .split_once('>') + .unwrap() + .1 + .split("") + .next() + .unwrap(); + let document: serde_json::Value = serde_json::from_str(encoded).unwrap(); + let compressed = data_encoding::BASE64 + .decode( + document["report_archive"]["data"] + .as_str() + .unwrap() + .as_bytes(), + ) + .unwrap(); + let embedded: serde_json::Value = + serde_json::from_reader(flate2::read::GzDecoder::new(compressed.as_slice())).unwrap(); + assert_eq!(&embedded, original_report.as_ref().unwrap()); + assert_eq!(embedded["graph"]["findings"].as_array().unwrap().len(), 7); + let snapshot = document["sources"] + .as_array() + .unwrap() + .iter() + .find(|snapshot| snapshot["path"] == "src/lib.rs") + .unwrap(); + assert_eq!(snapshot["after"]["text"], source); + } + assert_eq!( + before, + std::fs::read(database).unwrap(), + "audit inspection must be read-only" + ); +} diff --git a/atomic-cli/tests/review_comparison.rs b/atomic-cli/tests/review_comparison.rs new file mode 100644 index 00000000..6e2c94ed --- /dev/null +++ b/atomic-cli/tests/review_comparison.rs @@ -0,0 +1,393 @@ +//! Paired recorded views: identity, local observations, source parity, no writes. +use atomic_core::{change::ChangeHeader, pristine::ViewScope, types::Base32}; +use atomic_repository::{record::RecordOptions, tracking::TrackingOptions, Repository}; +use serde_json::Value; +use std::{collections::BTreeSet, path::Path, process::Command}; + +fn record(repo: &Repository) { + repo.record( + repo.require_working_copy_id().unwrap(), + ChangeHeader::new("comparison fixture"), + RecordOptions::new() + .with_all(true) + .save_to_store(true) + .apply_after_record(true) + .enrich_kg(false), + ) + .unwrap(); +} +fn write(repo: &Repository, path: &str, text: &str) { + let full = repo.root().join(path); + let exists = full.exists(); + std::fs::write(full, text).unwrap(); + if !exists { + repo.add( + repo.require_working_copy_id().unwrap(), + path, + TrackingOptions::default(), + ) + .unwrap(); + } +} +fn command(root: &Path, args: &[&str]) -> std::process::Output { + Command::new(env!("CARGO_BIN_EXE_atomic")) + .current_dir(root) + .env("PATH", root.join("no-executables")) + .env("ATOMIC_SESSION_ID", "../must-not-be-used") + .env("OPENAI_API_KEY", "must-not-be-used") + .env("ANTHROPIC_API_KEY", "must-not-be-used") + .env("OPENAI_BASE_URL", "http://127.0.0.1:1") + .env("ANTHROPIC_BASE_URL", "http://127.0.0.1:1") + .args(args) + .output() + .unwrap() +} +fn review(root: &Path, from: &str, to: &str) -> Value { + let output = command(root, &["review", "--from", from, "--to", to, "--json"]); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).unwrap() +} +fn file<'a>(report: &'a Value, path: &str) -> &'a Value { + report["view_comparison"]["files"] + .as_array() + .unwrap() + .iter() + .find(|f| f["path"] == path) + .unwrap_or_else(|| panic!("Missing {path} in {}", report["view_comparison"]["files"])) +} +fn states(report: &Value, path: &str) -> BTreeSet { + file(report, path)["finding_states"] + .as_object() + .unwrap() + .values() + .map(|s| s["status"].as_str().unwrap().to_owned()) + .collect() +} +fn document(html: &str) -> Value { + serde_json::from_str( + html.split("id=\"review-data\"") + .nth(1) + .unwrap() + .split_once('>') + .unwrap() + .1 + .split("") + .next() + .unwrap(), + ) + .unwrap() +} + +#[test] +fn compare_recorded_views_in_both_directions_without_touching_the_working_copy() { + let directory = tempfile::tempdir().unwrap(); + let mut repo = Repository::init(directory.path()).unwrap(); + repo.init_vault().unwrap(); + let wc = repo.require_working_copy_id().unwrap(); + let from = repo.current_view().to_owned(); + for (path, text) in [ + ("same.rs", "pub fn same() { todo!(); }\n"), + ("old.rs", "pub fn renamed() { todo!(); }\n"), + ("removed.rs", "pub fn removed() { todo!(); }\n"), + ("fixed.rs", "pub fn fixed() { todo!(); }\n"), + ( + "changed.rs", + "pub fn changed() { todo!(\"before\"); todo!(); }\n", + ), + ("metrics.rs", "pub fn metric(a: bool) -> bool { a }\n"), + ("parse.rs", "pub fn parse() { todo!(); }\n"), + ("notes.txt", "Unsupported recorded source\n"), + ("replace.rs", "pub fn original() { todo!(); }\n"), + ( + "overload.ts", + "function f(a: string) { return a; }\nfunction f(a: number) { return a; }\n", + ), + ] { + write(&repo, path, text); + } + for path in ["clone-a.ts", "clone-b.ts"] { + write(&repo,path,"export function clone(value) { const a = value + 1; const b = a * 2; const c = b - value; if (c > 0) { return c + a; } else { return value - c; } }\n"); + } + record(&repo); + repo.create_draft_view("after", &from).unwrap(); + repo.switch_view(wc, "after").unwrap(); + write(&repo, "fixed.rs", "pub fn fixed() {}\n"); + write( + &repo, + "changed.rs", + "pub fn changed() { todo!(\"after\"); todo!(); }\n", + ); + write( + &repo, + "metrics.rs", + "pub fn metric(a: bool) -> bool { if a { true } else { false } }\n", + ); + write(&repo, "parse.rs", "pub fn parse( {\n"); + std::fs::rename( + directory.path().join("old.rs"), + directory.path().join("renamed.rs"), + ) + .unwrap(); + repo.move_file(wc, "old.rs", "renamed.rs").unwrap(); + std::fs::remove_file(directory.path().join("removed.rs")).unwrap(); + std::fs::remove_file(directory.path().join("clone-b.ts")).unwrap(); + std::fs::remove_file(directory.path().join("replace.rs")).unwrap(); + record(&repo); + write(&repo, "added.rs", "pub fn added() { todo!(); }\n"); + write(&repo, "replace.rs", "pub fn replacement() { todo!(); }\n"); + record(&repo); + let expected_after = repo.get_view_info("after").unwrap().state.to_base32(); + repo.create_view_with_identity("empty", ViewScope::Shared, None) + .unwrap(); + repo.switch_view(wc, &from).unwrap(); + std::fs::write(directory.path().join("same.rs"), "DIRTY_NOT_RECORDED\n").unwrap(); + write(&repo, "staged.rs", "STAGED_NOT_RECORDED\n"); + std::fs::write( + directory.path().join("untracked.rs"), + "UNTRACKED_NOT_RECORDED\n", + ) + .unwrap(); + let wc_record = repo.working_copy_record(wc).unwrap(); + let database = repo.dot_dir().join("atomic.redb"); + let active_path = repo.dot_dir().join("current_view"); + let active_bytes = std::fs::read(&active_path).unwrap(); + drop(repo); + let db_bytes = std::fs::read(&database).unwrap(); + + let report = review(directory.path(), &from, "after"); + assert_eq!(report["schema_version"], 4); + assert_eq!(report["selection"]["kind"], "view_comparison"); + assert_eq!(report["view_comparison"]["from"]["view"], from); + assert_eq!(report["view_comparison"]["to"]["state"], expected_after); + assert!(report["changes"].as_array().unwrap().is_empty()); + assert!(report["selected_roots"].as_array().unwrap().is_empty()); + assert!(report.get("view_snapshot").is_none()); + for (path, status) in [ + ("same.rs", "unchanged"), + ("renamed.rs", "renamed"), + ("removed.rs", "removed"), + ("fixed.rs", "modified"), + ("added.rs", "added"), + ("notes.txt", "unavailable"), + // Re-creation at this name is a recorded restore of the same inode. + ("replace.rs", "modified"), + ] { + assert_eq!(file(&report, path)["status"], status, "{path}"); + } + assert_eq!( + file(&report, "renamed.rs")["before_inode"], + file(&report, "renamed.rs")["after_inode"] + ); + assert_eq!( + file(&report, "replace.rs")["before_inode"], + file(&report, "replace.rs")["after_inode"] + ); + assert_eq!( + states(&report, "same.rs"), + BTreeSet::from(["existing".into()]) + ); + assert_eq!( + states(&report, "renamed.rs"), + BTreeSet::from(["existing".into()]) + ); + assert_eq!(states(&report, "added.rs"), BTreeSet::from(["new".into()])); + assert_eq!( + states(&report, "removed.rs"), + BTreeSet::from(["resolved".into()]) + ); + assert_eq!( + states(&report, "fixed.rs"), + BTreeSet::from(["resolved".into()]) + ); + assert_eq!( + states(&report, "changed.rs"), + BTreeSet::from(["changed".into(), "existing".into()]) + ); + assert!(states(&report, "parse.rs").contains("unknown")); + for finding in report["graph"]["findings"].as_array().unwrap() { + assert!(finding["comparison"].is_object()); + assert_eq!( + finding["finding"]["introduced_by_change"]["status"], + "unknown" + ); + } + let metric = file(&report, "metrics.rs")["analysis"]["metrics"] + .as_array() + .unwrap() + .iter() + .find(|m| m["observation"]["metric"] == "cyclomatic_complexity") + .unwrap(); + assert_eq!(metric["delta"], 1); + let clones = file(&report, "clone-a.ts")["analysis"]["metrics"] + .as_array() + .unwrap() + .iter() + .find(|m| m["observation"]["metric"] == "duplicated_tokens") + .unwrap(); + assert!( + clones["observation"]["before"]["value"] + .as_u64() + .unwrap_or_else(|| panic!("Clone measurement: {clones}")) + > 0 + ); + assert_eq!(clones["observation"]["after"]["value"], 0); + assert!( + clones["delta"].as_i64().unwrap() < 0, + "Unchanged file metrics must retain side-wide clone context" + ); + for m in file(&report, "overload.ts")["analysis"]["metrics"] + .as_array() + .unwrap() + .iter() + .filter(|m| m["subject_identity_ambiguous"] == true) + { + assert!(m["delta"].is_null()); + assert_eq!(m["observation"]["before"]["status"], "unavailable"); + } + let reverse = review(directory.path(), "after", &from); + let metric = file(&reverse, "metrics.rs")["analysis"]["metrics"] + .as_array() + .unwrap() + .iter() + .find(|m| m["observation"]["metric"] == "cyclomatic_complexity") + .unwrap(); + assert_eq!(metric["delta"], -1); + assert_eq!( + states(&reverse, "added.rs"), + BTreeSet::from(["resolved".into()]) + ); + assert_eq!(file(&reverse, "old.rs")["status"], "renamed"); + let same = review(directory.path(), &from, &from); + for file in same["view_comparison"]["files"].as_array().unwrap() { + assert!(file["finding_states"] + .as_object() + .unwrap() + .values() + .all(|s| s["status"] == "existing")); + assert!(file["analysis"]["metrics"] + .as_array() + .unwrap() + .iter() + .all(|m| m["delta"].is_null() || m["delta"] == 0)); + } + let empty = review(directory.path(), "empty", "empty"); + assert!(empty["view_comparison"]["files"] + .as_array() + .unwrap() + .is_empty()); + assert!(empty["graph"]["findings"].as_array().unwrap().is_empty()); + let add_all = review(directory.path(), "empty", &from); + assert!(add_all["view_comparison"]["files"] + .as_array() + .unwrap() + .iter() + .all(|f| f["status"] == "added")); + + let output = command( + directory.path(), + &[ + "review", + "--from", + &from, + "--to", + "after", + "--html", + "--no-open", + ], + ); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let html = String::from_utf8(output.stdout).unwrap(); + if let Some(path) = std::env::var_os("ATOMIC_REVIEW_COMPARISON_ARTIFACT") { + std::fs::write(path, &html).unwrap(); + } + assert!(html.contains("data:image/png;base64,")); + for forbidden in [ + "DIRTY_NOT_RECORDED", + "STAGED_NOT_RECORDED", + "UNTRACKED_NOT_RECORDED", + ] { + assert!(!html.contains(forbidden)); + } + let doc = document(&html); + assert_eq!(doc["local_only"], true); + let sources = doc["sources"].as_array().unwrap(); + let renamed = sources + .iter() + .find(|s| { + s["change"] == file(&report, "renamed.rs")["source_ref"] && s["path"] == "renamed.rs" + }) + .unwrap(); + assert_eq!(renamed["before"]["text"], "pub fn renamed() { todo!(); }\n"); + assert_eq!(renamed["before"], renamed["after"]); + let removed = sources.iter().find(|s| s["path"] == "removed.rs").unwrap(); + assert_eq!(removed["after"]["status"], "absent"); + let added = sources.iter().find(|s| s["path"] == "added.rs").unwrap(); + assert_eq!(added["before"]["status"], "absent"); + let compressed = data_encoding::BASE64 + .decode(doc["report_archive"]["data"].as_str().unwrap().as_bytes()) + .unwrap(); + let restored: Value = + serde_json::from_reader(flate2::read::GzDecoder::new(compressed.as_slice())).unwrap(); + assert_eq!(restored, report); + let terminal = command( + directory.path(), + &["review", "--from", &from, "--to", "after"], + ); + assert!(terminal.status.success()); + assert!(String::from_utf8_lossy(&terminal.stdout) + .contains(&format!("BEFORE {from} -> AFTER after"))); + for args in [ + vec!["review", "--from", &from], + vec!["review", "--to", "after"], + vec!["review", "--from", "missing", "--to", "after"], + vec!["review", "--from", &from, "--to", "after", "--view", &from], + vec![ + "review", "--from", &from, "--to", "after", "--change", "unused", + ], + vec![ + "review", "--from", &from, "--to", "after", "--intent", "unused", + ], + vec![ + "review", "--from", &from, "--to", "after", "--turn", "unused:1", + ], + vec![ + "review", + "--from", + &from, + "--to", + "after", + "--findings", + "unused", + ], + vec![ + "review", + "--from", + &from, + "--to", + "after", + "--risk-profile", + "unused", + ], + ] { + let output = command(directory.path(), &args); + assert!(!output.status.success(), "{args:?}"); + assert!(output.stdout.is_empty()); + } + assert_eq!(std::fs::read(database).unwrap(), db_bytes); + assert_eq!(std::fs::read(active_path).unwrap(), active_bytes); + assert_eq!( + std::fs::read_to_string(directory.path().join("same.rs")).unwrap(), + "DIRTY_NOT_RECORDED\n" + ); + let repo = Repository::open_readonly(directory.path()).unwrap(); + assert_eq!(repo.current_view(), from); + assert_eq!(repo.working_copy_record(wc).unwrap(), wc_record); +} diff --git a/atomic-cli/tests/review_comparison_passes.rs b/atomic-cli/tests/review_comparison_passes.rs new file mode 100644 index 00000000..2574e954 --- /dev/null +++ b/atomic-cli/tests/review_comparison_passes.rs @@ -0,0 +1,620 @@ +//! All three passes, with the complete JSON finding set in offline HTML. +use atomic_core::{ + change::{session::SessionTurn, ChangeHeader, ProvenanceGraph}, + types::{Base32, Hash}, +}; +use atomic_repository::{ + record::RecordOptions, tracking::TrackingOptions, IntentCreateOptions, IntentUpdateOptions, + Repository, +}; +use serde_json::Value; +use std::{path::Path, process::Command}; + +fn record(repo: &Repository) -> Hash { + *repo + .record( + repo.require_working_copy_id().unwrap(), + ChangeHeader::new("comparison passes fixture"), + RecordOptions::new() + .with_all(true) + .save_to_store(true) + .apply_after_record(true) + .enrich_kg(false), + ) + .unwrap() + .hash() +} +fn add(repo: &Repository, path: &str, text: &str) { + let full = repo.root().join(path); + std::fs::create_dir_all(full.parent().unwrap()).unwrap(); + std::fs::write(full, text).unwrap(); + repo.add( + repo.require_working_copy_id().unwrap(), + path, + TrackingOptions::default(), + ) + .unwrap(); +} +fn governance(repo: &Repository, hash: Hash, plan: &str) { + let session = format!("comparison-{plan}"); + let graph = ProvenanceGraph::builder(&session, "test") + .timestamp(10) + .plan_id(plan) + .add_change_explained(hash) + .build(); + let provenance_hash = Hash::of(&graph.serialize().unwrap()); + repo.publish_provenance_checkpoint( + &graph, + SessionTurn { + session_id: session, + turn_number: 0, + goal: None, + provenance_hash, + change_hashes: vec![hash], + previous_provenance: None, + timestamp: 10, + plan_id: Some(plan.into()), + todos: vec![], + boundary_start: None, + boundary_end: None, + outcome: None, + }, + ) + .unwrap(); +} + +#[test] +fn missing_recorded_criteria_use_explicit_context_and_ambiguous_governance_is_not_guessed() { + let dir = tempfile::tempdir().unwrap(); + let mut repo = Repository::init(dir.path()).unwrap(); + repo.init_vault().unwrap(); + let wc = repo.require_working_copy_id().unwrap(); + let from = repo.current_view().to_owned(); + let create = || { + repo.vault_intent_create(IntentCreateOptions { + title: "Current-vault-only criterion".into(), + priority: None, + assignee: None, + labels: vec![], + session_id: None, + turn_id: None, + kind: None, + }) + .unwrap() + }; + let intent = create(); + let other = create(); + repo.vault_intent_update(&intent.id,IntentUpdateOptions {content:Some(format!(":::why\nContext only.\n:::\n:::acceptance-criterion{{#{}-ac-1 status=unmet}}\nCURRENT_CONTEXT_NOT_RECORDED_PROOF\n:::\n",intent.uid)),..Default::default()}).unwrap(); + add(&repo, "lib.rs", "pub fn work() {}\n"); + record(&repo); + repo.create_draft_view("after", &from).unwrap(); + repo.switch_view(wc, "after").unwrap(); + std::fs::write(dir.path().join("lib.rs"), "pub fn work() { let n=1; }\n").unwrap(); + let hash = record(&repo); + governance(&repo, hash, &intent.uid); + drop(repo); + let report = review(dir.path(), &from, "after"); + let criterion = &report["view_comparison"]["conformance"]["criteria"][0]; + assert!(criterion["before"].is_null() && criterion["after"].is_null()); + assert_eq!( + criterion["current_context"]["source_kind"], + "current_vault_context" + ); + assert_eq!( + report["graph"]["criteria"][0]["review_assessment"], + "unknown" + ); + let repo = Repository::open(dir.path()).unwrap(); + governance(&repo, hash, &other.uid); + drop(repo); + let report = review(dir.path(), &from, "after"); + assert!(report["graph"]["criteria"].as_array().unwrap().is_empty()); + assert_eq!( + report["view_comparison"]["conformance"]["changes"][0]["intent_context"]["status"], + "ambiguous" + ); + assert!(report["view_comparison"]["conformance"]["diagnostics"] + .as_array() + .unwrap() + .iter() + .any(|note| note.as_str().unwrap().contains("ambiguous"))); +} + +#[test] +fn blast_radius_compares_final_states_not_an_intermediate_breaking_patch() { + let dir = tempfile::tempdir().unwrap(); + let mut repo = Repository::init(dir.path()).unwrap(); + repo.init_vault().unwrap(); + let wc = repo.require_working_copy_id().unwrap(); + let from = repo.current_view().to_owned(); + let source = "fn work(a:i32) {}\nfn consumer() { work(1); }\n"; + add(&repo, "lib.rs", source); + record(&repo); + repo.create_draft_view("after", &from).unwrap(); + repo.switch_view(wc, "after").unwrap(); + std::fs::write( + dir.path().join("lib.rs"), + "fn work(a:i32,b:i32) {}\nfn consumer() { work(1); }\n", + ) + .unwrap(); + record(&repo); + std::fs::write(dir.path().join("lib.rs"), source).unwrap(); + record(&repo); + drop(repo); + let report = review(dir.path(), &from, "after"); + assert!(report["graph"]["risk"]["impact"][0]["issues"] + .as_array() + .unwrap() + .is_empty()); + assert_eq!( + report["graph"]["risk"]["assessment"]["rating"], + "not_applicable" + ); + assert_eq!( + report["view_comparison"]["conformance"]["changes"] + .as_array() + .unwrap() + .len(), + 2 + ); +} +fn command(root: &Path, args: &[&str]) -> String { + let output = Command::new(env!("CARGO_BIN_EXE_atomic")) + .current_dir(root) + .env("PATH", root.join("no-executables")) + .env("ATOMIC_SESSION_ID", "../must-not-be-used") + .env("OPENAI_BASE_URL", "http://127.0.0.1:1") + .env("ANTHROPIC_BASE_URL", "http://127.0.0.1:1") + .args(args) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() +} +fn review(root: &Path, from: &str, to: &str) -> Value { + serde_json::from_str(&command( + root, + &["review", "--from", from, "--to", to, "--json"], + )) + .unwrap() +} +fn document(html: &str) -> Value { + serde_json::from_str( + html.split("id=\"review-data\"") + .nth(1) + .unwrap() + .split_once('>') + .unwrap() + .1 + .split("") + .next() + .unwrap(), + ) + .unwrap() +} + +fn scoped_intent(repo: &Repository, title: &str) -> atomic_repository::IntentCreateResult { + repo.vault_intent_create(IntentCreateOptions { + title: title.into(), + priority: None, + assignee: None, + labels: vec![], + session_id: None, + turn_id: None, + kind: None, + }) + .unwrap() +} + +#[test] +fn unlinked_view_intents_are_scoped_to_the_requested_view_not_the_active_view() { + let dir = tempfile::tempdir().unwrap(); + let mut repo = Repository::init(dir.path()).unwrap(); + repo.init_vault().unwrap(); + let wc = repo.require_working_copy_id().unwrap(); + let base = repo.current_view().to_owned(); + let parent = scoped_intent(&repo, "PARENT_SCOPE_MUST_NOT_APPEAR"); + repo.vault_intent_update(&parent.id,IntentUpdateOptions {content:Some(format!(":::why\nParent work.\n:::\n:::acceptance-criterion{{#{}-ac-1 status=unmet}}\nPARENT_CRITERION_MUST_NOT_APPEAR\n:::\n",parent.uid)),..Default::default()}).unwrap(); + let parent_path = format!(".vault/{}", parent.intent_file); + let parent_source = std::fs::read_to_string(dir.path().join(&parent_path)).unwrap(); + add(&repo, &parent_path, &parent_source); + add(&repo, "lib.rs", "pub fn before() {}\n"); + record(&repo); + repo.create_draft_view("target", &base).unwrap(); + repo.create_draft_view("foreign", &base).unwrap(); + repo.switch_view(wc, "target").unwrap(); + std::fs::write(dir.path().join("lib.rs"), "pub fn after() {}\n").unwrap(); + record(&repo); + // Neither of these view assignments has a recorded governing-plan link, + // and neither intent document has been added to the VCS graph. + let work = scoped_intent(&repo, "View-scoped API intent"); + repo.vault_intent_update(&work.id,IntentUpdateOptions {content:Some(format!(":::why\nTarget work.\n:::\n:::acceptance-criterion{{#{}-ac-1 status=unmet}}\nFIRST_VIEW_SCOPED_CRITERION\n:::\n:::acceptance-criterion{{#{}-ac-2 status=unmet}}\nSECOND_VIEW_SCOPED_CRITERION\n:::\n:::task{{#{}-1 status=open criteria={}-ac-1}}\nImplement target work.\n::file-ref{{path=lib.rs}}\n:::\n",work.uid,work.uid,work.uid,work.uid)),..Default::default()}).unwrap(); + let empty = scoped_intent(&repo, "View-scoped checklist without criteria"); + repo.vault_intent_update( + &empty.id, + IntentUpdateOptions { + content: Some(":::why\nNo criteria have been defined yet.\n:::\n".into()), + ..Default::default() + }, + ) + .unwrap(); + repo.switch_view(wc, "foreign").unwrap(); + let foreign = scoped_intent(&repo, "FOREIGN_SCOPE_MUST_NOT_APPEAR"); + repo.vault_intent_update(&foreign.id,IntentUpdateOptions {content:Some(format!(":::why\nForeign work.\n:::\n:::acceptance-criterion{{#{}-ac-1 status=unmet}}\nFOREIGN_CRITERION_MUST_NOT_APPEAR\n:::\n",foreign.uid)),..Default::default()}).unwrap(); + std::fs::write( + dir.path().join("lib.rs"), + "DIRTY_ACTIVE_VIEW_NOT_TARGET_SOURCE", + ) + .unwrap(); + let db = repo.dot_dir().join("atomic.redb"); + let active = repo.dot_dir().join("current_view"); + let wc_before = repo.working_copy_record(wc).unwrap(); + drop(repo); + let db_before = std::fs::read(&db).unwrap(); + let active_before = std::fs::read(&active).unwrap(); + let report = review(dir.path(), &base, "target"); + let context = &report["view_comparison"]["conformance"]; + assert_eq!(context["scope"]["view"], "target"); + assert_eq!(context["intents"].as_array().unwrap().len(), 2); + assert_eq!(context["criteria"].as_array().unwrap().len(), 2); + assert_eq!(report["graph"]["passes"][1]["status"], "partial"); + assert!(context["criteria"] + .as_array() + .unwrap() + .iter() + .all(|criterion| criterion["governing_changes"] + .as_array() + .unwrap() + .is_empty() + && criterion["current_context"]["source_kind"] == "current_vault_context")); + assert!(report["graph"]["criteria"] + .as_array() + .unwrap() + .iter() + .all(|criterion| criterion["review_assessment"] == "unknown")); + let snapshot: Value = serde_json::from_str(&command( + dir.path(), + &["review", "--view", "target", "--json"], + )) + .unwrap(); + assert_eq!( + snapshot["view_snapshot"]["conformance"]["scope"]["view"], + "target" + ); + assert_eq!(snapshot["graph"]["criteria"].as_array().unwrap().len(), 2); + assert_eq!(snapshot["graph"]["risk"]["basis"], "view_snapshot"); + let reverse = review(dir.path(), "target", &base); + assert_eq!( + reverse["view_comparison"]["conformance"]["intents"] + .as_array() + .unwrap() + .len(), + 1 + ); + assert_eq!( + reverse["view_comparison"]["conformance"]["intents"][0]["human_key"], + parent.id + ); + let same = review(dir.path(), "target", "target"); + assert_eq!(same["graph"]["passes"][1]["status"], "partial"); + for (args, artifact) in [ + ( + vec![ + "review", + "--from", + base.as_str(), + "--to", + "target", + "--html", + "--no-open", + ], + "ATOMIC_REVIEW_SCOPED_INTENTS_ARTIFACT", + ), + ( + vec!["review", "--view", "target", "--html", "--no-open"], + "ATOMIC_REVIEW_SCOPED_VIEW_ARTIFACT", + ), + ] { + let html = command(dir.path(), &args); + if let Some(path) = std::env::var_os(artifact) { + std::fs::write(path, &html).unwrap(); + } + for forbidden in [ + "PARENT_SCOPE_MUST_NOT_APPEAR", + "FOREIGN_SCOPE_MUST_NOT_APPEAR", + "PARENT_CRITERION_MUST_NOT_APPEAR", + "FOREIGN_CRITERION_MUST_NOT_APPEAR", + "DIRTY_ACTIVE_VIEW_NOT_TARGET_SOURCE", + ] { + assert!(!html.contains(forbidden), "Leaked {forbidden}"); + } + let doc = document(&html); + assert_eq!( + doc["view"]["graph"]["criteria"].as_array().unwrap().len(), + 2 + ); + } + assert_eq!(std::fs::read(db).unwrap(), db_before); + assert_eq!(std::fs::read(active).unwrap(), active_before); + let repo = Repository::open_readonly(dir.path()).unwrap(); + assert_eq!(repo.current_view(), "foreign"); + assert_eq!(repo.working_copy_record(wc).unwrap(), wc_before); +} + +#[test] +fn recorded_view_assignment_survives_dirty_or_missing_current_vault_definitions() { + let dir = tempfile::tempdir().unwrap(); + let mut repo = Repository::init(dir.path()).unwrap(); + repo.init_vault().unwrap(); + let wc = repo.require_working_copy_id().unwrap(); + let base = repo.current_view().to_owned(); + add(&repo, "lib.rs", "pub fn code() {}\n"); + record(&repo); + repo.create_draft_view("target", &base).unwrap(); + repo.switch_view(wc, "target").unwrap(); + let work = scoped_intent(&repo, "Recorded view-assigned work"); + repo.vault_intent_update(&work.id,IntentUpdateOptions {content:Some(format!(":::why\nRecorded target work.\n:::\n:::acceptance-criterion{{#{}-ac-1 status=unmet}}\nPINNED_VIEW_ASSIGNMENT_CRITERION\n:::\n",work.uid)),..Default::default()}).unwrap(); + let path = format!(".vault/{}", work.intent_file); + let source = std::fs::read_to_string(dir.path().join(&path)).unwrap(); + add(&repo, &path, &source); + record(&repo); + repo.vault_intent_update( + &work.id, + IntentUpdateOptions { + title: Some("DIRTY_SCOPE_TITLE_NOT_RENDERED".into()), + content: Some(":::why\nDIRTY_SCOPE_BODY_NOT_RENDERED\n:::\n".into()), + ..Default::default() + }, + ) + .unwrap(); + drop(repo); + for before_delete in [true, false] { + if !before_delete { + let repo = Repository::open(dir.path()).unwrap(); + repo.vault_intent_delete(&work.id).unwrap(); + } + let report = review(dir.path(), &base, "target"); + let context = &report["view_comparison"]["conformance"]; + assert_eq!(context["intents"].as_array().unwrap().len(), 1); + assert_eq!( + context["intents"][0]["title"], + "Recorded view-assigned work" + ); + assert_eq!(context["intents"][0]["source_kind"], "recorded_view"); + assert_eq!( + context["criteria"][0]["after"]["text"], + "PINNED_VIEW_ASSIGNMENT_CRITERION" + ); + assert_eq!( + context["criteria"][0]["governing_changes"] + .as_array() + .unwrap() + .len(), + 0 + ); + let html = command( + dir.path(), + &[ + "review", + "--from", + &base, + "--to", + "target", + "--html", + "--no-open", + ], + ); + assert!( + !html.contains("DIRTY_SCOPE_TITLE_NOT_RENDERED") + && !html.contains("DIRTY_SCOPE_BODY_NOT_RENDERED") + ); + } +} + +#[test] +fn pinned_conformance_and_semantic_blast_radius_export_every_contract_finding() { + let dir = tempfile::tempdir().unwrap(); + let mut repo = Repository::init(dir.path()).unwrap(); + repo.init_vault().unwrap(); + let wc = repo.require_working_copy_id().unwrap(); + let from = repo.current_view().to_owned(); + let intent = repo + .vault_intent_create(IntentCreateOptions { + title: "Preserve the direct consumer contract".into(), + priority: None, + assignee: None, + labels: vec![], + session_id: None, + turn_id: None, + kind: None, + }) + .unwrap(); + let body = |status: &str| { + format!(":::why\nPreserve compatibility.\n:::\n:::acceptance-criterion{{#{}-ac-1 status={status} verifiedBy=author evidence=claimed}}\nRECORDED_CONTRACT_CRITERION: consumers can still call work with one argument.\n:::\n:::task{{#{}-1 status=done criteria={}-ac-1}}\nImplement the API update.\n::file-ref{{path=src/lib.rs}}\n:::\n",intent.uid,intent.uid,intent.uid) + }; + repo.vault_intent_update( + &intent.id, + IntentUpdateOptions { + content: Some(body("unmet")), + ..Default::default() + }, + ) + .unwrap(); + let intent_path = format!(".vault/{}", intent.intent_file); + let intent_bytes = std::fs::read_to_string(dir.path().join(&intent_path)).unwrap(); + add(&repo, &intent_path, &intent_bytes); + add( + &repo, + "src/lib.rs", + "mod consumer;\npub fn work(x:i32) {}\n", + ); + let consumers = (0..137) + .map(|index| format!("pub fn consumer_{index}() {{ crate::work(1); }}\n")) + .collect::(); + add(&repo, "src/consumer.rs", &consumers); + record(&repo); + repo.create_draft_view("after", &from).unwrap(); + repo.switch_view(wc, "after").unwrap(); + repo.vault_intent_update( + &intent.id, + IntentUpdateOptions { + content: Some(body("met")), + ..Default::default() + }, + ) + .unwrap(); + std::fs::write( + dir.path().join("src/lib.rs"), + "mod consumer;\npub fn work(x:i32,y:i32) {}\n", + ) + .unwrap(); + let changed = record(&repo); + governance(&repo, changed, &intent.uid); + repo.switch_view(wc, &from).unwrap(); + // Neither dirty code nor later current-vault definitions may replace a + // pinned recorded definition. No review command/test evidence is executed. + repo.vault_intent_update( + &intent.id, + IntentUpdateOptions { + content: Some(":::why\nDIRTY_CRITERION_MUST_NOT_REPLACE_RECORDED_SOURCE\n:::\n".into()), + ..Default::default() + }, + ) + .unwrap(); + std::fs::write( + dir.path().join("src/lib.rs"), + "DIRTY_SOURCE_MUST_NOT_BE_ANALYZED", + ) + .unwrap(); + std::fs::write( + dir.path().join("untracked.rs"), + "UNTRACKED_CALLER_MUST_NOT_BE_ANALYZED", + ) + .unwrap(); + let database = repo.dot_dir().join("atomic.redb"); + let active = repo.dot_dir().join("current_view"); + let expected_wc = repo.working_copy_record(wc).unwrap(); + drop(repo); + let db_before = std::fs::read(&database).unwrap(); + let active_before = std::fs::read(&active).unwrap(); + + let report = review(dir.path(), &from, "after"); + assert_eq!(report["graph"]["passes"][1]["status"], "partial"); + assert_eq!(report["graph"]["passes"][2]["status"], "partial"); + let criterion = &report["view_comparison"]["conformance"]["criteria"][0]; + assert_eq!(criterion["before"]["status"], "unmet"); + assert_eq!(criterion["after"]["status"], "met"); + assert_eq!(criterion["after"]["source_kind"], "recorded_view"); + assert!(criterion["current_context"].is_null()); + assert_eq!(criterion["governing_changes"][0], changed.to_base32()); + assert_eq!( + criterion["after"]["tasks"][0]["files"][0]["path"], + "src/lib.rs" + ); + assert_eq!( + report["graph"]["criteria"][0]["review_assessment"], "unknown", + "Author met is not independent acceptance proof" + ); + let risk = &report["graph"]["risk"]; + assert_eq!(risk["assessment"]["rating"], "high"); + let impact = &risk["impact"][0]; + assert_eq!(impact["callers_after"].as_array().unwrap().len(), 137); + assert_eq!(impact["issues"].as_array().unwrap().len(), 137); + assert_eq!(impact["checked_call_contracts"], 137); + let findings: Vec<_> = report["graph"]["findings"] + .as_array() + .unwrap() + .iter() + .filter(|finding| { + finding["passes"] + .as_array() + .unwrap() + .iter() + .any(|pass| pass == "blast_radius_risk") + }) + .collect(); + assert_eq!(findings.len(), 137, "No numbered-finding truncation at 100"); + assert!(findings + .iter() + .all(|finding| finding["finding"]["introduced_by_change"]["status"] == "unknown")); + let reverse = review(dir.path(), "after", &from); + assert!(reverse["graph"]["risk"]["impact"][0]["issues"] + .as_array() + .unwrap() + .is_empty()); + assert_eq!( + reverse["view_comparison"]["conformance"]["changes"][0]["direction"], + "removed_from_after" + ); + assert_eq!( + reverse["view_comparison"]["conformance"]["criteria"][0]["before"]["status"], + "met" + ); + let same = review(dir.path(), &from, &from); + assert_eq!( + same["graph"]["risk"]["assessment"]["rating"], + "not_applicable" + ); + + let html = command( + dir.path(), + &[ + "review", + "--from", + &from, + "--to", + "after", + "--html", + "--no-open", + ], + ); + if let Some(path) = std::env::var_os("ATOMIC_REVIEW_PASSES_ARTIFACT") { + std::fs::write(path, &html).unwrap(); + } + for forbidden in [ + "DIRTY_SOURCE_MUST_NOT_BE_ANALYZED", + "DIRTY_CRITERION_MUST_NOT_REPLACE_RECORDED_SOURCE", + "UNTRACKED_CALLER_MUST_NOT_BE_ANALYZED", + ] { + assert!(!html.contains(forbidden)); + } + let doc = document(&html); + assert_eq!( + doc["view"]["graph"]["findings"], + report["graph"]["findings"] + ); + assert_eq!( + doc["view"]["view_comparison"]["conformance"], + report["view_comparison"]["conformance"] + ); + let callers = doc["sources"] + .as_array() + .unwrap() + .iter() + .find(|source| { + source["path"] == "src/consumer.rs" + && source["change"] == report["view_comparison"]["source_ref"] + }) + .unwrap(); + assert_eq!(callers["after"]["text"], consumers); + let compressed = data_encoding::BASE64 + .decode(doc["report_archive"]["data"].as_str().unwrap().as_bytes()) + .unwrap(); + let archive: Value = + serde_json::from_reader(flate2::read::GzDecoder::new(compressed.as_slice())).unwrap(); + assert_eq!(archive, report); + let terminal = command(dir.path(), &["review", "--from", &from, "--to", "after"]); + assert!( + terminal.contains("RECORDED_CONTRACT_CRITERION") + && terminal.contains("137 current bound caller(s)") + ); + assert_eq!(std::fs::read(database).unwrap(), db_before); + assert_eq!(std::fs::read(active).unwrap(), active_before); + let repo = Repository::open_readonly(dir.path()).unwrap(); + assert_eq!(repo.current_view(), from); + assert_eq!(repo.working_copy_record(wc).unwrap(), expected_wc); +} diff --git a/atomic-cli/tests/review_impact.rs b/atomic-cli/tests/review_impact.rs new file mode 100644 index 00000000..e12ec4af --- /dev/null +++ b/atomic-cli/tests/review_impact.rs @@ -0,0 +1,93 @@ +//! Exercise the shipped command against a real, tiny recorded repository. + +use std::process::Command; + +use atomic_core::{change::ChangeHeader, types::Base32}; +use atomic_repository::{record::RecordOptions, tracking::TrackingOptions, Repository}; + +#[test] +fn recorded_contract_breakage_is_assessed_without_supplied_findings_or_pipe_animation() { + let directory = tempfile::tempdir().unwrap(); + let repo = Repository::init(directory.path()).unwrap(); + repo.init_vault().unwrap(); + let wc = repo.require_working_copy_id().unwrap(); + std::fs::create_dir_all(directory.path().join("src")).unwrap(); + let path = directory.path().join("src/lib.rs"); + std::fs::write(&path, "fn work(x:i32) {} fn consumer() { work(1); }\n").unwrap(); + repo.add(wc, "src/lib.rs", TrackingOptions::default()) + .unwrap(); + let options = || { + RecordOptions::new() + .with_all(true) + .save_to_store(true) + .apply_after_record(true) + .enrich_kg(false) + }; + repo.record(wc, ChangeHeader::new("initial"), options()) + .unwrap(); + std::fs::write( + &path, + "fn work(x:i32,y:i32) {} fn consumer() { work(1); }\n", + ) + .unwrap(); + let hash = repo + .record(wc, ChangeHeader::new("change arity"), options()) + .unwrap() + .hash() + .to_base32(); + let database = repo.dot_dir().join("atomic.redb"); + drop(repo); + let database_before = std::fs::read(&database).unwrap(); + for json in [true, false] { + let mut command = Command::new(env!("CARGO_BIN_EXE_atomic")); + command + .current_dir(directory.path()) + .env_remove("ATOMIC_SESSION_ID") + .args(["review", "--change", &hash]); + if json { + command.arg("--json"); + } + let output = command.output().unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let text = String::from_utf8(output.stdout).unwrap(); + assert!( + !text.contains("Thinking") + && !String::from_utf8_lossy(&output.stderr).contains("Thinking") + ); + assert!( + !text.contains('\u{1b}'), + "captured output cannot contain spinner/ANSI frames" + ); + if json { + let report: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!(report["graph"]["risk"]["assessment"]["rating"], "high"); + assert_eq!( + report["graph"]["risk"]["impact"][0]["checked_call_contracts"], + 1 + ); + assert_eq!( + report["graph"]["risk"]["impact"][0]["issues"] + .as_array() + .unwrap() + .len(), + 1 + ); + assert_eq!( + report["graph"]["findings"][0]["finding"]["requirement_or_rule"]["id"], + "compatibility.resolved-direct-call-contract" + ); + } else { + assert!(text.contains("Risk: High") && text.contains("1 current bound caller(s)")); + assert!(text.contains("F1") && text.contains("1 incompatible after-contract(s)")); + } + } + assert_eq!( + database_before, + std::fs::read(database).unwrap(), + "review remains read-only" + ); +} diff --git a/atomic-cli/tests/review_view.rs b/atomic-cli/tests/review_view.rs new file mode 100644 index 00000000..ec81a990 --- /dev/null +++ b/atomic-cli/tests/review_view.rs @@ -0,0 +1,353 @@ +//! Whole-view audits are local recorded snapshots, not per-change history replay. + +use atomic_core::{change::ChangeHeader, pristine::ViewScope, types::Base32}; +use atomic_repository::{record::RecordOptions, tracking::TrackingOptions, Repository}; +use serde_json::Value; +use std::{collections::BTreeSet, path::Path, process::Command}; + +fn record(repo: &Repository, message: &str) -> String { + repo.record( + repo.require_working_copy_id().unwrap(), + ChangeHeader::new(message), + RecordOptions::new() + .with_all(true) + .save_to_store(true) + .apply_after_record(true) + .enrich_kg(false), + ) + .unwrap() + .hash() + .to_base32() +} +fn write(repo: &Repository, path: &str, text: &str) { + let full = repo.root().join(path); + std::fs::create_dir_all(full.parent().unwrap()).unwrap(); + let tracked = full.exists(); + std::fs::write(full, text).unwrap(); + if !tracked { + repo.add( + repo.require_working_copy_id().unwrap(), + path, + TrackingOptions::default(), + ) + .unwrap(); + } +} + +fn command(root: &Path) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_atomic")); + command + .current_dir(root) + .env("ATOMIC_SESSION_ID", "../ambient-session-must-not-be-used") + .env("PATH", root.join("no-external-executables")) + .env("OPENAI_API_KEY", "must-not-be-used") + .env("ANTHROPIC_API_KEY", "must-not-be-used") + .env("OPENAI_BASE_URL", "http://127.0.0.1:1") + .env("ANTHROPIC_BASE_URL", "http://127.0.0.1:1"); + command +} + +fn document(html: &str) -> Value { + serde_json::from_str( + html.split("id=\"review-data\"") + .nth(1) + .unwrap() + .split_once('>') + .unwrap() + .1 + .split("") + .next() + .unwrap(), + ) + .unwrap() +} + +#[test] +fn named_view_audits_live_snapshot_once_without_switching_or_reading_dirty_bytes() { + let directory = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + let mut repo = Repository::init(directory.path()).unwrap(); + repo.init_vault().unwrap(); + let wc = repo.require_working_copy_id().unwrap(); + let active = repo.current_view().to_owned(); + write(&repo, "inherited.rs", "pub fn inherited() { todo!(); }\n"); + write(&repo, ".vault/generated.rs", "VAULT_NOT_CODE invalid {{{\n"); + write( + &repo, + "deleted.rs", + "pub fn deleted_marker() { todo!(); }\n", + ); + let base = record(&repo, "parent source"); + repo.create_draft_view("audit-target", &active).unwrap(); + repo.switch_view(wc, "audit-target").unwrap(); + write( + &repo, + "old-name.rs", + "pub fn OBSOLETE_REVISION() { todo!(); }\n", + ); + record(&repo, "old target source"); + let current = "pub fn current_revision() { todo!(); }\n"; + write(&repo, "old-name.rs", current); + record(&repo, "current target source"); + std::fs::rename( + directory.path().join("old-name.rs"), + directory.path().join("renamed.rs"), + ) + .unwrap(); + repo.move_file(wc, "old-name.rs", "renamed.rs").unwrap(); + std::fs::remove_file(directory.path().join("deleted.rs")).unwrap(); + write(&repo, "notes.txt", "unsupported source remains explicit\n"); + #[cfg(unix)] + { + std::fs::write( + outside.path().join("secret.rs"), + "pub fn EXTERNAL_SOURCE_MUST_NOT_BE_READ() { todo!(); }\n", + ) + .unwrap(); + std::os::unix::fs::symlink( + outside.path().join("secret.rs"), + directory.path().join("link.rs"), + ) + .unwrap(); + repo.add(wc, "link.rs", TrackingOptions::default()).unwrap(); + } + record(&repo, "rename delete and metadata"); + let expected_state = repo + .get_view_info("audit-target") + .unwrap() + .state + .to_base32(); + repo.create_draft_view("unrelated", &active).unwrap(); + repo.switch_view(wc, "unrelated").unwrap(); + write( + &repo, + "foreign.rs", + "pub fn FOREIGN_VIEW_ONLY() { todo!(); }\n", + ); + let foreign = record(&repo, "unrelated source"); + repo.switch_view(wc, &active).unwrap(); + std::fs::write( + directory.path().join("inherited.rs"), + "DIRTY_WORKTREE_NOT_RECORDED\n", + ) + .unwrap(); + std::fs::write( + directory.path().join("untracked.rs"), + "UNTRACKED_NOT_SOURCE\n", + ) + .unwrap(); + write(&repo, "staged.rs", "STAGED_NOT_RECORDED\n"); + let database = repo.dot_dir().join("atomic.redb"); + let compatibility = repo.dot_dir().join("current_view"); + let wc_id = repo.dot_dir().join("working_copy_id"); + let expected_wc = repo.working_copy_record(wc).unwrap(); + drop(repo); + let bytes = std::fs::read(&database).unwrap(); + let current_view = std::fs::read(&compatibility).unwrap(); + let id_bytes = std::fs::read(&wc_id).unwrap(); + let output = command(directory.path()) + .args(["review", "--view", "audit-target", "--json"]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(report["selection"]["kind"], "view"); + assert_eq!(report["source"]["view"], "audit-target"); + assert_eq!(report["source"]["view_state"], expected_state); + assert_eq!(report["source"]["working_copy_view"], active); + assert!(report["changes"].as_array().unwrap().is_empty()); + assert!(report["selected_roots"].as_array().unwrap().is_empty()); + let snapshot = &report["view_snapshot"]; + let reference = snapshot["source_ref"].as_str().unwrap(); + assert!(reference.starts_with("urn:atomic:view-snapshot:")); + let paths = snapshot["paths"].as_array().unwrap(); + for path in [ + "inherited.rs", + "renamed.rs", + "notes.txt", + ".vault/generated.rs", + ] { + assert!( + paths.contains(&Value::String(path.into())), + "missing {path}" + ); + } + for path in [ + "deleted.rs", + "old-name.rs", + "foreign.rs", + "staged.rs", + "untracked.rs", + ] { + assert!( + !paths.contains(&Value::String(path.into())), + "unexpected {path}" + ); + } + let findings = snapshot["analysis"]["findings"].as_array().unwrap(); + assert!(findings.len() >= 2); + for finding in findings { + assert_eq!(finding["change"], reference); + assert_eq!(finding["introduced_by_change"]["status"], "unknown"); + assert!(finding["evidence"] + .as_array() + .unwrap() + .iter() + .all(|item| item["kind"] != "diff")); + } + let metrics = snapshot["analysis"]["metrics"].as_array().unwrap(); + assert!(!metrics.is_empty()); + let mut identities = BTreeSet::new(); + for metric in metrics { + assert!( + identities.insert(( + metric["path"].to_string(), + metric["observation"]["metric"].to_string(), + metric["observation"]["subject"].to_string() + )), + "history duplicated a snapshot measurement" + ); + assert_eq!(metric["observation"]["before"]["status"], "unavailable"); + assert!(metric["delta"].is_null()); + } + let checks = snapshot["analysis"]["checks"].as_array().unwrap(); + #[cfg(unix)] + assert!(checks.iter().any(|check| check["path"] == "link.rs" + && check["status"] == "skipped" + && check["detail"].as_str().unwrap().contains("symlink"))); + for card in atomic_audit::AUDIT_CARDS { + assert!(checks.iter().any(|check| check["rule"] == card.id)); + } + assert!(report["dependency_closure"] + .as_array() + .unwrap() + .contains(&Value::String(base))); + assert!(!report["dependency_closure"] + .as_array() + .unwrap() + .contains(&Value::String(foreign))); + assert_eq!(report["graph"]["risk"]["basis"], "view_snapshot"); + assert_eq!(report["graph"]["risk"]["assessment"]["rating"], "unknown"); + let output = command(directory.path()) + .args(["review", "--view", "audit-target", "--html", "--no-open"]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let html = String::from_utf8(output.stdout).unwrap(); + if let Some(path) = std::env::var_os("ATOMIC_REVIEW_VIEW_ARTIFACT") { + std::fs::write(path, &html).unwrap(); + } + for forbidden in [ + "DIRTY_WORKTREE_NOT_RECORDED", + "OBSOLETE_REVISION", + "FOREIGN_VIEW_ONLY", + "STAGED_NOT_RECORDED", + "EXTERNAL_SOURCE_MUST_NOT_BE_READ", + ] { + assert!(!html.contains(forbidden)); + } + let doc = document(&html); + assert_eq!(doc["local_only"], true); + assert_eq!(doc["view"]["view_snapshot"]["view"], "audit-target"); + assert_eq!(doc["audit_cards"].as_array().unwrap().len(), 10); + assert_eq!(doc["metric_cards"].as_array().unwrap().len(), 10); + let source = doc["sources"] + .as_array() + .unwrap() + .iter() + .find(|source| source["path"] == "renamed.rs") + .unwrap(); + assert_eq!(source["after"]["text"], current); + assert_eq!(source["before"]["status"], "unavailable"); + let compressed = data_encoding::BASE64 + .decode(doc["report_archive"]["data"].as_str().unwrap().as_bytes()) + .unwrap(); + let embedded: Value = + serde_json::from_reader(flate2::read::GzDecoder::new(compressed.as_slice())).unwrap(); + assert_eq!(embedded, report); + let output = command(directory.path()) + .args(["review", "--view", "audit-target"]) + .output() + .unwrap(); + assert!(output.status.success()); + let terminal = String::from_utf8(output.stdout).unwrap(); + assert!( + terminal.contains("Selected view snapshot: audit-target") + && terminal.contains("View snapshot metrics") + ); + assert_eq!(std::fs::read(&database).unwrap(), bytes); + assert_eq!(std::fs::read(compatibility).unwrap(), current_view); + assert_eq!(std::fs::read(wc_id).unwrap(), id_bytes); + let repo = Repository::open_readonly(directory.path()).unwrap(); + assert_eq!(repo.current_view(), active); + assert_eq!(repo.working_copy_record(wc).unwrap(), expected_wc); + assert_eq!( + std::fs::read_to_string(directory.path().join("inherited.rs")).unwrap(), + "DIRTY_WORKTREE_NOT_RECORDED\n" + ); +} + +#[test] +fn empty_named_view_is_not_latest_change_and_selectors_fail_closed() { + let directory = tempfile::tempdir().unwrap(); + let mut repo = Repository::init(directory.path()).unwrap(); + repo.init_vault().unwrap(); + write(&repo, "live.rs", "fn active_only() { todo!(); }\n"); + let hash = record(&repo, "active-only source"); + repo.create_view_with_identity("empty", ViewScope::Shared, None) + .unwrap(); + drop(repo); + let output = command(directory.path()) + .args(["review", "--view", "empty", "--json"]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert!(report["view_snapshot"]["paths"] + .as_array() + .unwrap() + .is_empty()); + assert!(report["graph"]["findings"].as_array().unwrap().is_empty()); + let output = command(directory.path()) + .args(["review", "--view", "empty", "--html", "--no-open"]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let html = String::from_utf8(output.stdout).unwrap(); + if let Some(path) = std::env::var_os("ATOMIC_REVIEW_EMPTY_VIEW_ARTIFACT") { + std::fs::write(path, &html).unwrap(); + } + let doc = document(&html); + assert_eq!(doc["view"]["view_snapshot"]["file_count"], 0); + assert_eq!(doc["audit_cards"].as_array().unwrap().len(), 10); + assert_eq!(doc["metric_cards"].as_array().unwrap().len(), 10); + for args in [ + vec!["review", "--view", "missing"], + vec!["review", "--view", "empty", "--change", &hash], + vec!["review", "--view", "empty", "--intent", "unused"], + vec!["review", "--view", "empty", "--turn", "session:1"], + vec!["review", "--view", "empty", "--findings", "unused.json"], + vec!["review", "--view", "empty", "--risk-profile", "unused.json"], + vec!["review", "--view", "empty", "publish", "--view", "empty"], + ] { + let output = command(directory.path()).args(args).output().unwrap(); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + } +} diff --git a/atomic-cli/tests/review_viewer_browser.mjs b/atomic-cli/tests/review_viewer_browser.mjs new file mode 100644 index 00000000..3db2b20c --- /dev/null +++ b/atomic-cli/tests/review_viewer_browser.mjs @@ -0,0 +1,301 @@ +// Optional browser regression without npm dependencies. +// node review_viewer_browser.mjs REPORT.html CHROME_BINARY SCRATCH_PARENT +import { spawn } from 'node:child_process'; +import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { StringDecoder } from 'node:string_decoder'; +import assert from 'node:assert/strict'; +import { gzipSync, gunzipSync } from 'node:zlib'; + +const artifact = resolve(process.argv[2]); +const chrome = process.argv[3] || process.env.CHROME; +assert(chrome, 'Supply a Chrome/Chromium executable; the test never uses an existing browser profile.'); +const directory = mkdtempSync(join(process.argv[4] || tmpdir(), 'atomic-review-browser-')); +const child = spawn(chrome, ['--headless=new', '--remote-debugging-pipe', '--disable-gpu', '--disable-extensions', '--disable-background-networking', '--disable-component-update', '--no-first-run', '--no-default-browser-check', '--user-data-dir=' + join(directory, 'profile'), 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'] }); +let stderr = '', input = '', serial = 0; +const decoder = new StringDecoder('utf8'), pending = new Map(), listeners = new Set(); +child.stderr.on('data', chunk => { stderr += chunk; }); +child.stdio[4].on('data', chunk => { + input += decoder.write(chunk); + for (let end; (end = input.indexOf('\0')) >= 0;) { + const frame = input.slice(0, end); input = input.slice(end + 1); + if (!frame) continue; + const message = JSON.parse(frame); + if (message.id && pending.has(message.id)) { + const request = pending.get(message.id); pending.delete(message.id); clearTimeout(request.timeout); + if (message.error) request.reject(new Error(JSON.stringify(message.error))); else request.resolve(message.result); + } + for (const listener of listeners) listener(message); + } +}); +function send(method, params = {}, sessionId) { + return new Promise((resolve, reject) => { + const id = ++serial; + const timeout = setTimeout(() => { pending.delete(id); reject(new Error('CDP timed out: ' + method + '\n' + stderr)); }, 30000); + pending.set(id, { resolve, reject, timeout }); + child.stdio[3].write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + '\0'); + }); +} +function event(method, sessionId) { + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { listeners.delete(listener); reject(new Error('Missing browser event: ' + method)); }, 30000); + const listener = message => { + if (message.method === method && message.sessionId === sessionId) { clearTimeout(timeout); listeners.delete(listener); resolve(message.params); } + }; + listeners.add(listener); + }); +} +child.once('error', error => { for (const request of pending.values()) { clearTimeout(request.timeout); request.reject(error); } }); +child.once('exit', () => { for (const request of pending.values()) { clearTimeout(request.timeout); request.reject(new Error('Browser exited')); } pending.clear(); }); + +try { + await send('Browser.getVersion'); + const { targetId } = await send('Target.createTarget', { url: 'about:blank' }); + const { sessionId } = await send('Target.attachToTarget', { targetId, flatten: true }); + const page = (method, params) => send(method, params, sessionId); + const evaluate = async expression => { + const result = await page('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true, userGesture: true }); + assert(!result.exceptionDetails, JSON.stringify(result.exceptionDetails)); + return result.result.value; + }; + const errors = [], requests = []; + listeners.add(message => { + if (message.sessionId !== sessionId) return; + if (message.method === 'Runtime.exceptionThrown') errors.push(message.params.exceptionDetails); + if (message.method === 'Network.requestWillBeSent') requests.push(message.params.request.url); + }); + await page('Page.enable'); await page('Runtime.enable'); await page('Network.enable'); + await page('Emulation.setDeviceMetricsOverride', { width: 1600, height: 1100, deviceScaleFactor: 1, mobile: false }); + const load = async path => { const loaded = event('Page.loadEventFired', sessionId); await page('Page.navigate', { url: pathToFileURL(path).href }); await loaded; }; + await load(artifact); + assert.equal(errors.length, 0, JSON.stringify(errors)); + assert.equal(await evaluate(`document.querySelectorAll('[role="tab"]').length`), 4); + assert(await evaluate(`document.getElementById('tab-summary').getAttribute('aria-selected')==='true' && !document.getElementById('panel-summary').hidden`)); + assert(await evaluate(`document.getElementById('review-toolbar').hidden && document.getElementById('file-navigation').hidden && document.getElementById('card-inspector').hidden`)); + assert(await evaluate(`['audit-overview','conformance-overview','risk-overview'].every(id=>document.getElementById(id).closest('[role="tabpanel"]').id==='panel-summary')`),'Report-wide overviews belong only to Summary'); + assert.equal(await evaluate(`document.querySelectorAll('#summary-actions button').length`),3); + let image = await page('Page.captureScreenshot', { format: 'png' }); + writeFileSync(join(directory,'summary-desktop.png'),Buffer.from(image.data,'base64')); + const expected = await evaluate(`(() => { const d=JSON.parse(document.getElementById('review-data').textContent); const r=d.view; const c=r.view_comparison?.conformance || r.view_snapshot?.conformance; return { findings:r.graph.findings.filter(f=>f.passes.includes('anti_slop')).length, riskFindings:r.graph.findings.filter(f=>f.passes.includes('blast_radius_risk')).map(f=>f.number), criteria:r.graph.criteria.length, viewIntents:c?.intents || [], intentView:c?.scope?.view || null, metrics:d.metric_cards.length, observations:r.graph.nodes.filter(n=>n.kind==='metric').length, scope:r.graph.scope.selected_roots, snapshot:r.view_snapshot?.view || null, comparison:r.view_comparison || null }; })()`); + assert(await evaluate(`(()=>{const logo=document.querySelector('.atomic-logo');return logo?.complete && logo.naturalWidth===560 && logo.src.startsWith('data:image/png;base64,') && logo.alt==='Atomic';})()`), 'Official logo must be embedded and decoded offline'); + assert.equal(await evaluate(`getComputedStyle(document.documentElement).getPropertyValue('--canvas').trim()`),'#07041a'); + assert.equal(await evaluate(`getComputedStyle(document.documentElement).getPropertyValue('--accent').trim()`),'#ff0a8c'); + const contrasts = await evaluate(`(() => { + const rgba = color => (color.match(/[\\d.]+/g) || []).map(Number); + const over = (a,b) => a.slice(0,3).map((channel,index)=>channel*(a[3]??1)+b[index]*(1-(a[3]??1))); + function background(element) { if(!element)return [7,4,26]; return over(rgba(getComputedStyle(element).backgroundColor),background(element.parentElement)); } + const luminance = color => color.map(value=>{value/=255;return value<=.04045?value/12.92:((value+.055)/1.055)**2.4}).reduce((sum,value,index)=>sum+value*[.2126,.7152,.0722][index],0); + return ['body','.region-meta','.overview p','a','.badge','.source-toolbar button[aria-pressed=true]'].flatMap(selector=>Array.from(document.querySelectorAll(selector)).slice(0,12).filter(node=>node.getClientRects().length).map(node=>{ + const bg=background(node), fg=over(rgba(getComputedStyle(node).color),bg), a=luminance(fg), b=luminance(bg); + return {selector,ratio:(Math.max(a,b)+.05)/(Math.min(a,b)+.05)}; + })); + })()`); + assert(contrasts.every(item=>item.ratio>=4.5),'Review text must meet AA contrast: '+JSON.stringify(contrasts)); + if (expected.comparison) { + assert(await evaluate(`document.querySelector('.comparison-direction').textContent.includes('From · before') && document.querySelector('.comparison-direction').textContent.includes('To · after')`)); + assert.equal(await evaluate(`document.querySelectorAll('[data-file-comparison]').length`),expected.comparison.files.length); + } + assert.equal(expected.metrics, 10); + assert.equal(await evaluate(`document.querySelectorAll('#card-picker optgroup[label="Metric cards"] option').length`), 10); + const localCoverage = await evaluate(`(() => { + const d=JSON.parse(document.getElementById('review-data').textContent); + const rows=Array.from(document.querySelectorAll('#card-coverage tr[data-card-id]')); + return {local:d.local_only, audits:rows.filter(row=>row.dataset.kind==='audit').map(row=>row.dataset.cardId).sort(), + metrics:rows.filter(row=>row.dataset.kind==='metric').map(row=>row.dataset.cardId).sort(), + expectedAudits:d.audit_cards.map(card=>card.id).sort(), expectedMetrics:d.metric_cards.map(card=>'metric.'+card.metric.replaceAll('_','-')).sort(), + totals:rows.filter(row=>row.dataset.kind==='metric').reduce((sum,row)=>sum+Number(row.cells[3].textContent),0)}; + })()`); + assert.equal(localCoverage.local, true); + assert.deepEqual(localCoverage.audits, localCoverage.expectedAudits); + assert.deepEqual(localCoverage.metrics, localCoverage.expectedMetrics); + assert.equal(localCoverage.totals, expected.observations, 'All observations must be accounted for, not just finding-related metrics'); + await evaluate(`document.getElementById('card-coverage').dataset.renderProbe='stable';document.querySelector('#summary-actions button[data-section="conformance"]').click()`); + assert(await evaluate(`!document.getElementById('panel-conformance').hidden && document.getElementById('panel-summary').hidden`)); + await evaluate(`document.getElementById('tab-summary').click()`); + await evaluate(`document.getElementById('card-coverage').open=true;document.querySelector('#card-coverage tr[data-kind="metric"] button').click()`); + assert(await evaluate(`!document.getElementById('panel-slop').hidden && document.getElementById('panel-summary').hidden && !document.getElementById('card-inspector').hidden`),'Summary card links must open the visible detail inspector'); + assert(await evaluate(`document.getElementById('panel-slop').firstElementChild.id==='slop-selection' && !document.querySelector('#panel-slop .overview')`),'File views must start with the selected evidence, not the report overview'); + assert(await evaluate(`document.getElementById('card-content').textContent.includes('Definition')`)); + assert(await evaluate(`document.getElementById('card-content').textContent.includes('All recorded observations')`)); + await evaluate(`document.getElementById('card-coverage').open=false`); + if(expected.comparison) { + for (const value of ['new','existing','resolved','uncertain']) { + await evaluate(`document.getElementById('region-filter').value=${JSON.stringify(value)};document.getElementById('region-filter').dispatchEvent(new Event('change',{bubbles:true}))`); + const selected=await evaluate(`Array.from(document.querySelectorAll('#slop-selection .finding h3 .badge:last-child')).map(node=>node.textContent.toLowerCase())`); + assert(selected.every(status=>value==='uncertain' ? ['changed','unknown'].includes(status) : status===value), 'Lifecycle filter must also filter findings in the selected region'); + } + await evaluate(`document.getElementById('region-filter').value='concerns';document.getElementById('region-filter').dispatchEvent(new Event('change',{bubbles:true}))`); + } + assert(await evaluate(`document.body.textContent.includes('not signed approval')`)); + if (expected.findings) { + const auditRendered=await evaluate(`(()=>{ + const d=JSON.parse(document.getElementById('review-data').textContent),numbers=new Set(d.view.graph.findings.filter(f=>f.passes.includes('anti_slop')).map(f=>f.number)),seen=new Set(); + for(const region of d.regions.filter(region=>region.findings.some(number=>numbers.has(number)))) { + const control=Array.from(document.querySelectorAll('#files .region-button')).find(button=>button.dataset.region===region.id);if(!control)continue;control.click(); + for(const finding of document.querySelectorAll('#slop-selection .finding'))seen.add(Number(finding.dataset.finding)); + } + return {seen:[...seen].sort((a,b)=>a-b),expected:[...numbers].sort((a,b)=>a-b)}; + })()`); + assert.deepEqual(auditRendered.seen,auditRendered.expected,'Every JSON audit finding must be renderable in HTML'); + assert(await evaluate(`document.querySelectorAll('#files .region-button').length > 0`)); + const selectedRegion=await evaluate(`document.querySelector('#files .region-button[aria-current=true]').dataset.region`); + await evaluate(`document.getElementById('tab-summary').click();document.getElementById('tab-slop').click()`); + assert.equal(await evaluate(`document.querySelector('#files .region-button[aria-current=true]').dataset.region`),selectedRegion,'Returning from Summary must retain the selected region'); + assert.equal(await evaluate(`document.getElementById('card-coverage').dataset.renderProbe`),'stable','Summary tables must not be rebuilt on each file selection'); + assert(await evaluate(`document.querySelector('#slop-selection .finding').textContent.includes('F')`)); + await evaluate(`document.querySelector('#slop-selection .finding .card-callout').click()`); + assert(await evaluate(`document.getElementById('card-content').textContent.includes('Supported patterns')`)); + if (await evaluate(`!!document.querySelector('.metrics-block .card-callout')`)) { + await evaluate(`for(const item of document.querySelectorAll('#slop-selection details')){if(item.querySelector('summary').textContent.includes('measurements & metric cards'))item.open=true}`); + await evaluate(`document.querySelector('.metrics-block .card-callout').click()`); + assert(await evaluate(`document.getElementById('card-content').textContent.includes('Definition')`)); + await evaluate(`for(const item of document.querySelectorAll('#slop-selection details')){if(item.querySelector('summary').textContent.includes('measurements & metric cards'))item.open=false}`); + } + if (expected.snapshot) { + assert(await evaluate(`document.querySelector('#slop-selection .source-toolbar button').hidden`)); + assert(await evaluate(`document.querySelectorAll('#slop-selection .source-toolbar button')[2].hidden`)); + assert(await evaluate(`document.querySelectorAll('#slop-selection .source-toolbar button')[1].textContent==='View snapshot'`)); + assert.equal(await evaluate(`document.getElementById('region-filter').value`),'all'); + assert(await evaluate(`document.querySelector('#region-filter option[value="changed"]').disabled`)); + } else { + await evaluate(`document.querySelector('#slop-selection .source-toolbar button').click()`); + assert(await evaluate(`document.querySelector('#slop-selection .source-toolbar button').getAttribute('aria-pressed')==='true'`)); + await evaluate(`document.querySelectorAll('#slop-selection .source-toolbar button')[1].click()`); + assert(await evaluate(`document.querySelectorAll('#slop-selection .source-toolbar button')[1].getAttribute('aria-pressed')==='true'`)); + } + await evaluate(`document.getElementById('search').value='NO_MATCH_FOR_REVIEW_VIEWER_TEST';document.getElementById('search').dispatchEvent(new Event('input',{bubbles:true}))`); + assert.equal(await evaluate(`document.querySelectorAll('#files .region-button').length`), 0); + await evaluate(`document.getElementById('search').value='';document.getElementById('search').dispatchEvent(new Event('input',{bubbles:true}))`); + const comparable = await evaluate(`(()=>{const d=JSON.parse(document.getElementById('review-data').textContent);const nodes=new Map(d.view.graph.nodes.map(n=>[n.id,n]));for(const r of d.regions){if(!r.findings.length||r.side!=='after')continue;for(const id of r.metrics){const n=nodes.get(id);if(n?.properties.before_location&&n.properties.observation.before.status==='measured'&&n.properties.observation.after.status==='measured')return{id:r.id,start:n.properties.before_location.start_line};}}return null;})()`); + if (comparable) { + await evaluate(`Array.from(document.querySelectorAll('#files .region-button')).find(button=>button.dataset.region===${JSON.stringify(comparable.id)}).click();document.querySelector('#slop-selection .source-toolbar button').click()`); + assert.equal(await evaluate(`document.querySelector('#slop-selection .source-line.highlight .line-number').textContent`), String(comparable.start)); + assert(await evaluate(`document.querySelector('#slop-selection .source-caption').textContent.includes('Matched recorded subject') || document.querySelector('#slop-selection .source-caption').textContent.includes('Matched local observation')`)); + } + } + await evaluate(`document.getElementById('region-filter').value='all';document.getElementById('region-filter').dispatchEvent(new Event('change',{bubbles:true}))`); + assert.equal(await evaluate(`document.querySelectorAll('#files .region-button').length>0`), expected.observations > 0); + await evaluate(`document.getElementById('region-filter').value='concerns';document.getElementById('region-filter').dispatchEvent(new Event('change',{bubbles:true}))`); + await evaluate(`document.getElementById('tab-conformance').click()`); + assert(await evaluate(`!document.getElementById('panel-conformance').hidden && document.getElementById('panel-slop').hidden`)); + if(expected.intentView)assert.equal(await evaluate(`document.getElementById('navigation-title').textContent`),'View intents'); + for(const intent of expected.viewIntents) { + assert.equal(intent.view,expected.intentView); + assert(await evaluate(`(()=>{const row=Array.from(document.querySelectorAll('#files .intent-button')).find(node=>node.dataset.intent===${JSON.stringify(intent.id)});return !!row && row.textContent.includes(${JSON.stringify(intent.human_key)}) && row.textContent.includes(${JSON.stringify(intent.title)});})()`),'Every scoped intent must appear by human key/title even without change governance'); + for(const query of [intent.title,intent.human_key]) { + await evaluate(`document.getElementById('search').value=${JSON.stringify(query)};document.getElementById('search').dispatchEvent(new Event('input',{bubbles:true}))`); + assert(await evaluate(`Array.from(document.querySelectorAll('#files .intent-button')).some(node=>node.dataset.intent===${JSON.stringify(intent.id)})`),'Intent title/key must be searchable'); + } + await evaluate(`document.getElementById('search').value='';document.getElementById('search').dispatchEvent(new Event('input',{bubbles:true}))`); + } + if(expected.viewIntents.length) { + const withoutCriteria=await evaluate(`(()=>{const d=JSON.parse(document.getElementById('review-data').textContent).view,c=d.view_comparison?.conformance || d.view_snapshot?.conformance;return c.intents.find(intent=>!d.graph.criteria.some(criterion=>criterion.intent===intent.id))?.id || null;})()`); + if(withoutCriteria) { + await evaluate(`Array.from(document.querySelectorAll('#files .intent-button')).find(node=>node.dataset.intent===${JSON.stringify(withoutCriteria)}).click()`); + assert(await evaluate(`document.getElementById('criteria').textContent.includes('No acceptance criteria are available for this scoped intent')`)); + } + } + const firstCriterion=await evaluate(`JSON.parse(document.getElementById('review-data').textContent).view.graph.criteria[0]?.id || null`); + const linkedFinding=await evaluate(`(()=>{const g=JSON.parse(document.getElementById('review-data').textContent).view.graph;const f=g.findings.find(f=>f.related_criteria.some(id=>g.criteria.some(c=>c.id===id)));return f?{number:f.number,criterion:f.related_criteria.find(id=>g.criteria.some(c=>c.id===id))}:null;})()`); + if(linkedFinding) { + await evaluate(`document.getElementById('search').value='F'+${linkedFinding.number};document.getElementById('search').dispatchEvent(new Event('input',{bubbles:true}))`); + assert(await evaluate(`Array.from(document.querySelectorAll('#files .criterion-button')).some(node=>node.dataset.criterion===${JSON.stringify(linkedFinding.criterion)})`),'Related finding numbers must be searchable without treating them as acceptance verdicts'); + await evaluate(`document.getElementById('search').value='';document.getElementById('search').dispatchEvent(new Event('input',{bubbles:true}))`); + } + if(firstCriterion)await evaluate(`Array.from(document.querySelectorAll('#files .criterion-button')).find(node=>node.dataset.criterion===${JSON.stringify(firstCriterion)}).click()`); + if (!expected.criteria) assert(await evaluate(`document.getElementById('criteria').textContent.includes(${JSON.stringify(expected.viewIntents.length?'No acceptance criteria are available for this scoped intent':'No scoped criterion assessment')})`)); + else { + assert(await evaluate(`(()=>{const r=JSON.parse(document.getElementById('review-data').textContent).view;const criterion=r.graph.criteria[0];const text=document.getElementById('criteria').textContent;return text.includes(criterion.text)&&text.includes('Author declared: '+criterion.declared_status)&&text.includes('Review: '+criterion.review_assessment.replaceAll('_',' ').replace(/^./,c=>c.toUpperCase()));})()`)); + const nested=await evaluate(`(()=>{const row=document.querySelector('#files .criterion-button[aria-current=true]');return !!row?.closest('.intent-group')?.querySelector('.intent-button');})()`); + assert(nested,'Criteria must be grouped beneath their intent'); + const query=await evaluate(`JSON.parse(document.getElementById('review-data').textContent).view.graph.criteria[0].text`); + await evaluate(`document.getElementById('search').value=${JSON.stringify(query)};document.getElementById('search').dispatchEvent(new Event('input',{bubbles:true}))`); + assert(await evaluate(`Array.from(document.querySelectorAll('#files .criterion-button')).some(node=>node.dataset.criterion===${JSON.stringify(firstCriterion)})`)); + await evaluate(`document.getElementById('search').value='';document.getElementById('search').dispatchEvent(new Event('input',{bubbles:true}))`); + if (await evaluate(`!!document.querySelector('#criteria > .callouts button, #criteria .criterion-declaration .callouts button')`)) { + await evaluate(`document.querySelector('#criteria > .callouts button, #criteria .criterion-declaration .callouts button').click()`); + assert(await evaluate(`!!document.querySelector('#criteria .source-toolbar')`)); + } + } + assert(await evaluate(`document.documentElement.scrollWidth <= window.innerWidth`)); + image=await page('Page.captureScreenshot',{format:'png'});writeFileSync(join(directory,'conformance-desktop.png'),Buffer.from(image.data,'base64')); + await evaluate(`document.getElementById('tab-risk').click();document.getElementById('tab-risk').focus()`); + assert(await evaluate(`!document.getElementById('panel-risk').hidden`)); + assert(await evaluate(`document.getElementById('panel-risk').firstElementChild.id==='risk-selection' && !document.querySelector('#panel-risk .overview')`)); + assert(await evaluate(`document.getElementById('risk-overview').textContent.includes('risk')`)); + if(expected.riskFindings.length) { + const rendered=await evaluate(`(()=>{ + const d=JSON.parse(document.getElementById('review-data').textContent),numbers=new Set(d.view.graph.findings.filter(f=>f.passes.includes('blast_radius_risk')).map(f=>f.number)),seen=new Set(); + for(const region of d.regions.filter(region=>region.findings.some(number=>numbers.has(number)))) { + const control=Array.from(document.querySelectorAll('#files .region-button')).find(button=>button.dataset.region===region.id);if(!control)continue;control.click(); + for(const finding of document.querySelectorAll('#risk-selection .finding'))seen.add(Number(finding.dataset.finding)); + } + return [...seen].sort((a,b)=>a-b); + })()`); + assert.deepEqual(rendered,expected.riskFindings.sort((a,b)=>a-b),'Every JSON risk finding must be renderable in HTML, including finding 101 and beyond'); + } + await page('Input.dispatchKeyEvent', { type: 'keyDown', key: 'ArrowLeft', code: 'ArrowLeft', windowsVirtualKeyCode: 37 }); + await page('Input.dispatchKeyEvent', { type: 'keyUp', key: 'ArrowLeft', code: 'ArrowLeft', windowsVirtualKeyCode: 37 }); + assert.equal(await evaluate(`document.activeElement.id`), 'tab-conformance'); + for(const [key,id] of [['Home','tab-summary'],['End','tab-risk'],['ArrowRight','tab-summary'],['ArrowLeft','tab-risk']]) { + await page('Input.dispatchKeyEvent',{type:'keyDown',key,code:key}); + await page('Input.dispatchKeyEvent',{type:'keyUp',key,code:key}); + assert.equal(await evaluate(`document.activeElement.id`),id); + } + await evaluate(`document.getElementById('tab-slop').click();document.getElementById('tab-slop').focus();window.scrollTo(0,0)`); + assert(await evaluate(`document.documentElement.scrollWidth <= window.innerWidth`)); + image = await page('Page.captureScreenshot', { format: 'png' }); + writeFileSync(join(directory, 'desktop.png'), Buffer.from(image.data, 'base64')); + const mobileReady = evaluate(`new Promise(resolve=>{const query=matchMedia('(max-width:700px)');if(query.matches)resolve(true);else query.addEventListener('change',()=>resolve(true),{once:true});})`); + await page('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true }); + await mobileReady; + assert(await evaluate(`!document.getElementById('file-drawer').open`)); + assert(await evaluate(`document.documentElement.scrollWidth <= window.innerWidth`), 'Mobile viewport must not overflow horizontally'); + image = await page('Page.captureScreenshot', { format: 'png' }); + writeFileSync(join(directory, 'mobile.png'), Buffer.from(image.data, 'base64')); + await evaluate(`document.getElementById('tab-summary').click();document.getElementById('tab-summary').focus();window.scrollTo(0,0)`); + assert(await evaluate(`document.documentElement.scrollWidth <= window.innerWidth && document.getElementById('review-toolbar').hidden && document.getElementById('file-navigation').hidden && document.getElementById('card-inspector').hidden`)); + image=await page('Page.captureScreenshot',{format:'png'}); + writeFileSync(join(directory,'summary-mobile.png'),Buffer.from(image.data,'base64')); + await evaluate(`document.getElementById('tab-conformance').click();document.getElementById('tab-conformance').focus();window.scrollTo(0,0)`); + if(expected.viewIntents.length) { + await evaluate(`document.getElementById('file-drawer').open=true;(document.querySelector('#files .criterion-button') || document.querySelector('#files .intent-button')).click()`); + assert(await evaluate(`!document.getElementById('file-drawer').open`),'Mobile intent/criterion selection must close the navigation drawer'); + } + assert(await evaluate(`document.documentElement.scrollWidth <= window.innerWidth`),'Grouped conformance navigation must fit the mobile viewport'); + image=await page('Page.captureScreenshot',{format:'png'});writeFileSync(join(directory,'conformance-mobile.png'),Buffer.from(image.data,'base64')); + + // Hostile report/source content must remain inert, even in navigation labels. + // Keep this explicitly synthetic artifact in the private scratch directory. + const original = readFileSync(artifact, 'utf8'); + const pattern = /(]*\bid="review-data"[^>]*>)([\s\S]*?)(<\/script>)/; + const fixture = JSON.parse(original.match(pattern)[2]); + const hostile = ''; + fixture.view.graph.scope.view = hostile; + fixture.view.warnings.push(hostile); + if(fixture.view.view_comparison) { + fixture.view.view_comparison.from.view=hostile; + fixture.view.view_comparison.files[0].path=hostile; + } + fixture.audit_cards[0].title = hostile; + const scoped=fixture.view.view_comparison?.conformance || fixture.view.view_snapshot?.conformance; + if(scoped?.intents?.length){scoped.intents[0].title=hostile;scoped.intents[0].human_key=hostile;} + const reportText = gunzipSync(Buffer.from(fixture.report_archive.data,'base64')).toString('utf8'); + fixture.report_archive.data = gzipSync(reportText.slice(0,-1) + ',"precision_probe":18446744073709551615}',{level:1}).toString('base64'); + const encoded = JSON.stringify(fixture).replace(/[<>&\u2028\u2029]/g, character => '\\u' + character.charCodeAt(0).toString(16).padStart(4, '0')); + const hostilePath = join(directory, 'hostile-fixture.html'); + writeFileSync(hostilePath, original.replace(pattern, (_, prefix, _data, suffix) => prefix + encoded + suffix)); + await load(hostilePath); + await evaluate(`document.getElementById('tab-conformance').click()`); + assert(await evaluate(`!document.getElementById('audit-xss') && !globalThis.__audit_xss`)); + const downloaded = await evaluate(`(async()=>{let captured,ready;const prepared=new Promise(resolve=>ready=resolve); const create=URL.createObjectURL;const click=HTMLAnchorElement.prototype.click;URL.createObjectURL=blob=>{captured=blob;ready();return create.call(URL,blob)};HTMLAnchorElement.prototype.click=function(){};document.getElementById('download').click();await prepared;const text=await captured.text();URL.createObjectURL=create;HTMLAnchorElement.prototype.click=click;return text.includes('"precision_probe":18446744073709551615');})()`); + assert(downloaded, 'Downloads must preserve original u64 JSON text'); + assert.equal(errors.length, 0, JSON.stringify(errors)); + assert(requests.every(url => url.startsWith('file:') || url.startsWith('data:')), 'Viewer must not make external requests: ' + requests.join(', ')); + console.log(JSON.stringify({ passed: true, findings: expected.findings, riskFindings:expected.riskFindings.length, criteria:expected.criteria, viewIntents:expected.viewIntents.length, intentView:expected.intentView, metricCards: expected.metrics, selectedRoots: expected.scope, snapshotView: expected.snapshot, screenshots: ['summary-desktop.png','desktop.png','conformance-desktop.png','summary-mobile.png','mobile.png','conformance-mobile.png'].map(path=>join(directory,path)), externalRequests: 0, javascriptErrors: errors.length }, null, 2)); +} finally { + await send('Browser.close').catch(() => {}); + if (child.exitCode === null) child.kill('SIGTERM'); +} diff --git a/atomic-core/examples/compact_semantic_codec.rs b/atomic-core/examples/compact_semantic_codec.rs new file mode 100644 index 00000000..e0fe6291 --- /dev/null +++ b/atomic-core/examples/compact_semantic_codec.rs @@ -0,0 +1,213 @@ +//! Read-only, redb-free sizing experiment. See docs/COMPACT-SEMANTIC-CODEC-EXPERIMENT.md. +#[path = "compact_semantic_codec/codec.rs"] +mod codec; + +use anyhow::{ensure, Context, Result}; +use atomic_core::change::{ + format_v3::{ChangeReader, SectionType}, + FileOps, +}; +use atomic_core::Base32; +use serde::Serialize; +use std::{ + fs, + io::{BufReader, Read}, + path::{Path, PathBuf}, + time::Instant, +}; + +#[derive(Default, Serialize)] +struct Sizes { + objects: usize, + original_object_bytes: usize, + original_semantic_bytes: usize, + baseline_semantic_bytes: usize, + compact_semantic_bytes: usize, + projected_object_bytes: usize, + compressed_content_bytes: usize, + authored_content_bytes: usize, + files: usize, + lines: usize, + tokens: usize, +} + +impl Sizes { + fn add(&mut self, s: &Self) { + self.objects += s.objects; + self.original_object_bytes += s.original_object_bytes; + self.original_semantic_bytes += s.original_semantic_bytes; + self.baseline_semantic_bytes += s.baseline_semantic_bytes; + self.compact_semantic_bytes += s.compact_semantic_bytes; + self.projected_object_bytes += s.projected_object_bytes; + self.compressed_content_bytes += s.compressed_content_bytes; + self.authored_content_bytes += s.authored_content_bytes; + self.files += s.files; + self.lines += s.lines; + self.tokens += s.tokens; + } +} + +#[derive(Serialize)] +struct Row { + path: PathBuf, + schema: u32, + verified_hash: String, + sizes: Sizes, + encode_ms: f64, + decode_ms: f64, + exact_roundtrip: bool, +} + +fn collect(path: &Path, paths: &mut Vec) -> Result<()> { + if path.is_dir() { + for entry in fs::read_dir(path)? { + collect(&entry?.path(), paths)?; + } + } else if path.extension().is_some_and(|s| s == "change") { + paths.push(path.into()); + } + Ok(()) +} + +fn measure(path: &Path, level: i32) -> Result { + let mut input = BufReader::new(fs::File::open(path)?); + let mut reader = ChangeReader::open(&mut input)?; + let schema = reader.file_header().version; + let mut semantic = None; + let mut content = Vec::new(); + let mut sizes = Sizes { + objects: 1, + original_object_bytes: fs::metadata(path)?.len().try_into()?, + ..Sizes::default() + }; + let mut next_chunk = 0; + while let Some(section) = reader.next_section()? { + match section.section_type { + SectionType::Semantic => { + ensure!( + semantic.is_none(), + "experiment expects one aggregate semantic section" + ); + sizes.original_semantic_bytes += section.compressed_size as usize; + semantic = Some(section.payload); + } + SectionType::Content => { + let info = section + .content_chunk_info + .context("missing chunk metadata")?; + ensure!( + info.chunk_index == next_chunk, + "nonsequential content chunks" + ); + ensure!( + section.payload.len() == info.uncompressed_len as usize, + "chunk length mismatch" + ); + ensure!( + *blake3::hash(§ion.payload).as_bytes() == info.chunk_hash, + "chunk hash mismatch" + ); + next_chunk += 1; + sizes.compressed_content_bytes += section.compressed_size as usize; + content.extend(section.payload); + } + _ => {} + } + } + let hash = reader.verify()?; + ensure!( + input.read(&mut [0])? == 0, + "trailing bytes after change trailer" + ); + sizes.authored_content_bytes = content.len(); + let mut encode_ms = 0.0; + let mut decode_ms = 0.0; + if let Some(raw) = semantic { + let (ops, rest): (Vec, _) = postcard::take_from_bytes(&raw)?; + ensure!(rest.is_empty(), "trailing semantic bytes"); + sizes.files = ops.len(); + sizes.lines = ops.iter().map(FileOps::line_count).sum(); + sizes.tokens = ops.iter().map(FileOps::token_count).sum(); + sizes.baseline_semantic_bytes = zstd::encode_all(raw.as_slice(), level)?.len(); + let start = Instant::now(); + let encoded = codec::encode(&ops, &content, level)?; + encode_ms = start.elapsed().as_secs_f64() * 1000.0; + sizes.compact_semantic_bytes = encoded.len(); + let start = Instant::now(); + // Only encoded bytes + authored content are passed: no repository, no redb. + let decoded = codec::decode(&encoded, &content)?; + decode_ms = start.elapsed().as_secs_f64() * 1000.0; + ensure!( + decoded == ops, + "semantic operation/identity round-trip mismatch" + ); + ensure!( + postcard::to_allocvec(&decoded)? == raw, + "expanded postcard bytes differ" + ); + } + sizes.projected_object_bytes = + sizes.original_object_bytes - sizes.original_semantic_bytes + sizes.compact_semantic_bytes; + Ok(Row { + path: path.into(), + schema, + verified_hash: atomic_core::types::Hash::from_bytes(hash).to_base32(), + sizes, + encode_ms, + decode_ms, + exact_roundtrip: true, + }) +} + +fn main() -> Result<()> { + let mut args = std::env::args().skip(1); + let source = args + .next() + .context("usage: compact_semantic_codec [zstd-level:1..19]")?; + let level: i32 = args.next().map_or(Ok(3), |s| s.parse())?; + ensure!( + (1..=19).contains(&level) && args.next().is_none(), + "expected zstd level 1..19" + ); + ensure!(Path::new(&source).exists(), "source does not exist"); + let mut paths = Vec::new(); + collect(Path::new(&source), &mut paths)?; + paths.sort(); + ensure!(!paths.is_empty(), "no .change files found"); + let mut totals = Sizes::default(); + let mut rows = Vec::new(); + let mut failures = Vec::new(); + for path in paths { + match measure(&path, level).with_context(|| path.display().to_string()) { + Ok(row) => { + eprintln!( + "{}: semantic {} -> {} bytes; object {} -> {}; exact round-trip OK", + path.file_name().unwrap().to_string_lossy(), + row.sizes.original_semantic_bytes, + row.sizes.compact_semantic_bytes, + row.sizes.original_object_bytes, + row.sizes.projected_object_bytes + ); + totals.add(&row.sizes); + rows.push(row); + } + Err(error) => { + eprintln!("FAILED: {error:#}"); + failures.push(format!("{error:#}")); + } + } + } + println!( + "{}", + serde_json::to_string_pretty(&serde_json::json!({ + "experiment": "compact-semantic-v1-not-production", "zstd_level": level, + "notes": "Projected objects replace only the semantic payload; all graph/content/owner/dependency/signature bytes remain counted. New object hashes/signatures would be required. No Git-pack equivalence claimed.", + "totals": totals, "rows": rows, "failures": failures, + }))? + ); + ensure!( + failures.is_empty(), + "one or more inputs failed; results cover successful inputs only" + ); + Ok(()) +} diff --git a/atomic-core/examples/compact_semantic_codec/codec.rs b/atomic-core/examples/compact_semantic_codec/codec.rs new file mode 100644 index 00000000..215db0ca --- /dev/null +++ b/atomic-core/examples/compact_semantic_codec/codec.rs @@ -0,0 +1,499 @@ +//! Experiment only: columnar, reversible FileOps encoding. Not a wire contract. +use anyhow::{bail, ensure, Context, Result}; +use atomic_core::{ + change::{FileOps, LineOps}, + crdt::{BranchId, BranchOp, LeafId, LeafOp, TrunkId, TrunkOp}, + diff::token::TokenKind, + types::{ChangePosition, NodeId}, +}; +use serde::{Deserialize, Serialize}; +use std::{collections::HashMap, io::Read}; + +const MAGIC: &[u8; 5] = b"ATSC\x01"; +const MAX_DECODED: u64 = 512 * 1024 * 1024; + +#[derive(Default, Serialize, Deserialize)] +struct Columns { + content_hash: [u8; 32], + files: Vec<(TrunkId, String, Option)>, + control: Vec, + owners: Vec, + indices: Vec, + numbers: Vec, + positions: Vec, + kinds: Vec, + references: Vec, + literals: Vec, +} + +fn put(out: &mut Vec, mut n: u64) { + while n >= 128 { + out.push((n as u8) | 128); + n >>= 7; + } + out.push(n as u8); +} + +fn get(input: &mut &[u8]) -> Result { + let mut n = 0; + for shift in (0..70).step_by(7) { + let (&b, rest) = input.split_first().context("truncated varint")?; + *input = rest; + ensure!(shift != 63 || b <= 1, "varint overflow"); + n |= u64::from(b & 127) << shift; + if b < 128 { + ensure!(shift == 0 || b != 0, "noncanonical varint"); + return Ok(n); + } + } + bail!("varint overflow") +} + +// Wrapping differences cover the entire u64 domain, including descending IDs. +fn delta(out: &mut Vec, previous: &mut u64, next: u64) { + let d = next.wrapping_sub(*previous); + put(out, (d << 1) ^ ((d as i64 >> 63) as u64)); + *previous = next; +} + +fn undelta(input: &mut &[u8], previous: &mut u64) -> Result { + let z = get(input)?; + let d = (z >> 1) ^ 0u64.wrapping_sub(z & 1); + *previous = previous.wrapping_add(d); + Ok(*previous) +} + +#[derive(Default)] +struct State { + owner: u64, + index: u64, + number: u64, + position: u64, + reference: u64, + content_cursor: usize, +} + +struct Encoder<'a> { + c: Columns, + s: State, + content: &'a [u8], + lines: HashMap<&'a [u8], usize>, + literals: HashMap, usize>, +} + +impl Encoder<'_> { + fn id(&mut self, owner: NodeId, index: u32) { + delta(&mut self.c.owners, &mut self.s.owner, owner.get()); + delta(&mut self.c.indices, &mut self.s.index, index.into()); + } + + fn branch(&mut self, id: BranchId) { + self.id(id.change_id(), id.branch_idx()); + } + + fn optional_branch(&mut self, id: Option) { + put(&mut self.c.control, u64::from(id.is_some())); + if let Some(id) = id { + self.branch(id); + } + } + + fn leaf(&mut self, id: LeafId) { + self.id(id.change_id(), id.leaf_idx()); + } + + fn optional_number(&mut self, n: Option) { + put(&mut self.c.control, u64::from(n.is_some())); + if let Some(n) = n { + delta(&mut self.c.numbers, &mut self.s.number, n as u64); + } + } + + fn bytes(&mut self, bytes: &[u8], offset: Option) { + // Range references never stand in for a token's kind or identity. + let (tag, at) = if let Some(at) = offset { + if at == self.s.content_cursor { + (0, at) + } else { + (1, at) + } + } else { + let at = *self.literals.entry(bytes.to_vec()).or_insert_with(|| { + let at = self.c.literals.len(); + self.c.literals.extend_from_slice(bytes); + at + }); + (2, at) + }; + put(&mut self.c.control, tag); + put(&mut self.c.control, bytes.len() as u64); + if tag != 0 { + delta(&mut self.c.references, &mut self.s.reference, at as u64); + } + if tag != 2 { + self.s.content_cursor = at + bytes.len(); + } + } + + fn leaves( + &mut self, + ops: &[LeafOp], + range: Option<(ChangePosition, ChangePosition)>, + ) -> Result<()> { + // Match whole authored fragments, not each token against the whole blob. + // Old/deleted text absent from this change goes into a lossless literal pool. + let joined: Vec = ops + .iter() + .filter_map(LeafOp::content) + .flatten() + .copied() + .collect(); + let hinted = range.and_then(|(a, b)| { + let a = usize::try_from(a.get()).ok()?; + let b = usize::try_from(b.get()).ok()?; + (self.content.get(a..b)? == joined).then_some(a) + }); + let sequential = self + .content + .get(self.s.content_cursor..) + .filter(|rest| rest.starts_with(&joined)) + .map(|_| self.s.content_cursor); + let mut offset = hinted + .or(sequential) + .or_else(|| self.lines.get(joined.as_slice()).copied()); + put(&mut self.c.control, ops.len() as u64); + for op in ops { + match op { + LeafOp::Insert { + after, + kind, + content, + } => { + put(&mut self.c.control, 0); + put(&mut self.c.control, u64::from(after.is_some())); + if let Some(after) = after { + self.leaf(*after); + } + self.c.kinds.extend(postcard::to_allocvec(kind)?); + self.bytes(content, offset); + } + LeafOp::Delete { leaf } => { + put(&mut self.c.control, 1); + self.leaf(*leaf); + } + LeafOp::Replace { leaf, new_content } => { + put(&mut self.c.control, 2); + self.leaf(*leaf); + self.bytes(new_content, offset); + } + LeafOp::Restore { leaf } => { + put(&mut self.c.control, 3); + self.leaf(*leaf); + } + } + if let (Some(at), Some(bytes)) = (&mut offset, op.content()) { + *at += bytes.len(); + } + } + Ok(()) + } +} + +pub(super) fn encode(ops: &[FileOps], content: &[u8], level: i32) -> Result> { + let mut lines = HashMap::new(); + let mut offset = 0; + for line in content.split_inclusive(|b| *b == b'\n') { + lines.entry(line).or_insert(offset); + // Semantic snapshots sometimes omit the line ending. + let trimmed = line.strip_suffix(b"\n").unwrap_or(line); + lines.entry(trimmed).or_insert(offset); + offset += line.len(); + } + let mut e = Encoder { + c: Columns { + content_hash: *blake3::hash(content).as_bytes(), + ..Columns::default() + }, + s: State::default(), + content, + lines, + literals: HashMap::new(), + }; + for file in ops { + e.c.files.push(( + file.trunk_id(), + file.path().into(), + file.trunk_op().cloned(), + )); + put(&mut e.c.control, file.line_ops().len() as u64); + for line in file.line_ops() { + e.branch(line.branch_id()); + e.optional_number(line.old_line_num()); + e.optional_number(line.new_line_num()); + put(&mut e.c.control, u64::from(line.content_range().is_some())); + if let Some((a, b)) = line.content_range() { + delta(&mut e.c.positions, &mut e.s.position, a.get()); + delta(&mut e.c.positions, &mut e.s.position, b.get()); + } + match line.operation() { + BranchOp::Insert { after, content } => { + put(&mut e.c.control, 0); + e.optional_branch(*after); + e.leaves(content, line.content_range())?; + } + BranchOp::Delete { branch, content } => { + put(&mut e.c.control, 1); + e.branch(*branch); + e.leaves(content, None)?; + } + BranchOp::Modify { + branch, + old_content, + new_content, + } => { + put(&mut e.c.control, 2); + e.branch(*branch); + e.leaves(old_content, None)?; + e.leaves(new_content, line.content_range())?; + } + BranchOp::Restore { branch } => { + put(&mut e.c.control, 3); + e.branch(*branch); + } + BranchOp::Reparent { branch, new_after } => { + put(&mut e.c.control, 4); + e.branch(*branch); + e.optional_branch(*new_after); + } + } + } + } + let raw = postcard::to_allocvec(&e.c)?; + let mut out = MAGIC.to_vec(); + out.extend(zstd::encode_all(raw.as_slice(), level)?); + Ok(out) +} + +struct Decoder<'a> { + control: &'a [u8], + owners: &'a [u8], + indices: &'a [u8], + numbers: &'a [u8], + positions: &'a [u8], + kinds: &'a [u8], + references: &'a [u8], + literals: &'a [u8], + content: &'a [u8], + s: State, + output_bytes: u64, +} + +impl Decoder<'_> { + fn flag(&mut self) -> Result { + let flag = get(&mut self.control)?; + ensure!(flag <= 1, "invalid optional flag"); + Ok(flag == 1) + } + + fn count(&mut self) -> Result { + let n = usize::try_from(get(&mut self.control)?)?; + ensure!( + n <= self.control.len(), + "count exceeds available control data" + ); + Ok(n) + } + + fn id(&mut self) -> Result<(NodeId, u32)> { + Ok(( + NodeId::new(undelta(&mut self.owners, &mut self.s.owner)?), + u32::try_from(undelta(&mut self.indices, &mut self.s.index)?)?, + )) + } + + fn branch(&mut self) -> Result { + let (owner, index) = self.id()?; + Ok(BranchId::new(owner, index)) + } + + fn optional_branch(&mut self) -> Result> { + if self.flag()? { + Ok(Some(self.branch()?)) + } else { + Ok(None) + } + } + + fn leaf(&mut self) -> Result { + let (owner, index) = self.id()?; + Ok(LeafId::new(owner, index)) + } + + fn optional_number(&mut self) -> Result> { + if self.flag()? { + Ok(Some(usize::try_from(undelta( + &mut self.numbers, + &mut self.s.number, + )?)?)) + } else { + Ok(None) + } + } + + fn bytes(&mut self) -> Result> { + let tag = get(&mut self.control)?; + ensure!(tag <= 2, "unknown byte reference"); + let len = usize::try_from(get(&mut self.control)?)?; + let at = if tag == 0 { + self.s.content_cursor + } else { + usize::try_from(undelta(&mut self.references, &mut self.s.reference)?)? + }; + let end = at.checked_add(len).context("byte range overflow")?; + let pool = if tag == 2 { + self.literals + } else { + self.content + }; + let bytes = pool.get(at..end).context("byte range outside pool")?; + self.output_bytes = self + .output_bytes + .checked_add(len as u64) + .context("output overflow")?; + ensure!( + self.output_bytes <= MAX_DECODED, + "expanded token byte limit" + ); + if tag != 2 { + self.s.content_cursor = end; + } + Ok(bytes.to_vec()) + } + + fn leaves(&mut self) -> Result> { + let count = self.count()?; + let mut ops = Vec::new(); + for _ in 0..count { + ops.push(match get(&mut self.control)? { + 0 => { + let after = if self.flag()? { + Some(self.leaf()?) + } else { + None + }; + let (kind, rest): (TokenKind, _) = postcard::take_from_bytes(self.kinds)?; + self.kinds = rest; + LeafOp::Insert { + after, + kind, + content: self.bytes()?, + } + } + 1 => LeafOp::Delete { leaf: self.leaf()? }, + 2 => LeafOp::Replace { + leaf: self.leaf()?, + new_content: self.bytes()?, + }, + 3 => LeafOp::Restore { leaf: self.leaf()? }, + _ => bail!("unknown leaf operation"), + }); + } + Ok(ops) + } +} + +pub(super) fn decode(encoded: &[u8], content: &[u8]) -> Result> { + let compressed = encoded + .strip_prefix(MAGIC) + .context("wrong codec magic/version")?; + let mut raw = Vec::new(); + zstd::stream::read::Decoder::new(compressed)? + .take(MAX_DECODED + 1) + .read_to_end(&mut raw)?; + ensure!(raw.len() as u64 <= MAX_DECODED, "decompression limit"); + let (c, trailing): (Columns, _) = postcard::take_from_bytes(&raw)?; + ensure!(trailing.is_empty(), "trailing codec data"); + ensure!( + c.content_hash == *blake3::hash(content).as_bytes(), + "authored content mismatch" + ); + let mut d = Decoder { + control: &c.control, + owners: &c.owners, + indices: &c.indices, + numbers: &c.numbers, + positions: &c.positions, + kinds: &c.kinds, + references: &c.references, + literals: &c.literals, + content, + s: State::default(), + output_bytes: 0, + }; + let mut files = Vec::new(); + for (trunk, path, op) in c.files { + let mut file = FileOps::new(trunk, path, op); + let count = d.count()?; + for _ in 0..count { + let branch_id = d.branch()?; + let old = d.optional_number()?; + let new = d.optional_number()?; + let range = if d.flag()? { + Some(( + undelta(&mut d.positions, &mut d.s.position)?, + undelta(&mut d.positions, &mut d.s.position)?, + )) + } else { + None + }; + let op = match get(&mut d.control)? { + 0 => BranchOp::Insert { + after: d.optional_branch()?, + content: d.leaves()?, + }, + 1 => BranchOp::Delete { + branch: d.branch()?, + content: d.leaves()?, + }, + 2 => BranchOp::Modify { + branch: d.branch()?, + old_content: d.leaves()?, + new_content: d.leaves()?, + }, + 3 => BranchOp::Restore { + branch: d.branch()?, + }, + 4 => BranchOp::Reparent { + branch: d.branch()?, + new_after: d.optional_branch()?, + }, + _ => bail!("unknown branch operation"), + }; + let mut line = LineOps::new_with_line_nums(branch_id, op, old, new); + if let Some((a, b)) = range { + line.set_content_range(ChangePosition::new(a), ChangePosition::new(b)); + } + file.add_line_op(line); + } + files.push(file); + } + ensure!( + [ + d.control, + d.owners, + d.indices, + d.numbers, + d.positions, + d.kinds, + d.references + ] + .iter() + .all(|s| s.is_empty()), + "unconsumed column data" + ); + Ok(files) +} + +#[cfg(test)] +#[path = "tests.rs"] +mod tests; diff --git a/atomic-core/examples/compact_semantic_codec/tests.rs b/atomic-core/examples/compact_semantic_codec/tests.rs new file mode 100644 index 00000000..fb418d6e --- /dev/null +++ b/atomic-core/examples/compact_semantic_codec/tests.rs @@ -0,0 +1,336 @@ +use super::*; +use atomic_core::{ + change::{ + span_patch::{ExternalFile, SpanProjectionId}, + Encoding, InodeKind, + }, + types::Hash, +}; + +fn insert(after: Option, bytes: &[u8]) -> LeafOp { + LeafOp::Insert { + after, + kind: TokenKind::Word, + content: bytes.into(), + } +} + +fn fixtures() -> Vec { + let trunk = TrunkId::new(NodeId::new(u64::MAX), u32::MAX); + let b = |owner, index| BranchId::new(NodeId::new(owner), index); + let l = |owner, index| LeafId::new(NodeId::new(owner), index); + let tokens = vec![ + insert(None, b""), + insert(Some(LeafId::ROOT), b"\xff\0"), + insert(Some(l(u64::MAX, u32::MAX)), "é\r\n".as_bytes()), + LeafOp::Delete { leaf: l(71, 5) }, + LeafOp::Replace { + leaf: l(3, 0), + new_content: b"absent old text".to_vec(), + }, + LeafOp::Restore { leaf: l(0, 99) }, + ]; + let branches = vec![ + BranchOp::Insert { + after: None, + content: tokens.clone(), + }, + BranchOp::Insert { + after: Some(BranchId::ROOT), + content: vec![], + }, + BranchOp::Insert { + after: Some(b(u64::MAX, 17)), + content: vec![insert(None, b"new\n")], + }, + BranchOp::Delete { + branch: b(7, 8), + content: tokens.clone(), + }, + BranchOp::Modify { + branch: b(9, 10), + old_content: tokens, + new_content: vec![insert(None, b"new\n")], + }, + BranchOp::Restore { branch: b(4, 0) }, + BranchOp::Reparent { + branch: b(6, u32::MAX), + new_after: Some(b(8, 5)), + }, + BranchOp::Reparent { + branch: b(6, 3), + new_after: None, + }, + ]; + let variants = vec![ + None, + Some(TrunkOp::Create { + path: "α\0".into(), + encoding: Some(Encoding::Utf8), + }), + Some(TrunkOp::Create { + path: "binary".into(), + encoding: None, + }), + Some(TrunkOp::Delete { trunk }), + Some(TrunkOp::Move { + trunk, + new_path: "elsewhere".into(), + }), + Some(TrunkOp::Undelete { trunk }), + Some(TrunkOp::SetMode { trunk, mode: 0o755 }), + Some(TrunkOp::SetKind { + trunk, + kind: InodeKind::Regular, + }), + Some(TrunkOp::ProjectedSpanEdit { + file: ExternalFile { + owner: Hash::of(b"owner"), + ordinal: 7, + }, + baseline: SpanProjectionId(Hash::of(b"projection")), + }), + ]; + variants + .into_iter() + .map(|op| { + let mut file = FileOps::new(trunk, "path".into(), op); + for (i, branch) in branches.iter().enumerate() { + let mut line = LineOps::new_with_line_nums( + b(i as u64, i as u32), + branch.clone(), + (i % 2 == 0).then_some(usize::MAX - i), + (i % 3 == 0).then_some(i), + ); + if i % 2 == 0 { + // Preserve metadata even when it is not usable as a content hint. + line.set_content_range(ChangePosition::new(u64::MAX), ChangePosition::new(0)); + } + file.add_line_op(line); + } + file + }) + .collect() +} + +#[test] +fn exact_all_variants_foreign_ids_and_metadata_without_database() -> Result<()> { + let ops = fixtures(); + for content in [&b"new\n"[..], &b""[..], &b"\xff\0new\n"[..]] { + let bytes = encode(&ops, content, 3)?; + let restored = decode(&bytes, content)?; + assert_eq!(restored, ops); + assert_eq!( + postcard::to_allocvec(&restored)?, + postcard::to_allocvec(&ops)? + ); + assert_eq!( + bytes, + encode(&ops, content, 3)?, + "encoding must be deterministic" + ); + } + assert_eq!(decode(&encode(&[], b"", 3)?, b"")?, vec![]); + Ok(()) +} + +#[test] +fn exact_content_references_and_literal_fallbacks() -> Result<()> { + let mut file = FileOps::edit(TrunkId::ROOT, "f".into()); + for (i, text) in [b"a\n".as_slice(), b"b\n", b"a\n", b"not in content"] + .iter() + .enumerate() + { + file.add_line_op( + LineOps::insert( + BranchId::new(NodeId::ROOT, i as u32), + None, + vec![insert(None, text)], + ) + .with_content_range(ChangePosition::new(0), ChangePosition::new(2)), + ); + } + let ops = vec![file]; + let encoded = encode(&ops, b"a\nb\n", 3)?; + assert_eq!(decode(&encoded, b"a\nb\n")?, ops); + assert!(decode(&encoded, b"a\nc\n").is_err()); + Ok(()) +} + +#[test] +fn rejects_truncation_wrong_version_trailing_and_bad_columns() -> Result<()> { + let encoded = encode(&fixtures(), b"new\n", 3)?; + for end in 0..encoded.len() { + assert!(decode(&encoded[..end], b"new\n").is_err(), "end={end}"); + } + let mut bad = encoded.clone(); + bad[4] = 99; + assert!(decode(&bad, b"new\n").is_err()); + let raw = zstd::decode_all(&encoded[MAGIC.len()..])?; + let mut c: Columns = postcard::from_bytes(&raw)?; + c.control.push(0); + let mut bad = MAGIC.to_vec(); + bad.extend(zstd::encode_all(postcard::to_allocvec(&c)?.as_slice(), 3)?); + assert!(decode(&bad, b"new\n").is_err()); + let mut raw_trailing = raw.clone(); + raw_trailing.push(1); + let mut bad = MAGIC.to_vec(); + bad.extend(zstd::encode_all(raw_trailing.as_slice(), 3)?); + assert!(decode(&bad, b"new\n").is_err()); + Ok(()) +} + +#[test] +fn varints_and_deltas_cover_full_domain() -> Result<()> { + let values = [0, 1, 127, 128, u32::MAX as u64, u64::MAX, 0, 1 << 63, 5]; + let mut bytes = Vec::new(); + let mut previous = 0; + for value in values { + delta(&mut bytes, &mut previous, value); + } + let mut input = bytes.as_slice(); + previous = 0; + for value in values { + assert_eq!(undelta(&mut input, &mut previous)?, value); + } + assert!(input.is_empty()); + assert!(get(&mut &[0x80, 0][..]).is_err()); + assert!(get(&mut &[0xff; 10][..]).is_err()); + Ok(()) +} + +#[test] +fn rejects_unknown_operations_flags_counts_and_out_of_bounds_references() -> Result<()> { + let make = |control: Vec| Columns { + content_hash: *blake3::hash(b"").as_bytes(), + files: vec![(TrunkId::ROOT, "f".into(), None)], + control, + owners: vec![0], + indices: vec![0], + kinds: postcard::to_allocvec(&TokenKind::Word).unwrap(), + ..Columns::default() + }; + for c in [ + make(vec![1, 0, 0, 0, 99]), // unknown branch tag + make(vec![1, 2]), // invalid optional line-number flag + make(vec![127]), // line count with no corresponding data + make(vec![1, 0, 0, 0, 0, 0, 1, 99]), // unknown leaf tag + make(vec![1, 0, 0, 0, 0, 0, 1, 0, 0, 2, 1]), // nonempty reference into empty literal pool + ] { + let mut encoded = MAGIC.to_vec(); + encoded.extend(zstd::encode_all(postcard::to_allocvec(&c)?.as_slice(), 3)?); + assert!(decode(&encoded, b"").is_err()); + } + Ok(()) +} + +#[test] +fn generated_irregular_semantics_roundtrip() -> Result<()> { + // Deterministic generated coverage, including high/descending IDs and arbitrary bytes. + let mut seed = 0x7e57u64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for _ in 0..64 { + let mut file = FileOps::edit(TrunkId::new(NodeId::new(next()), next() as u32), "f".into()); + for _ in 0..16 { + let leaf = LeafId::new(NodeId::new(next()), next() as u32); + let content = (0..next() % 50).map(|_| next() as u8).collect::>(); + let op = match next() % 4 { + 0 => insert(Some(leaf), &content), + 1 => LeafOp::Delete { leaf }, + 2 => LeafOp::Replace { + leaf, + new_content: content, + }, + _ => LeafOp::Restore { leaf }, + }; + file.add_line_op( + LineOps::insert( + BranchId::new(NodeId::new(next()), next() as u32), + None, + vec![op], + ) + .with_old_line_num(next() as usize) + .with_new_line_num(next() as usize), + ); + } + let ops = vec![file]; + assert_eq!(decode(&encode(&ops, b"", 3)?, b"")?, ops); + } + Ok(()) +} + +#[test] +fn measure_synthetic_add_and_edit_without_database() -> Result<()> { + use atomic_core::diff::token::Tokenizer; + let mut content = Vec::new(); + let mut file = FileOps::create(TrunkId::ROOT, "generated.rs".into(), Some(Encoding::Utf8)); + let mut leaf_index = 0; + for i in 0..4096u32 { + let text = format!("let variable_{i} = compute({i}, input);\n"); + let start = content.len(); + content.extend_from_slice(text.as_bytes()); + let mut previous = None; + let tokens = Tokenizer::new(text.as_bytes()) + .map(|token| { + let op = LeafOp::Insert { + after: previous, + kind: token.kind(), + content: token.content().into(), + }; + previous = Some(LeafId::new(NodeId::ROOT, leaf_index)); + leaf_index += 1; + op + }) + .collect(); + file.add_line_op( + LineOps::insert_at( + BranchId::new(NodeId::ROOT, i), + i.checked_sub(1).map(|j| BranchId::new(NodeId::ROOT, j)), + tokens, + i as usize + 1, + ) + .with_content_range( + ChangePosition::new(start as u64), + ChangePosition::new(content.len() as u64), + ), + ); + } + let old = vec![insert( + Some(LeafId::new(NodeId::new(19), 900)), + b"old value not in new content", + )]; + let mut edit = FileOps::edit(TrunkId::new(NodeId::new(19), 0), "generated.rs".into()); + edit.add_line_op( + LineOps::modify_at( + BranchId::new(NodeId::new(19), 64), + old, + vec![insert(None, b"new value\n")], + 65, + 65, + ) + .with_content_range(ChangePosition::new(0), ChangePosition::new(10)), + ); + for (label, ops, content) in [ + ("4096-line-add", vec![file], content), + ( + "interior-edit-with-old-snapshot", + vec![edit], + b"new value\n".to_vec(), + ), + ] { + let raw = postcard::to_allocvec(&ops)?; + let baseline = zstd::encode_all(raw.as_slice(), 3)?.len(); + let encoded = encode(&ops, &content, 3)?; + let no_references = encode(&ops, b"", 3)?.len(); + assert_eq!(decode(&encoded, &content)?, ops); + assert_eq!(postcard::to_allocvec(&decode(&encoded, &content)?)?, raw); + println!("{label}: content_zstd3={} baseline_semantic_zstd3={baseline} compact_semantic_zstd3={} compact_without_content_refs={no_references}", + zstd::encode_all(content.as_slice(), 3)?.len(), encoded.len()); + } + Ok(()) +} diff --git a/atomic-identity/src/store.rs b/atomic-identity/src/store.rs index 0a98d065..e4e638f7 100644 --- a/atomic-identity/src/store.rs +++ b/atomic-identity/src/store.rs @@ -627,6 +627,72 @@ impl IdentityStore { Ok(KeyPair::from_secret_key(secret)) } + /// Remove an identity's stored signing secret without retiring its public identity. + /// + /// Public verification data, defaults, delegations, and revocations remain + /// available. Repeating this operation succeeds even if the secret is already + /// absent. The secret is removed before atomically replacing its metadata, + /// so retrying after an interrupted retirement completes the metadata update. + /// This unlinks the stored key; it does not erase backups or keys in memory. + /// + /// Returns an error if the identity is unknown or its metadata cannot be + /// validated, or if a filesystem operation fails. + pub fn retire_secret_key(&self, id: &IdentityId) -> Result<(), IdentityError> { + use std::io::Write; + + let identity_dir = self.find_identity_dir(id)?; + let identity_path = identity_dir.join(Self::IDENTITY_FILE); + let mut stored: StoredIdentity = toml::from_str(&fs::read_to_string(&identity_path)?)?; + // Directory discovery uses a short suffix, not the complete identity ID. + if stored.to_identity()?.id != *id { + return Err(IdentityError::NotFound { + name: id.to_base32(), + }); + } + stored.has_secret_key = false; + let content = toml::to_string_pretty(&stored)?; + match fs::remove_file(identity_dir.join(Self::SECRET_KEY_FILE)) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error.into()), + } + // Persist the unlink before publishing metadata claiming no secret exists. + #[cfg(unix)] + fs::File::open(&identity_dir)?.sync_all()?; + + let (temporary_path, mut temporary) = loop { + let path = + identity_dir.join(format!(".retire-secret-{:016x}.tmp", rand::random::())); + match fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + { + Ok(file) => break (path, file), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error.into()), + } + }; + let result = (|| -> Result<(), IdentityError> { + temporary.set_permissions(fs::metadata(&identity_path)?.permissions())?; + temporary.write_all(content.as_bytes())?; + temporary.sync_all()?; + Ok(()) + })(); + drop(temporary); + let result = result.and_then(|()| { + fs::rename(&temporary_path, &identity_path)?; + #[cfg(unix)] + fs::File::open(&identity_dir)?.sync_all()?; + Ok(()) + }); + if result.is_err() { + // Only remove the temporary file created by this call, never public data. + let _ = fs::remove_file(&temporary_path); + } + result + } + /// Delete an identity from the store. pub fn delete(&mut self, id: &IdentityId) -> Result<(), IdentityError> { let identity_dir = self.find_identity_dir(id)?; @@ -1031,6 +1097,147 @@ mod tests { assert!(!store.exists(&identity.id)); } + #[test] + fn retire_secret_key_preserves_public_verification_and_audit_data() { + let (_temp, store) = create_test_store(); + let keypair = KeyPair::generate(); + let identity = Identity::new("ephemeral-reviewer", &keypair); + store.save_with_keypair(&identity, &keypair, None).unwrap(); + let identity_dir = store.find_identity_dir(&identity.id).unwrap(); + let identity_path = identity_dir.join(IdentityStore::IDENTITY_FILE); + let mut expected: toml::Value = + toml::from_str(&fs::read_to_string(&identity_path).unwrap()).unwrap(); + expected["has_secret_key"] = toml::Value::Boolean(false); + fs::write(identity_dir.join("certificate.json"), b"public certificate").unwrap(); + store + .save_delegation("review-grant", "signed delegation") + .unwrap(); + store + .save_revocation("review-grant", "signed revocation") + .unwrap(); + let message = b"evidence signed before key retirement"; + let signature = keypair.sign(message); + + store.retire_secret_key(&identity.id).unwrap(); + + let public = store.load(&identity.id).unwrap(); + assert_eq!(public.id, identity.id); + assert_eq!(public.name, identity.name); + assert_eq!(public.public_key, identity.public_key); + public.verify(message, &signature).unwrap(); + assert!(store.load_keypair(&identity.id, None).is_err()); + assert!(!identity_dir.join(IdentityStore::SECRET_KEY_FILE).exists()); + let actual: toml::Value = + toml::from_str(&fs::read_to_string(identity_path).unwrap()).unwrap(); + assert_eq!(actual, expected, "only secret-presence metadata changes"); + assert!(store + .list_filtered(&IdentityFilter::all().with_secret_key()) + .unwrap() + .is_empty()); + assert_eq!( + fs::read(identity_dir.join("certificate.json")).unwrap(), + b"public certificate" + ); + assert_eq!( + store.load_delegation("review-grant").unwrap(), + "signed delegation" + ); + assert_eq!( + store.load_revocation("review-grant").unwrap().as_deref(), + Some("signed revocation") + ); + } + + #[test] + fn retire_secret_key_keeps_global_and_usage_defaults() { + let (_temp, mut store) = create_test_store(); + let keypair = KeyPair::generate(); + let identity = Identity::new("default-reviewer", &keypair); + store.save_with_keypair(&identity, &keypair, None).unwrap(); + store.set_default(&identity.id).unwrap(); + store + .set_default_for_usage(&IdentityUsage::Work, &identity.id) + .unwrap(); + let config = fs::read(store.root().join(IdentityStore::CONFIG_FILE)).unwrap(); + + store.retire_secret_key(&identity.id).unwrap(); + + let reopened = IdentityStore::open_existing(store.root()).unwrap(); + assert_eq!(reopened.get_default().unwrap().unwrap().id, identity.id); + assert_eq!( + reopened + .get_default_for_usage(&IdentityUsage::Work) + .unwrap() + .unwrap() + .id, + identity.id + ); + assert_eq!( + fs::read(store.root().join(IdentityStore::CONFIG_FILE)).unwrap(), + config + ); + } + + #[test] + fn retire_secret_key_is_idempotent_for_retired_and_public_only_identities() { + let (_temp, store) = create_test_store(); + let keypair = KeyPair::generate(); + let identity = Identity::new("reviewer", &keypair); + store.save_with_keypair(&identity, &keypair, None).unwrap(); + store.retire_secret_key(&identity.id).unwrap(); + store.retire_secret_key(&identity.id).unwrap(); + assert_eq!( + store.load(&identity.id).unwrap().public_key, + identity.public_key + ); + + let public_only = Identity::generate("public-only"); + store.save(&public_only).unwrap(); + store.retire_secret_key(&public_only.id).unwrap(); + assert!(store.load(&public_only.id).is_ok()); + } + + #[test] + fn retire_secret_key_resumes_after_secret_unlink() { + let (_temp, store) = create_test_store(); + let keypair = KeyPair::generate(); + let identity = Identity::new("interrupted-reviewer", &keypair); + store.save_with_keypair(&identity, &keypair, None).unwrap(); + let identity_dir = store.find_identity_dir(&identity.id).unwrap(); + fs::remove_file(identity_dir.join(IdentityStore::SECRET_KEY_FILE)).unwrap(); + + store.retire_secret_key(&identity.id).unwrap(); + + let stored: StoredIdentity = toml::from_str( + &fs::read_to_string(identity_dir.join(IdentityStore::IDENTITY_FILE)).unwrap(), + ) + .unwrap(); + assert!(!stored.has_secret_key); + assert_eq!( + store.load(&identity.id).unwrap().public_key, + identity.public_key + ); + } + + #[test] + fn retire_secret_key_refuses_unknown_identity() { + let (_temp, store) = create_test_store(); + let keypair = KeyPair::generate(); + let known = Identity::new("known", &keypair); + store.save_with_keypair(&known, &keypair, None).unwrap(); + let unknown = Identity::generate("unknown"); + + assert!(matches!( + store.retire_secret_key(&unknown.id), + Err(IdentityError::NotFound { .. }) + )); + assert_eq!( + store.load_keypair(&known.id, None).unwrap().public, + keypair.public + ); + assert_eq!(store.count().unwrap(), 1); + } + #[test] fn test_store_default_identity() { let (_temp, mut store) = create_test_store(); diff --git a/atomic-repository/src/analysis_scope.rs b/atomic-repository/src/analysis_scope.rs new file mode 100644 index 00000000..8b869943 --- /dev/null +++ b/atomic-repository/src/analysis_scope.rs @@ -0,0 +1,39 @@ +//! Source-selection policy shared by review and static code relationship adapters. + +use std::path::{Component, Path}; + +/// Vault artifacts remain repository/review evidence, but are never application +/// code inputs merely because an artifact happens to have a source extension. +/// This accepts canonical repository-relative paths and native path components. +pub fn is_vault_path(path: &str) -> bool { + Path::new(path) + .components() + .any(|component| matches!(component, Component::Normal(name) if name == ".vault")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn vault_components_are_metadata_but_lookalikes_are_not() { + for path in [ + ".vault", + ".vault/memory/a.md", + "./.vault/attestations/a.md", + ".vault/generated.ts", + "nested/.vault/generated.rs", + ] { + assert!(is_vault_path(path), "{path}"); + } + for path in [ + "src/vault.ts", + ".vaultish/code.ts", + "src/.vault-backup/code.rs", + "vault/code.ts", + "README.md", + ] { + assert!(!is_vault_path(path), "{path}"); + } + } +} diff --git a/atomic-repository/src/content_search.rs b/atomic-repository/src/content_search.rs index 3d7a9616..a77913ad 100644 --- a/atomic-repository/src/content_search.rs +++ b/atomic-repository/src/content_search.rs @@ -240,7 +240,54 @@ pub(crate) struct RecordedContentSearch { display_limit: usize, } +pub(crate) struct RecordedSourceMatches { + pub sources: Vec<(String, String)>, + pub searched_files: usize, + pub omitted_files: usize, +} + impl RecordedContentSearch { + /// Select matching recorded source before AST budgets. Unlike display search, + /// this retains one source per matching path, not the first N matching lines. + pub(crate) fn matching_sources( + self, + max_files: usize, + max_bytes: usize, + mut retrieve: impl FnMut(&str) -> Result>, E>, + mut accept: impl FnMut(&str, &[u8]) -> bool, + ) -> Result { + let mut result = RecordedSourceMatches { + sources: vec![], + searched_files: 0, + omitted_files: 0, + }; + let mut bytes = 0; + for path in self.paths { + result.searched_files += 1; + let Some(content) = retrieve(&path)? else { + continue; + }; + if syntext::index::is_binary(&content) + || !self.re.is_match(&content) + || !accept(&path, &content) + { + continue; + } + if result.sources.len() >= max_files + || bytes + content.len() > max_bytes + || content.len() > atomic_semantic::MAX_SOURCE_BYTES + { + result.omitted_files += 1; + continue; + } + bytes += content.len(); + match String::from_utf8(content) { + Ok(source) => result.sources.push((path, source)), + Err(_) => result.omitted_files += 1, + } + } + Ok(result) + } pub(crate) fn new<'path>( paths: impl IntoIterator, pattern: &str, @@ -705,6 +752,45 @@ impl From for ContentSearchError { mod tests { use super::*; + #[test] + fn recorded_semantic_candidates_ignore_display_limits_and_filter_before_budgets() { + let files = std::collections::BTreeMap::from([ + ( + "a_dense.ts".to_string(), + "needle\n".repeat(1000).into_bytes(), + ), + ("b_outside_scope.ts".to_string(), b"needle\n".to_vec()), + ("z_real.ts".to_string(), b"needle\n".to_vec()), + ]); + let plan = RecordedContentSearch::new( + files.keys().map(String::as_str), + "needle", + ContentSearchOptions { + max_results: Some(1), + ..Default::default() + }, + ) + .unwrap(); + let selected = plan + .matching_sources( + 2, + 1024 * 1024, + |path| Ok::<_, ()>(Some(files[path].clone())), + |path, _| path != "b_outside_scope.ts", + ) + .unwrap(); + assert_eq!( + selected + .sources + .iter() + .map(|(path, _)| path.as_str()) + .collect::>(), + ["a_dense.ts", "z_real.ts"] + ); + assert_eq!(selected.searched_files, 3); + assert_eq!(selected.omitted_files, 0); + } + fn streaming( files: &std::collections::BTreeMap>, pattern: &str, diff --git a/atomic-repository/src/lib.rs b/atomic-repository/src/lib.rs index 5eb1913a..3aca80cc 100644 --- a/atomic-repository/src/lib.rs +++ b/atomic-repository/src/lib.rs @@ -87,6 +87,8 @@ //! - [`unrecord`] - Undo applied changes // Core modules +pub mod analysis_scope; +pub use analysis_scope::is_vault_path; pub mod apply; pub mod change_source; pub mod changestore; diff --git a/atomic-repository/src/repository/content.rs b/atomic-repository/src/repository/content.rs index bbf2de30..bff5e08d 100644 --- a/atomic-repository/src/repository/content.rs +++ b/atomic-repository/src/repository/content.rs @@ -1,7 +1,7 @@ use super::*; use atomic_core::pristine::{CachedGraphTxn, ViewGraph}; -fn graph_visibility_at_change( +pub(super) fn graph_visibility_at_change( txn: &T, view: &atomic_core::pristine::ViewState, change_hash: &Hash, @@ -322,6 +322,76 @@ impl Repository { paths: &[String], view_name: &str, ) -> Result, RepositoryError> { + Ok(self + .recorded_identity_rows_on_view(paths, view_name)? + .into_iter() + .map(|row| row.0) + .collect()) + } + + /// Canonical recorded file identities in requested-path order. Absent paths + /// and directories have no inode; ambiguous names fail rather than guessing + /// a rename. This performs no content rendering or working-copy lookup. + pub fn recorded_file_inodes_on_view( + &self, + paths: &[String], + view_name: &str, + ) -> Result>, RepositoryError> { + self.recorded_identity_rows_on_view(paths, view_name)? + .into_iter() + .zip(paths) + .map(|((presence, inode), path)| { + if let RecordedPresence::NameConflict { paths, claimants } = presence { + return Err(name_conflict_error(path, paths, claimants)); + } + Ok(inode) + }) + .collect() + } + + /// Enumerate the canonical recorded names and file identities of a view. + /// Unlike recovery-oriented working-copy enumeration, this never revives a + /// superseded name merely because an inode still has live content. Staged + /// paths and directories are excluded; ambiguous recorded names fail closed. + pub fn recorded_file_identities_on_view( + &self, + view_name: &str, + ) -> Result, RepositoryError> { + let txn = self + .pristine + .read_txn() + .map_err(|error| RepositoryError::Database(error.to_string()))?; + let view = txn + .get_view(view_name) + .map_err(|error| RepositoryError::Database(error.to_string()))? + .ok_or_else(|| RepositoryError::ViewNotFound { + name: view_name.into(), + })?; + let visibility = graph_visibility_closure(&txn, &view)?; + let projection = self.project_tree_for_visibility(&txn, &visibility)?; + if let Some((path, conflict)) = projection + .name_conflicts + .iter() + .min_by_key(|(path, _)| *path) + { + return Err(name_conflict_error( + path, + conflict.paths.len(), + conflict.sides.len(), + )); + } + Ok(projection + .present + .into_iter() + .filter_map(|(path, item)| (!item.is_directory).then_some((path, item.inode))) + .collect()) + } + + fn recorded_identity_rows_on_view( + &self, + paths: &[String], + view_name: &str, + ) -> Result)>, RepositoryError> { let txn = self .pristine .read_txn() @@ -344,14 +414,19 @@ impl Repository { .map(|path| { let normalized = normalize_path(Path::new(path)); if let Some(conflict) = projection.name_conflicts.get(&normalized) { - return RecordedPresence::NameConflict { - paths: conflict.paths.len(), - claimants: conflict.sides.len(), - }; + return ( + RecordedPresence::NameConflict { + paths: conflict.paths.len(), + claimants: conflict.sides.len(), + }, + None, + ); } match projection.present.get(&normalized) { - Some(item) if !item.is_directory => RecordedPresence::Present, - _ => RecordedPresence::Absent, + Some(item) if !item.is_directory => { + (RecordedPresence::Present, Some(item.inode)) + } + _ => (RecordedPresence::Absent, None), } }) .collect()) @@ -421,6 +496,52 @@ impl Repository { paths: &[String], view_name: &str, mut visit: impl FnMut(&str, Option>) -> Result<(), RepositoryError>, + ) -> Result<(), RepositoryError> { + self.visit_recorded_files_on_view(paths, view_name, false, |path, bytes, _| { + visit(path, bytes) + }) + } + + /// Stream recorded bytes and inode kinds without consulting the working copy + /// or following symlinks. Directories/absent paths have no bytes or kind; + /// unresolved names or inode attributes fail closed. + /// The transaction/visitor constraints are the same as + /// [`Self::for_each_file_content_on_view`]. + /// + /// ```no_run + /// # use atomic_repository::{Repository, RepositoryError}; + /// # let repo = Repository::open_readonly(".")?; + /// repo.for_each_file_content_and_kind_on_view( + /// &["src/lib.rs".into()], "dev", |path, bytes, kind| { + /// println!("{path}: {kind:?}, {} bytes", bytes.as_ref().map_or(0, Vec::len)); + /// Ok(()) + /// }, + /// )?; + /// # Ok::<(), RepositoryError>(()) + /// ``` + pub fn for_each_file_content_and_kind_on_view( + &self, + paths: &[String], + view_name: &str, + visit: impl FnMut( + &str, + Option>, + Option, + ) -> Result<(), RepositoryError>, + ) -> Result<(), RepositoryError> { + self.visit_recorded_files_on_view(paths, view_name, true, visit) + } + + fn visit_recorded_files_on_view( + &self, + paths: &[String], + view_name: &str, + include_kind: bool, + mut visit: impl FnMut( + &str, + Option>, + Option, + ) -> Result<(), RepositoryError>, ) -> Result<(), RepositoryError> { let txn = self .pristine @@ -449,6 +570,31 @@ impl Repository { conflict.sides.len(), )); } + let kind = if include_kind { + match projection + .present + .get(&normalized) + .filter(|item| !item.is_directory) + { + Some(item) => { + let attrs = atomic_core::output::project_inode_attributes( + &txn, + item.position, + visibility.attribute_visibility(), + ) + .map_err(|error| RepositoryError::Database(error.to_string()))?; + if attrs.is_conflicted() { + return Err(RepositoryError::Output(format!( + "cannot inspect '{normalized}' with conflicting inode attributes" + ))); + } + Some(attrs.materialization.kind) + } + None => None, + } + } else { + None + }; let bytes = match projection.present.get(&normalized) { Some(item) if !item.is_directory => Some(render_projected_file( &txn, @@ -459,7 +605,7 @@ impl Repository { )?), _ => None, }; - visit(path, bytes)?; + visit(path, bytes, kind)?; } Ok(()) } diff --git a/atomic-repository/src/repository/mod.rs b/atomic-repository/src/repository/mod.rs index 598d0c54..ddbe2374 100644 --- a/atomic-repository/src/repository/mod.rs +++ b/atomic-repository/src/repository/mod.rs @@ -131,6 +131,7 @@ mod revise; mod sandbox; mod semantic_closure; mod semantic_materialize; +mod semantic_review; mod set_id; mod snapshot; mod snapshot_split; @@ -139,6 +140,7 @@ mod staging; mod stash; mod switch; mod syntax_index; +pub use semantic_review::RecordedSemanticView; mod synthesis; pub use syntax_index::{Caller, SyntaxIndex}; mod tag_projection; @@ -263,6 +265,7 @@ mod project_identity; pub mod provenance_gate; mod provenance_summary; pub mod publication_review; +pub mod review_authorization; pub use project_identity::{ build_project_identity, project_identity_hash, verify_project_identity, IdentityAdoption, }; diff --git a/atomic-repository/src/repository/publication_review/graph.rs b/atomic-repository/src/repository/publication_review/graph.rs index e9212d3c..2e571859 100644 --- a/atomic-repository/src/repository/publication_review/graph.rs +++ b/atomic-repository/src/repository/publication_review/graph.rs @@ -164,8 +164,18 @@ pub(super) fn build( return Err(refused("unsupported review schema")); } chrono::DateTime::parse_from_rfc3339(&review.reviewed_at).map_err(refused)?; - let bytes = - keys(&review.attributed_to).ok_or_else(|| refused("review signing key unavailable"))?; + let bytes = match keys(&review.attributed_to) { + Some(bytes) => bytes, + None => super::super::review_authorization::retained_public_key(repo, review, config)? + .ok_or_else(|| refused("review signing key unavailable"))?, + }; + // Transported exact-scope authorization retains the authenticated public + // reviewer key even after its local secret/identity store is unavailable. + // This resolves key material only; the authority result below is rechecked. + let supplied_keys = keys; + let retained_keys = + |did: &str| supplied_keys(did).or_else(|| (did == review.attributed_to).then_some(bytes)); + let keys: DidKeyProvider<'_> = &retained_keys; let key = key(bytes)?; if !atomic_canonical::did::did_matches_public_key(&review.attributed_to, &key) { return Err(refused("review identity does not match its key")); @@ -264,10 +274,7 @@ pub(super) fn build( graph.result( &artifact, P::AuthorityResult, - config - .trust - .evaluate(&review.attributed_to, config.repository_identity.as_deref()) - == atomic_config::SignerTrust::Trusted, + super::super::review_authorization::reviewer_is_authorized(repo, review, config, keys)?, ); graph.node(&review.attributed_to, C::Identity); if signed { diff --git a/atomic-repository/src/repository/publication_review/mod.rs b/atomic-repository/src/repository/publication_review/mod.rs index 1637f38f..2f9dda9c 100644 --- a/atomic-repository/src/repository/publication_review/mod.rs +++ b/atomic-repository/src/repository/publication_review/mod.rs @@ -82,16 +82,23 @@ pub(super) struct ReviewGateCache { } impl Repository { - /// Writers affecting review evidence participate in the common operation - /// boundary once retrospective artifacts exist. No feature means no bypass. + /// Writers affecting reviewable evidence participate even before the first + /// artifact exists. Otherwise a first publication can race a writer which + /// observed an empty artifact inventory and skipped the common boundary. pub(super) fn review_evidence_lock( &self, ) -> Result, RepositoryError> { - if self.vault_list(PREFIX, None)?.is_empty() { - return Ok(None); - } self.review_evidence_common_lock().map(Some) } + + /// Hold the canonical evidence/operation boundary across final scope and + /// authority revalidation, authorization, signatures and receipt retention. + /// Does not lock an agent run or create a new view; contention is retryable. + pub fn lock_review_publication( + &self, + ) -> Result { + self.review_evidence_common_lock() + } /// Prepare a present-day review from fresh signed intents and exact original /// changes. This does not grant trust, sign, store, or publish anything. pub fn prepare_publication_review( @@ -337,7 +344,7 @@ impl Repository { ))); } let existing = self.publication_reviews()?; - self.review_supersession(review, &existing, keys)?; + self.review_supersession(review, &existing, config, keys)?; let path = format!("{PREFIX}{}/review.md", review.artifact_hash()); // Everything that can refuse the artifact itself runs before anything // is created for it on disk or in the vault. @@ -475,9 +482,9 @@ impl Repository { .ancestry .entry(address.clone()) .or_insert_with(|| { - self.verify_review_signature(review, keys) + self.verify_review_signature(review, config, keys) .and_then(|()| { - self.review_supersession(review, &inventory.reviews, keys) + self.review_supersession(review, &inventory.reviews, config, keys) }) .map_err(|error| error.to_string()) }) @@ -509,11 +516,15 @@ impl Repository { fn verify_review_signature( &self, review: &PublicationReview, + config: &PublicationGateConfig, keys: DidKeyProvider<'_>, ) -> Result<(), RepositoryError> { - let public = - key(keys(&review.attributed_to) - .ok_or_else(|| refused("review signing key unavailable"))?)?; + let bytes = match keys(&review.attributed_to) { + Some(bytes) => bytes, + None => super::review_authorization::retained_public_key(self, review, config)? + .ok_or_else(|| refused("review signing key unavailable"))?, + }; + let public = key(bytes)?; if !atomic_canonical::did::did_matches_public_key(&review.attributed_to, &public) { return Err(refused("review DID is not key-bound")); } @@ -525,6 +536,7 @@ impl Repository { &self, review: &PublicationReview, all: &[PublicationReview], + config: &PublicationGateConfig, keys: DidKeyProvider<'_>, ) -> Result, RepositoryError> { let mut visited = std::collections::BTreeSet::new(); @@ -543,7 +555,7 @@ impl Repository { .iter() .find(|old| old.artifact_hash() == hash) .ok_or_else(|| refused("superseded review is unavailable"))?; - self.verify_review_signature(old, keys)?; + self.verify_review_signature(old, config, keys)?; let scope = |r: &PublicationReview| { ( r.subject.project.clone(), diff --git a/atomic-repository/src/repository/publication_review/tests.rs b/atomic-repository/src/repository/publication_review/tests.rs index 5ac72772..f459a52e 100644 --- a/atomic-repository/src/repository/publication_review/tests.rs +++ b/atomic-repository/src/repository/publication_review/tests.rs @@ -306,6 +306,109 @@ fn exact_signed_shacl_review_discharges_only_missing_attestation() { ); } +#[test] +fn purpose_bound_ephemeral_publication_passes_without_allowlisting_the_reviewer() { + let fixture = Fixture::new(); + let config = PublicationGateConfig { + trust: atomic_config::GitTrustConfig { + signers: vec![atomic_canonical::did::did_for_public_key( + &fixture.author.public_key, + )], + revoked: vec![], + }, + repository_identity: None, + }; + let mut review = fixture + .repo + .prepare_publication_review(&fixture.review, &[fixture.change], &|did| fixture.keys(did)) + .unwrap(); + assert!(!fixture.conforms(&fixture.sign(review.clone()), &config)); + super::super::review_authorization::mint_and_store( + &fixture.repo, + &review.subject, + &fixture.reviewer.public_key, + &fixture.author, + &fixture.author_key, + chrono::Utc::now() + chrono::Duration::minutes(30), + &config, + ) + .unwrap(); + review.reviewed_at = chrono::Utc::now().to_rfc3339(); + assert!(super::super::review_authorization::reviewer_may_sign_now( + &fixture.repo, + &review, + &config, + &|did| fixture.keys(did), + ) + .unwrap()); + let review = fixture.sign(review); + assert!(fixture.conforms(&review, &config)); + fixture + .repo + .record_publication_review(&review, &config, &|did| fixture.keys(did)) + .unwrap(); + let gate = fixture + .repo + .evaluate_publication_gate( + &[fixture.change], + &config, + None, + Some(&|did| fixture.keys(did)), + ) + .unwrap(); + assert!(gate.allowed(), "{}", gate.refusal_report()); + assert_eq!( + config.trust.signers.len(), + 1, + "reviewer was never added to raw trust" + ); + let transported_keys = |did: &str| { + atomic_canonical::did::did_matches_public_key(did, &fixture.author.public_key) + .then_some(*fixture.author.public_key.as_bytes()) + }; + assert!( + fixture + .repo + .validate_publication_review(&review, &config, &transported_keys) + .unwrap() + .conforms, + "retained issuer-authenticated public reviewer key survives local identity-store absence" + ); + assert!(fixture + .repo + .evaluate_publication_gate(&[fixture.change], &config, None, Some(&transported_keys)) + .unwrap() + .allowed()); +} + +#[test] +fn first_publication_boundary_fences_vault_writers_before_any_artifact_exists() { + let fixture = Fixture::new(); + assert!(fixture.repo.publication_reviews().unwrap().is_empty()); + let root = fixture.repo.root().to_path_buf(); + let _boundary = fixture.repo.lock_review_publication().unwrap(); + let result = std::thread::spawn(move || { + let repo = Repository::open_existing(root)?; + repo.vault_store( + "memory/concurrent-review-write.md", + VaultEntryType::Memory, + b"must not land".to_vec(), + "{}".into(), + ) + }) + .join() + .unwrap(); + assert!( + result.is_err(), + "a concurrent writer must not bypass the first-publication fence" + ); + assert!(fixture + .repo + .vault_retrieve("memory/concurrent-review-write.md") + .unwrap() + .is_none()); +} + #[test] fn stale_wrong_scope_and_truncated_subjects_fail_even_when_resigned() { let f = Fixture::new(); diff --git a/atomic-repository/src/repository/review_authorization.rs b/atomic-repository/src/repository/review_authorization.rs new file mode 100644 index 00000000..f69ba894 --- /dev/null +++ b/atomic-repository/src/repository/review_authorization.rs @@ -0,0 +1,956 @@ +//! Purpose-bound local authority for a disposable publication reviewer. +//! +//! These certificates are not identity grants and never modify signer trust. +//! Only an issuer trusted by the current raw signer policy can delegate, and +//! only for one exact immutable subject. Configured repository identity trust +//! is accepted; broad identity grants and transitive trust are not consulted. +//! SHACL remains the publication policy evaluator. +use super::provenance_gate::{DidKeyProvider, PublicationGateConfig}; +use super::{Repository, RepositoryError}; +use atomic_canonical::{ + node::Proof, + publication_review::{PublicationReview, ReviewSubject}, +}; +use atomic_config::SignerTrust; +use atomic_core::{ + pristine::{MutTxnT, VaultEntry, VaultEntryType, VaultMutTxnT, VaultTxnT}, + types::{Base32, Hash, Merkle}, +}; +use atomic_identity::{Identity, KeyPair, PublicKey}; +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; + +pub const PREFIX: &str = "review-authorizations/"; +const SCHEMA: &str = "atomic.review-authorization.v1"; +const REVOCATION_SCHEMA: &str = "atomic.review-authorization-revocation.v1"; +const PURPOSE: &str = "review-publication"; +const MAX_BYTES: usize = 4 * 1024 * 1024; + +/// An issuer-signed exact-subject capability, including only public key material. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ReviewAuthorization { + pub schema: String, + pub id: String, + pub purpose: String, + pub project: String, + pub delegate: String, + pub delegate_public_key: String, + /// Full signed scope: no wildcards, subset matching, or inferred closure. + pub subject: ReviewSubject, + pub created_at: String, + pub expires_at: String, + #[serde(rename = "attributedTo")] + pub issuer: String, + pub issuer_public_key: String, + #[serde( + rename = "contentHash", + default, + skip_serializing_if = "Option::is_none" + )] + pub content_hash: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub proof: Option, +} + +/// Explicit, issuer-signed invalidation. It deliberately denies even historical +/// authority, while retained public keys remain available for inspection. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ReviewAuthorizationRevocation { + pub schema: String, + pub purpose: String, + pub authorization: String, + pub project: String, + pub revoked_at: String, + #[serde(rename = "attributedTo")] + pub issuer: String, + #[serde( + rename = "contentHash", + default, + skip_serializing_if = "Option::is_none" + )] + pub content_hash: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub proof: Option, +} + +fn refused(error: impl std::fmt::Display) -> RepositoryError { + RepositoryError::InvalidOperation { + message: format!("review authorization: {error}"), + } +} + +fn value(document: &T) -> Result { + serde_json::to_value(document).map_err(refused) +} + +fn time(text: &str) -> Result, RepositoryError> { + DateTime::parse_from_rfc3339(text) + .map(|date| date.with_timezone(&Utc)) + .map_err(refused) +} + +fn public_key(text: &str) -> Result { + let bytes: [u8; 32] = data_encoding::BASE32_NOPAD + .decode(text.as_bytes()) + .map_err(refused)? + .try_into() + .map_err(|_| refused("invalid public key length"))?; + let key = PublicKey::from_bytes(&bytes).map_err(refused)?; + if key.to_base32() != text { + return Err(refused("noncanonical public key")); + } + Ok(key) +} + +fn issuer_is_trusted(config: &PublicationGateConfig, issuer: &str) -> bool { + // Use only the configured raw trust roots, never broad identity grants or + // recursive delegation. Explicit revocation wins for either root form. + config + .trust + .evaluate(issuer, config.repository_identity.as_deref()) + == SignerTrust::Trusted +} + +fn path(id: &str) -> String { + format!("{PREFIX}{id}.json") +} +fn revocation_path(id: &str) -> String { + format!("{PREFIX}revocations/{id}.json") +} + +fn identifier(authorization: &ReviewAuthorization) -> Result { + let mut document = value(authorization)?; + let object = document + .as_object_mut() + .ok_or_else(|| refused("expected object"))?; + for field in ["id", "proof", "contentHash"] { + object.remove(field); + } + let mut hash = blake3::Hasher::new(); + hash.update(b"atomic.review-authorization.id.v1\0"); + hash.update(atomic_canonical::jcs::canonicalize(&document).as_bytes()); + Ok(hash.finalize().to_hex().to_string()) +} + +fn validate_subject(repo: &Repository, subject: &ReviewSubject) -> Result<(), RepositoryError> { + if subject.project != repo.project_id()?.to_urn() { + return Err(refused("project mismatch")); + } + // Canonical roots and closure are an unambiguous exact list, not a pattern. + for hashes in [ + &subject.roots, + &subject + .changes + .iter() + .map(|pin| pin.hash.clone()) + .collect::>(), + ] { + if hashes.is_empty() || hashes.windows(2).any(|pair| pair[0] >= pair[1]) { + return Err(refused("scope hashes must be nonempty, sorted and unique")); + } + for text in hashes { + if !Hash::from_base32(text.as_bytes()).is_some_and(|hash| hash.to_base32() == *text) { + return Err(refused("scope requires full canonical change hashes")); + } + } + } + if subject.view_chain.is_empty() || subject.effective_set_id.is_empty() { + return Err(refused("missing exact source perspective")); + } + Ok(()) +} + +impl ReviewAuthorization { + fn verify( + &self, + repo: &Repository, + config: &PublicationGateConfig, + ) -> Result { + if self.schema != SCHEMA + || self.purpose != PURPOSE + || self.id != identifier(self)? + || self.project != self.subject.project + || !issuer_is_trusted(config, &self.issuer) + { + return Err(refused("unsupported, changed, or untrusted authorization")); + } + validate_subject(repo, &self.subject)?; + let issuer = public_key(&self.issuer_public_key)?; + let delegate = public_key(&self.delegate_public_key)?; + if !atomic_canonical::did::did_matches_public_key(&self.issuer, &issuer) + || !atomic_canonical::did::did_matches_public_key(&self.delegate, &delegate) + { + return Err(refused("identity/key mismatch")); + } + atomic_canonical::proof::verify_value(&value(self)?, &issuer).map_err(refused)?; + let created = time(&self.created_at)?; + if created > Utc::now() || time(&self.expires_at)? <= created { + return Err(refused("invalid authorization validity window")); + } + Ok(delegate) + } + + fn covers(&self, review: &PublicationReview) -> bool { + self.delegate == review.attributed_to && self.subject == review.subject + } +} + +/// Mint and durably retain a capability using an explicitly supplied issuer. +/// No private key is serialized. The issuer must be trusted by the raw configured +/// signer policy: `trust.signers` or `repository_identity`, with revocation winning. +#[allow(clippy::too_many_arguments)] +pub fn mint_and_store( + repo: &Repository, + subject: &ReviewSubject, + delegate: &PublicKey, + issuer: &Identity, + issuer_keypair: &KeyPair, + expires_at: DateTime, + config: &PublicationGateConfig, +) -> Result { + if issuer.public_key != issuer_keypair.secret.public_key() { + return Err(refused("issuer keypair mismatch")); + } + let now = Utc::now(); + if expires_at <= now { + return Err(refused("authorization already expired")); + } + let mut authorization = ReviewAuthorization { + schema: SCHEMA.into(), + id: String::new(), + purpose: PURPOSE.into(), + project: repo.project_id()?.to_urn(), + delegate: atomic_canonical::did::did_for_public_key(delegate), + delegate_public_key: delegate.to_base32(), + subject: subject.clone(), + created_at: now.to_rfc3339(), + expires_at: expires_at.to_rfc3339(), + issuer: atomic_canonical::did::did_for_public_key(&issuer.public_key), + issuer_public_key: issuer.public_key.to_base32(), + content_hash: None, + proof: None, + }; + authorization.id = identifier(&authorization)?; + authorization = serde_json::from_value(atomic_canonical::proof::attest_value( + value(&authorization)?, + issuer, + issuer_keypair, + )) + .map_err(refused)?; + authorization.verify(repo, config)?; + store_immutable(repo, &path(&authorization.id), &authorization)?; + Ok(authorization) +} + +/// Store immutable canonical bytes and update the vault manifest in the same +/// transaction. Content-address verification also detects replacement through +/// generic vault APIs. No indexing or inference confers authority on this entry. +fn store_immutable( + repo: &Repository, + path: &str, + document: &T, +) -> Result<(), RepositoryError> { + let _boundary = repo.review_evidence_lock()?; + let bytes = atomic_canonical::jcs::canonicalize(&value(document)?).into_bytes(); + if bytes.len() > MAX_BYTES { + return Err(refused("authorization exceeds size limit")); + } + let now = Utc::now().to_rfc3339(); + let entry = VaultEntry::new(VaultEntryType::Attestation, bytes, "{}".into(), now.clone()); + let mut txn = repo.pristine.write_txn().map_err(refused)?; + if let Some(old) = txn.get_vault_entry(path).map_err(refused)? { + if old.content_bytes != entry.content_bytes || old.entry_type != entry.entry_type { + return Err(refused("authorization entries are immutable")); + } + return Ok(()); + } + txn.put_vault_entry(path, &entry).map_err(refused)?; + let mut manifest = txn.get_vault_manifest().map_err(refused)?; + manifest.file_count = manifest.file_count.saturating_add(1); + manifest.total_bytes = manifest + .total_bytes + .saturating_add(entry.content_size() as u64); + let previous = Merkle::from_base32(manifest.merkle.as_bytes()).unwrap_or(Merkle::ZERO); + manifest.merkle = previous + .next(&Hash::from_bytes(entry.content_hash)) + .to_base32(); + manifest.updated_at = now; + txn.put_vault_manifest(&manifest).map_err(refused)?; + txn.commit().map_err(refused) +} + +fn parse(bytes: &[u8]) -> Result { + if bytes.len() > MAX_BYTES { + return Err(refused("authorization exceeds size limit")); + } + serde_json::from_value(atomic_canonical::jcs::admit_document(bytes).map_err(refused)?) + .map_err(refused) +} + +fn authorizations(repo: &Repository) -> Result, RepositoryError> { + let mut result = Vec::new(); + for meta in repo.vault_list(PREFIX, None)? { + if meta.path.starts_with(&format!("{PREFIX}revocations/")) { + continue; + } + let entry = repo + .vault_retrieve(&meta.path)? + .ok_or_else(|| refused("authorization disappeared"))?; + let authorization: ReviewAuthorization = parse(&entry.content_bytes)?; + if meta.path != path(&authorization.id) { + return Err(refused("authorization path/ID mismatch")); + } + result.push(authorization); + } + Ok(result) +} + +fn is_revoked( + repo: &Repository, + authorization: &ReviewAuthorization, +) -> Result { + let Some(entry) = repo.vault_retrieve(&revocation_path(&authorization.id))? else { + return Ok(false); + }; + let revocation: ReviewAuthorizationRevocation = parse(&entry.content_bytes)?; + if revocation.schema != REVOCATION_SCHEMA + || revocation.purpose != PURPOSE + || revocation.authorization != authorization.id + || revocation.project != authorization.project + || revocation.issuer != authorization.issuer + || time(&revocation.revoked_at)? > Utc::now() + || time(&revocation.revoked_at)? < time(&authorization.created_at)? + { + return Err(refused("invalid revocation")); + } + atomic_canonical::proof::verify_value( + &value(&revocation)?, + &public_key(&authorization.issuer_public_key)?, + ) + .map_err(refused)?; + Ok(true) +} + +/// Explicitly invalidate a capability, without deleting retained verification +/// keys. Only its original, still trusted issuer may revoke it here. This is a +/// deliberate approval withdrawal, NOT credential retirement: successful +/// publication must retain its certificate when retiring the ephemeral secret +/// or revoking a separate recording delegation. +pub fn revoke_and_store( + repo: &Repository, + authorization: &ReviewAuthorization, + issuer: &Identity, + issuer_keypair: &KeyPair, + config: &PublicationGateConfig, +) -> Result<(), RepositoryError> { + authorization.verify(repo, config)?; + if issuer.public_key != issuer_keypair.secret.public_key() + || atomic_canonical::did::did_for_public_key(&issuer.public_key) != authorization.issuer + { + return Err(refused("revocation issuer mismatch")); + } + if is_revoked(repo, authorization)? { + return Ok(()); + } + let revocation = ReviewAuthorizationRevocation { + schema: REVOCATION_SCHEMA.into(), + purpose: PURPOSE.into(), + authorization: authorization.id.clone(), + project: authorization.project.clone(), + revoked_at: Utc::now().to_rfc3339(), + issuer: authorization.issuer.clone(), + content_hash: None, + proof: None, + }; + let signed = atomic_canonical::proof::attest_value(value(&revocation)?, issuer, issuer_keypair); + store_immutable(repo, &revocation_path(&authorization.id), &signed) +} + +/// Resolve only a public key authenticated by a currently raw-policy-trusted +/// issuer and matching this exact subject/delegate. This is key resolution, not +/// authority: expiry/revocation are checked separately, so deleting an ephemeral +/// secret never destroys historical signature verification. Compose with an +/// identity-store provider; never infer trust from the returned key alone. +pub fn retained_public_key( + repo: &Repository, + review: &PublicationReview, + config: &PublicationGateConfig, +) -> Result, RepositoryError> { + for authorization in authorizations(repo)? { + if authorization.covers(review) { + if let Ok(key) = authorization.verify(repo, config) { + return Ok(Some(*key.as_bytes())); + } + } + } + Ok(None) +} + +/// Check authority for a retained signed review at its signed `reviewed_at`. +/// Unsigned previews are checked *now* as well. Explicit signer revocation has +/// unconditional deny precedence, including over direct trust and certificates. +pub fn reviewer_is_authorized( + repo: &Repository, + review: &PublicationReview, + config: &PublicationGateConfig, + keys: DidKeyProvider<'_>, +) -> Result { + match config + .trust + .evaluate(&review.attributed_to, config.repository_identity.as_deref()) + { + SignerTrust::Revoked => return Ok(false), + SignerTrust::Trusted => return Ok(true), + SignerTrust::Unknown => {} + } + delegated_authority(repo, review, config, keys, review.proof.is_none()) +} + +/// Mandatory pre-signing check: unlike historical verification, expiry is +/// evaluated at wall-clock time even if a caller supplies a backdated review. +pub fn reviewer_may_sign_now( + repo: &Repository, + review: &PublicationReview, + config: &PublicationGateConfig, + keys: DidKeyProvider<'_>, +) -> Result { + match config + .trust + .evaluate(&review.attributed_to, config.repository_identity.as_deref()) + { + SignerTrust::Revoked => return Ok(false), + SignerTrust::Trusted => return Ok(true), + SignerTrust::Unknown => {} + } + delegated_authority(repo, review, config, keys, true) +} + +fn delegated_authority( + repo: &Repository, + review: &PublicationReview, + config: &PublicationGateConfig, + keys: DidKeyProvider<'_>, + signing_now: bool, +) -> Result { + let reviewed = time(&review.reviewed_at)?; + let now = Utc::now(); + if reviewed > now { + return Ok(false); + } + for authorization in authorizations(repo)? { + if !authorization.covers(review) { + continue; + } + let Ok(key) = authorization.verify(repo, config) else { + continue; + }; + let created = time(&authorization.created_at)?; + let expires = time(&authorization.expires_at)?; + if reviewed < created + || reviewed >= expires + || (signing_now && (now < created || now >= expires)) + || is_revoked(repo, &authorization)? + { + continue; + } + if keys(&review.attributed_to).is_some_and(|bytes| bytes != *key.as_bytes()) { + return Ok(false); + } + if review.proof.is_some() { + if atomic_canonical::proof::verify_value(&review.value(), &key).is_err() { + return Ok(false); + } + } else if !signing_now { + return Ok(false); + } + return Ok(true); + } + Ok(false) +} + +#[cfg(test)] +mod tests { + use super::*; + use atomic_canonical::publication_review::{ChangePin, IntentPin, ReviewViewPin}; + use chrono::Duration; + + struct Fixture { + _dir: tempfile::TempDir, + repo: Repository, + issuer: Identity, + issuer_key: KeyPair, + delegate: Identity, + delegate_key: KeyPair, + config: PublicationGateConfig, + review: PublicationReview, + } + + impl Fixture { + fn new() -> Self { + let dir = tempfile::tempdir().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + repo.ensure_project_identity(atomic_core::kg::project_id::MintReason::Upgrade) + .unwrap(); + let issuer_key = KeyPair::generate(); + let issuer = Identity::new("test-issuer", &issuer_key); + let delegate_key = KeyPair::generate(); + let delegate = Identity::new("temporary-reviewer", &delegate_key); + let issuer_did = atomic_canonical::did::did_for_public_key(&issuer.public_key); + let root = Hash::of(b"exact-root").to_base32(); + let pin = IntentPin { + id: "urn:atomic:intent:test-only".into(), + source_hash: "source".into(), + signed_hash: "signed".into(), + public_key: delegate.public_key.to_base32(), + }; + let review = PublicationReview { + schema: atomic_canonical::publication_review::LEGACY_SCHEMA.into(), + reviewed_at: Utc::now().to_rfc3339(), + subject: ReviewSubject { + project: repo.project_id().unwrap().to_urn(), + roots: vec![root.clone()], + changes: vec![ChangePin { + hash: root, + session: None, + governing_intents: vec![], + provenance: vec![], + observations: vec![], + }], + review: pin, + work: vec![], + set_aside: vec![], + profile_hash: "policy-digest".into(), + view_chain: vec![ReviewViewPin { + name: "historical-source".into(), + state: "state-digest".into(), + scope: "draft".into(), + }], + effective_set_id: "membership-digest".into(), + snapshot: None, + }, + supersedes: vec![], + attributed_to: atomic_canonical::did::did_for_public_key(&delegate.public_key), + content_hash: None, + proof: None, + }; + Self { + _dir: dir, + repo, + issuer, + issuer_key, + delegate, + delegate_key, + config: PublicationGateConfig { + trust: atomic_config::GitTrustConfig { + signers: vec![issuer_did], + revoked: vec![], + }, + repository_identity: None, + }, + review, + } + } + + fn mint(&mut self) -> ReviewAuthorization { + let authorization = mint_and_store( + &self.repo, + &self.review.subject, + &self.delegate.public_key, + &self.issuer, + &self.issuer_key, + Utc::now() + Duration::minutes(10), + &self.config, + ) + .unwrap(); + self.review.reviewed_at = Utc::now().to_rfc3339(); + authorization + } + + fn sign_review(&mut self) { + self.review = serde_json::from_value(atomic_canonical::proof::attest_value( + self.review.value(), + &self.delegate, + &self.delegate_key, + )) + .unwrap(); + } + + fn authorized(&self) -> bool { + reviewer_is_authorized(&self.repo, &self.review, &self.config, &|_| None).unwrap() + } + + fn store_reissued(&self, mut authorization: ReviewAuthorization) -> ReviewAuthorization { + authorization.proof = None; + authorization.content_hash = None; + authorization.id = identifier(&authorization).unwrap(); + let authorization: ReviewAuthorization = + serde_json::from_value(atomic_canonical::proof::attest_value( + value(&authorization).unwrap(), + &self.issuer, + &self.issuer_key, + )) + .unwrap(); + store_immutable(&self.repo, &path(&authorization.id), &authorization).unwrap(); + authorization + } + } + + #[test] + fn exact_authorization_and_retained_public_key_work_without_identity_store() { + let mut f = Fixture::new(); + assert!(!f.authorized()); + let auth = f.mint(); + assert!(f.authorized()); + assert!(reviewer_may_sign_now(&f.repo, &f.review, &f.config, &|_| None).unwrap()); + f.sign_review(); + assert!(f.authorized()); + assert_eq!( + retained_public_key(&f.repo, &f.review, &f.config).unwrap(), + Some(*f.delegate.public_key.as_bytes()) + ); + let stored = f.repo.vault_retrieve(&path(&auth.id)).unwrap().unwrap(); + assert_eq!( + stored.content_bytes, + atomic_canonical::jcs::canonicalize(&value(&auth).unwrap()).as_bytes() + ); + assert!(stored.frontmatter_json == "{}"); + // Key resolution is authenticated by issuer bytes, not arbitrary local keys. + let other = KeyPair::generate(); + assert!( + !reviewer_is_authorized(&f.repo, &f.review, &f.config, &|_| Some( + *other.public.as_bytes() + )) + .unwrap() + ); + } + + #[test] + fn scope_never_widens_roots_closure_views_intent_pins_or_project() { + let mut f = Fixture::new(); + f.mint(); + let original = f.review.clone(); + let mut changed = vec![]; + let mut r = original.clone(); + r.subject.roots = vec![Hash::of(b"another-root").to_base32()]; + changed.push(r); + let mut r = original.clone(); + r.subject.changes[0].hash = Hash::of(b"another-dependency").to_base32(); + changed.push(r); + let mut r = original.clone(); + r.subject.view_chain[0].name = "other-view".into(); + changed.push(r); + let mut r = original.clone(); + r.subject.view_chain[0].state = "different-state".into(); + changed.push(r); + let mut r = original.clone(); + r.subject.effective_set_id = "changed-membership".into(); + changed.push(r); + let mut r = original.clone(); + r.subject.review.signed_hash = "changed-revision".into(); + changed.push(r); + let mut r = original.clone(); + r.subject.profile_hash = "changed-policy".into(); + changed.push(r); + let mut r = original.clone(); + r.subject.project = "urn:atomic:project:other".into(); + changed.push(r); + for r in changed { + assert!(!reviewer_is_authorized(&f.repo, &r, &f.config, &|_| None).unwrap()); + assert!(retained_public_key(&f.repo, &r, &f.config) + .unwrap() + .is_none()); + } + let other = Fixture::new(); + let auth = f.repo.vault_list(PREFIX, None).unwrap().pop().unwrap(); + let entry = f.repo.vault_retrieve(&auth.path).unwrap().unwrap(); + let certificate: ReviewAuthorization = parse(&entry.content_bytes).unwrap(); + store_immutable(&other.repo, &auth.path, &certificate).unwrap(); + assert!(!reviewer_is_authorized(&other.repo, &original, &f.config, &|_| None).unwrap()); + } + + #[test] + fn issuer_requires_current_configured_trust_not_arbitrary_local_keys() { + let mut f = Fixture::new(); + let mut untrusted = f.config.clone(); + untrusted.trust.signers.clear(); + assert!(mint_and_store( + &f.repo, + &f.review.subject, + &f.delegate.public_key, + &f.issuer, + &f.issuer_key, + Utc::now() + Duration::minutes(10), + &untrusted + ) + .is_err()); + f.mint(); + assert!(!reviewer_is_authorized(&f.repo, &f.review, &untrusted, &|_| None).unwrap()); + f.config + .trust + .revoked + .push(f.config.trust.signers[0].clone()); + assert!(!f.authorized()); + } + + #[test] + fn configured_repository_identity_can_issue_but_revocation_still_wins() { + let mut f = Fixture::new(); + f.config.repository_identity = f.config.trust.signers.pop(); + let auth = f.mint(); + f.sign_review(); + assert!(f.authorized()); + assert!(reviewer_may_sign_now(&f.repo, &f.review, &f.config, &|_| None).unwrap()); + assert!(retained_public_key(&f.repo, &f.review, &f.config) + .unwrap() + .is_some()); + f.config.trust.revoked.push(auth.issuer); + assert!(!f.authorized()); + assert!(!reviewer_may_sign_now(&f.repo, &f.review, &f.config, &|_| None).unwrap()); + } + + #[test] + fn revoked_delegate_overrides_both_certificate_and_direct_trust() { + let mut f = Fixture::new(); + f.mint(); + f.sign_review(); + f.config.trust.revoked.push(f.review.attributed_to.clone()); + assert!(!f.authorized()); + f.config.trust.signers.push(f.review.attributed_to.clone()); + f.config.repository_identity = Some(f.review.attributed_to.clone()); + assert!(!f.authorized()); + assert!(!reviewer_may_sign_now(&f.repo, &f.review, &f.config, &|_| None).unwrap()); + } + + #[test] + fn direct_signer_trust_is_preserved_without_any_certificate() { + let mut f = Fixture::new(); + f.config.repository_identity = Some(f.review.attributed_to.clone()); + assert!(f.authorized()); + } + + #[test] + fn expiry_blocks_new_signing_not_authenticated_historical_reviews() { + let mut f = Fixture::new(); + let mut auth = f.mint(); + // Remove the still-live certificate using a fresh repository rather than + // deleting authority. Only the intentionally expired fixture is retained. + let other = Fixture::new(); + auth.project = other.repo.project_id().unwrap().to_urn(); + auth.subject.project = auth.project.clone(); + auth.created_at = (Utc::now() - Duration::hours(2)).to_rfc3339(); + auth.expires_at = (Utc::now() - Duration::hours(1)).to_rfc3339(); + auth.content_hash = None; + auth.proof = None; + auth.id = identifier(&auth).unwrap(); + let signed: ReviewAuthorization = serde_json::from_value( + atomic_canonical::proof::attest_value(value(&auth).unwrap(), &f.issuer, &f.issuer_key), + ) + .unwrap(); + store_immutable(&other.repo, &path(&signed.id), &signed).unwrap(); + f.review.subject = auth.subject; + f.review.reviewed_at = (Utc::now() - Duration::minutes(90)).to_rfc3339(); + f.sign_review(); + assert!(reviewer_is_authorized(&other.repo, &f.review, &f.config, &|_| None).unwrap()); + assert!(!reviewer_may_sign_now(&other.repo, &f.review, &f.config, &|_| None).unwrap()); + assert!(retained_public_key(&other.repo, &f.review, &f.config) + .unwrap() + .is_some()); + f.review.proof = None; + assert!(!reviewer_is_authorized(&other.repo, &f.review, &f.config, &|_| None).unwrap()); + } + + #[test] + fn backdating_future_dates_and_tampered_reviews_are_denied() { + let mut f = Fixture::new(); + let auth = f.mint(); + f.review.reviewed_at = + (time(&auth.created_at).unwrap() - Duration::seconds(1)).to_rfc3339(); + f.sign_review(); + assert!(!f.authorized()); + f.review.reviewed_at = (Utc::now() + Duration::minutes(1)).to_rfc3339(); + f.sign_review(); + assert!(!f.authorized()); + f.review.reviewed_at = Utc::now().to_rfc3339(); + f.sign_review(); + assert!(f.authorized()); + f.review.reviewed_at = (Utc::now() - Duration::milliseconds(1)).to_rfc3339(); + assert!(!f.authorized()); + } + + #[test] + fn malformed_scope_wrong_purpose_and_mismatched_issuer_keys_fail_closed() { + let mut f = Fixture::new(); + let auth = f.mint(); + let mut bad = auth.clone(); + bad.purpose = "read-record".into(); + let bad = f.store_reissued(bad); + assert!(bad.verify(&f.repo, &f.config).is_err()); + let mut bad = auth.clone(); + bad.delegate_public_key = f.issuer.public_key.to_base32(); + let bad = f.store_reissued(bad); + assert!(bad.verify(&f.repo, &f.config).is_err()); + let mut bad = auth.clone(); + bad.issuer_public_key = f.delegate.public_key.to_base32(); + let bad = f.store_reissued(bad); + assert!(bad.verify(&f.repo, &f.config).is_err()); + let mut bad = auth.clone(); + bad.subject.roots.push(bad.subject.roots[0].clone()); + let bad = f.store_reissued(bad); + assert!(bad.verify(&f.repo, &f.config).is_err()); + let mut bad = auth.clone(); + bad.subject.roots[0] = "*".into(); + let bad = f.store_reissued(bad); + assert!(bad.verify(&f.repo, &f.config).is_err()); + let mut bad = auth.clone(); + bad.expires_at = (Utc::now() + Duration::hours(3)).to_rfc3339(); + // Recomputing an ID is not a replacement for an issuer signature. + bad.id = identifier(&bad).unwrap(); + assert!(bad.verify(&f.repo, &f.config).is_err()); + assert!(mint_and_store( + &f.repo, + &f.review.subject, + &f.delegate.public_key, + &f.issuer, + &f.delegate_key, + Utc::now() + Duration::minutes(10), + &f.config + ) + .is_err()); + } + + #[test] + fn signed_revocation_blocks_authority_but_preserves_public_verification_key() { + let mut f = Fixture::new(); + let auth = f.mint(); + f.sign_review(); + assert!(f.authorized()); + assert!(revoke_and_store(&f.repo, &auth, &f.delegate, &f.delegate_key, &f.config).is_err()); + revoke_and_store(&f.repo, &auth, &f.issuer, &f.issuer_key, &f.config).unwrap(); + revoke_and_store(&f.repo, &auth, &f.issuer, &f.issuer_key, &f.config).unwrap(); + assert!(!f.authorized()); + assert!(!reviewer_may_sign_now(&f.repo, &f.review, &f.config, &|_| None).unwrap()); + assert_eq!( + retained_public_key(&f.repo, &f.review, &f.config).unwrap(), + Some(*f.delegate.public_key.as_bytes()) + ); + } + + #[test] + fn ordinary_secret_retirement_keeps_signed_approval_authority() { + let mut f = Fixture::new(); + let auth = f.mint(); + f.sign_review(); + // Retire the actual signing secret, retaining only the public identity + // and signed certificate. No approval-withdrawal operation is implied. + drop(f.delegate_key); + assert!(reviewer_is_authorized(&f.repo, &f.review, &f.config, &|_| None).unwrap()); + assert_eq!( + retained_public_key(&f.repo, &f.review, &f.config).unwrap(), + Some(*f.delegate.public_key.as_bytes()) + ); + assert!(f + .repo + .vault_retrieve(&revocation_path(&auth.id)) + .unwrap() + .is_none()); + } + + #[test] + fn immutable_storage_and_untrusted_revocation_assertions() { + let mut f = Fixture::new(); + let auth = f.mint(); + store_immutable(&f.repo, &path(&auth.id), &auth).unwrap(); + let mut changed = auth.clone(); + changed.purpose = "*".into(); + assert!(store_immutable(&f.repo, &path(&auth.id), &changed).is_err()); + store_immutable( + &f.repo, + &revocation_path(&auth.id), + &serde_json::json!({"revoked":true}), + ) + .unwrap(); + assert!(reviewer_is_authorized(&f.repo, &f.review, &f.config, &|_| None).is_err()); + assert!(parse::(br#"{"id":"a","id":"b"}"#).is_err()); + } + + #[test] + fn generic_vault_mutations_cannot_erase_or_rewrite_approval_withdrawal() { + let mut f = Fixture::new(); + let auth = f.mint(); + f.sign_review(); + revoke_and_store(&f.repo, &auth, &f.issuer, &f.issuer_key, &f.config).unwrap(); + assert!(!f.authorized()); + let manifest_before = serde_json::to_value(f.repo.vault_manifest().unwrap()).unwrap(); + for retained_path in [path(&auth.id), revocation_path(&auth.id)] { + let original = f.repo.vault_retrieve(&retained_path).unwrap().unwrap(); + // Content, metadata, and entry-type replacement are all forbidden + // through both generic store APIs, not just the mint/revoke helpers. + for (content, frontmatter, entry_type) in [ + ( + b"{\"revoked\":false}".to_vec(), + original.frontmatter_json.clone(), + original.entry_type, + ), + ( + original.content_bytes.clone(), + "{\"revoked\":false}".into(), + original.entry_type, + ), + ( + original.content_bytes.clone(), + original.frontmatter_json.clone(), + VaultEntryType::Scratch, + ), + ] { + assert!(f + .repo + .vault_store( + &retained_path, + entry_type, + content.clone(), + frontmatter.clone() + ) + .is_err()); + let replacement = + VaultEntry::new(entry_type, content, frontmatter, Utc::now().to_rfc3339()); + assert!(f + .repo + .vault_store_entry(&retained_path, &replacement) + .is_err()); + assert!(!f.authorized()); + } + assert!(f.repo.vault_delete(&retained_path).is_err()); + // Explicit-file deflation routes edits/deletes through the same + // protections and must not be an alternative mutation channel. + assert!(f + .repo + .vault_record_files(&[(retained_path.clone(), Some("tampered".into()))]) + .is_err()); + assert!(f + .repo + .vault_record_files(&[(retained_path.clone(), None)]) + .is_err()); + let after = f.repo.vault_retrieve(&retained_path).unwrap().unwrap(); + assert_eq!(after.content_bytes, original.content_bytes); + assert_eq!(after.frontmatter_json, original.frontmatter_json); + assert_eq!(after.entry_type, original.entry_type); + assert!(!f.authorized()); + } + assert_eq!( + serde_json::to_value(f.repo.vault_manifest().unwrap()).unwrap(), + manifest_before + ); + + // The ordinary on-disk deflation path cannot delete a withdrawal either. + f.repo.vault_materialize_all().unwrap(); + std::fs::remove_file(f.repo.vault_dir().join(revocation_path(&auth.id))).unwrap(); + assert!(f.repo.vault_record_working_copy().is_err()); + assert!(is_revoked(&f.repo, &auth).unwrap()); + assert!(!f.authorized()); + assert!(retained_public_key(&f.repo, &f.review, &f.config) + .unwrap() + .is_some()); + } +} diff --git a/atomic-repository/src/repository/sandbox.rs b/atomic-repository/src/repository/sandbox.rs index 441d3e65..e7785d17 100644 --- a/atomic-repository/src/repository/sandbox.rs +++ b/atomic-repository/src/repository/sandbox.rs @@ -411,6 +411,82 @@ impl Repository { Ok(count) } + /// Provision a new sandbox from the recorded `view`, never from working files. + /// + /// The destination must not exist and its parent must exist. The checkout + /// renderer supplies bytes, inode modes, symlink kinds, and conflict output. + /// Absolute symlinks and symlinks containing parent components are not + /// supported: a review snapshot must not expose files outside itself. + /// Entries may not traverse symlink ancestors or overwrite sandbox metadata. + /// On failure, the newly created directory is retained for owner inspection + /// and cleanup; no existing destination is overwritten or removed. + pub fn provision_recorded_sandbox( + &self, + dest: impl AsRef, + view: &str, + ) -> Result { + let dest = dest.as_ref(); + let name = dest.file_name().ok_or_else(|| unsafe_snapshot_path(dest))?; + if !matches!( + dest.components().next_back(), + Some(std::path::Component::Normal(_)) + ) { + return Err(unsafe_snapshot_path(dest)); + } + // Resolve the caller's parent once, then keep output beneath the new + // directory. create_dir refuses existing directories and dangling links. + let parent = dest + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + let dest = parent.canonicalize()?.join(name); + let mut builder = std::fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + builder.create(&dest)?; + let snapshot = self.materialize_view_entries(view, |entry| { + write_recorded_snapshot_entry(&dest, &entry) + })??; + + let pointer = SandboxPointer { + canonical: self + .dot_dir + .parent() + .ok_or_else(|| RepositoryError::InvalidOperation { + message: "canonical repository directory has no parent".to_string(), + })? + .to_path_buf(), + view: view.to_string(), + }; + use std::io::Write; + let bytes = serde_json::to_vec_pretty(&pointer) + .map_err(|e| RepositoryError::Database(e.to_string()))?; + std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(dest.join(SANDBOX_POINTER))? + .write_all(&bytes)?; + let layout = working_copy::layout_for_paths( + dest.clone(), + self.dot_dir.clone(), + dest.join(DOT_DIR), + false, + )?; + let (_, registered_view) = working_copy::migrate_identity(&self.pristine, &layout, view)?; + if registered_view != view { + return Err(RepositoryError::InvalidOperation { + message: format!( + "sandbox location is already registered on view '{registered_view}', not '{view}'; retained '{}' for inspection", + dest.display() + ), + }); + } + Ok(snapshot) + } + fn materialized_view_files( &self, view_name: &str, @@ -670,6 +746,108 @@ fn recreate_symlink(src: &Path, dest: &Path) -> std::io::Result<()> { std::fs::copy(src, dest).map(|_| ()) } +fn unsafe_snapshot_path(path: &Path) -> RepositoryError { + RepositoryError::InvalidOperation { + message: format!( + "unsafe recorded sandbox path '{}': paths must be relative, without parent components, symlink ancestors, or repository metadata; external/parent symlinks are unsupported", + path.display() + ), + } +} + +fn validate_snapshot_relative(path: &Path) -> Result<(), RepositoryError> { + use std::path::Component; + let bytes = path.as_os_str().as_encoded_bytes(); + if bytes.is_empty() + || bytes.contains(&b'\\') + || bytes.contains(&b':') + || bytes.contains(&0) + || bytes.split(|b| *b == b'/').any(|part| { + part.is_empty() + || part == b"." + || part == b".." + || [DOT_DIR, ".git", SANDBOX_POINTER, SANDBOX_CACHE_DIR] + .iter() + .any(|reserved| part.eq_ignore_ascii_case(reserved.as_bytes())) + }) + || path + .components() + .any(|part| !matches!(part, Component::Normal(_))) + { + return Err(unsafe_snapshot_path(path)); + } + Ok(()) +} + +fn ensure_snapshot_directories(root: &Path, relative: &Path) -> Result<(), RepositoryError> { + let mut current = root.to_path_buf(); + for component in relative.components() { + current.push(component); + match std::fs::symlink_metadata(¤t) { + Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {} + Ok(_) => return Err(unsafe_snapshot_path(relative)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + std::fs::create_dir(¤t)?; + } + Err(error) => return Err(error.into()), + } + } + Ok(()) +} + +fn write_recorded_snapshot_entry( + root: &Path, + entry: &super::ViewEntry, +) -> Result<(), RepositoryError> { + use super::ViewEntryKind; + use std::io::Write; + let relative = Path::new(&entry.path); + validate_snapshot_relative(relative)?; + let target = root.join(relative); + if let Some(parent) = relative.parent() { + ensure_snapshot_directories(root, parent)?; + } + match entry.kind { + ViewEntryKind::Directory => ensure_snapshot_directories(root, relative)?, + ViewEntryKind::File => { + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&target)?; + file.write_all(&entry.content)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + file.set_permissions(std::fs::Permissions::from_mode(u32::from( + entry.mode & 0o777, + )))?; + } + } + ViewEntryKind::Symlink => { + #[cfg(unix)] + { + use std::os::unix::ffi::OsStrExt; + let link = Path::new(std::ffi::OsStr::from_bytes(&entry.content)); + validate_snapshot_relative(link)?; + std::os::unix::fs::symlink(link, &target)?; + } + #[cfg(not(unix))] + return Err(RepositoryError::InvalidOperation { + message: "recorded sandbox symlinks are unsupported on this platform".to_string(), + }); + } + } + #[cfg(unix)] + if entry.kind == ViewEntryKind::Directory { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions( + target, + std::fs::Permissions::from_mode(u32::from(entry.mode & 0o777)), + )?; + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -691,6 +869,11 @@ mod tests { } std::fs::write(&path, contents).unwrap(); + record_path(&repo, rel); + repo + } + + fn record_path(repo: &Repository, rel: &str) { repo.add( repo.require_working_copy_id().unwrap(), rel, @@ -707,8 +890,219 @@ mod tests { .unwrap(); repo.write_recorded(&outcome, InsertOptions::default()) .unwrap(); + } - repo + #[test] + fn recorded_sandbox_excludes_dirty_files_and_keeps_source_identity() { + let dir = tempdir().unwrap(); + let source = dir.path().join("repo"); + let repo = repo_with_recorded_file(&source, "src/file.txt", b"recorded\0bytes\n"); + let source_id = repo.require_working_copy_id().unwrap(); + let source_view = std::fs::read(source.join(DOT_DIR).join("current_view")).unwrap(); + let source_identity = std::fs::read(source.join(DOT_DIR).join("working_copy_id")).unwrap(); + std::fs::write(source.join("src/file.txt"), b"dirty\n").unwrap(); + std::fs::write(source.join(".env"), b"SECRET=never-copy\n").unwrap(); + let dest = dir.path().join("review"); + + let snapshot = repo.provision_recorded_sandbox(&dest, "dev").unwrap(); + assert_eq!(snapshot.view, "dev"); + assert_eq!(snapshot.change_count, 1); + let expected = repo + .materialize_view_entries::("dev", |_| Ok(())) + .unwrap() + .unwrap(); + assert_eq!(snapshot.state, expected.state); + assert_eq!( + std::fs::read(dest.join("src/file.txt")).unwrap(), + b"recorded\0bytes\n" + ); + assert!(!dest.join(".env").exists()); + assert_eq!( + std::fs::read(source.join("src/file.txt")).unwrap(), + b"dirty\n" + ); + assert_eq!( + std::fs::read(source.join(".env")).unwrap(), + b"SECRET=never-copy\n" + ); + assert_eq!( + std::fs::read(source.join(DOT_DIR).join("current_view")).unwrap(), + source_view + ); + assert_eq!( + std::fs::read(source.join(DOT_DIR).join("working_copy_id")).unwrap(), + source_identity + ); + assert_eq!(repo.require_working_copy_id().unwrap(), source_id); + drop(repo); + + let sandbox = Repository::open_existing(&dest).unwrap(); + let sandbox_id = sandbox.require_working_copy_id().unwrap(); + assert_ne!(sandbox_id, source_id); + assert_eq!(sandbox.desired_view_name(sandbox_id).unwrap(), "dev"); + assert_eq!(sandbox.current_view, "dev"); + } + + #[test] + fn recorded_sandbox_refuses_existing_destination_without_mutation() { + let dir = tempdir().unwrap(); + let repo = repo_with_recorded_file(&dir.path().join("repo"), "file", b"recorded"); + let dest = dir.path().join("existing"); + std::fs::create_dir(&dest).unwrap(); + std::fs::write(dest.join("keep"), b"owned by someone else").unwrap(); + assert!(repo.provision_recorded_sandbox(&dest, "dev").is_err()); + assert_eq!( + std::fs::read(dest.join("keep")).unwrap(), + b"owned by someone else" + ); + assert!(!dest.join("file").exists()); + assert!(!dest.join(SANDBOX_POINTER).exists()); + } + + fn snapshot_entry( + path: &str, + kind: super::super::ViewEntryKind, + content: &[u8], + ) -> super::super::ViewEntry { + super::super::ViewEntry { + path: path.to_string(), + inode: 1, + kind, + mode: 0o755, + content: content.to_vec(), + hash: atomic_core::types::Hash::of(content), + conflict_marker_line: None, + } + } + + #[test] + fn recorded_sandbox_rejects_traversal_and_metadata_paths() { + use super::super::ViewEntryKind; + let dir = tempdir().unwrap(); + for path in [ + "../escape", + "/absolute", + "a/../../escape", + "a/./file", + "a\\escape", + "C:/escape", + ".atomic/current_view", + ".atomic-sandbox", + ".git/config", + ] { + let entry = snapshot_entry(path, ViewEntryKind::File, b"unsafe"); + assert!( + write_recorded_snapshot_entry(dir.path(), &entry).is_err(), + "{path}" + ); + } + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0); + } + + #[cfg(unix)] + #[test] + fn recorded_sandbox_preserves_recorded_mode_and_safe_symlink() { + use std::os::unix::fs::{symlink, PermissionsExt}; + let dir = tempdir().unwrap(); + let source = dir.path().join("repo"); + let repo = Repository::init(&source).unwrap(); + std::fs::write(source.join("tool"), b"#!/bin/sh\nexit 0\n").unwrap(); + std::fs::set_permissions(source.join("tool"), std::fs::Permissions::from_mode(0o751)) + .unwrap(); + record_path(&repo, "tool"); + symlink("tool", source.join("link")).unwrap(); + record_path(&repo, "link"); + std::fs::set_permissions(source.join("tool"), std::fs::Permissions::from_mode(0o600)) + .unwrap(); + let dest = dir.path().join("review"); + + repo.provision_recorded_sandbox(&dest, "dev").unwrap(); + assert_eq!( + std::fs::metadata(dest.join("tool")) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o751 + ); + assert!(std::fs::symlink_metadata(dest.join("link")) + .unwrap() + .file_type() + .is_symlink()); + assert_eq!( + std::fs::read_link(dest.join("link")).unwrap(), + Path::new("tool") + ); + assert_eq!( + std::fs::metadata(source.join("tool")) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o600 + ); + assert_eq!( + std::fs::read_link(source.join("link")).unwrap(), + Path::new("tool") + ); + } + + #[cfg(unix)] + #[test] + fn recorded_sandbox_rejects_external_links_and_symlink_ancestors() { + use super::super::ViewEntryKind; + use std::os::unix::fs::symlink; + let dir = tempdir().unwrap(); + let outside = tempdir().unwrap(); + for target in ["../outside", "/etc/passwd", "dir/../../outside"] { + let entry = snapshot_entry("link", ViewEntryKind::Symlink, target.as_bytes()); + assert!(write_recorded_snapshot_entry(dir.path(), &entry).is_err()); + assert!(std::fs::symlink_metadata(dir.path().join("link")).is_err()); + } + symlink(outside.path(), dir.path().join("ancestor")).unwrap(); + let entry = snapshot_entry("ancestor/escape", ViewEntryKind::File, b"unsafe"); + assert!(write_recorded_snapshot_entry(dir.path(), &entry).is_err()); + assert!(!outside.path().join("escape").exists()); + } + + #[cfg(unix)] + #[test] + fn recorded_sandbox_refuses_recorded_external_symlink() { + use std::os::unix::fs::symlink; + let dir = tempdir().unwrap(); + let source = dir.path().join("repo"); + let repo = Repository::init(&source).unwrap(); + symlink("../private-secret", source.join("link")).unwrap(); + record_path(&repo, "link"); + let dest = dir.path().join("review"); + + let error = repo.provision_recorded_sandbox(&dest, "dev").unwrap_err(); + assert!(error + .to_string() + .contains("external/parent symlinks are unsupported")); + assert!( + dest.is_dir(), + "partial output is retained, not recursively deleted" + ); + assert!(!dest.join(SANDBOX_POINTER).exists()); + assert_eq!( + std::fs::read_link(source.join("link")).unwrap(), + Path::new("../private-secret") + ); + } + + #[cfg(unix)] + #[test] + fn recorded_sandbox_refuses_dangling_destination_symlink() { + let dir = tempdir().unwrap(); + let repo = repo_with_recorded_file(&dir.path().join("repo"), "file", b"recorded"); + let dest = dir.path().join("review"); + let outside = dir.path().join("not-created"); + std::os::unix::fs::symlink(&outside, &dest).unwrap(); + + assert!(repo.provision_recorded_sandbox(&dest, "dev").is_err()); + assert_eq!(std::fs::read_link(&dest).unwrap(), outside); + assert!(!outside.exists()); } #[test] diff --git a/atomic-repository/src/repository/semantic_review.rs b/atomic-repository/src/repository/semantic_review.rs new file mode 100644 index 00000000..e19a0df8 --- /dev/null +++ b/atomic-repository/src/repository/semantic_review.rs @@ -0,0 +1,360 @@ +//! Recorded-source selection for semantic consumers. Search precedes AST work. + +use std::collections::{BTreeMap, BTreeSet, VecDeque}; + +use atomic_core::{ + pristine::GraphVisibilityClosure, + types::{Hash, Inode, NodeId, Position}, + ReadTxn, +}; +use atomic_semantic::{ + relationships::context_paths, + source::{SourceSet, Symbol}, + Language, ParserRegistry, +}; + +use super::{Repository, RepositoryError}; +use crate::content_search::{ContentSearchOptions, RecordedContentSearch, RECORDED_CONTENT_LIMIT}; + +pub struct RecordedSemanticView<'repo> { + repo: &'repo Repository, + txn: ReadTxn, + visibility: GraphVisibilityClosure, + files: BTreeMap)>, +} + +impl Repository { + /// Pin source selection to exactly the before/after recorded view prefix. + pub fn semantic_view_at_change( + &self, + hash: &Hash, + include_change: bool, + ) -> Result, RepositoryError> { + use atomic_core::pristine::ViewTxnT; + let txn = self.pristine.read_txn()?; + let view = + txn.get_view(&self.current_view)? + .ok_or_else(|| RepositoryError::ViewNotFound { + name: self.current_view.clone(), + })?; + let visibility = + super::content::graph_visibility_at_change(&txn, &view, hash, include_change)? + .ok_or_else(|| RepositoryError::InvalidOperation { + message: format!("recorded semantic context unavailable for {hash}"), + })?; + self.semantic_view_with_visibility(txn, visibility) + } + + /// Pin semantic source selection to the complete effective recorded state of + /// a named view, without switching or consulting working-copy content. + pub fn semantic_view_on_view( + &self, + name: &str, + ) -> Result, RepositoryError> { + use atomic_core::pristine::ViewTxnT; + let txn = self.pristine.read_txn()?; + let view = txn + .get_view(name)? + .ok_or_else(|| RepositoryError::ViewNotFound { name: name.into() })?; + let visibility = super::graph_visibility_closure(&txn, &view)?; + self.semantic_view_with_visibility(txn, visibility) + } + + fn semantic_view_with_visibility( + &self, + txn: ReadTxn, + visibility: GraphVisibilityClosure, + ) -> Result, RepositoryError> { + let projection = self.project_tree_for_visibility(&txn, &visibility)?; + if !projection.name_conflicts.is_empty() { + return Err(RepositoryError::InvalidOperation { + message: "semantic review refuses unresolved name conflicts".into(), + }); + } + let files = projection + .present + .into_values() + .filter(|entry| { + !entry.is_directory + && !crate::is_vault_path(&entry.path) + && atomic_semantic::is_supported(&entry.path) + }) + .map(|entry| (entry.path, (entry.inode, entry.position))) + .collect(); + Ok(RecordedSemanticView { + repo: self, + txn, + visibility, + files, + }) + } +} + +impl RecordedSemanticView<'_> { + fn content(&self, path: &str) -> Result>, RepositoryError> { + let Some(&(inode, position)) = self.files.get(path) else { + return Ok(None); + }; + let attributes = atomic_core::output::project_inode_attributes( + &self.txn, + position, + self.visibility.attribute_visibility(), + )?; + if attributes.is_conflicted() + || attributes.materialization.kind != atomic_core::change::InodeKind::Regular + { + return Err(RepositoryError::InvalidOperation { + message: format!( + "{path}: semantic source is non-regular or has conflicting attributes" + ), + }); + } + let content = match super::content::retrieve_span_bounded_if_present( + &self.txn, + &self.repo.change_store, + inode, + &self.visibility, + RECORDED_CONTENT_LIMIT, + )? { + Some(content) => content, + None => super::content::retrieve_content_bounded( + &self.txn, + &self.repo.change_store, + inode, + position, + atomic_core::output::alive::RetrieveOptions::new() + .with_graph_visibility(self.visibility.clone()), + RECORDED_CONTENT_LIMIT, + ) + .map_err(|error| RepositoryError::Database(error.to_string()))?, + }; + match content { + super::content::BoundedContent::Complete(bytes) => Ok(Some(bytes)), + super::content::BoundedContent::Oversized { .. } => { + Err(RepositoryError::InvalidOperation { + message: format!("{path}: recorded content exceeds semantic search byte limit"), + }) + } + } + } + + /// Parse changed files first. Unrelated paths cannot consume their budget. + pub fn changed_sources(&self, paths: &[String], parser: &mut ParserRegistry) -> SourceSet { + let mut set = SourceSet { + paths: self.files.keys().cloned().collect(), + complete: true, + paths_complete: true, + ..Default::default() + }; + let (mut bytes, mut omitted) = (0, 0); + for (index, path) in paths + .iter() + .filter(|path| self.files.contains_key(*path)) + .collect::>() + .into_iter() + .enumerate() + { + if index >= 256 { + omitted += 1; + continue; + } + match self.content(path).and_then(|bytes| { + bytes + .map(|bytes| { + String::from_utf8(bytes).map_err(|error| { + RepositoryError::InvalidOperation { + message: error.to_string(), + } + }) + }) + .transpose() + }) { + Ok(Some(source)) => { + if bytes + source.len() > 8 * 1024 * 1024 { + omitted += 1; + continue; + } + bytes += source.len(); + match parser.analyze_source(path, &source) { + Ok(file) => set.files.push(file), + Err(error) => { + set.complete = false; + set.gaps.push(format!("{path}: {error}")); + } + } + } + Ok(None) => {} + Err(error) => { + set.complete = false; + set.gaps + .push(format!("{path}: changed source unavailable: {error}")); + } + } + } + if omitted > 0 { + set.complete = false; + set.gaps.push(format!("{omitted} changed source(s) exceed the root parsing budget (256 changed files / 8 MiB)")); + } + set + } + + /// Reuse recorded syntext path/regex selection, then parse only matching + /// files and explicit declaration/import context. No working-copy index use. + pub fn select_context( + &self, + mut set: SourceSet, + targets: &[Symbol], + parser: &mut ParserRegistry, + ) -> Result { + if targets.is_empty() { + return Ok(set); + } + let mut known: BTreeSet<_> = set.files.iter().map(|file| file.path.clone()).collect(); + let patterns = targets + .iter() + .map(|symbol| { + let name = regex::escape(&symbol.entity.name); + let pattern = if let Some(owner) = &symbol.owner { + let owner = regex::escape(owner); + format!(r"(?s:\b{owner}\b.*\b{name}\b|\b{name}\b.*\b{owner}\b)") + } else { + format!(r"\b{name}\b") + }; + regex::bytes::Regex::new(&pattern).map(|pattern| (symbol, pattern)) + }) + .collect::, _>>() + .map_err(|error| RepositoryError::InvalidOperation { + message: error.to_string(), + })?; + let pattern = patterns + .iter() + .map(|(_, pattern)| pattern.as_str()) + .collect::>() + .into_iter() + .collect::>() + .join("|"); + let plan = RecordedContentSearch::new( + self.files + .keys() + .filter(|path| { + !known.contains(*path) + && targets.iter().any(|target| candidate_path(path, target)) + }) + .map(String::as_str), + &pattern, + ContentSearchOptions::default(), + ) + .map_err(|error| RepositoryError::InvalidOperation { + message: error.to_string(), + })?; + let mut failed = 0; + let matches = plan.matching_sources( + 256usize.saturating_sub(set.files.len()), + 8 * 1024 * 1024, + |path| match self.content(path) { + Ok(content) => Ok::<_, RepositoryError>(content), + Err(_) => { + failed += 1; + Ok(None) + } + }, + |path, source| { + patterns.iter().any(|(target, pattern)| { + candidate_path(path, target) && pattern.is_match(source) + }) + }, + )?; + set.searched_files = matches.searched_files; + if matches.omitted_files > 0 || failed > 0 { + set.complete = false; + set.gaps.push(format!("Semantic candidate selection omitted {} matching/unavailable source(s); caller coverage is incomplete", matches.omitted_files + failed)); + } + for (path, source) in matches.sources { + known.insert(path.clone()); + match parser.analyze_source(&path, &source) { + Ok(file) => set.files.push(file), + Err(error) => { + set.complete = false; + set.gaps + .push(format!("{path}: candidate syntax unavailable: {error}")); + } + } + } + let inventory: BTreeSet<_> = self.files.keys().cloned().collect(); + let mut pending: VecDeque<_> = set + .files + .iter() + .flat_map(|file| context_paths(file, &inventory)) + .collect(); + let (mut omitted, mut context_count, mut context_bytes) = (0, 0, 0); + while let Some(path) = pending.pop_front() { + if !known.insert(path.clone()) { + continue; + } + if context_count >= 64 { + omitted += 1; + continue; + } + context_count += 1; + match self.content(&path) { + Ok(Some(bytes)) => { + if context_bytes + bytes.len() > 8 * 1024 * 1024 { + omitted += 1; + continue; + } + context_bytes += bytes.len(); + match String::from_utf8(bytes) + .map_err(|error| error.to_string()) + .and_then(|source| parser.analyze_source(&path, &source)) + { + Ok(file) => { + pending.extend(context_paths(&file, &inventory)); + set.files.push(file); + } + Err(error) => { + set.complete = false; + set.gaps.push(format!( + "{path}: declaration/import context unavailable: {error}" + )); + } + } + } + _ => { + omitted += 1; + } + } + } + if omitted > 0 { + set.complete = false; + set.gaps.push(format!("{omitted} required declaration/import context source(s) unavailable or over budget")); + } + Ok(set) + } +} + +fn candidate_path(path: &str, target: &Symbol) -> bool { + if path == target.location.path || target.public { + return true; + } + if Language::detect(&target.location.path) != Some(Language::Rust) { + return false; + } + let file = std::path::Path::new(&target.location.path); + let mut region = file + .parent() + .unwrap_or_else(|| std::path::Path::new("")) + .to_path_buf(); + if !matches!( + file.file_name().and_then(|name| name.to_str()), + Some("lib.rs" | "main.rs" | "mod.rs") + ) { + region.push(file.file_stem().unwrap_or_default()); + } + for module in &target.module_scope { + region.push(module); + } + if target.parent_visible { + region.pop(); + } + std::path::Path::new(path).starts_with(region) +} diff --git a/atomic-repository/src/repository/syntax_index.rs b/atomic-repository/src/repository/syntax_index.rs index d9c1aa3a..cb7bd90e 100644 --- a/atomic-repository/src/repository/syntax_index.rs +++ b/atomic-repository/src/repository/syntax_index.rs @@ -1,6 +1,7 @@ //! Request-scoped source relationships. Nothing here is persisted in the KG. use super::*; +use atomic_semantic::relationships::{script_candidates, SourceGraph}; use atomic_semantic::{Entity, EntityKind, ParserRegistry}; use std::collections::{BTreeMap, BTreeSet}; @@ -18,6 +19,8 @@ pub struct SyntaxIndex { pub calls: BTreeSet<(String, String)>, pub file_deps: BTreeSet<(String, String)>, pub file_modules: BTreeMap, + bound_callers: BTreeMap>, + aliases: BTreeMap>, } fn selector(entity: &Entity) -> String { @@ -27,51 +30,17 @@ fn callable(entity: &Entity) -> bool { matches!(entity.kind, EntityKind::Function | EntityKind::Method) } -fn relative_script_import(importer: &str, module: &str, target: &str) -> Option { - let script = |path: &Path| { - matches!( - path.extension().and_then(|ext| ext.to_str()), - Some("ts" | "tsx" | "js" | "jsx" | "mjs" | "mts" | "cjs" | "cts") - ) - }; - if !script(Path::new(importer)) || !module.starts_with('.') { - return None; - } - if !script(Path::new(target)) { - return Some(false); - } - let mut resolved = std::path::PathBuf::new(); - let joined = Path::new(importer) - .parent() - .unwrap_or_else(|| Path::new("")) - .join(module); - for component in joined.components() { - match component { - std::path::Component::Normal(name) => resolved.push(name), - std::path::Component::ParentDir if !resolved.pop() => return Some(false), - std::path::Component::ParentDir | std::path::Component::CurDir => {} - _ => return Some(false), - } - } - let target = Path::new(target); - let stem = target.with_extension(""); - Some(target == resolved || stem == resolved || stem == resolved.join("index")) -} - impl SyntaxIndex { pub fn from_sources(sources: &[(String, String)]) -> Self { let mut parser = ParserRegistry::new(); let mut index = Self::default(); let mut parsed = Vec::new(); - let mut names = BTreeMap::>::new(); + let mut paths = BTreeSet::new(); for (path, source) in sources { - let entities = parser.extract(path, source); - for entity in entities.iter().filter(|entity| callable(entity)) { - names - .entry(entity.name.clone()) - .or_default() - .insert(selector(entity)); + if crate::is_vault_path(path) { + continue; } + paths.insert(path.clone()); index.file_modules.insert( path.clone(), Path::new(path) @@ -80,49 +49,67 @@ impl SyntaxIndex { .unwrap_or_default() .to_owned(), ); - index.entities.extend(entities.clone()); - parsed.push((path, source, entities)); - } - for (path, source, entities) in &parsed { - for reference in parser.extract_references(path, source) { - let Some(caller) = entities - .iter() - .filter(|entity| { - callable(entity) - && reference.line >= entity.line - && reference.line <= entity.end_line - }) - .min_by_key(|entity| entity.end_line - entity.line) - else { - continue; - }; - let caller = selector(caller); - if let Some(targets) = names.get(&reference.symbol) { - for target in targets { - if target != &caller { - index.calls.insert((target.clone(), caller.clone())); - } - } + match parser.analyze_source(path, source) { + Ok(file) => { + index.entities.extend(file.entities.clone()); + parsed.push(file); } + Err(_) => index.entities.extend(parser.extract(path, source)), } - for import in entities + } + let graph = SourceGraph::new(parsed, paths, true); + for symbol in graph + .symbols + .values() + .filter(|symbol| callable(&symbol.entity)) + { + for alias in [ + symbol.id.clone(), + selector(&symbol.entity), + symbol.entity.name.clone(), + ] { + index + .aliases + .entry(alias) + .or_default() + .insert(symbol.id.clone()); + } + } + for call in graph + .bind_calls(None) + .into_iter() + .filter(|call| call.present && call.accessible) + { + let caller = &graph.symbols[&call.call.caller]; + index + .calls + .insert((call.symbol.id.clone(), caller.id.clone())); + index + .bound_callers + .entry(call.symbol.id.clone()) + .or_default() + .push(Caller { + path: caller.location.path.clone(), + name: caller.entity.name.clone(), + line: caller.location.start_line, + summary: caller.entity.signature.clone(), + }); + if caller.location.path != call.symbol.location.path { + index.file_deps.insert(( + caller.location.path.clone(), + call.symbol.location.path.clone(), + )); + } + } + for file in graph.files.values() { + for import in file + .entities .iter() .filter(|entity| entity.kind == EntityKind::Import) { - let tokens: BTreeSet<_> = import - .name - .split(|c: char| !c.is_alphanumeric() && c != '_') - .filter(|s| !s.is_empty()) - .collect(); - for (target, _) in sources { - let stem = Path::new(target) - .file_stem() - .and_then(|s| s.to_str()) - .unwrap_or_default(); - let matches = relative_script_import(path, &import.name, target) - .unwrap_or_else(|| tokens.contains(stem)); - if target != *path && matches { - index.file_deps.insert(((*path).clone(), target.clone())); + for target in script_candidates(&file.path, &import.name, &graph.paths) { + if target != file.path { + index.file_deps.insert((file.path.clone(), target)); } } } @@ -131,36 +118,13 @@ impl SyntaxIndex { } pub fn callers(&self, target: &str) -> Vec { - let (path, name) = target - .rsplit_once('#') - .map(|(path, name)| (Some(path), name)) - .unwrap_or((None, target)); - let targets: BTreeSet<_> = self - .entities - .iter() - .filter(|entity| { - callable(entity) - && entity.name == name - && path.is_none_or(|path| entity.file == path) - }) - .map(selector) - .collect(); - let callers: BTreeSet<_> = self - .calls - .iter() - .filter(|(callee, _)| targets.contains(callee)) - .map(|(_, caller)| caller.as_str()) - .collect(); let mut result: Vec<_> = self - .entities - .iter() - .filter(|entity| callable(entity) && callers.contains(selector(entity).as_str())) - .map(|entity| Caller { - path: entity.file.clone(), - name: entity.name.clone(), - line: entity.line, - summary: entity.signature.clone(), - }) + .aliases + .get(target) + .into_iter() + .flatten() + .flat_map(|id| self.bound_callers.get(id).into_iter().flatten()) + .cloned() .collect(); result.sort_by(|a, b| (&a.path, &a.name, a.line).cmp(&(&b.path, &b.name, b.line))); result.dedup_by(|a, b| a.path == b.path && a.name == b.name && a.line == b.line); @@ -195,7 +159,7 @@ impl Repository { }; let mut sources = Vec::new(); for path in paths { - if !atomic_semantic::is_supported(&path) { + if crate::is_vault_path(&path) || !atomic_semantic::is_supported(&path) { continue; } let bytes = if let Some(view) = view { @@ -223,6 +187,58 @@ impl Repository { mod tests { use super::*; + #[test] + fn caller_queries_use_shared_qualified_bindings_not_global_name_joins() { + let index = SyntaxIndex::from_sources(&[ + ("api.ts".into(), "export function value() {}".into()), + ( + "noise.ts".into(), + "function unrelated() { table.value(); }".into(), + ), + ( + "user.ts".into(), + "import {value as read} from './api'; function consumer() { read(); }".into(), + ), + ("api.rs".into(), "pub fn value() {}".into()), + ]); + let callers = index.callers("api.ts#value"); + assert_eq!(callers.len(), 1); + assert_eq!(callers[0].name, "consumer"); + assert!(index.callers("api.rs#value").is_empty()); + } + + #[test] + fn static_relationships_never_treat_vault_source_as_application_code() { + let index = SyntaxIndex::from_sources(&[ + ("src/api.ts".into(), "export function work() {}".into()), + ( + ".vault/fake.ts".into(), + "import { work } from '../src/api'; export function fake() { work(); }".into(), + ), + ( + "nested/.vault/more.ts".into(), + "export function another() {}".into(), + ), + ( + ".vaultish/real.ts".into(), + "export function real() {}".into(), + ), + ]); + assert!(!index + .entities + .iter() + .any(|entity| crate::is_vault_path(&entity.file))); + assert!(index.callers("src/api.ts#work").is_empty()); + assert!(!index + .file_modules + .keys() + .any(|path| crate::is_vault_path(path))); + assert!(index + .entities + .iter() + .any(|entity| entity.file == ".vaultish/real.ts")); + } + #[test] fn script_imports_follow_relative_paths_instead_of_duplicate_file_stems() { let index = SyntaxIndex::from_sources(&[ diff --git a/atomic-repository/src/repository/tests/query_view_tests.rs b/atomic-repository/src/repository/tests/query_view_tests.rs index bb320f89..72bfdc0e 100644 --- a/atomic-repository/src/repository/tests/query_view_tests.rs +++ b/atomic-repository/src/repository/tests/query_view_tests.rs @@ -418,12 +418,12 @@ fn fixture() -> (TempDir, TestRepository, Hash) { repo.switch_view("feature").unwrap(); std::fs::write( temp.path().join("src/lib.rs"), - "pub fn target(secret: SiblingSecret) {}\npub fn caller() {}\n// inherited_marker\n", + "pub fn target(secret: SiblingSecret) {}\npub fn caller() {}\npub mod sibling;\n// inherited_marker\n", ) .unwrap(); std::fs::write( temp.path().join("src/sibling.rs"), - "pub fn sibling_only() { target(); }\n// sibling_marker\n", + "pub fn sibling_only() { crate::target(); }\n// sibling_marker\n", ) .unwrap(); repo.add("src/sibling.rs", TrackingOptions::default()) diff --git a/atomic-repository/src/repository/vault.rs b/atomic-repository/src/repository/vault.rs index 97e5f43e..7d22d149 100644 --- a/atomic-repository/src/repository/vault.rs +++ b/atomic-repository/src/repository/vault.rs @@ -8,6 +8,13 @@ use atomic_core::types::{Hash, Merkle}; /// Directory name for the vault at the project root. const VAULT_DIR: &str = ".vault"; +/// Signed approvals and their explicit withdrawal tombstones are retained +/// evidence. Generic vault mutation must not erase or rewrite either side. +fn retained_review_evidence(path: &str) -> bool { + path.starts_with(super::publication_review::PREFIX) + || path.starts_with(super::review_authorization::PREFIX) +} + impl Repository { /// Path to the vault directory (`.vault/` at the project root). pub fn vault_dir(&self) -> PathBuf { @@ -222,7 +229,7 @@ impl Repository { let previous_entry = txn .get_vault_entry(path) .map_err(|e| RepositoryError::Database(e.to_string()))?; - if path.starts_with(super::publication_review::PREFIX) + if retained_review_evidence(path) && previous_entry.as_ref().is_some_and(|old| { old.content_bytes != entry.content_bytes || old.frontmatter_json != entry.frontmatter_json @@ -303,7 +310,7 @@ impl Repository { let previous_entry = txn .get_vault_entry(path) .map_err(|e| RepositoryError::Database(e.to_string()))?; - if path.starts_with(super::publication_review::PREFIX) + if retained_review_evidence(path) && previous_entry.as_ref().is_some_and(|old| { old.content_bytes != entry.content_bytes || old.frontmatter_json != entry.frontmatter_json @@ -431,7 +438,7 @@ impl Repository { /// Delete a vault entry by path. Also updates the manifest. pub fn vault_delete(&self, path: &str) -> Result { let _review_boundary = self.review_evidence_lock()?; - if path.starts_with(super::publication_review::PREFIX) { + if retained_review_evidence(path) { return Err(super::publication_review::refused( "review history is retained; use signed supersession", )); diff --git a/atomic-repository/src/triage/report.rs b/atomic-repository/src/triage/report.rs index 62ed7452..99f63406 100644 --- a/atomic-repository/src/triage/report.rs +++ b/atomic-repository/src/triage/report.rs @@ -679,10 +679,9 @@ pub fn build_report( } // 8. BLAST_UNREVIEWED (warn, best-effort): callers of modified code that - // live outside the candidate change-set. For each change's defined - // entities, walk incoming CALLS to caller entities, resolve each - // caller's defining file, and flag any caller whose file no candidate - // modifies. No CALLS/DEFINES edges (unenriched KG) → nothing emitted. + // live outside the candidate change-set. Use the shared semantic source + // relationships, not stored KG code edges or global simple-name joins. + // Unresolved references are not asserted as callers. let mut emitted_blast: HashSet = HashSet::new(); for (i, entities) in change_entities.iter().enumerate() { let mut callers: BTreeSet = BTreeSet::new(); diff --git a/atomic-semantic/src/entity.rs b/atomic-semantic/src/entity.rs index 2e6037ab..c25ef70c 100644 --- a/atomic-semantic/src/entity.rs +++ b/atomic-semantic/src/entity.rs @@ -267,6 +267,17 @@ pub struct Reference { /// Confidence level of this reference match #[serde(default = "default_confidence")] pub confidence: Confidence, + /// AST call spelling and owner; syntactic context is not resolved binding. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub call: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CallContext { + pub target: String, + pub receiver: Option, + pub caller: String, + pub arguments: Option, } fn default_confidence() -> Confidence { diff --git a/atomic-semantic/src/lib.rs b/atomic-semantic/src/lib.rs index 1233bbe8..4b54e7d1 100644 --- a/atomic-semantic/src/lib.rs +++ b/atomic-semantic/src/lib.rs @@ -19,6 +19,12 @@ pub mod entity; pub mod parser; pub mod parsers; +pub mod relationships; +pub mod source; + +/// Shared default byte budget for bounded source inspection. Parsing callers +/// decide when to apply it; this is not an audit rule or a grammar limitation. +pub const MAX_SOURCE_BYTES: usize = 1024 * 1024; /// Find the largest byte index ≤ `max_bytes` that falls on a UTF-8 char boundary. /// @@ -36,6 +42,8 @@ pub(crate) fn truncate_to_char_boundary(s: &str, max_bytes: usize) -> usize { } pub use entity::{ - ChangeType, Confidence, Entity, EntityChange, EntityKind, FileSummary, Reference, + CallContext, ChangeType, Confidence, Entity, EntityChange, EntityKind, FileSummary, Reference, }; pub use parsers::{is_supported, Language, LanguageParser, ParserRegistry, ALL_EXTENSIONS}; +/// Raw syntax-node type used by optional analysis adapters over this registry. +pub use tree_sitter::Node as SyntaxNode; diff --git a/atomic-semantic/src/parser.rs b/atomic-semantic/src/parser.rs index 19a27a5d..91e5a446 100644 --- a/atomic-semantic/src/parser.rs +++ b/atomic-semantic/src/parser.rs @@ -40,6 +40,11 @@ impl TypeScriptExtractor { Self { parser } } + /// Parse with the same configured TypeScript/TSX grammar used for extraction. + pub fn parse_tree(&mut self, source: &str) -> Option { + self.parser.parse(source, None) + } + /// Parse source code and extract all entities pub fn extract(&mut self, source: &str, file_path: &str) -> Vec { let tree = match self.parser.parse(source, None) { @@ -47,6 +52,16 @@ impl TypeScriptExtractor { None => return vec![], }; + self.extract_from_tree(&tree, source, file_path) + } + + /// Annotate the same tree used by shared semantic source analysis. + pub fn extract_from_tree( + &self, + tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { let mut entities = Vec::new(); self.walk_tree(&tree.root_node(), source, file_path, &mut entities, false); entities @@ -59,6 +74,15 @@ impl TypeScriptExtractor { None => return vec![], }; + self.extract_references_from_tree(&tree, source, file_path) + } + + pub fn extract_references_from_tree( + &self, + tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { let mut references = Vec::new(); let mut seen = HashSet::new(); self.walk_tree_for_references( @@ -269,6 +293,7 @@ impl TypeScriptExtractor { column: Some(node.start_position().column as u32), context, confidence: Confidence::High, + call: None, }) } @@ -333,6 +358,7 @@ impl TypeScriptExtractor { column: Some(property.start_position().column as u32), context, confidence: Confidence::Medium, + call: None, }) } @@ -462,6 +488,7 @@ impl TypeScriptExtractor { column: Some(node.start_position().column as u32), context, confidence: Confidence::Low, + call: None, }) } @@ -538,6 +565,7 @@ impl TypeScriptExtractor { column: Some(node.start_position().column as u32), context, confidence: Confidence::High, + call: None, }) } diff --git a/atomic-semantic/src/parsers/cpp.rs b/atomic-semantic/src/parsers/cpp.rs index 90442e9c..e28a1ceb 100644 --- a/atomic-semantic/src/parsers/cpp.rs +++ b/atomic-semantic/src/parsers/cpp.rs @@ -713,6 +713,7 @@ impl CppParser { column: Some(node.start_position().column as u32), context: None, confidence: Confidence::High, + call: None, }); } } @@ -761,6 +762,10 @@ impl Default for CppParser { } impl LanguageParser for CppParser { + fn parse_tree(&mut self, source: &str) -> Option { + self.parser.parse(source, None) + } + fn language(&self) -> Language { if self.is_c { Language::C @@ -775,6 +780,15 @@ impl LanguageParser for CppParser { None => return vec![], }; + self.extract_from_tree(&tree, source, file_path) + } + + fn extract_from_tree( + &mut self, + tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { let mut entities = Vec::new(); self.walk_tree( &tree.root_node(), @@ -792,6 +806,15 @@ impl LanguageParser for CppParser { Some(t) => t, None => return vec![], }; + self.extract_references_from_tree(&tree, source, file_path) + } + + fn extract_references_from_tree( + &mut self, + tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { let mut refs = Vec::new(); self.walk_tree_for_calls(&tree.root_node(), source, file_path, &mut refs); refs diff --git a/atomic-semantic/src/parsers/go.rs b/atomic-semantic/src/parsers/go.rs index 46d26845..d6107856 100644 --- a/atomic-semantic/src/parsers/go.rs +++ b/atomic-semantic/src/parsers/go.rs @@ -346,6 +346,7 @@ impl GoParser { column: Some(node.start_position().column as u32), context: None, confidence: Confidence::High, + call: None, }); } } @@ -387,6 +388,10 @@ impl Default for GoParser { } impl LanguageParser for GoParser { + fn parse_tree(&mut self, source: &str) -> Option { + self.parser.parse(source, None) + } + fn language(&self) -> Language { Language::Go } @@ -397,6 +402,15 @@ impl LanguageParser for GoParser { None => return vec![], }; + self.extract_from_tree(&tree, source, file_path) + } + + fn extract_from_tree( + &mut self, + tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { let mut entities = Vec::new(); self.walk_tree(&tree.root_node(), source, file_path, &mut entities); entities @@ -407,6 +421,15 @@ impl LanguageParser for GoParser { Some(t) => t, None => return vec![], }; + self.extract_references_from_tree(&tree, source, file_path) + } + + fn extract_references_from_tree( + &mut self, + tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { let mut refs = Vec::new(); self.walk_tree_for_calls(&tree.root_node(), source, file_path, &mut refs); refs diff --git a/atomic-semantic/src/parsers/java.rs b/atomic-semantic/src/parsers/java.rs index ca97da03..fab54612 100644 --- a/atomic-semantic/src/parsers/java.rs +++ b/atomic-semantic/src/parsers/java.rs @@ -618,6 +618,7 @@ impl JavaParser { column: Some(node.start_position().column as u32), context: None, confidence: Confidence::High, + call: None, }); } } @@ -637,6 +638,10 @@ impl Default for JavaParser { } impl LanguageParser for JavaParser { + fn parse_tree(&mut self, source: &str) -> Option { + self.parser.parse(source, None) + } + fn language(&self) -> Language { Language::Java } @@ -647,6 +652,15 @@ impl LanguageParser for JavaParser { None => return vec![], }; + self.extract_from_tree(&tree, source, file_path) + } + + fn extract_from_tree( + &mut self, + tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { let mut entities = Vec::new(); self.walk_tree(&tree.root_node(), source, file_path, &mut entities, None); entities @@ -657,6 +671,15 @@ impl LanguageParser for JavaParser { Some(t) => t, None => return vec![], }; + self.extract_references_from_tree(&tree, source, file_path) + } + + fn extract_references_from_tree( + &mut self, + tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { let mut refs = Vec::new(); self.walk_tree_for_calls(&tree.root_node(), source, file_path, &mut refs); refs diff --git a/atomic-semantic/src/parsers/mod.rs b/atomic-semantic/src/parsers/mod.rs index 812a37d1..294f2a91 100644 --- a/atomic-semantic/src/parsers/mod.rs +++ b/atomic-semantic/src/parsers/mod.rs @@ -185,6 +185,13 @@ pub trait LanguageParser: Send { /// The language this parser handles. fn language(&self) -> Language; + /// Parse a full source file for structural inspection. Error nodes remain + /// visible; callers must not treat a recovered syntax tree as a clean parse. + /// External entity-only parsers can leave this unsupported. + fn parse_tree(&mut self, _source: &str) -> Option { + None + } + /// Extract AST entities (functions, classes, etc.) from source code. /// /// # Arguments @@ -197,6 +204,17 @@ pub trait LanguageParser: Send { /// A list of entities found in the source code. fn extract(&mut self, source: &str, file_path: &str) -> Vec; + /// Reuse a registered grammar's tree when enriching existing entities. + /// Entity-only adapters may fall back to their ordinary extraction path. + fn extract_from_tree( + &mut self, + _tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { + self.extract(source, file_path) + } + /// Extract references (function calls, variable usages) from source code. /// /// The default implementation returns an empty list. Languages that @@ -214,6 +232,17 @@ pub trait LanguageParser: Send { let _ = (source, file_path); Vec::new() } + + /// Visit references without reparsing. The tree must use this parser's + /// configured grammar and correspond to `source`. + fn extract_references_from_tree( + &mut self, + _tree: &tree_sitter::Tree, + source: &str, + path: &str, + ) -> Vec { + self.extract_references(source, path) + } } // ═══════════════════════════════════════════════════════════════════════ @@ -223,7 +252,7 @@ pub trait LanguageParser: Send { /// Registry of language parsers. /// /// Provides a single entry point for extracting entities from any supported -/// file. Lazily creates parsers on first use for each language. +/// file. Registered grammar instances are reused across source requests. /// /// # Thread Safety /// @@ -247,6 +276,53 @@ pub struct ParserRegistry { } impl ParserRegistry { + /// Convenience adapter for consumers supplying an in-memory source corpus. + pub fn analyze_sources(&mut self, sources: &[(String, String)]) -> crate::source::SourceSet { + let mut result = crate::source::SourceSet { + paths: sources.iter().map(|(path, _)| path.clone()).collect(), + complete: true, + paths_complete: true, + ..Default::default() + }; + let unique: std::collections::BTreeSet<_> = result.paths.iter().collect(); + if unique.len() != result.paths.len() { + result.complete = false; + result.gaps.push("Duplicate semantic source paths".into()); + return result; + } + for (path, source) in sources { + match self.analyze_source(path, source) { + Ok(file) => result.files.push(file), + Err(error) => { + result.complete = false; + result.gaps.push(format!("{path}: {error}")); + } + } + } + result + } + /// Shared source context for search, callers and review. Qualified targets, + /// receivers and lexical owners are retained instead of flattened names. + pub fn analyze_source( + &mut self, + path: &str, + source: &str, + ) -> Result { + if source.len() > crate::MAX_SOURCE_BYTES || source.contains('\0') { + return Err("Semantic source exceeds byte limit or is binary".into()); + } + let language = Language::detect(path).ok_or("Unsupported semantic source language")?; + let parser = self + .parsers + .get_mut(&language) + .ok_or("No registered semantic parser")?; + let tree = parser + .parse_tree(source) + .ok_or("No registered semantic syntax tree")?; + crate::source::SourceAnalysis::from_tree(path, source, language, &tree, || { + parser.extract_from_tree(&tree, source, path) + }) + } /// Create a new registry with all supported language parsers. pub fn new() -> Self { let mut parsers: HashMap> = HashMap::new(); @@ -282,6 +358,13 @@ impl ParserRegistry { Language::detect(path) } + /// Parse with the existing registered language parser. `None` means an + /// unsupported language/parser or parsing failure, not a clean file. + pub fn parse_tree(&mut self, file_path: &str, source: &str) -> Option { + let language = Language::detect(file_path)?; + self.parsers.get_mut(&language)?.parse_tree(source) + } + /// Extract entities from a source file. /// /// Automatically selects the right parser based on the file extension. @@ -309,10 +392,39 @@ impl ParserRegistry { None => return Vec::new(), }; - match self.parsers.get_mut(&language) { - Some(parser) => parser.extract_references(source, file_path), - None => Vec::new(), + let Some(parser) = self.parsers.get_mut(&language) else { + return vec![]; + }; + let Some(tree) = parser.parse_tree(source) else { + return parser.extract_references(source, file_path); + }; + if source.len() > crate::MAX_SOURCE_BYTES { + return vec![]; + } + let Ok(analysis) = + crate::source::SourceAnalysis::from_tree(file_path, source, language, &tree, || { + parser.extract_from_tree(&tree, source, file_path) + }) + else { + return vec![]; + }; + let mut references = parser.extract_references_from_tree(&tree, source, file_path); + let calls: std::collections::BTreeMap<_, _> = analysis + .calls + .iter() + .map(|call| ((call.location.start_line, call.column), call)) + .collect(); + for reference in &mut references { + if let Some(call) = calls.get(&(reference.line, reference.column.unwrap_or(0))) { + reference.call = Some(crate::entity::CallContext { + target: call.expression.clone(), + receiver: call.receiver.clone(), + caller: call.caller.clone(), + arguments: call.arguments, + }); + } } + references } /// Get a list of all supported languages. @@ -344,6 +456,87 @@ impl fmt::Debug for ParserRegistry { mod tests { use super::*; + #[test] + fn source_and_reference_context_reuse_one_registered_tree_per_request() { + use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, + }; + struct Counted { + inner: rust::RustParser, + parses: Arc, + entities: Arc, + references: Arc, + } + impl LanguageParser for Counted { + fn language(&self) -> Language { + Language::Rust + } + fn parse_tree(&mut self, source: &str) -> Option { + self.parses.fetch_add(1, Ordering::Relaxed); + self.inner.parse_tree(source) + } + fn extract(&mut self, _: &str, _: &str) -> Vec { + panic!("shared source analysis must not reparse through extract") + } + fn extract_from_tree( + &mut self, + tree: &tree_sitter::Tree, + source: &str, + path: &str, + ) -> Vec { + self.entities.fetch_add(1, Ordering::Relaxed); + self.inner.extract_from_tree(tree, source, path) + } + fn extract_references(&mut self, _: &str, _: &str) -> Vec { + panic!("shared references must not reparse") + } + fn extract_references_from_tree( + &mut self, + tree: &tree_sitter::Tree, + source: &str, + path: &str, + ) -> Vec { + self.references.fetch_add(1, Ordering::Relaxed); + self.inner.extract_references_from_tree(tree, source, path) + } + } + let (parses, entities, references) = ( + Arc::new(AtomicUsize::new(0)), + Arc::new(AtomicUsize::new(0)), + Arc::new(AtomicUsize::new(0)), + ); + let mut registry = ParserRegistry::new(); + registry.parsers.insert( + Language::Rust, + Box::new(Counted { + inner: rust::RustParser::new(), + parses: parses.clone(), + entities: entities.clone(), + references: references.clone(), + }), + ); + let source = "fn target() {} fn consumer() { target(); }"; + assert_eq!( + registry + .analyze_source("lib.rs", source) + .unwrap() + .symbols + .len(), + 2 + ); + assert!(registry + .extract_references("lib.rs", source) + .iter() + .any(|reference| reference + .call + .as_ref() + .is_some_and(|call| call.target == "target"))); + assert_eq!(parses.load(Ordering::Relaxed), 2); + assert_eq!(entities.load(Ordering::Relaxed), 2); + assert_eq!(references.load(Ordering::Relaxed), 1); + } + // ── Language detection ────────────────────────────────────────── #[test] diff --git a/atomic-semantic/src/parsers/python.rs b/atomic-semantic/src/parsers/python.rs index 5f66973f..a56afddd 100644 --- a/atomic-semantic/src/parsers/python.rs +++ b/atomic-semantic/src/parsers/python.rs @@ -371,6 +371,7 @@ impl PythonParser { column: Some(node.start_position().column as u32), context: None, confidence: Confidence::High, + call: None, }); } } @@ -412,6 +413,10 @@ impl Default for PythonParser { } impl LanguageParser for PythonParser { + fn parse_tree(&mut self, source: &str) -> Option { + self.parser.parse(source, None) + } + fn language(&self) -> Language { Language::Python } @@ -422,6 +427,15 @@ impl LanguageParser for PythonParser { None => return vec![], }; + self.extract_from_tree(&tree, source, file_path) + } + + fn extract_from_tree( + &mut self, + tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { let mut entities = Vec::new(); self.walk_tree(&tree.root_node(), source, file_path, &mut entities, None); entities @@ -432,6 +446,15 @@ impl LanguageParser for PythonParser { Some(t) => t, None => return vec![], }; + self.extract_references_from_tree(&tree, source, file_path) + } + + fn extract_references_from_tree( + &mut self, + tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { let mut refs = Vec::new(); self.walk_tree_for_calls(&tree.root_node(), source, file_path, &mut refs); refs diff --git a/atomic-semantic/src/parsers/rust.rs b/atomic-semantic/src/parsers/rust.rs index 2f914224..de6ffe77 100644 --- a/atomic-semantic/src/parsers/rust.rs +++ b/atomic-semantic/src/parsers/rust.rs @@ -525,6 +525,7 @@ impl RustParser { column: Some(node.start_position().column as u32), context: None, confidence: Confidence::High, + call: None, }); } } @@ -583,6 +584,10 @@ impl Default for RustParser { } impl LanguageParser for RustParser { + fn parse_tree(&mut self, source: &str) -> Option { + self.parser.parse(source, None) + } + fn language(&self) -> Language { Language::Rust } @@ -593,6 +598,15 @@ impl LanguageParser for RustParser { None => return vec![], }; + self.extract_from_tree(&tree, source, file_path) + } + + fn extract_from_tree( + &mut self, + tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { let mut entities = Vec::new(); self.walk_tree(&tree.root_node(), source, file_path, &mut entities, None); entities @@ -610,6 +624,15 @@ impl LanguageParser for RustParser { Some(t) => t, None => return vec![], }; + self.extract_references_from_tree(&tree, source, file_path) + } + + fn extract_references_from_tree( + &mut self, + tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { let mut refs = Vec::new(); self.walk_tree_for_calls(&tree.root_node(), source, file_path, &mut refs); refs diff --git a/atomic-semantic/src/parsers/swift.rs b/atomic-semantic/src/parsers/swift.rs index 52865ab1..5db2509a 100644 --- a/atomic-semantic/src/parsers/swift.rs +++ b/atomic-semantic/src/parsers/swift.rs @@ -583,6 +583,7 @@ impl SwiftParser { column: Some(node.start_position().column as u32), context: None, confidence: Confidence::High, + call: None, }); } } @@ -637,6 +638,10 @@ impl Default for SwiftParser { } impl LanguageParser for SwiftParser { + fn parse_tree(&mut self, source: &str) -> Option { + self.parser.parse(source, None) + } + fn language(&self) -> Language { Language::Swift } @@ -647,6 +652,15 @@ impl LanguageParser for SwiftParser { None => return vec![], }; + self.extract_from_tree(&tree, source, file_path) + } + + fn extract_from_tree( + &mut self, + tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { let mut entities = Vec::new(); self.walk_tree(&tree.root_node(), source, file_path, &mut entities, None); entities @@ -657,6 +671,15 @@ impl LanguageParser for SwiftParser { Some(t) => t, None => return vec![], }; + self.extract_references_from_tree(&tree, source, file_path) + } + + fn extract_references_from_tree( + &mut self, + tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { let mut refs = Vec::new(); self.walk_tree_for_calls(&tree.root_node(), source, file_path, &mut refs); refs diff --git a/atomic-semantic/src/parsers/typescript.rs b/atomic-semantic/src/parsers/typescript.rs index b78eac90..1013ffa5 100644 --- a/atomic-semantic/src/parsers/typescript.rs +++ b/atomic-semantic/src/parsers/typescript.rs @@ -38,6 +38,27 @@ impl TypeScriptParser { } impl LanguageParser for TypeScriptParser { + fn extract_references_from_tree( + &mut self, + tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { + self.extractor + .extract_references_from_tree(tree, source, file_path) + } + fn extract_from_tree( + &mut self, + tree: &tree_sitter::Tree, + source: &str, + file_path: &str, + ) -> Vec { + self.extractor.extract_from_tree(tree, source, file_path) + } + fn parse_tree(&mut self, source: &str) -> Option { + self.extractor.parse_tree(source) + } + fn language(&self) -> Language { self.language } diff --git a/atomic-semantic/src/relationships.rs b/atomic-semantic/src/relationships.rs new file mode 100644 index 00000000..b0a8a81e --- /dev/null +++ b/atomic-semantic/src/relationships.rs @@ -0,0 +1,679 @@ +//! Scoped source relationships shared by callers, review and other consumers. +//! A symbol spelling alone is never sufficient evidence of a binding. + +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::path::{Component, Path, PathBuf}; + +use crate::source::{CallSite, SourceAnalysis, Symbol}; +use crate::Language; + +#[derive(Clone, Debug)] +pub struct BoundCall<'a> { + pub call: &'a CallSite, + pub symbol: &'a Symbol, + pub present: bool, + pub accessible: bool, + pub expected_min: usize, + pub expected_max: Option, + pub reason: String, + pub configuration_dependent: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct Placement { + root: String, + module: Vec, +} + +struct ModuleAccess { + public: Option, + conditional: bool, +} + +pub struct SourceGraph { + pub files: BTreeMap, + pub symbols: BTreeMap, + pub paths: BTreeSet, + pub ambiguous: BTreeSet, + placements: BTreeMap>, + names: BTreeMap<(String, Vec, String), BTreeSet>, + modules: BTreeMap<(String, Vec), ModuleAccess>, + complete: bool, +} + +pub fn module_candidates(file: &str, scope: &[String]) -> Vec { + let path = Path::new(file); + let mut base = path.parent().unwrap_or_else(|| Path::new("")).to_path_buf(); + if !matches!( + path.file_name().and_then(|name| name.to_str()), + Some("lib.rs" | "main.rs" | "mod.rs") + ) { + base.push(path.file_stem().unwrap_or_default()); + } + for name in scope { + base.push(name); + } + vec![ + base.with_extension("rs").to_string_lossy().into_owned(), + base.join("mod.rs").to_string_lossy().into_owned(), + ] +} + +/// Standard explicit relative script import candidates. Full source inventory is +/// consulted even when only matching files are parsed, preserving ambiguity. +pub fn script_candidates(importer: &str, module: &str, paths: &BTreeSet) -> Vec { + let script = |path: &str| { + matches!( + Path::new(path) + .extension() + .and_then(|extension| extension.to_str()), + Some("ts" | "tsx" | "mts" | "cts" | "js" | "jsx" | "mjs" | "cjs") + ) + }; + if !script(importer) || !module.starts_with('.') { + return vec![]; + } + let Some(requested) = Path::new(importer) + .parent() + .and_then(|base| normalize(base.join(module))) + else { + return vec![]; + }; + paths + .iter() + .filter(|target| { + if !script(target) { + return false; + } + let target = Path::new(target); + let stem = target.with_extension(""); + target == requested || stem == requested || stem == requested.join("index") + }) + .cloned() + .collect() +} + +/// Declaration/import context needed to interpret a selected source file. +/// This returns paths only; repository adapters own recorded-byte retrieval. +pub fn context_paths(file: &SourceAnalysis, paths: &BTreeSet) -> BTreeSet { + let mut result = BTreeSet::new(); + if file.language == Language::Rust { + let mut ancestor = Path::new(&file.path).parent(); + while let Some(directory) = ancestor { + for candidate in [ + directory.join("lib.rs"), + directory.join("main.rs"), + directory.join("mod.rs"), + directory.with_extension("rs"), + ] { + let candidate = candidate.to_string_lossy().into_owned(); + if paths.contains(&candidate) { + result.insert(candidate); + } + } + ancestor = directory.parent().filter(|parent| *parent != directory); + } + } + for import in &file.imports { + if let Some(module) = &import.script_module { + result.extend(script_candidates(&file.path, module, paths)); + continue; + } + if file.language != Language::Rust { + continue; + } + let mut base = Path::new(&file.path) + .parent() + .unwrap_or_else(|| Path::new("")) + .to_path_buf(); + if !matches!( + Path::new(&file.path) + .file_name() + .and_then(|name| name.to_str()), + Some("lib.rs" | "main.rs" | "mod.rs") + ) { + base.push(Path::new(&file.path).file_stem().unwrap_or_default()); + } + for part in &import.scope { + base.push(part); + } + let mut target = import.target.as_slice(); + match target.first().map(String::as_str) { + Some("crate") => { + let mut root = PathBuf::new(); + for component in Path::new(&file.path).components() { + root.push(component.as_os_str()); + if component.as_os_str() == "src" { + break; + } + } + base = root; + target = &target[1..]; + } + Some("self") => target = &target[1..], + Some("super") => { + while target.first().is_some_and(|part| part == "super") { + base.pop(); + target = &target[1..]; + } + } + _ => continue, + } + for end in 1..=target.len() { + let mut module = base.clone(); + for part in &target[..end] { + module.push(part); + } + for candidate in [module.with_extension("rs"), module.join("mod.rs")] { + let candidate = candidate.to_string_lossy().into_owned(); + if paths.contains(&candidate) { + result.insert(candidate); + } + } + } + } + result.remove(&file.path); + result +} + +fn normalize(path: PathBuf) -> Option { + let mut result = PathBuf::new(); + for part in path.components() { + match part { + Component::Normal(name) => result.push(name), + Component::ParentDir if !result.pop() => return None, + Component::ParentDir | Component::CurDir => {} + _ => return None, + } + } + Some(result) +} + +impl SourceGraph { + /// Build from selected semantic facts and the full visible path inventory. + /// `complete` describes that inventory, not whether every file was parsed. + pub fn new( + files: Vec, + paths: impl IntoIterator, + complete: bool, + ) -> Self { + let mut graph = Self { + files: files + .into_iter() + .map(|file| (file.path.clone(), file)) + .collect(), + symbols: BTreeMap::new(), + paths: paths.into_iter().collect(), + ambiguous: BTreeSet::new(), + placements: BTreeMap::new(), + names: BTreeMap::new(), + modules: BTreeMap::new(), + complete, + }; + let mut queue = VecDeque::new(); + for (path, file) in &graph.files { + if file.language == Language::Rust + && matches!( + Path::new(path).file_name().and_then(|name| name.to_str()), + Some("lib.rs" | "main.rs") + ) + { + queue.push_back(( + path.clone(), + Placement { + root: path.clone(), + module: vec![], + }, + )); + } + } + while let Some((path, placement)) = queue.pop_front() { + if !graph + .placements + .entry(path.clone()) + .or_default() + .insert(placement.clone()) + { + continue; + } + for module in &graph.files[&path].modules { + let mut namespace = placement.module.clone(); + namespace.extend(module.scope.clone()); + let known = module.visibility.as_deref().is_none_or(|visibility| { + matches!( + visibility, + "pub" | "pub(crate)" | "pub(self)" | "pub(super)" + ) + }); + let public = known.then_some(module.public); + graph + .modules + .entry((placement.root.clone(), namespace.clone())) + .and_modify(|access| { + if access.public != public { + access.public = None; + } + access.conditional |= module.conditional; + }) + .or_insert(ModuleAccess { + public, + conditional: module.conditional, + }); + if module.external { + let targets: Vec<_> = module_candidates(&path, &module.scope) + .into_iter() + .filter(|path| graph.paths.contains(path)) + .collect(); + if targets.len() == 1 && graph.files.contains_key(&targets[0]) { + queue.push_back(( + targets[0].clone(), + Placement { + root: placement.root.clone(), + module: namespace, + }, + )); + } + } + } + } + for (path, file) in &graph.files { + for symbol in &file.symbols { + if graph + .symbols + .insert(symbol.id.clone(), symbol.clone()) + .is_some() + { + graph.ambiguous.insert(symbol.id.clone()); + } + for placement in graph.placements.get(path).into_iter().flatten() { + let mut namespace = placement.module.clone(); + namespace.extend(symbol.scope.clone()); + graph + .names + .entry(( + placement.root.clone(), + namespace, + symbol.entity.name.clone(), + )) + .or_default() + .insert(symbol.id.clone()); + } + } + } + for id in &graph.ambiguous { + graph.symbols.remove(id); + } + graph + } + + fn symbol<'a>(&'a self, id: &str, before: Option<&'a Self>) -> Option<&'a Symbol> { + if self.ambiguous.contains(id) { + return None; + } + let current = self.symbols.get(id); + let symbol = current.or_else(|| before.and_then(|graph| graph.symbols.get(id)))?; + if let Some(file) = self.files.get(&symbol.location.path) { + if file + .globals + .get(&symbol.scope) + .is_some_and(|names| names.contains(&symbol.entity.name)) + { + return None; + } + } else if self.paths.contains(&symbol.location.path) { + return None; + } + Some(symbol) + } + + fn local( + &self, + file: &SourceAnalysis, + caller: &Symbol, + call: &CallSite, + before: Option<&Self>, + ) -> Option { + let name = call.target.first()?; + let mut scope = caller.scope.clone(); + scope.push(caller.entity.name.clone()); + loop { + let id = format!( + "{}#{}", + file.path, + scope + .iter() + .chain(std::iter::once(name)) + .cloned() + .collect::>() + .join("::") + ); + if self.ambiguous.contains(&id) { + return None; + } + if let Some(symbol) = self.symbol(&id, before).filter(|symbol| { + symbol.owner.is_none() && symbol.entity.kind != crate::EntityKind::Method + }) { + if call.start_byte >= symbol.lexical_range.0 + && call.start_byte <= symbol.lexical_range.1 + { + return Some(id); + } + } + if scope.len() <= caller.module_scope.len() { + break; + } + scope.pop(); + } + None + } + + fn resolve( + &self, + file: &SourceAnalysis, + call: &CallSite, + before: Option<&Self>, + check_access: bool, + ) -> Option<(String, String)> { + let caller = self.symbol(&call.caller, None)?; + if !matches!( + file.language, + Language::Rust | Language::TypeScript | Language::Tsx + ) && (call.receiver.is_some() || caller.owner.is_some()) + { + return None; + } + let head = call.target.first()?; + // Known lexical receiver, not a global lookup for a common method name. + if let Some(receiver) = &call.receiver { + let owner = if matches!(receiver.as_str(), "self" | "this") { + caller.owner.as_ref() + } else { + caller.parameter_types.get(receiver) + }; + if let Some(owner) = owner { + let name = call.target.last()?; + let candidates: Vec<_> = self + .symbols + .values() + .filter(|symbol| { + symbol.location.path == file.path + && symbol.owner.as_ref() == Some(owner) + && symbol.entity.name == *name + && symbol.module_scope == caller.module_scope + }) + .collect(); + if candidates.len() == 1 { + if check_access + && candidates[0].member_private + && caller.owner != candidates[0].owner + { + return None; + } + return Some(( + candidates[0].id.clone(), + "AST lexical/declared receiver type and unique owned declaration".into(), + )); + } + return None; + } + } + if caller.shadows.contains(head) + || file + .globals + .get(&call.scope) + .is_some_and(|names| names.contains(head)) + { + return None; + } + let mut lexical = caller.scope.clone(); + lexical.push(caller.entity.name.clone()); + let imports = loop { + let imports: Vec<_> = file + .imports + .iter() + .filter(|import| { + import.scope == lexical + && import.local == *head + && call.start_byte >= import.lexical_range.0 + && call.start_byte <= import.lexical_range.1 + }) + .collect(); + if !imports.is_empty() || lexical.len() <= caller.module_scope.len() { + break imports; + } + lexical.pop(); + }; + if imports.len() > 1 { + return None; + } + if file.language != Language::Rust { + if let Some(import) = imports.first() { + if !self.complete { + return None; + } + let mut paths = self.paths.clone(); + if let Some(before) = before { + paths.extend(before.paths.iter().cloned()); + } + let targets = + script_candidates(&file.path, import.script_module.as_deref()?, &paths); + if targets.len() != 1 { + return None; + } + let name = if import.namespace && call.target.len() == 2 { + call.target[1].clone() + } else if !import.namespace && call.target.len() == 1 { + import.target.first()?.clone() + } else { + return None; + }; + let id = format!("{}#{name}", targets[0]); + let symbol = self.symbol(&id, before)?; + if !symbol.public + && (!check_access && !self.files.get(&symbol.location.path)?.exports_complete) + { + return None; + } + return (symbol.public || !check_access).then_some(( + id, + "AST explicit relative import and exported declaration".into(), + )); + } + if call.target.len() == 1 { + return self.local(file, caller, call, before).map(|id| { + ( + id, + "AST lexical declaration and scope, no shadow binding".into(), + ) + }); + } + return None; + } + if imports.is_empty() && call.target.len() == 1 { + if let Some(id) = self.local(file, caller, call, before) { + return Some(( + id, + "AST lexical declaration and scope, no shadow binding".into(), + )); + } + } + // Explicit associated functions in the same file use retained owner context. + if imports.is_empty() && call.receiver.is_none() && call.target.len() == 2 { + let owner = if head == "Self" { + caller.owner.as_ref()? + } else { + head + }; + let matches: Vec<_> = self + .symbols + .values() + .filter(|symbol| { + symbol.location.path == file.path + && symbol.module_scope == caller.module_scope + && symbol.owner.as_ref() == Some(owner) + && symbol.entity.name == call.target[1] + }) + .collect(); + if matches.len() == 1 { + return Some(( + matches[0].id.clone(), + "AST explicit associated type and unique owned declaration".into(), + )); + } + } + if !self.complete { + return None; + } + let placements: BTreeSet<_> = self + .placements + .get(&file.path) + .into_iter() + .flatten() + .chain( + before + .into_iter() + .flat_map(|graph| graph.placements.get(&file.path).into_iter().flatten()), + ) + .cloned() + .collect(); + if placements.len() != 1 { + return None; + } + let placement = placements.iter().next()?; + let mut namespace = placement.module.clone(); + namespace.extend(caller.module_scope.clone()); + let mut target = if let Some(import) = imports.first() { + let mut target = import.target.clone(); + target.extend(call.target.iter().skip(1).cloned()); + target + } else { + call.target.clone() + }; + let mut module = namespace.clone(); + match target.first()?.as_str() { + "crate" => { + module.clear(); + target.remove(0); + } + "self" => { + target.remove(0); + } + "super" => { + while target.first().is_some_and(|part| part == "super") { + module.pop()?; + target.remove(0); + } + } + _ if !imports.is_empty() => return None, + _ => {} + } + let name = target.pop()?; + module.extend(target); + let key = (placement.root.clone(), module.clone(), name); + let ids: BTreeSet<_> = self + .names + .get(&key) + .into_iter() + .flatten() + .chain( + before + .into_iter() + .flat_map(|graph| graph.names.get(&key).into_iter().flatten()) + .filter(|id| !self.symbols.contains_key(*id)), + ) + .cloned() + .collect(); + if ids.len() != 1 { + return None; + } + let id = ids.into_iter().next()?; + let symbol = self.symbol(&id, before)?; + let region = if symbol.parent_visible { + &module[..module.len().saturating_sub(1)] + } else { + module.as_slice() + }; + if symbol.restricted || (check_access && !symbol.public && !namespace.starts_with(region)) { + return None; + } + for depth in 1..=module.len() { + let key = (placement.root.clone(), module[..depth].to_vec()); + let access = self.modules.get(&key).or_else(|| { + if !self.symbols.contains_key(&id) { + before.and_then(|graph| graph.modules.get(&key)) + } else { + None + } + })?; + let public = access.public?; + if check_access && !public && !namespace.starts_with(&module[..depth - 1]) { + return None; + } + } + Some(( + id, + "AST explicit Rust import/module chain and declared access".into(), + )) + } + + /// Resolve retained lexical/import/owner evidence. A prior graph preserves + /// references to removed declarations; presence and access remain separate. + pub fn bind_calls<'a>(&'a self, before: Option<&'a Self>) -> Vec> { + let mut result = Vec::new(); + for file in self.files.values() { + for call in &file.calls { + let strict = self.resolve(file, call, before, true); + let accessible = strict.is_some(); + if let Some((id, reason)) = + strict.or_else(|| self.resolve(file, call, before, false)) + { + let symbol = self.symbol(&id, before).expect("resolved symbol"); + let explicit_receiver = usize::from( + file.language == Language::Rust + && symbol.receiver_parameter + && call.receiver.is_none(), + ); + result.push(BoundCall { + call, + symbol, + present: self.symbols.contains_key(&id), + accessible, + expected_min: symbol.min + explicit_receiver, + expected_max: symbol.max.map(|max| max + explicit_receiver), + reason, + configuration_dependent: symbol.conditional + || self.conditional_path(&call.location.path) + || if self.symbols.contains_key(&id) { + self.conditional_path(&symbol.location.path) + } else { + before.is_some_and(|before| { + before.conditional_path(&symbol.location.path) + }) + } + || self.symbols.get(&call.caller).is_some_and(|symbol| { + symbol.conditional || symbol.expansion_dependent + }), + }); + } + } + } + result.sort_by(|a, b| { + (&a.call.location, &a.symbol.id).cmp(&(&b.call.location, &b.symbol.id)) + }); + result + } + + fn conditional_path(&self, path: &str) -> bool { + self.placements + .get(path) + .into_iter() + .flatten() + .any(|placement| { + (1..=placement.module.len()).any(|depth| { + self.modules + .get(&(placement.root.clone(), placement.module[..depth].to_vec())) + .is_some_and(|access| access.conditional) + }) + }) + } +} diff --git a/atomic-semantic/src/source.rs b/atomic-semantic/src/source.rs new file mode 100644 index 00000000..12e53064 --- /dev/null +++ b/atomic-semantic/src/source.rs @@ -0,0 +1,919 @@ +//! Context retained from the registered grammars for shared code intelligence. +//! Entity extraction remains owned by the existing language parsers; this module +//! annotates those entities and call nodes instead of reducing calls to a name. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; +use tree_sitter::{Node, Tree}; + +use crate::{Entity, EntityKind, Language}; + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct SourceSpan { + pub path: String, + pub start_line: u32, + pub end_line: u32, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Symbol { + pub id: String, + pub entity: Entity, + pub scope: Vec, + pub module_scope: Vec, + pub owner: Option, + pub location: SourceSpan, + pub signature: Vec, + pub tokens: Vec, + pub min: usize, + pub max: Option, + pub arity_known: bool, + pub receiver_parameter: bool, + pub public: bool, + pub restricted: bool, + pub parent_visible: bool, + pub conditional: bool, + pub expansion_dependent: bool, + pub member_private: bool, + pub shadows: BTreeSet, + pub parameter_types: BTreeMap, + pub lexical_range: (usize, usize), +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct CallSite { + pub caller: String, + pub scope: Vec, + /// Qualified AST spelling, never just the final method/function name. + pub expression: String, + pub target: Vec, + pub receiver: Option, + pub arguments: Option, + pub location: SourceSpan, + pub tokens: Vec, + pub start_byte: usize, + pub column: u32, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct ImportBinding { + pub scope: Vec, + pub local: String, + pub target: Vec, + pub script_module: Option, + pub namespace: bool, + pub lexical_range: (usize, usize), +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct ModuleDeclaration { + pub scope: Vec, + pub external: bool, + pub public: bool, + pub visibility: Option, + pub conditional: bool, +} + +#[derive(Clone, Debug)] +pub struct SourceAnalysis { + pub path: String, + pub language: Language, + pub entities: Vec, + pub symbols: Vec, + pub calls: Vec, + pub imports: Vec, + pub modules: Vec, + pub globals: BTreeMap, BTreeSet>, + pub tokens: Vec, + pub outside_tokens: Vec, + pub exports_complete: bool, +} + +/// A selected source set and the complete path inventory it was selected from. +/// Completeness concerns selection/availability, not compiler/runtime proof. +#[derive(Clone, Debug, Default)] +pub struct SourceSet { + pub files: Vec, + pub paths: Vec, + pub gaps: Vec, + pub complete: bool, + pub paths_complete: bool, + pub searched_files: usize, +} + +pub(crate) fn children(node: Node<'_>) -> Vec> { + let mut cursor = node.walk(); + node.named_children(&mut cursor).collect() +} + +fn text<'a>(node: Node<'_>, source: &'a str) -> &'a str { + &source[node.byte_range()] +} + +pub(crate) fn qualified_path(value: &str, separator: &str) -> Option> { + let parts: Vec<_> = value + .trim() + .trim_start_matches("::") + .split(separator) + .map(str::trim) + .collect(); + parts + .iter() + .all(|part| { + !part.is_empty() + && part + .chars() + .all(|ch| ch.is_alphanumeric() || ch == '_' || ch == '#') + }) + .then(|| parts.into_iter().map(str::to_owned).collect()) +} + +fn callable(node: Node<'_>) -> bool { + matches!( + node.kind(), + "function_item" + | "function_declaration" + | "function_definition" + | "method_definition" + | "method_declaration" + | "constructor_declaration" + | "init_declaration" + ) +} + +fn enclosing_callable(mut node: Node<'_>) -> Option> { + while let Some(parent) = node.parent() { + if matches!( + parent.kind(), + "closure_expression" + | "arrow_function" + | "lambda_expression" + | "lambda" + | "lambda_literal" + ) { + return None; + } + if callable(parent) { + return Some(parent); + } + node = parent; + } + None +} + +fn lexical_container(mut node: Node<'_>) -> Node<'_> { + while let Some(parent) = node.parent() { + if matches!( + parent.kind(), + "block" + | "statement_block" + | "source_file" + | "program" + | "declaration_list" + | "class_body" + ) { + return parent; + } + node = parent; + } + node +} + +fn parameters(mut node: Node<'_>) -> Option> { + for _ in 0..16 { + if let Some(parameters) = node.child_by_field_name("parameters") { + return Some(parameters); + } + node = node.child_by_field_name("declarator")?; + } + None +} + +fn owner(node: Node<'_>, source: &str) -> Option { + match node.kind() { + "impl_item" => node + .child_by_field_name("type") + .map(|node| nominal(text(node, source))), + "class_declaration" + | "class_definition" + | "class_specifier" + | "struct_specifier" + | "trait_item" + | "interface_declaration" => node + .child_by_field_name("name") + .map(|node| text(node, source).into()), + _ => None, + } +} + +fn nominal(value: &str) -> String { + value + .trim() + .trim_start_matches('&') + .trim_start_matches("mut ") + .split('<') + .next() + .unwrap_or(value) + .trim() + .into() +} + +fn scope(mut node: Node<'_>, source: &str) -> (Vec, Option) { + let (mut parts, mut receiver) = (Vec::new(), None); + let mut nested_function = false; + while let Some(parent) = node.parent() { + if let Some(name) = owner(parent, source) { + if receiver.is_none() && !nested_function { + receiver = Some(name.clone()); + } + parts.push(name); + } else if callable(parent) + || matches!( + parent.kind(), + "mod_item" | "namespace_definition" | "internal_module" + ) + { + if let Some(name) = parent.child_by_field_name("name") { + parts.push(text(name, source).into()); + } + if callable(parent) { + nested_function = true; + } + } + node = parent; + } + parts.reverse(); + (parts, receiver) +} + +fn module_scope(mut node: Node<'_>, source: &str) -> Vec { + let mut parts = Vec::new(); + while let Some(parent) = node.parent() { + if matches!( + parent.kind(), + "mod_item" | "namespace_definition" | "internal_module" + ) { + if let Some(name) = parent.child_by_field_name("name") { + parts.push(text(name, source).into()); + } + } + node = parent; + } + parts.reverse(); + parts +} + +fn span(node: Node<'_>, path: &str) -> SourceSpan { + SourceSpan { + path: path.into(), + start_line: node.start_position().row as u32 + 1, + end_line: (node.end_position().row + + usize::from( + node.end_position().column > 0 + || node.end_position().row == node.start_position().row, + )) as u32, + } +} + +fn tokens( + root: Node<'_>, + source: &str, + skip_body: Option, + skip_functions: bool, +) -> Vec { + let mut result = Vec::new(); + let mut stack = vec![root]; + while let Some(node) = stack.pop() { + if node.kind().contains("comment") + || Some(node.id()) == skip_body + || (skip_functions && callable(node)) + { + continue; + } + if node.child_count() == 0 { + if !text(node, source).trim().is_empty() { + result.push(text(node, source).into()); + } + } else { + let mut cursor = node.walk(); + stack.extend( + node.children(&mut cursor) + .collect::>() + .into_iter() + .rev(), + ); + } + } + result +} + +fn binding_names(root: Node<'_>, source: &str, names: &mut BTreeSet) { + let mut stack = vec![root]; + while let Some(node) = stack.pop() { + if matches!( + node.kind(), + "identifier" | "shorthand_property_identifier_pattern" + ) { + names.insert(text(node, source).into()); + } else { + stack.extend(children(node)); + } + } +} + +fn conditional(mut node: Node<'_>, source: &str) -> bool { + loop { + let mut previous = node.prev_named_sibling(); + while let Some(attribute) = previous.filter(|node| node.kind() == "attribute_item") { + if text(attribute, source).contains("cfg") { + return true; + } + previous = attribute.prev_named_sibling(); + } + let Some(parent) = node.parent() else { + return false; + }; + node = parent; + } +} + +fn rust_import( + node: Node<'_>, + source: &str, + scope: &[String], + prefix: &[String], + imports: &mut Vec, +) { + match node.kind() { + "use_list" => { + for child in children(node) { + rust_import(child, source, scope, prefix, imports); + } + } + "scoped_use_list" => { + let Some(qualified) = node + .child_by_field_name("path") + .and_then(|node| qualified_path(text(node, source), "::")) + else { + return; + }; + let mut prefix = prefix.to_vec(); + prefix.extend(qualified); + for list in children(node) + .into_iter() + .filter(|node| node.kind() == "use_list") + { + rust_import(list, source, scope, &prefix, imports); + } + } + "use_wildcard" => {} + _ => { + let argument = node.child_by_field_name("path").unwrap_or(node); + let Some(target) = qualified_path(text(argument, source), "::") else { + return; + }; + let mut full = prefix.to_vec(); + full.extend(target); + if full.last().is_some_and(|name| name == "self") { + full.pop(); + } + if let Some(local) = node + .child_by_field_name("alias") + .map(|node| text(node, source).to_owned()) + .or_else(|| full.last().cloned()) + { + let lexical = lexical_container(node); + imports.push(ImportBinding { + scope: scope.to_vec(), + local, + target: full, + script_module: None, + namespace: false, + lexical_range: (lexical.start_byte(), lexical.end_byte()), + }); + } + } + } +} + +impl SourceAnalysis { + pub(crate) fn from_tree( + path: &str, + source: &str, + language: Language, + tree: &Tree, + extract: impl FnOnce() -> Vec, + ) -> Result { + if tree.root_node().has_error() { + return Err("Source has recovered/missing syntax; semantic facts unavailable".into()); + } + let mut nodes = Vec::new(); + let mut stack = vec![(tree.root_node(), 0)]; + while let Some((node, depth)) = stack.pop() { + if nodes.len() >= 100_000 || depth > 256 { + return Err("Semantic source analysis budget exceeded".into()); + } + nodes.push(node); + stack.extend( + children(node) + .into_iter() + .rev() + .map(|node| (node, depth + 1)), + ); + } + let mut result = Self { + path: path.into(), + language, + entities: extract(), + symbols: vec![], + calls: vec![], + imports: vec![], + modules: vec![], + globals: BTreeMap::new(), + tokens: tokens(tree.root_node(), source, None, false), + outside_tokens: tokens(tree.root_node(), source, None, true), + exports_complete: true, + }; + let mut used = BTreeSet::new(); + let mut declarations = BTreeMap::<(u32, String), Vec>>::new(); + let mut declarations_by_line = BTreeMap::>>::new(); + for node in nodes.iter().filter(|node| callable(**node)) { + declarations_by_line + .entry(node.start_position().row as u32 + 1) + .or_default() + .push(*node); + if let Some(name) = node.child_by_field_name("name") { + declarations + .entry(( + node.start_position().row as u32 + 1, + text(name, source).into(), + )) + .or_default() + .push(*node); + } + } + let mut symbol_nodes = BTreeMap::new(); + let file_conditional = children(tree.root_node()).iter().any(|node| { + node.kind() == "inner_attribute_item" && text(*node, source).contains("cfg") + }); + for entity in result + .entities + .iter() + .filter(|entity| matches!(entity.kind, EntityKind::Function | EntityKind::Method)) + { + let Some(&node) = declarations + .get(&(entity.line, entity.name.clone())) + .and_then(|nodes| nodes.iter().find(|node| !used.contains(&node.id()))) + .or_else(|| { + declarations_by_line.get(&entity.line).and_then(|nodes| { + nodes.iter().find(|node| { + !used.contains(&node.id()) + && node.end_position().row as u32 + 1 == entity.end_line + }) + }) + }) + else { + continue; + }; + used.insert(node.id()); + let (scope, owner) = scope(node, source); + let name = entity.name.clone(); + let id = format!( + "{path}#{}", + scope + .iter() + .chain(std::iter::once(&name)) + .cloned() + .collect::>() + .join("::") + ); + let body = node.child_by_field_name("body"); + let parameters = parameters(node); + let (mut min, mut max) = (0, Some(0)); + let mut arity_known = parameters.is_some() + && matches!( + language, + Language::Rust | Language::TypeScript | Language::Tsx + ); + if node.kind() == "method_definition" { + let mut cursor = node.walk(); + if node + .children(&mut cursor) + .any(|child| matches!(child.kind(), "get" | "set")) + { + // `reader.value(args)` can call the value returned by a + // getter, not pass those arguments to the accessor itself. + arity_known = false; + } + } + let mut parameters_conditional = false; + let mut receiver_parameter = node.kind() == "method_definition" + && !tokens(node, source, body.map(|body| body.id()), false) + .iter() + .any(|token| token == "static"); + let (mut shadows, mut parameter_types) = (BTreeSet::new(), BTreeMap::new()); + for parameter in parameters + .map(children) + .unwrap_or_else(|| { + children(node) + .into_iter() + .filter(|node| node.kind() == "parameter") + .collect() + }) + .into_iter() + .filter(|node| !node.kind().contains("comment")) + { + if parameter.kind() == "attribute_item" + || children(parameter) + .iter() + .any(|node| node.kind() == "attribute_item") + { + arity_known = false; + parameters_conditional = true; + } + if parameter.kind() == "self_parameter" + || parameter + .child_by_field_name("pattern") + .is_some_and(|node| { + text(node, source) == "self" + || (language != Language::Rust && text(node, source) == "this") + }) + { + receiver_parameter = true; + continue; + } + let mut patterns = Vec::new(); + let mut parameter_cursor = parameter.walk(); + patterns.extend(parameter.children_by_field_name("name", &mut parameter_cursor)); + if patterns.is_empty() { + patterns.extend( + parameter + .child_by_field_name("pattern") + .or_else(|| parameter.child_by_field_name("declarator")) + .or_else(|| (parameter.kind() == "identifier").then_some(parameter)) + .or_else(|| { + children(parameter).into_iter().find(|node| { + node.kind() == "identifier" + && parameter + .child_by_field_name("type") + .is_none_or(|kind| kind.id() != node.id()) + }) + }), + ); + } + for pattern in patterns { + binding_names(pattern, source, &mut shadows); + if let Some(kind) = parameter.child_by_field_name("type") { + parameter_types.insert( + text(pattern, source).into(), + nominal(text(kind, source).trim_start_matches(':').trim()), + ); + } + } + let spelling = tokens(parameter, source, None, false); + if spelling.iter().any(|part| part == "...") { + max = None; + } else { + if let Some(max) = &mut max { + *max += 1; + } + if parameter.kind() != "optional_parameter" + && parameter.child_by_field_name("value").is_none() + { + min = max.unwrap_or(min + 1); + } + } + } + let begin = nodes.partition_point(|item| item.start_byte() < node.start_byte()); + for item in nodes[begin..] + .iter() + .take_while(|item| item.start_byte() < node.end_byte()) + .filter(|item| { + enclosing_callable(**item).is_some_and(|owner| owner.id() == node.id()) + }) + { + if matches!( + item.kind(), + "let_declaration" + | "variable_declarator" + | "assignment" + | "augmented_assignment" + | "assignment_expression" + | "augmented_assignment_expression" + | "for_expression" + | "for_in_statement" + | "catch_clause" + | "let_condition" + ) { + if let Some(pattern) = item + .child_by_field_name("pattern") + .or_else(|| item.child_by_field_name("name")) + .or_else(|| item.child_by_field_name("left")) + .or_else(|| item.child_by_field_name("parameter")) + { + binding_names(pattern, source, &mut shadows); + } + } + } + let visibility = children(node) + .into_iter() + .find(|node| node.kind() == "visibility_modifier") + .map(|node| text(node, source)); + let exported = node.parent().is_some_and(|node| { + node.kind() == "export_statement" + && !tokens(node, source, None, false) + .iter() + .any(|token| token == "default") + }); + let public = if language == Language::Rust { + matches!(visibility, Some("pub" | "pub(crate)")) + } else { + exported || entity.exported + }; + let lexical = lexical_container(node); + let expansion_dependent = nodes[begin..] + .iter() + .take_while(|item| item.start_byte() < node.end_byte()) + .any(|item| item.kind() == "macro_invocation"); + let member_private = name.starts_with('#') + || children(node).iter().any(|node| { + node.kind() == "accessibility_modifier" && text(*node, source) == "private" + }); + symbol_nodes.insert(node.id(), result.symbols.len()); + result.symbols.push(Symbol { + id, + entity: entity.clone(), + scope, + module_scope: module_scope(node, source), + owner, + location: span(node, path), + signature: tokens(node, source, body.map(|body| body.id()), false), + tokens: tokens(node, source, None, false), + min, + max, + arity_known, + receiver_parameter, + public, + restricted: visibility.is_some_and(|value| { + !matches!(value, "pub" | "pub(crate)" | "pub(self)" | "pub(super)") + }), + parent_visible: visibility == Some("pub(super)"), + conditional: conditional(node, source) + || file_conditional + || parameters_conditional, + expansion_dependent, + member_private, + shadows, + parameter_types, + lexical_range: (lexical.start_byte(), lexical.end_byte()), + }); + } + let mut initializers = BTreeMap::new(); + for node in &nodes { + match node.kind() { + "call_expression" | "call" | "method_invocation" => { + let caller_index = if let Some(index) = enclosing_callable(*node) + .and_then(|node| symbol_nodes.get(&node.id())) + .copied() + { + index + } else { + let mut parent = node.parent(); + let mut nested = false; + while let Some(item) = parent { + if callable(item) + || matches!( + item.kind(), + "closure_expression" + | "arrow_function" + | "lambda" + | "lambda_expression" + | "lambda_literal" + ) + { + nested = true; + break; + } + parent = item.parent(); + } + let (scope, owner) = scope(*node, source); + if nested || owner.is_some() { + continue; + } + if let Some(index) = initializers.get(&scope) { + *index + } else { + let id = if scope.is_empty() { + format!("{path}#") + } else { + format!("{path}#{}::", scope.join("::")) + }; + let index = result.symbols.len(); + result.symbols.push(Symbol { + id, + entity: Entity::new( + "", + EntityKind::Module, + path, + 1, + tree.root_node().end_position().row as u32 + 1, + ), + scope: scope.clone(), + module_scope: scope.clone(), + owner: None, + location: span(tree.root_node(), path), + signature: vec![], + tokens: vec![], + min: 0, + max: None, + arity_known: false, + receiver_parameter: false, + public: false, + restricted: false, + parent_visible: false, + conditional: conditional(*node, source) || file_conditional, + expansion_dependent: false, + member_private: false, + shadows: BTreeSet::new(), + parameter_types: BTreeMap::new(), + lexical_range: (0, source.len()), + }); + initializers.insert(scope, index); + index + } + }; + let caller = &result.symbols[caller_index]; + let Some(function) = node + .child_by_field_name("function") + .or_else(|| node.child_by_field_name("name")) + .or_else(|| { + (language == Language::Swift) + .then(|| children(*node).into_iter().next()) + .flatten() + }) + else { + continue; + }; + let function = if function.kind() == "generic_function" { + function.child_by_field_name("function").unwrap_or(function) + } else { + function + }; + let receiver = function + .child_by_field_name("value") + .or_else(|| function.child_by_field_name("object")) + .or_else(|| function.child_by_field_name("operand")) + .or_else(|| function.child_by_field_name("argument")) + .or_else(|| node.child_by_field_name("object")) + .map(|node| text(node, source).to_owned()); + let expression = if node.kind() == "method_invocation" { + receiver + .as_ref() + .map(|receiver| format!("{receiver}.{}", text(function, source))) + .unwrap_or_else(|| text(function, source).into()) + } else { + text(function, source).to_owned() + }; + let target = qualified_path( + &expression, + if receiver.is_some() || expression.contains('.') { + "." + } else { + "::" + }, + ) + .unwrap_or_default(); + let arguments = node.child_by_field_name("arguments").and_then(|arguments| { + let args: Vec<_> = children(arguments) + .into_iter() + .filter(|node| !node.kind().contains("comment")) + .collect(); + (!args.iter().any(|node| node.kind() == "spread_element")) + .then_some(args.len()) + }); + result.calls.push(CallSite { + caller: caller.id.clone(), + scope: caller.scope.clone(), + expression, + target, + receiver, + arguments, + location: span(*node, path), + tokens: tokens(*node, source, None, false), + start_byte: node.start_byte(), + column: node.start_position().column as u32, + }); + } + "use_declaration" => { + if let Some(argument) = node.child_by_field_name("argument") { + rust_import( + argument, + source, + &scope(*node, source).0, + &[], + &mut result.imports, + ); + } + } + "import_statement" => { + let (scope, _) = scope(*node, source); + if tokens(*node, source, None, false) + .iter() + .any(|token| token == "type") + { + continue; + } + let Some(module) = node + .child_by_field_name("source") + .map(|node| text(node, source)) + else { + continue; + }; + if module.len() < 2 || module.contains('\\') { + continue; + } + for item in nodes.iter().filter(|item| { + item.start_byte() >= node.start_byte() && item.end_byte() <= node.end_byte() + }) { + if item.kind() == "import_specifier" { + if let Some(name) = item.child_by_field_name("name") { + result.imports.push(ImportBinding { + scope: scope.clone(), + local: text( + item.child_by_field_name("alias").unwrap_or(name), + source, + ) + .into(), + target: vec![text(name, source).into()], + script_module: Some(module[1..module.len() - 1].into()), + namespace: false, + lexical_range: (0, source.len()), + }); + } + } else if item.kind() == "namespace_import" { + if let Some(name) = children(*item) + .into_iter() + .find(|node| node.kind() == "identifier") + { + result.imports.push(ImportBinding { + scope: scope.clone(), + local: text(name, source).into(), + target: vec![], + script_module: Some(module[1..module.len() - 1].into()), + namespace: true, + lexical_range: (0, source.len()), + }); + } + } + } + } + "mod_item" => { + if let Some(name) = node.child_by_field_name("name") { + let mut module = scope(*node, source).0; + module.push(text(name, source).into()); + let public = children(*node) + .into_iter() + .find(|node| node.kind() == "visibility_modifier") + .is_some_and(|node| matches!(text(node, source), "pub" | "pub(crate)")); + result.modules.push(ModuleDeclaration { + scope: module, + external: node.child_by_field_name("body").is_none(), + public, + visibility: children(*node) + .into_iter() + .find(|node| node.kind() == "visibility_modifier") + .map(|node| text(node, source).into()), + conditional: conditional(*node, source) || file_conditional, + }); + } + } + "variable_declarator" + | "const_item" + | "static_item" + | "function_signature" + | "assignment" + | "augmented_assignment" => { + if let Some(name) = node + .child_by_field_name("name") + .or_else(|| node.child_by_field_name("left")) + { + binding_names( + name, + source, + result.globals.entry(scope(*node, source).0).or_default(), + ); + } + } + "export_statement" if node.child_by_field_name("declaration").is_none() => { + result.exports_complete = false + } + _ => {} + } + } + Ok(result) + } +} + +#[cfg(test)] +mod tests; diff --git a/atomic-semantic/src/source/tests.rs b/atomic-semantic/src/source/tests.rs new file mode 100644 index 00000000..78e1c55c --- /dev/null +++ b/atomic-semantic/src/source/tests.rs @@ -0,0 +1,157 @@ +use crate::{relationships::SourceGraph, ParserRegistry, Reference}; + +#[test] +fn shared_entity_and_reference_apis_keep_qualified_targets_and_owners() { + let source = "struct Reader; impl Reader { fn value(&self, x:i32) {} fn run(&self) { self.value(1); } } fn value(x:i32) {} fn consumer(reader:&Reader) { reader.value(2); value(3); module::value(4); }"; + let mut parser = ParserRegistry::new(); + let analysis = parser.analyze_source("lib.rs", source).unwrap(); + assert_eq!( + serde_json::to_value(&analysis.entities).unwrap(), + serde_json::to_value(parser.extract("lib.rs", source)).unwrap() + ); + let member = analysis + .calls + .iter() + .find(|call| call.expression == "self.value") + .unwrap(); + assert_eq!(member.receiver.as_deref(), Some("self")); + assert_eq!(member.caller, "lib.rs#Reader::run"); + assert!(analysis + .calls + .iter() + .any(|call| call.target == ["module", "value"] && call.receiver.is_none())); + let refs = parser.extract_references("lib.rs", source); + assert!(refs + .iter() + .filter_map(|reference| reference.call.as_ref()) + .any(|context| context.target == "self.value" && context.caller == "lib.rs#Reader::run")); + assert!(refs + .iter() + .filter_map(|reference| reference.call.as_ref()) + .any(|context| context.target == "module::value")); + let graph = SourceGraph::new(vec![analysis], ["lib.rs".into()], true); + let calls = graph.bind_calls(None); + assert_eq!( + calls.len(), + 3, + "unresolved module::value must not match an unrelated free function" + ); + assert_eq!( + calls + .iter() + .filter(|call| call.symbol.id == "lib.rs#Reader::value") + .count(), + 2 + ); + assert_eq!( + calls + .iter() + .filter(|call| call.symbol.id == "lib.rs#value") + .count(), + 1 + ); +} + +#[test] +fn typescript_this_and_declared_receiver_types_do_not_collapse_to_method_names() { + let source = "class Reader { value(x:number) { return x; } run() { return this.value(1); } } function consumer(reader: Reader) { return reader.value(2); } function value(x:number) { return x; }"; + let mut parser = ParserRegistry::new(); + let file = parser.analyze_source("app.ts", source).unwrap(); + let graph = SourceGraph::new(vec![file], ["app.ts".into()], true); + let calls = graph.bind_calls(None); + assert_eq!(calls.len(), 2); + assert!(calls + .iter() + .all(|call| call.symbol.id == "app.ts#Reader::value")); +} + +#[test] +fn normal_attributes_and_macros_retain_semantic_source_facts() { + let mut parser = ParserRegistry::new(); + let source = "#[cfg(test)] mod tests { #[allow(dead_code)] fn work() {} fn consumer() { assert!(true); work(); } }"; + let file = parser.analyze_source("lib.rs", source).unwrap(); + assert_eq!(file.symbols.len(), 2); + let graph = SourceGraph::new(vec![file], ["lib.rs".into()], true); + let calls = graph.bind_calls(None); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0].symbol.id, "lib.rs#tests::work"); + assert!(calls[0].configuration_dependent); +} + +#[test] +fn lexical_block_boundaries_and_shadowed_names_do_not_create_wrong_callers() { + let source = "fn work(x:i32) {} fn consumer() { if true { fn work(x:i32,y:i32) {} work(1,2); } work(1); } fn shadow(work:fn(i32)) { work(1); }"; + let mut parser = ParserRegistry::new(); + let file = parser.analyze_source("lib.rs", source).unwrap(); + let graph = SourceGraph::new(vec![file], ["lib.rs".into()], true); + let calls = graph.bind_calls(None); + assert_eq!(calls.len(), 2); + assert!(calls + .iter() + .any(|call| call.symbol.id == "lib.rs#consumer::work" && call.call.arguments == Some(2))); + assert!(calls + .iter() + .any(|call| call.symbol.id == "lib.rs#work" && call.call.arguments == Some(1))); +} + +#[test] +fn legacy_reference_deserialization_and_optional_call_context_remain_compatible() { + let reference: Reference = serde_json::from_value( + serde_json::json!({"symbol":"work","file":"lib.rs","line":1,"confidence":"high"}), + ) + .unwrap(); + assert!(reference.call.is_none()); + assert!(serde_json::to_value(reference) + .unwrap() + .get("call") + .is_none()); +} + +#[test] +fn top_level_calls_keep_the_module_owner_and_do_not_disappear() { + let mut parser = ParserRegistry::new(); + let file = parser + .analyze_source("app.ts", "function work(x:number) {} work(1);") + .unwrap(); + let graph = SourceGraph::new(vec![file], ["app.ts".into()], true); + let calls = graph.bind_calls(None); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0].call.caller, "app.ts#"); + assert_eq!(calls[0].symbol.id, "app.ts#work"); +} + +#[test] +fn custom_visibility_remains_explicit_context_not_a_guessed_access_failure() { + let source = "mod parent { pub(in crate) mod api { pub fn work() {} } } fn consumer() { crate::parent::api::work(); }"; + let mut parser = ParserRegistry::new(); + let file = parser.analyze_source("lib.rs", source).unwrap(); + assert!(file + .modules + .iter() + .any(|module| module.visibility.as_deref() == Some("pub(in crate)"))); + let graph = SourceGraph::new(vec![file], ["lib.rs".into()], true); + assert!(graph.bind_calls(None).is_empty()); +} + +#[test] +fn existing_language_parameter_bindings_do_not_turn_callbacks_into_global_calls() { + let mut parser = ParserRegistry::new(); + for (path, source) in [ + ( + "app.py", + "def work():\n pass\ndef consumer(work):\n work()\n", + ), + ( + "app.go", + "package p\nfunc work() {}\nfunc consumer(a, work func()) { work() }", + ), + ( + "app.c", + "void work(void) {} void consumer(void (*work)(void)) { work(); }", + ), + ] { + let file = parser.analyze_source(path, source).unwrap(); + let graph = SourceGraph::new(vec![file], [path.into()], true); + assert!(graph.bind_calls(None).is_empty(), "{path}"); + } +} diff --git a/docs/COMPACT-SEMANTIC-CODEC-EXPERIMENT.md b/docs/COMPACT-SEMANTIC-CODEC-EXPERIMENT.md new file mode 100644 index 00000000..e729d500 --- /dev/null +++ b/docs/COMPACT-SEMANTIC-CODEC-EXPERIMENT.md @@ -0,0 +1,152 @@ +# Compact semantic codec experiment + +This is a sizing experiment, **not a production change format**. It does not +rewrite `.change` files or modify Atomic's writer, reader, identity, signatures, +database schema, or server. + +## Reproduce + +```bash +cargo test -p atomic-core --example compact_semantic_codec +cargo run --release -p atomic-core --example compact_semantic_codec -- .atomic/changes 3 > compact-semantic-level3.json +``` + +The first argument can also name one `.change` file. The second is the zstd +compression level (1–19, default 3). JSON goes to stdout; progress and failures +go to stderr. Put result files outside the repository if they should not be +recorded. A failed object is reported explicitly and makes the command exit +nonzero; totals then cover only successful objects. + +The example reads only `.change` files. It never opens redb or a Repository. +For each input it verifies the source object's trailer hash and content-chunk +hashes, decodes the original semantic section, encodes the experimental payload, +and decodes using only that payload and the authored content. Both `FileOps` +equality and byte-for-byte equality with the original expanded postcard semantic +section must hold. + +## Encoding under test + +The codec preserves the complete authored semantic operations; it does not +retokenize content or infer semantic identities from the resulting text. + +- File identity, path, and every trunk-operation variant are retained. +- A control stream retains operation tags, list lengths, and optional fields. +- Separate numeric columns use reversible wrapping-delta/zigzag/varint encoding + for owners, indices, line numbers, byte ranges, and content-reference offsets. +- Token kinds are retained explicitly in a separate column. +- When a semantic token sequence exactly matches an authored fragment, token + bytes reference that content. Consecutive references omit their offset. +- Old/deleted text absent from this change, and fragments not matched by the + experiment's lookup, use a deduplicated literal pool **inside the payload**. + No information is dropped when a content match is unavailable. +- The columns, literal pool, and a hash binding the supplied content are encoded + with postcard and compressed together with zstd. Magic/version and the content + hash are included in the reported size. + +Fragment matching tries the recorded content-range hint, the next content +position, and an exact whole-line lookup. It does not search all content for every +token. Lookup limitations affect compression only, not correctness. Even unusual +or reversed recorded content ranges survive unchanged as metadata; they are not +treated as valid lookup hints. + +## Reading the numbers + +The JSON reports: + +- `original_semantic_bytes`: actual compressed semantic payload bytes on disk. +- `baseline_semantic_bytes`: the original expanded semantic payload recompressed + at the requested level, to distinguish codec savings from compression-level + changes. +- `compact_semantic_bytes`: the entire experimental compressed semantic payload, + including its magic/version and content binding. +- `projected_object_bytes`: original object size minus its original semantic + payload plus the experimental payload. All other original bytes remain counted, + including graph/content sections, dependency/owner context, framing and signature. +- Encode/decode times are single warm-process measurements, not rigorous latency + benchmarks. Encoding includes fragment indexing, serialization and compression; + decoding includes decompression, content hashing and operation reconstruction. + +These are projected object sizes, not valid rewritten objects: changing the hashed +semantic section would require new change identities and signatures. Graph-span +compaction is deliberately not included in the projection. + +## Server-side losslessness boundary + +The decoder needs only the encoded semantic payload and the change's authored +content. Existing dependency and portable-owner declarations remain necessary +for cross-change interpretation; they are not replaced by a database-only lookup +or excluded from projected object sizes. Recovering identical numeric names is not, +by itself, proof that historical objects have complete portable owner declarations. + +This experiment proves exact semantic reconstruction, not a complete new format, +remote push/pull integration, historical blame engine, or authentication scheme +for the experimental envelope. Source hash verification is not Ed25519 signature +verification. A production format would need an authenticated section contract, +resource limits hardened for hostile inputs, and a selective-read directory. + +The prototype decodes a whole semantic section and hashes the supplied content; +it does **not** yet provide per-file/per-range compressed random access. This +explicitly retains losslessness but defers server query-latency optimization. + +Git blobs contain bytes rather than Atomic's semantic/causal information. The +reported compressed-content bytes are a useful local baseline, **not** a measured +Git loose-object or Git-pack comparison. + +## Results + +Local corpus: 23 objects (schema 1/2, no schema-3 span objects), containing 6,470 +file-operation containers, 1,631,730 line operations, and 9,533,568 tokens counted +by the existing `FileOps::token_count` API. All 23 source object hashes and content +chunks verified, and all 23 expanded semantic payloads matched byte-for-byte after +the experimental round-trip. There were no skipped or failed objects. + +At zstd level 3 (the current writer default): + +| Measurement | Original | Experimental | Reduction | +|---|---:|---:|---:| +| Semantic payload bytes | 54,509,352 | 16,722,130 | **69.3%** | +| Whole-object bytes (projected) | 80,243,191 | 42,455,969 | **47.1%** | + +Recompressing the baseline at level 3 exactly reproduced its original compressed +size, so this comparison is not benefiting from a higher compression level. +The largest object projected from 43,277,858 to 22,913,772 bytes, with its semantic +payload reduced from 30,327,896 to 9,963,810 bytes. + +The original content chunks total 11,855,733 compressed bytes. The projected +objects are still **3.58×** that content-only baseline: this first codec is a +substantial reduction, but **not yet close to blob-only size**. Unchanged graph +operations remain counted, as do 16.7 MB of compact semantic metadata/literals. + +One release-process pass measured approximately 634 ms total encode time and +385 ms total decode time over the corpus, excluding original file reading and +baseline recompression. These are observational timings, not latency promises. + +At level 9, the compact semantic payloads total **14,518,607 bytes** and projected +objects total **40,252,446 bytes**: 73.4% less semantic storage and **49.8% less +whole-object storage** than the original files. Recompressing the expanded +baseline at level 9 gives 51,683,824 bytes; relative to that same-level baseline, +the codec saves **71.9%**. The level-9 pass measured approximately 1,102 ms total +encode and 383 ms total decode time. All 23 exact round-trips passed again. + +Synthetic checks at level 3: + +| Fixture | Compressed authored bytes | Current semantics | Compact semantics | +|---|---:|---:|---:| +| 4,096 generated Rust lines with unique variable names | 6,994 | 189,106 | 16,973 | +| One interior edit retaining an absent old-text snapshot | 19 | 85 | 130 | + +The generated-add fixture uses 68,563 semantic bytes with the columnar codec but +without authored-content references, versus 16,973 with references. That isolates +the benefit of sharing authored bytes, rather than attributing everything to +numeric encoding. Synthetic tokenization constructs the fixture only; decoding +never tokenizes. + +The tiny edit **regresses by 45 bytes**. A production design should consider a +versioned raw/compact discriminator and select the smaller complete encoding, +including its discriminator overhead. That adaptive choice is not implemented +or silently included in these measurements. + +No savings are assumed by the tests: an encoding that gets larger is reported as +such. These measurements motivate further work on run encodings, column layout, +literal pooling, and graph-span integration; they do not justify dropping semantic +information to hit a size target. From 03d6e1e5d909c27d3ff7fe2d9a9938d463a80a66 Mon Sep 17 00:00:00 2001 From: Lee Faus Date: Wed, 25 Nov 2026 15:27:00 -0500 Subject: [PATCH 2/4] cleanup command structure --- atomic-canonical/src/lib.rs | 1 + atomic-canonical/src/review_decision.rs | 810 +++++++++ atomic-cli/README.md | 75 +- atomic-cli/skills/review/SKILL.md | 109 +- .../review/references/review-contract.md | 63 +- atomic-cli/src/commands/insert.rs | 4 + atomic-cli/src/commands/review/graph.rs | 4 +- atomic-cli/src/commands/review/html.rs | 36 +- atomic-cli/src/commands/review/incremental.rs | 4 +- atomic-cli/src/commands/review/mod.rs | 36 +- atomic-cli/src/commands/review/publish.rs | 1480 +++-------------- .../commands/review/publish/legacy_cancel.rs | 114 ++ atomic-cli/src/commands/review/scope.rs | 564 ------- atomic-cli/src/commands/review/terminal.rs | 2 +- .../src/commands/review/view_comparison.rs | 30 +- .../review/view_comparison/conformance.rs | 63 +- .../commands/review/view_comparison/impact.rs | 8 +- atomic-cli/src/commands/review/viewer.html | 2 +- atomic-cli/src/commands/review/viewer.js | 54 +- atomic-cli/src/commands/rpc.rs | 18 + atomic-cli/src/main.rs | 2 +- atomic-cli/tests/review_comparison.rs | 18 +- atomic-cli/tests/review_comparison_passes.rs | 18 +- atomic-cli/tests/review_publish_native.rs | 406 +++++ atomic-cli/tests/review_viewer_browser.mjs | 40 +- atomic-repository/src/apply/cross_view.rs | 3 + atomic-repository/src/apply/types.rs | 3 + atomic-repository/src/intent_bridge.rs | 73 + atomic-repository/src/repository/insert.rs | 32 +- atomic-repository/src/repository/mod.rs | 2 + .../src/repository/review_decision.rs | 418 +++++ .../src/repository/review_decision/tests.rs | 300 ++++ atomic-repository/src/repository/sandbox.rs | 16 +- atomic-repository/src/repository/vault.rs | 1 + atomic-repository/tests/native_span_record.rs | 4 +- .../repository_mutation_messages.proto | 11 + libatomic/src/daemon/change_impact.rs | 14 +- libatomic/src/daemon/services.rs | 13 + libatomic/tests/local_service_test.rs | 38 +- libatomic/tests/query_view_service_test.rs | 4 +- 40 files changed, 2831 insertions(+), 2062 deletions(-) create mode 100644 atomic-canonical/src/review_decision.rs create mode 100644 atomic-cli/src/commands/review/publish/legacy_cancel.rs delete mode 100644 atomic-cli/src/commands/review/scope.rs create mode 100644 atomic-cli/tests/review_publish_native.rs create mode 100644 atomic-repository/src/repository/review_decision.rs create mode 100644 atomic-repository/src/repository/review_decision/tests.rs diff --git a/atomic-canonical/src/lib.rs b/atomic-canonical/src/lib.rs index 51df2a56..16379114 100644 --- a/atomic-canonical/src/lib.rs +++ b/atomic-canonical/src/lib.rs @@ -44,6 +44,7 @@ pub mod prov; #[cfg(feature = "dsse-export")] pub mod provenance_export; pub mod render; +pub mod review_decision; pub mod review_finding; pub mod review_graph; pub mod triage_ref; diff --git a/atomic-canonical/src/review_decision.rs b/atomic-canonical/src/review_decision.rs new file mode 100644 index 00000000..2e00f866 --- /dev/null +++ b/atomic-canonical/src/review_decision.rs @@ -0,0 +1,810 @@ +//! A user's attested evaluation of native review evidence, not a clean-code claim. +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +use crate::{node::Proof, review_graph::ReviewPass}; + +pub const SCHEMA: &str = "atomic.review-decision.v1"; +pub const EVALUATION_SCHEMA: &str = "atomic.review-evaluation.v1"; +pub const MAX_BYTES: usize = 256 * 1024 * 1024; + +fn digest(value: &impl Serialize) -> String { + let value = serde_json::to_value(value).expect("review evidence serializes"); + data_encoding::BASE32_NOPAD + .encode(blake3::hash(crate::jcs::canonicalize(&value).as_bytes()).as_bytes()) +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ViewPin { + pub view: String, + pub scope: String, + pub state: String, + pub membership_hash: String, + pub members: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ReviewScope { + pub project: String, + pub source: ViewPin, + pub target: ViewPin, + /// Sorted dependency-complete changes this insertion would add. + pub changes: Vec, + pub intent_scope_hash: String, + pub context_intent_hashes: BTreeMap, +} + +impl ReviewScope { + pub fn hash(&self) -> String { + digest(self) + } + + pub fn validate_report(&self, report: &Value) -> Result<(), String> { + if self.source.view.is_empty() + || self.target.view.is_empty() + || self.source.view == self.target.view + || self.source.scope != "draft" + || self.target.scope != "shared" + { + return Err( + "Native publication requires a draft/source and a distinct shared/target".into(), + ); + } + for pin in [&self.source, &self.target] { + if pin.membership_hash != digest(&pin.members) + || pin.members.iter().collect::>().len() != pin.members.len() + { + return Err("Recorded membership identity is inconsistent".into()); + } + } + for (key, pin) in [ + ("from", &self.source), + ("after", &self.source), + ("to", &self.target), + ("before", &self.target), + ] { + let actual = &report["view_comparison"][key]; + if actual["view"] != pin.view + || actual["state"] != pin.state + || actual["membership_hash"] != pin.membership_hash + { + return Err( + "Report source/target/before/after pins differ from the attested scope".into(), + ); + } + } + let conformance = &report["view_comparison"]["conformance"]; + if report["graph"]["scope"]["project"] != self.project + || report["graph"]["scope"]["view"] != self.source.view + || report["graph"]["scope"]["view_state"] != self.source.state + || conformance["scope"]["view"] != self.source.view + || conformance["scope"]["current_inventory_hash"] != self.intent_scope_hash + { + return Err("Review project or intent-scope pins differ".into()); + } + let contexts: BTreeMap<_, _> = conformance["criteria"] + .as_array() + .ok_or("Conformance criteria unavailable")? + .iter() + .filter_map(|criterion| { + Some(( + criterion["intent"].as_str()?.to_string(), + criterion["current_context"]["source_hash"] + .as_str()? + .to_string(), + )) + }) + .collect(); + if contexts != self.context_intent_hashes { + return Err("Current intent context changed since native review".into()); + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ReviewIssue { + pub id: String, + pub pass: ReviewPass, + pub kind: String, + pub reference: String, + pub summary: String, + pub waivable: bool, + /// Complete evidence references/details, including grouped coverage gaps. + pub evidence: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Disposition { + Ready, + AcceptedDegradation, + NotReady, +} + +impl Disposition { + pub fn as_str(self) -> &'static str { + match self { + Self::Ready => "ready", + Self::AcceptedDegradation => "accepted_degradation", + Self::NotReady => "not_ready", + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AcceptedDegradation { + pub issue: String, + pub rationale: String, + #[serde(default)] + pub evidence: Vec, + #[serde(default)] + pub follow_up: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PassEvaluation { + pub pass: ReviewPass, + pub evaluated: bool, + pub disposition: Disposition, + pub rationale: String, + pub accepted_degradations: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ReviewEvaluation { + pub schema: String, + pub scope_hash: String, + pub report_hash: String, + pub passes: Vec, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ReviewDecision { + pub schema: String, + pub reviewed_at: String, + pub scope: ReviewScope, + pub report_hash: String, + pub report: Value, + pub issues: Vec, + /// Derived from evidence, never changed to ready by accepting degradation. + pub readiness: Disposition, + pub evaluation: ReviewEvaluation, + pub independent_approval: bool, + #[serde(rename = "attributedTo")] + pub attributed_to: String, + pub public_key: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub supersedes: Vec, + #[serde( + rename = "contentHash", + default, + skip_serializing_if = "Option::is_none" + )] + pub content_hash: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub proof: Option, +} + +pub const PASSES: [ReviewPass; 3] = [ + ReviewPass::AntiSlop, + ReviewPass::IntentConformance, + ReviewPass::BlastRadiusRisk, +]; + +/// Remove physical-workspace display fields, not source, findings or evidence. +pub fn normalize_report(mut report: Value) -> Value { + if let Some(source) = report["source"].as_object_mut() { + for key in [ + "repository_root", + "atomic_directory", + "working_copy_view", + "working_copy", + ] { + source.remove(key); + } + } + for reference in report["dependency_references"] + .as_array_mut() + .into_iter() + .flatten() + { + if let Some(reference) = reference.as_object_mut() { + reference.remove("on_current_view"); + } + } + report +} + +pub fn report_hash(report: &Value) -> String { + digest(report) +} + +fn pass(value: &Value) -> Result { + serde_json::from_value(value.clone()).map_err(|_| "Unknown native review pass".into()) +} + +/// Extract all current findings and criterion gaps; group coverage without +/// dropping any of its evidence. The original report is retained alongside it. +pub fn issues(report: &Value) -> Result, String> { + if report["schema_version"] != 5 || report["selection"]["kind"] != "view_comparison" { + return Err("Native publication requires a source-to-target v5 paired-view review".into()); + } + let graph = &report["graph"]; + let findings = graph["findings"] + .as_array() + .ok_or("Review findings unavailable")?; + let criteria = graph["criteria"] + .as_array() + .ok_or("Review criteria unavailable")?; + let statuses = graph["passes"] + .as_array() + .ok_or("Review pass coverage unavailable")?; + let mut coverage = BTreeMap::>::new(); + let mut seen = BTreeSet::new(); + for status in statuses { + let own = pass(&status["pass"])?; + if !seen.insert(own) { + return Err("Duplicate native review pass".into()); + } + if status["status"] != "not_applicable" && status["status"] != "complete" { + coverage.entry(own).or_default().push(format!( + "{}: {}", + status["status"], + status["detail"].as_str().unwrap_or("Coverage not supplied") + )); + } + } + if seen != PASSES.into_iter().collect() { + return Err("All three native review passes are required".into()); + } + let hash = report_hash(report); + let mut result = Vec::new(); + let mut push = + |own: ReviewPass, kind: &str, reference: String, summary: String, evidence: Vec| { + let id = format!( + "urn:atomic:review-issue:{}", + digest(&json!([hash, own, kind, reference, summary, evidence])) + ); + result.push(ReviewIssue { + id, + pass: own, + kind: kind.into(), + reference, + summary, + waivable: kind != "publication_integrity", + evidence, + }); + }; + for finding in findings { + if finding["comparison"]["status"] == "resolved" { + continue; + } + let id = finding["id"].as_str().ok_or("Finding identity missing")?; + for own in finding["passes"].as_array().ok_or("Finding pass missing")? { + push( + pass(own)?, + "finding", + id.into(), + finding["finding"]["summary"] + .as_str() + .unwrap_or("Current review finding") + .into(), + vec![ + format!("F{}", finding["number"]), + serde_json::to_string(&finding["comparison"]).unwrap(), + ], + ); + } + } + for criterion in criteria { + if criterion["review_assessment"] != "met" { + push( + ReviewPass::IntentConformance, + "criterion", + criterion["id"] + .as_str() + .ok_or("Criterion identity missing")? + .into(), + format!( + "Acceptance assessment {}: {}", + criterion["review_assessment"], + criterion["text"].as_str().unwrap_or("criterion") + ), + vec![format!( + "Intent {} · source {} · author declared {}", + criterion["intent"], criterion["source_hash"], criterion["declared_status"] + )], + ); + } + } + let gate = &report["publication_gate"]; + if gate["allowed"] != true + || gate["blocks"] + .as_array() + .is_none_or(|blocks| !blocks.is_empty()) + { + push( + ReviewPass::IntentConformance, + "publication_integrity", + "publication-gate".into(), + "Original provenance/publication integrity checks do not permit insertion".into(), + vec![serde_json::to_string(gate).unwrap()], + ); + } + for node in graph["nodes"] + .as_array() + .ok_or("Native review observations unavailable")? + { + let p = &node["properties"]; + if node["kind"] == "check" && p["status"] != "completed" { + coverage + .entry(ReviewPass::AntiSlop) + .or_default() + .push(format!( + "{} · {} · {} · {}", + p["path"], p["rule"], p["status"], p["detail"] + )); + } + if node["kind"] == "metric" { + let own = if matches!( + p["observation"]["metric"].as_str(), + Some("public_surface" | "dependency_fan_out") + ) { + ReviewPass::BlastRadiusRisk + } else { + ReviewPass::AntiSlop + }; + for side in ["before", "after"] { + if p["observation"][side]["status"] == "unavailable" { + coverage.entry(own).or_default().push(format!( + "{} · {} · {side}: {}", + node["id"], p["path"], p["observation"][side]["reason"] + )); + } + } + } + } + let risk = &graph["risk"]["assessment"]; + if risk["rating"] != "low" && risk["rating"] != "not_applicable" { + push( + ReviewPass::BlastRadiusRisk, + "risk", + "risk-summary".into(), + format!( + "Review risk {} · coverage {}", + risk["rating"], risk["coverage"] + ), + vec![risk["rationale"] + .as_str() + .unwrap_or("Risk assessment unavailable") + .into()], + ); + } + for limitation in risk["limitations"].as_array().into_iter().flatten() { + coverage + .entry(ReviewPass::BlastRadiusRisk) + .or_default() + .push( + limitation + .as_str() + .unwrap_or("Unspecified risk limitation") + .into(), + ); + } + for diagnostic in report["view_comparison"]["diagnostics"] + .as_array() + .into_iter() + .flatten() + { + coverage.entry(ReviewPass::AntiSlop).or_default().push( + diagnostic + .as_str() + .unwrap_or("Recorded corpus analysis unavailable") + .into(), + ); + } + for diagnostic in report["view_comparison"]["conformance"]["diagnostics"] + .as_array() + .into_iter() + .flatten() + { + coverage + .entry(ReviewPass::IntentConformance) + .or_default() + .push( + diagnostic + .as_str() + .unwrap_or("Conformance context unavailable") + .into(), + ); + } + for (own, details) in coverage { + let details: Vec<_> = details + .into_iter() + .collect::>() + .into_iter() + .collect(); + if !details.is_empty() { + push( + own, + "coverage", + format!("{}:coverage", own.id()), + format!( + "{} coverage has {} explicit limitation(s)", + own.label(), + details.len() + ), + details, + ); + } + } + result.sort_by(|a, b| a.pass.cmp(&b.pass).then(a.id.cmp(&b.id))); + Ok(result) +} + +impl ReviewEvaluation { + pub fn template(scope: &ReviewScope, report: &Value, issues: &[ReviewIssue]) -> Self { + Self { + schema: EVALUATION_SCHEMA.into(), + scope_hash: scope.hash(), + report_hash: report_hash(report), + passes: PASSES + .into_iter() + .map(|own| { + let hard = issues + .iter() + .any(|issue| issue.pass == own && !issue.waivable); + let accepted_degradations: Vec<_> = issues + .iter() + .filter(|issue| issue.pass == own && !hard) + .map(|issue| AcceptedDegradation { + issue: issue.id.clone(), + rationale: String::new(), + evidence: vec![], + follow_up: None, + }) + .collect(); + PassEvaluation { + pass: own, + evaluated: false, + disposition: if hard { + Disposition::NotReady + } else if accepted_degradations.is_empty() { + Disposition::Ready + } else { + Disposition::AcceptedDegradation + }, + rationale: String::new(), + accepted_degradations, + } + }) + .collect(), + } + } + + pub fn validate( + &self, + scope: &ReviewScope, + report: &Value, + issues: &[ReviewIssue], + ) -> Result<(), String> { + if self.schema != EVALUATION_SCHEMA + || self.scope_hash != scope.hash() + || self.report_hash != report_hash(report) + { + return Err("Evaluation is stale or belongs to a different review scope/report".into()); + } + let mut seen = BTreeSet::new(); + for evaluation in &self.passes { + if !seen.insert(evaluation.pass) + || !evaluation.evaluated + || evaluation.rationale.trim().is_empty() + { + return Err("Explicit evaluation and rationale are required exactly once for each of the three review passes".into()); + } + let expected: BTreeSet<_> = issues + .iter() + .filter(|issue| issue.pass == evaluation.pass) + .map(|issue| issue.id.as_str()) + .collect(); + let mut accepted = BTreeSet::new(); + for entry in &evaluation.accepted_degradations { + if entry.rationale.trim().is_empty() + || !expected.contains(entry.issue.as_str()) + || issues + .iter() + .any(|issue| issue.id == entry.issue && !issue.waivable) + || !accepted.insert(entry.issue.as_str()) + { + return Err("Accepted degradation must name an exact waivable current issue once with a nonempty rationale; integrity failures are not waivable".into()); + } + } + match evaluation.disposition { + Disposition::Ready if !expected.is_empty() || !accepted.is_empty()=>return Err("Outstanding native evidence cannot be labelled ready; explicitly accept degradation or retain not_ready".into()), + Disposition::AcceptedDegradation if expected.is_empty() || accepted!=expected=>return Err("Every outstanding issue in an accepted-degradation pass must be explicitly accounted for".into()), + Disposition::NotReady if !accepted.is_empty()=>return Err("A not-ready pass cannot also claim accepted degradation".into()), + _=>{}, + } + } + if seen != PASSES.into_iter().collect() { + return Err("All three passes must be explicitly evaluated".into()); + } + Ok(()) + } + + pub fn insertion_disposition(&self) -> Disposition { + if self + .passes + .iter() + .any(|pass| pass.disposition == Disposition::NotReady) + { + Disposition::NotReady + } else if self + .passes + .iter() + .any(|pass| pass.disposition == Disposition::AcceptedDegradation) + { + Disposition::AcceptedDegradation + } else { + Disposition::Ready + } + } +} + +impl ReviewDecision { + pub fn artifact_hash(&self) -> String { + digest(self) + } + pub fn value(&self) -> Value { + serde_json::to_value(self).expect("review decision serializes") + } + + pub fn validate(&self) -> Result<(), String> { + if self.schema != SCHEMA || self.independent_approval || self.reviewed_at.trim().is_empty() + { + return Err( + "Invalid native review decision header or unsupported independent-approval claim" + .into(), + ); + } + if self.report_hash != report_hash(&self.report) { + return Err("Attested review report digest mismatch".into()); + } + let issues = issues(&self.report)?; + if self.issues != issues { + return Err("Attested issue set differs from the complete native report".into()); + } + if self.readiness + != if issues.is_empty() { + Disposition::Ready + } else { + Disposition::NotReady + } + { + return Err("Accepted degradation cannot rewrite evidence readiness".into()); + } + self.scope.validate_report(&self.report)?; + self.evaluation + .validate(&self.scope, &self.report, &self.issues) + } + + pub fn parse(bytes: &[u8]) -> Result { + if bytes.len() > MAX_BYTES { + return Err("Review decision exceeds the explicit 256 MiB artifact byte budget; no findings were truncated".into()); + } + let value = crate::jcs::admit_document(bytes).map_err(|error| error.to_string())?; + let decision: Self = serde_json::from_value(value).map_err(|error| error.to_string())?; + decision.validate()?; + Ok(decision) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn evidence(count: usize) -> (ReviewScope, Value) { + let base = digest(&"base"); + let change = digest(&"change"); + let target = ViewPin { + view: "dev".into(), + scope: "shared".into(), + state: digest(&"before"), + membership_hash: digest(&vec![base.clone()]), + members: vec![base.clone()], + }; + let source = ViewPin { + view: "draft".into(), + scope: "draft".into(), + state: digest(&"after"), + membership_hash: digest(&vec![base.clone(), change.clone()]), + members: vec![base, change.clone()], + }; + let scope = ReviewScope { + project: "urn:atomic:project:fixture".into(), + source, + target, + changes: vec![change], + intent_scope_hash: digest(&"intents"), + context_intent_hashes: BTreeMap::new(), + }; + let pin = |pin: &ViewPin| json!({"view":pin.view,"state":pin.state,"membership_hash":pin.membership_hash}); + let findings:Vec<_>=(0..count).map(|index|json!({"number":index+1,"id":format!("finding:{index}"),"passes":["blast_radius_risk"],"finding":{"summary":format!("Consumer {index} remains incompatible")},"comparison":{"status":"new"}})).collect(); + let report = json!({"schema_version":5,"selection":{"kind":"view_comparison"},"source":{"repository_root":"/one","working_copy_view":"draft"},"dependency_references":[{"hash":"context","on_current_view":true}],"view_comparison":{"from":pin(&scope.source),"to":pin(&scope.target),"before":pin(&scope.target),"after":pin(&scope.source),"conformance":{"scope":{"view":"draft","current_inventory_hash":scope.intent_scope_hash},"criteria":[],"diagnostics":[]}},"graph":{"scope":{"project":scope.project,"view":"draft","view_state":scope.source.state},"findings":findings,"criteria":[{"id":"criterion:one","intent":"intent:one","text":"Tests demonstrate compatibility","review_assessment":"unknown","source_hash":"pinned","declared_status":"met"}],"nodes":[],"passes":PASSES.map(|pass|json!({"pass":pass,"status":"partial","detail":"Static source inspection, not runtime proof"})),"risk":{"assessment":{"rating":"high","coverage":"partial","rationale":"Known incompatible consumers","limitations":["Tests were not executed"]}}},"publication_gate":{"allowed":true,"blocks":[]}}); + (scope, normalize_report(report)) + } + fn evaluated(scope: &ReviewScope, report: &Value, issues: &[ReviewIssue]) -> ReviewEvaluation { + let mut value = ReviewEvaluation::template(scope, report, issues); + for pass in &mut value.passes { + pass.evaluated = true; + pass.rationale = + "Reviewed the complete scoped evidence and explicit limitations".into(); + for accepted in &mut pass.accepted_degradations { + accepted.rationale="Known incompatibility accepted by the responsible signer for a bounded rollout; follow-up required".into(); + } + } + value + } + + #[test] + fn all_137_findings_are_linked_and_acceptance_does_not_rewrite_readiness() { + let (scope, report) = evidence(137); + let issues = issues(&report).unwrap(); + assert_eq!( + issues + .iter() + .filter(|issue| issue.kind == "finding") + .count(), + 137 + ); + let evaluation = evaluated(&scope, &report, &issues); + evaluation.validate(&scope, &report, &issues).unwrap(); + assert_eq!( + evaluation.insertion_disposition(), + Disposition::AcceptedDegradation + ); + let decision = ReviewDecision { + schema: SCHEMA.into(), + reviewed_at: "2026-11-25T00:00:00Z".into(), + scope, + report_hash: report_hash(&report), + report, + issues, + readiness: Disposition::NotReady, + evaluation, + independent_approval: false, + attributed_to: "accountable-signer".into(), + public_key: "key".into(), + supersedes: vec![], + content_hash: None, + proof: None, + }; + decision.validate().unwrap(); + let mut false_ready = decision.clone(); + false_ready.readiness = Disposition::Ready; + assert!(false_ready.validate().is_err()); + let mut false_approval = decision; + false_approval.independent_approval = true; + assert!(false_approval.validate().is_err()); + } + + #[test] + fn opaque_partial_stale_duplicate_or_foreign_acceptance_is_refused() { + let (scope, report) = evidence(2); + let issues = issues(&report).unwrap(); + let good = evaluated(&scope, &report, &issues); + let validate = |value: &ReviewEvaluation| value.validate(&scope, &report, &issues); + assert!(validate(&ReviewEvaluation::template(&scope, &report, &issues)).is_err()); + let mut value = good.clone(); + value.passes.pop(); + assert!(validate(&value).is_err()); + let mut value = good.clone(); + value.passes[0].evaluated = false; + assert!(validate(&value).is_err()); + let mut value = good.clone(); + value.passes[0].rationale.clear(); + assert!(validate(&value).is_err()); + let mut value = good.clone(); + value.passes[2].accepted_degradations.pop(); + assert!(validate(&value).is_err()); + let mut value = good.clone(); + value.passes[2].accepted_degradations[0].rationale.clear(); + assert!(validate(&value).is_err()); + let mut value = good.clone(); + value.passes[2].accepted_degradations[0].issue = "foreign finding".into(); + assert!(validate(&value).is_err()); + let mut value = good.clone(); + let duplicate = value.passes[2].accepted_degradations[0].clone(); + value.passes[2].accepted_degradations.push(duplicate); + assert!(validate(&value).is_err()); + let mut value = good.clone(); + value.report_hash = "stale".into(); + assert!(validate(&value).is_err()); + let mut value = good; + value.scope_hash = "other scope".into(); + assert!(validate(&value).is_err()); + } + + #[test] + fn unresolved_evidence_cannot_be_called_ready_and_not_ready_does_not_authorize() { + let (scope, report) = evidence(1); + let issues = issues(&report).unwrap(); + let mut evaluation = evaluated(&scope, &report, &issues); + evaluation.passes[2].disposition = Disposition::Ready; + evaluation.passes[2].accepted_degradations.clear(); + assert!(evaluation.validate(&scope, &report, &issues).is_err()); + evaluation.passes[2].disposition = Disposition::NotReady; + evaluation.validate(&scope, &report, &issues).unwrap(); + assert_eq!(evaluation.insertion_disposition(), Disposition::NotReady); + } + + #[test] + fn provenance_integrity_failure_is_never_waivable_code_degradation() { + let (scope, mut report) = evidence(1); + report["publication_gate"] = + json!({"allowed":false,"blocks":["tampered original signature"]}); + let issues = issues(&report).unwrap(); + let mut evaluation = evaluated(&scope, &report, &issues); + evaluation.validate(&scope, &report, &issues).unwrap(); + assert_eq!(evaluation.insertion_disposition(), Disposition::NotReady); + let own = evaluation + .passes + .iter_mut() + .find(|pass| pass.pass == ReviewPass::IntentConformance) + .unwrap(); + own.disposition = Disposition::AcceptedDegradation; + own.accepted_degradations = issues + .iter() + .filter(|issue| issue.pass == ReviewPass::IntentConformance) + .map(|issue| AcceptedDegradation { + issue: issue.id.clone(), + rationale: "Attempted bypass".into(), + evidence: vec![], + follow_up: None, + }) + .collect(); + assert!(evaluation.validate(&scope, &report, &issues).is_err()); + } + + #[test] + fn corpus_budget_diagnostics_are_explicitly_evaluated_even_without_a_metric_node() { + let (scope, mut report) = evidence(0); + report["view_comparison"]["diagnostics"] = + json!(["Before target: file omitted by semantic byte budget"]); + let issues = issues(&report).unwrap(); + let issue = issues + .iter() + .find(|issue| issue.pass == ReviewPass::AntiSlop && issue.kind == "coverage") + .unwrap(); + assert!(issue + .evidence + .iter() + .any(|entry| entry.contains("file omitted by semantic byte budget"))); + let mut evaluation = evaluated(&scope, &report, &issues); + evaluation.passes[0].accepted_degradations.clear(); + assert!(evaluation.validate(&scope, &report, &issues).is_err()); + } + + #[test] + fn scope_roles_are_explicit_and_environment_does_not_change_report_identity() { + let (scope, report) = evidence(1); + scope.validate_report(&report).unwrap(); + let mut wrong = report.clone(); + wrong["view_comparison"]["before"] = wrong["view_comparison"]["from"].clone(); + assert!(scope.validate_report(&wrong).is_err()); + let mut physical = report.clone(); + physical["source"] = json!({"repository_root":"/other/machine","atomic_directory":"/other/.atomic","working_copy_view":"dev","working_copy":{"id":"foreign physical directory"}}); + physical["dependency_references"][0]["on_current_view"] = json!(false); + assert_eq!(normalize_report(physical), report); + } +} diff --git a/atomic-cli/README.md b/atomic-cli/README.md index 0cf18554..e5a340a4 100644 --- a/atomic-cli/README.md +++ b/atomic-cli/README.md @@ -49,13 +49,14 @@ atomic review --turn : atomic review --intent atomic review --change atomic review --view dev --html -atomic review --from release --to dev --html -atomic review --from release --to dev --json +atomic review --from feature-shipping --to dev --html +atomic review --from feature-shipping --to dev --json ``` Ordinary review is local-only: `atomic-semantic` / `atomic-audit`, no model or -credentials. `--view` audits one recorded snapshot. `--from BEFORE --to AFTER` -compares two recorded views without switching the working copy, showing measured +credentials. `--view` audits one recorded snapshot. `--from SOURCE --to TARGET` +uses pull-request direction: draft/source to shared/destination. Measurements +compare target-before with source-after without switching the working copy, showing measured deltas and new/existing/resolved or uncertain local observations. The offline HTML embeds Atomic's real logo and colors; no remote assets or analytics load. Unsupported/missing analysis stays explicit, not a fabricated pass or zero. @@ -65,51 +66,35 @@ risk estimate over the two actual view states. Every JSON finding is available in HTML; contract findings are not truncated at 100. These remain local review observations, not independent acceptance approval or runtime proof. -Publish an independent review using one comma-separated view option: +Publish an attested native evaluation of the same source-to-target scope: ```sh -atomic review publish --view feature-a -atomic review publish --view feature-a,feature-b -atomic review publish --session -atomic review publish --view feature-a,feature-b --dry-run --json +atomic review publish --from feature-shipping --to dev --dry-run --json > review-plan.json +# Inspect the complete report; fill evaluation_template for all three passes, +# naming every accepted issue and its rationale, or retain a not_ready decision. +atomic review publish --from feature-shipping --to dev \ + --evaluation review-plan.json --identity reviewer --yes +atomic review publish inspect ``` -The local publisher preflights a trusted issuer, requests one bounded approval, -creates purpose-bound ephemeral credentials without remote enrollment or global -signer rebinding, runs a separate OpenCode process over recorded-only inputs on -the existing logical view, and finalizes through real native `session_end`. -The final signed receipt binds the recorded subject, review, publisher manifest, -native attestations and retained publication artifacts. Source conversations may -continue; publication concerns the frozen recorded snapshot, not future edits. - -The issuer must already be trusted by the repository. A generic read/record grant -is not publication authority: the CLI issues a separate signed, exact-subject -authorization from that trusted issuer. It does not alter the signer allowlist. -Recording credentials are revoked and their secret retired only after successful -finalization or explicit cancellation; public verification material is retained. -`--yes` approves that exact local operation noninteractively; it never grants push. - -Blocked jobs retain diagnostics under `.atomic/review-jobs/`: - -```sh -atomic review publish --resume -atomic review publish --cancel -``` - -Completed jobs are revalidated, not re-executed. Partial signing may resume without -duplicating retained artifacts. An unknown/crashed process outcome is not guessed -successful or blindly relaunched; inspect the retained run or cancel it. Expired -authority is not silently renewed. Retained temporary evidence is not auto-deleted. - -View collections deduplicate shared history and test compatible combined inputs. -Unequal overlapping path deltas, unresolved conflicts and symlink composition -are conservatively refused; prepare an explicit integration view for those cases. -No logical review view is created. Current canonical limits (64 independent roots, -4096 closure changes) fail explicitly rather than truncating coverage. - -Publication means retained signed review approval, **not insertion or push**. -Legacy `atomic triage review` and `atomic triage publication-review` remain valid; -advanced prepare/sign/record/inspect are also under `atomic review publish`. +No agent, model, runner, ephemeral identity, delegation or provider configuration +is used. An existing local identity signs the evaluation under repository trust +policy. `--yes` only confirms the supplied evaluation; it cannot accept issues or +manufacture a passing review. All slop, unknown/unmet conformance, risk and coverage +gaps remain in the full report. Accepted degradation is explicitly linked to that +attestation and does not rewrite evidence readiness to clean/ready. + +Applicable decisions are revalidated at shared insertion and linked from immutable +operation evidence. A stale, tampered, untrusted, incomplete or explicitly not-ready +decision refuses insertion; original provenance/integrity gates are not waived. +Native publication never inserts or pushes automatically. Use `--supersedes HASH` +to explicitly replace a current evaluation without deleting its history. +`--html` can export the attested decision and its per-finding acceptance links. +`--cancel UUID` only cleans up a retained job from the former agent publisher; +there is no agent-job resume or runner in native publishing. + +Advanced retrospective `prepare/sign/record` remain available under +`atomic review publish` with their existing independent-review-intent requirements. The single agent-facing wrapper is [`skills/review/SKILL.md`](skills/review/SKILL.md). ## Global Options diff --git a/atomic-cli/skills/review/SKILL.md b/atomic-cli/skills/review/SKILL.md index 816a7551..4256e3c3 100644 --- a/atomic-cli/skills/review/SKILL.md +++ b/atomic-cli/skills/review/SKILL.md @@ -1,6 +1,6 @@ --- name: Review -description: Review recorded work through anti-slop, intent conformance and blast-radius/risk passes, returning a graph of numbered evidence-backed findings and criterion assessments; or publish an independent view review through Atomic. +description: Review recorded work through native anti-slop, conformance and blast-radius passes, or explicitly attest evaluated readiness and accepted degradation for a source-to-target insertion. --- # Review @@ -32,8 +32,8 @@ atomic review --change --html atomic review --change --html --no-open --output review.html atomic review --view --html atomic review --view --json -atomic review --from --to --html -atomic review --from --to --json +atomic review --from --to --html +atomic review --from --to --json ``` `--view NAME` explicitly audits the current recorded snapshot of that named view, @@ -50,18 +50,20 @@ criteria, independently of change-plan links; this scope context is not inferred governing-change attribution or acceptance approval. Change-regression risk still has no baseline in snapshot mode. -`--from BEFORE --to AFTER` compares two complete recorded view states without a +`--from SOURCE --to TARGET` compares two complete recorded view states without a working-copy switch. Both options are required; they conflict with the other -selectors and change-specific finding/risk inputs. From is before; To is after. +selectors and change-specific finding/risk inputs. From is the proposed source; +To is the destination/base, like a pull request. Measurements use target-before +and source-after. This is not a simulated merge result. Metrics are extracted independently over each whole supplied corpus and matched by canonical file inode and qualified subject. The report shows actual numeric deltas only when both measurements and identities are comparable. Missing data is unavailable, not an inferred zero. Audit observations are new, existing, resolved, changed or unknown; changed/unknown are deliberately uncertain rather than guessed resolutions. Renames use recorded identity, not content similarity. -The v4 `view_comparison.files[*].analysis` units use domain-separated source URIs, +The v5 `view_comparison.files[*].analysis` units use domain-separated source URIs, not authored change hashes. All three passes are populated: conformance includes -intents explicitly assigned to the **To** view even without a change-plan link, +intents explicitly assigned to the **From/source** view even without a change-plan link, plus separately identified membership-delta governing context, pinned recorded criterion declarations and task/file evidence. Current-vault context is labelled and source/scope-hashed; unrelated and inherited parent-view assignments are not @@ -233,57 +235,54 @@ certainty needs substantial work, report the risk, confidence and coverage gap instead. Stop after the three bounded passes (or explicit blockers), with a concise graph/findings summary and observed verification. No automatic fix phase. -## A view argument means independent publication +## Native publication: evaluation and accountable accepted degradation -For `@review --view a` or `@review --view a,b`, invoke: +A view argument alone remains a local snapshot audit. Invoke publication only +when explicitly requested, using the same source-to-target direction: ```sh -atomic review publish --view a -atomic review publish --view a,b -``` - -There is one `--view` option, not a separate `--views` spelling. The CLI freezes -the recorded scope, preflights issuer authority, asks once for bounded local -ephemeral authorization, runs an independent OpenCode publisher in a temporary -recorded-only working copy, dispatches genuine session_end after child completion, -verifies native completion evidence, and retains exact-scope signed approval. -It owns credentials, lifecycle and cleanup. Do not provision grants, launch a -second agent, call session-end, or build a VM/transfer pipeline from this skill. - -Use `--yes` only when the user has already approved the displayed exact local -scope/authority. No production enrollment or shared identity-default mutation is -part of this command. `--identity` selects a trusted local issuer explicitly. - -Other supported operations: - -```sh -atomic review publish --session -atomic review publish --view a,b --dry-run --json -atomic review publish --resume -atomic review publish --cancel +atomic review publish --from draft --to dev --dry-run --json +atomic review publish --from draft --to dev --evaluation evaluated-review.json --identity reviewer --yes +atomic review publish --from draft --to dev --evaluation evaluated-review.json --identity reviewer --html atomic review publish inspect ``` -An unknown/crashed process outcome is not guessed complete or blindly relaunched: -preserve its job and follow the actual recovery diagnostic. Cancellation retires -recording credentials; it is not withdrawal of a previously published approval. -Collection publication checks combined compatible inputs, deduplicates history, -and rejects ambiguous overlapping deltas or unsupported symlink composition -rather than picking a winner. An explicit integration view is needed for those -cases; the review command never creates one for the user. - -## Results and boundaries - -Distinguish inspection, independent review, native session completion and retained -publication approval. Report the CLI's actual blocker and job ID when blocked. -Do not revoke a still-resumable job merely because one step failed, silently renew -its authorization, weaken policy, infer intent ownership from shared filenames, -or fabricate historical session capture. Native work-session capture and a -present-day retrospective approval remain different evidence. - -Publication means signed review finalization, **not insertion or push**. Those -remain separately requested operations. Legacy triage and advanced external -signing commands remain compatible; they are not extra skill-level workflows. -Never run git, atomic add or atomic record for this workflow: normal agent hooks -record actual work and provenance. If the installed CLI lacks `atomic review`, -report the binary/version mismatch instead of simulating the missing command. +Publication is native semantic/audit evaluation plus an existing local identity's +attestation. It does not execute an agent, model or runner, create an ephemeral +identity/delegation, enroll a key, insert or push. It is independent of whether a +company uses Copilot or another recording integration. `--view draft` is a +single-source convenience, using its parent when a destination is not supplied; +publication collections, runner/provider flags and agent-job resume are not this +workflow. `--cancel UUID` is cleanup-only for an owned job from the former agent +publisher; it cannot resume or create one. + +The dry-run emits the complete report, stable report/scope digests, outstanding +issues and an unfilled `evaluation_template`. A user must evaluate each of +`anti_slop`, `intent_conformance`, and `blast_radius_risk`, with a nonempty +rationale and one disposition: `ready`, `accepted_degradation`, or `not_ready`. +Outstanding findings, unmet/unknown criteria, elevated risk and grouped coverage +gaps require explicit issue IDs and rationales under `accepted_degradations`. +No wildcard or `--yes` acceptance exists. `--yes` only confirms retention of an +already explicit evaluation. Do not fabricate the user's evaluation or consent. + +The evaluation file can be the edited dry-run envelope (fill only its +`evaluation_template`) or that template alone. Its digests must match a fresh +native review. Accepted code-quality degradation stays visible and linked to the +attested report; native evidence readiness remains `not_ready`, not a fabricated +clean or independent approval. `not_ready` decisions can also be retained to +document rejection and never authorize insertion. Signer trust, scope drift, +original provenance/integrity failures and unknown signing keys are not waivable +code degradation. Existing explicit retrospective `prepare/sign/record` tools +retain their own proof and review-intent requirements. + +Native decisions are immutable retained artifacts. An applicable decision is +revalidated under the existing shared-insertion boundary, and its hash is linked +from insertion operation evidence. Moving either view, changing intent context, +an untrusted/tampered report, incomplete acceptance or a `not_ready` disposition +refuses reuse. Replace a current evaluation only with explicit `--supersedes HASH`; +do not rewrite historical evidence. Existing original-capture gates still apply. + +Never change work-intent criteria to hide code shortcomings, silently weaken +policy, or treat a signature as proof that tests ran or code is defect-free. +Publication remains separate from insertion and push. Normal agent hooks own +recording actual code/provenance; no extra agent phase belongs in this skill. diff --git a/atomic-cli/skills/review/references/review-contract.md b/atomic-cli/skills/review/references/review-contract.md index 893b571d..64dd6b55 100644 --- a/atomic-cli/skills/review/references/review-contract.md +++ b/atomic-cli/skills/review/references/review-contract.md @@ -83,22 +83,24 @@ never silently passed. HTML source-text export retains its separate existing ## Compare two recorded views ```sh -atomic review --from release --to dev -atomic review --from release --to dev --json -atomic review --from release --to dev --html --no-open --output comparison.html +atomic review --from feature-shipping --to dev +atomic review --from feature-shipping --to dev --json +atomic review --from feature-shipping --to dev --html --no-open --output comparison.html ``` -Both names are exact and required. From is the before state and To is the after -state, not an ancestor range or a sequence of patches to replay. The selectors +Both names are exact and required. From is the proposed source; To is the +destination/base, matching pull-request direction. Measurements are target-before +and source-after, not an ancestor range or a sequence of patches to replay. The selectors conflict with `--view`, change/turn/intent selection and `--findings` / `--risk-profile`. Self-comparisons, inherited views and empty views are valid. Both effective memberships and view Merkles are checked through analysis and HTML export. No working-copy switch, mutation, dirty/staged/untracked source, model call, credential or runtime network request is involved. -Comparison reports use `schema_version: 4`, `selection.kind: view_comparison`, +Comparison reports use `schema_version: 5`, `selection.kind: view_comparison`, `purpose: local_view_comparison_review` and `view_comparison` with `from`/`to` -pins, diagnostics and `files`. The authored `changes` and `selected_roots` stay +pins, explicit `before` (target) / `after` (source) pins, diagnostics and `files`. +The v5 direction is not the earlier v4 before/after flag convention. The authored `changes` and `selected_roots` stay empty; historical changes remain metadata references only. A domain-separated comparison URI identifies the ordered pair of pins; each file has its own `source_ref`, before/after path, inode and (when inspected) content hash, file and @@ -144,7 +146,7 @@ controls alongside all twenty cards and all three review passes. in both directions (`added_to_after` / `removed_from_after`), path references and actual recorded governing-plan contexts. Common history is not swept into this scope. Independently, `conformance.scope.view` identifies the explicitly reviewed -view (To for a comparison), and `conformance.intents` enumerates its explicitly +view (From/source for a comparison), and `conformance.intents` enumerates its explicitly assigned intents by canonical ID, human key, title, status and source. An intent does not need a recorded change-plan link to appear in this view-work catalogue. Neither mere file visibility in an inherited view nor shared task paths assigns @@ -154,7 +156,7 @@ diagnostics, not a reason to hide valid view-assigned work or fabricate ownershi The Conformance sidebar groups criteria beneath intent keys/titles, includes selectable intents with no available criteria, and searches intent title/key, criterion text/ID and related F-numbers. Any actual change-linked criteria outside -the target's explicit assignment are separately labelled change-linked context, +the source's explicit assignment are separately labelled change-linked context, not silently presented as view-assigned work. Single-view reports carry the same catalogue under `view_snapshot.conformance` without inventing a comparison. @@ -169,7 +171,7 @@ invented historical before/after status. That context is checked for drift durin export. The current assignment catalogue is also source-hashed under `scope.current_inventory_hash`; new/reassigned/removed scoped intents and changed current definitions invalidate export rather than reusing stale context. Recorded -target-view intent definitions remain available even if their current vault entry +source-view intent definitions remain available even if their current vault entry is absent, and are preferred over dirty current definitions. Neither declarations nor evidence-command strings are executed or treated as independently authenticated approval; arbitrary semantic acceptance judgments stay unknown. Engineering findings in task files are related navigation evidence, @@ -181,7 +183,7 @@ the two named effective states instead of a current-view patch prefix. Changed roots are selected before parsing caller context; before/after static callers, callees, declaration/access/argument-count checks and the rule-based risk estimate are populated. It does not replay intermediate changes: a break fixed before the -To state is not presented as a current contract break. Source/path/parser/search +source-after state is not presented as a current contract break. Source/path/parser/search budgets and unsupported/dynamic bindings remain explicit coverage gaps. Semantic callable IDs remain module/path-addressed, so a file rename can change bindings. Compiler-resolved types, runtime behavior and executed-test coverage are not @@ -200,6 +202,45 @@ website palette. No remote fonts, website code, analytics or asset requests are included. See `src/commands/review/assets/README.md` for source URLs, hashes and the proportional downsample. Local installed font names have system fallbacks. +## Attested native evaluation and accepted degradation + +`review publish --from draft --to dev` resolves this same native report. It never +starts an agent/model, creates credentials, invokes a runner or requires a vendor's +provider configuration. A trusted existing local identity attests what it evaluated. + +`--dry-run --json` emits full evidence, stable normalized report/scope digests, +all outstanding issues and an unfilled `evaluation_template`. Fill that template +or supply it alone through `--evaluation FILE`. Every pass must be explicitly +evaluated with a rationale. `ready` requires no outstanding evidence; +`accepted_degradation` must name every waivable issue exactly once with a nonempty +rationale, and may attach evidence/follow-up references. `not_ready` retains a +negative decision without authorizing insertion. `--yes` is confirmation only, +never an opaque acceptance or waiver. + +The signed `atomic.review-decision.v1` retains the complete report, its digest, +source/target state and membership, exact insertion closure, current intent-context +pins, every issue and each pass evaluation. Evidence readiness remains `not_ready` +when shortcomings exist even if user insertion disposition is `accepted_degradation`. +No independent approval, test execution or clean-code claim is inferred. The +published HTML labels these dispositions and links acceptance rationales to the +actual finding/criterion; its JSON download contains the complete attested decision. + +The existing shared-insertion evidence boundary validates applicable retained +decisions, signatures/trust, exact scope/selection, intent context and dispositions +before mutation. A decision hash is retained in insertion operation evidence and +the outcome reports accepted degradation. Stale scopes, bad signatures, untrusted +signers and original provenance/integrity blockers cannot be waived as code debt. +Known not-ready decisions refuse insertion. Current evaluations are replaced only +by explicit signed `--supersedes HASH`, not by rewriting history; legacy insertion +without a native decision retains its existing provenance policy. + +Native publication is not an automatic insert or push. `publish inspect` exposes +retained reports and current applicability. Existing retrospective +`prepare/sign/record` tools retain their stronger review-intent/authority contract; +a native risk evaluation is not fabricated original session capture. Old agent +jobs may only be explicitly cleaned up with `--cancel UUID`; no native resume, +provider, runner, or agent-execution path is offered. + ## Three-pass graph and numbered findings `atomic review` renders a location-first report with anti-slop, intent-conformance and diff --git a/atomic-cli/src/commands/insert.rs b/atomic-cli/src/commands/insert.rs index e6ea1671..30fc46b8 100644 --- a/atomic-cli/src/commands/insert.rs +++ b/atomic-cli/src/commands/insert.rs @@ -844,6 +844,10 @@ pub(crate) fn print_cross_view_outcome(outcome: &CrossViewInsertOutcome, dry_run } } + if let Some(review) = &outcome.review_decision { + output::print_warning(&format!("Attested review {} · evidence readiness {:?} · user disposition {:?} · {} explicitly accepted degradation(s). Report {}. This is not a clean-code or independent-approval claim.",review.decision,review.readiness,review.disposition,review.accepted_degradations,review.report_hash)); + } + if outcome.has_conflicts { println!(); output::print_warning("Conflicts detected. Run 'atomic conflicts' to see details."); diff --git a/atomic-cli/src/commands/review/graph.rs b/atomic-cli/src/commands/review/graph.rs index 3d4a7912..a250ff9a 100644 --- a/atomic-cli/src/commands/review/graph.rs +++ b/atomic-cli/src/commands/review/graph.rs @@ -485,7 +485,7 @@ pub(super) fn build( } else { PassStatus::Blocked }; - graph.passes[1].detail="Intents explicitly assigned to the To view and their acceptance criteria are included independently of recorded change-plan links. Actual membership-delta governance remains separate context. Recorded definitions are preferred; current-vault fallback is labelled context only. Scope, author claims and file overlap do not establish an independent acceptance verdict.".into(); + graph.passes[1].detail="Intents explicitly assigned to the From/source view and their acceptance criteria are included independently of recorded change-plan links. Actual membership-delta governance remains separate context. Recorded definitions are preferred; current-vault fallback is labelled context only. Scope, author claims and file overlap do not establish an independent acceptance verdict.".into(); graph .diagnostics .extend(comparison.conformance.diagnostics.iter().cloned()); @@ -675,7 +675,7 @@ fn project(repo: &Repository, report: &IncrementalReport, graph: &mut ReviewGrap &comparison.source_ref, "view_comparison", "Paired recorded views", - json!({"from":comparison.from,"to":comparison.to,"diagnostics":comparison.diagnostics,"conformance":comparison.conformance}), + json!({"from":comparison.from,"to":comparison.to,"before":comparison.before,"after":comparison.after,"diagnostics":comparison.diagnostics,"conformance":comparison.conformance}), ); out.edge("review", "compares_views", &comparison.source_ref); for file in &comparison.files { diff --git a/atomic-cli/src/commands/review/html.rs b/atomic-cli/src/commands/review/html.rs index 6952b539..4ed295a7 100644 --- a/atomic-cli/src/commands/review/html.rs +++ b/atomic-cli/src/commands/review/html.rs @@ -44,6 +44,22 @@ struct Request { } pub(super) fn render(repo: &Repository, report: &IncrementalReport) -> CliResult { + render_with_decision(repo, report, None) +} + +pub(super) fn render_published( + repo: &Repository, + report: &IncrementalReport, + decision: &atomic_canonical::review_decision::ReviewDecision, +) -> CliResult { + render_with_decision(repo, report, Some(decision)) +} + +fn render_with_decision( + repo: &Repository, + report: &IncrementalReport, + decision: Option<&atomic_canonical::review_decision::ReviewDecision>, +) -> CliResult { super::view_snapshot::verify(repo, report)?; let graph = report.graph.as_ref().expect("resolved review graph"); let regions = presentation::regions(graph); @@ -59,8 +75,12 @@ pub(super) fn render(repo: &Repository, report: &IncrementalReport) -> CliResult Vec::new(), flate2::Compression::fast(), )); - serde_json::to_writer(&mut archive, report) - .map_err(|error| CliError::Internal(error.into()))?; + if let Some(decision) = decision { + serde_json::to_writer(&mut archive, decision) + } else { + serde_json::to_writer(&mut archive, report) + } + .map_err(|error| CliError::Internal(error.into()))?; let archive = archive .into_inner() .map_err(|error| CliError::Internal(error.into()))? @@ -69,7 +89,7 @@ pub(super) fn render(repo: &Repository, report: &IncrementalReport) -> CliResult let view = json!({ "selected_roots":report.selected_roots,"warnings":report.warnings, "view_snapshot":report.view_snapshot.as_ref().map(|snapshot|json!({"source_ref":snapshot.source_ref,"view":snapshot.view,"state":snapshot.state,"membership_hash":snapshot.membership_hash,"file_count":snapshot.paths.len(),"conformance":snapshot.conformance})), - "view_comparison":report.view_comparison.as_ref().map(|comparison|json!({"source_ref":comparison.source_ref,"from":comparison.from,"to":comparison.to,"diagnostics":comparison.diagnostics,"conformance":comparison.conformance,"files":comparison.files.iter().map(|file|json!({"source_ref":file.source_ref,"path":file.path,"before_path":file.before_path,"after_path":file.after_path,"status":file.status,"content_status":file.content_status})).collect::>()})), + "view_comparison":report.view_comparison.as_ref().map(|comparison|json!({"source_ref":comparison.source_ref,"from":comparison.from,"to":comparison.to,"before":comparison.before,"after":comparison.after,"diagnostics":comparison.diagnostics,"conformance":comparison.conformance,"files":comparison.files.iter().map(|file|json!({"source_ref":file.source_ref,"path":file.path,"before_path":file.before_path,"after_path":file.after_path,"status":file.status,"content_status":file.content_status})).collect::>()})), "changes":report.changes.iter().filter(|change|change.selected_root).map(|change|json!({"hash":change.hash,"diff":change.diff,"diff_status":change.diff_status})).collect::>(), "graph":{"scope":graph.scope,"passes":graph.passes,"findings":graph.findings,"criteria":graph.criteria,"diagnostics":graph.diagnostics,"risk":graph.risk, "nodes":graph.nodes.iter().filter(|node|matches!(node.kind.as_str(),"metric"|"check")).collect::>()} @@ -82,7 +102,7 @@ pub(super) fn render(repo: &Repository, report: &IncrementalReport) -> CliResult .transpose() .map_err(|error| CliError::Internal(error.into()))?; emit( - json!({"schema":"atomic.review-viewer.v1","local_only":true,"view":view,"report_archive":{"encoding":"gzip+base64","data":archive},"profile_json":profile_json,"regions":regions,"sources":sources,"audit_cards":atomic_audit::AUDIT_CARDS,"metric_cards":atomic_audit::METRIC_CARDS,"patterns":patterns}), + json!({"schema":"atomic.review-viewer.v1","local_only":true,"view":view,"review_decision":decision.map(|decision|json!({"id":decision.artifact_hash(),"report_hash":decision.report_hash,"readiness":decision.readiness,"disposition":decision.evaluation.insertion_disposition(),"signer":decision.attributed_to,"public_key":decision.public_key,"proof":decision.proof,"issues":decision.issues,"evaluation":decision.evaluation})),"report_archive":{"encoding":"gzip+base64","data":archive},"profile_json":profile_json,"regions":regions,"sources":sources,"audit_cards":atomic_audit::AUDIT_CARDS,"metric_cards":atomic_audit::METRIC_CARDS,"patterns":patterns}), &super::terminal::render(graph, false), ) } @@ -228,9 +248,9 @@ fn sources( ); } let pin = if side == "before" { - &comparison.from + &comparison.before } else { - &comparison.to + &comparison.after }; let belongs = comparison.files.iter().any(|file| { if side == "before" { @@ -259,9 +279,9 @@ fn sources( } if let (Some(comparison), Some(file)) = (&report.view_comparison, comparison_file) { let (actual, pin, hash) = if side == "before" { - (&file.before_path, &comparison.from, &file.before_hash) + (&file.before_path, &comparison.before, &file.before_hash) } else { - (&file.after_path, &comparison.to, &file.after_hash) + (&file.after_path, &comparison.after, &file.after_hash) }; let Some(actual) = actual else { return SourceText::Absent; diff --git a/atomic-cli/src/commands/review/incremental.rs b/atomic-cli/src/commands/review/incremental.rs index 8c6da02a..613fe71e 100644 --- a/atomic-cli/src/commands/review/incremental.rs +++ b/atomic-cli/src/commands/review/incremental.rs @@ -30,10 +30,10 @@ pub struct IncrementalArgs { /// Audit every live recorded file in this view, including inherited files. #[arg(long, value_name = "NAME", conflicts_with_all = ["turn", "intent", "change", "findings", "risk_profile"])] pub view: Option, - /// Before view for a local recorded-view comparison (requires --to). + /// Proposed source view (for example, a draft); requires --to. #[arg(long, value_name="VIEW", requires="to", conflicts_with_all=["view","change","turn","intent","findings","risk_profile"])] pub from: Option, - /// After view for a local recorded-view comparison (requires --from). + /// Destination/base view (for example, shared dev); requires --from. #[arg(long, value_name="VIEW", requires="from", conflicts_with_all=["view","change","turn","intent","findings","risk_profile"])] pub to: Option, #[arg(long, conflicts_with = "html")] diff --git a/atomic-cli/src/commands/review/mod.rs b/atomic-cli/src/commands/review/mod.rs index b94496a2..8d163f5b 100644 --- a/atomic-cli/src/commands/review/mod.rs +++ b/atomic-cli/src/commands/review/mod.rs @@ -1,4 +1,4 @@ -//! Incremental, in-session inspection and independently finalized publication. +//! Local recorded-source inspection and accountable native review publication. //! //! The command owns execution; skills only select the scope and explain results. @@ -13,7 +13,6 @@ mod progress; mod publish; mod risk; mod risk_facts; -mod scope; mod terminal; mod view_comparison; mod view_snapshot; @@ -34,7 +33,7 @@ pub struct Review { #[derive(Debug, Subcommand)] enum Action { - /// Run an independent ephemeral publisher and finalize at its session end. + /// Attest a native source-to-target review and explicit risk evaluation; no LLM. Publish(publish::PublishArgs), } @@ -68,10 +67,22 @@ mod tests { } #[test] - fn publication_uses_one_comma_separated_view_option() { - let cli = Cli::try_parse_from(["review", "publish", "--view", "a,b", "--dry-run"]).unwrap(); + fn publication_uses_native_source_to_target_scope_without_a_runner() { + let cli = Cli::try_parse_from([ + "review", + "publish", + "--from", + "draft", + "--to", + "dev", + "--dry-run", + ]) + .unwrap(); assert!(matches!(cli.review.action, Some(Action::Publish(_)))); assert!(Cli::try_parse_from(["review", "publish", "--views", "a,b"]).is_err()); + assert!(Cli::try_parse_from(["review", "publish", "--runner", "opencode"]).is_err()); + assert!(Cli::try_parse_from(["review", "publish", "--session", "session"]).is_err()); + assert!(Cli::try_parse_from(["review", "publish", "--resume", "job"]).is_err()); } #[test] @@ -83,7 +94,7 @@ mod tests { fn bundled_skill_is_a_thin_wrapper_for_the_implemented_routes() { let skill = include_str!("../../../skills/review/SKILL.md"); assert!(skill.contains("atomic review --json")); - assert!(skill.contains("atomic review publish --view a,b")); + assert!(skill.contains("atomic review publish --from draft --to dev")); assert!(!skill.contains("identity agent create")); assert!(!skill.contains("smolvm machine")); assert!(skill.contains("changes[].analysis")); @@ -112,8 +123,17 @@ mod tests { ); for args in [ vec!["review", "--json"], - vec!["review", "publish", "--view", "a,b"], - vec!["review", "publish", "--view", "a,b", "--dry-run", "--json"], + vec!["review", "publish", "--from", "draft", "--to", "dev"], + vec![ + "review", + "publish", + "--from", + "draft", + "--to", + "dev", + "--dry-run", + "--json", + ], ] { assert!(Cli::try_parse_from(args).is_ok()); } diff --git a/atomic-cli/src/commands/review/publish.rs b/atomic-cli/src/commands/review/publish.rs index 80ba8336..472a54ec 100644 --- a/atomic-cli/src/commands/review/publish.rs +++ b/atomic-cli/src/commands/review/publish.rs @@ -1,97 +1,76 @@ -//! An owned, bounded independent publisher. No view is created or switched. -use std::collections::{BTreeMap, BTreeSet}; -use std::fs::{self, File, OpenOptions}; -use std::io::Write; -use std::path::{Component, Path, PathBuf}; -use std::process::{Command as Process, Stdio}; -use std::time::{Duration, Instant}; +//! Native, accountable evaluation of the same recorded source-to-target review. +//! No agent process, provider, delegated issuer or model participates. +mod legacy_cancel; -use atomic_canonical::publication_review::PublicationReview; -use atomic_core::types::Base32; -use atomic_identity::delegation::{Delegation, DelegationPermission, DelegationScope}; -use atomic_identity::{Identity, IdentityStore, IdentityType, IdentityUsage, KeyPair}; -use atomic_repository::{ - intent_bridge, PublicationGateConfig, Repository, ViewEntry, ViewEntryKind, -}; +use std::{fs, io::Read, path::PathBuf}; + +use atomic_canonical::review_decision::{self, Disposition, ReviewDecision, ReviewEvaluation}; +use atomic_identity::IdentityStore; +use atomic_repository::{PublicationGateConfig, Repository}; use clap::Args; -use fs2::FileExt; -use serde::{Deserialize, Serialize}; -use serde_json::{json, Value}; +use serde_json::json; -use super::scope::{self, invalid, Scope}; +use super::incremental::{self, IncrementalArgs}; use crate::commands::triage::publication_review::{Action as Advanced, PublicationReviewCommand}; -use crate::commands::{find_repository_root, Command}; -use crate::error::{CliError, CliResult}; +use crate::{ + commands::{find_repository_root, Command}, + error::{CliError, CliResult}, +}; + +fn invalid(message: impl std::fmt::Display) -> CliError { + CliError::InvalidArgument { + message: message.to_string(), + } +} #[derive(Debug, Args)] #[command(args_conflicts_with_subcommands = true)] pub(super) struct PublishArgs { - /// One literal view or a comma-separated collection of views. - #[arg(long, conflicts_with_all = ["session", "resume", "cancel"])] + /// Proposed draft/source; paired with --to. + #[arg(long,requires="to",conflicts_with_all=["view","cancel"])] + from: Option, + /// Shared destination/base. Measurements use this view as before. + #[arg(long, conflicts_with = "cancel")] + to: Option, + /// One source view (not a collection); its shared parent is the default target. + #[arg(long,conflicts_with_all=["from","cancel"])] view: Option, - /// Publish this session's recorded changes, not its inherited view history. - #[arg(long, conflicts_with_all = ["view", "resume", "cancel"])] - session: Option, - /// Resume a retained publication job without widening its original scope. + /// Explicit evaluation file bound to this exact report and scope. + #[arg(long, value_name = "FILE", conflicts_with = "cancel")] + evaluation: Option, + /// Existing local signing identity; no credentials or agents are created. #[arg(long, conflicts_with = "cancel")] - resume: Option, - /// Cancel a retained job and retire its temporary recording credentials. - #[arg(long)] - cancel: Option, - /// Trusted local identity issuing this exact review-publication authorization. - #[arg(long)] identity: Option, - /// OpenCode executable. An executable path, not a shell command. - #[arg(long, default_value = "opencode")] - runner: PathBuf, - /// Maximum publisher process lifetime; no automatic renewal. - #[arg(long, default_value_t = 1800, value_parser = clap::value_parser!(u64).range(1..=3300))] - timeout_seconds: u64, - /// Show the frozen scope without credentials, agents, or repository writes. - #[arg(long, conflicts_with_all = ["resume", "cancel"])] + /// Existing decision(s) explicitly superseded by this new attestation. + #[arg(long, conflicts_with = "cancel")] + supersedes: Vec, + /// Show the full report, outstanding issues and an unfilled evaluation template. + #[arg(long,conflicts_with_all=["cancel","html"])] dry_run: bool, - /// Approve the displayed local, purpose-bound ephemeral review operation. + /// Confirm retention of the supplied evaluation; never accepts issues itself. #[arg(long)] yes: bool, - #[arg(long)] + #[arg(long, conflicts_with = "html")] json: bool, - /// Advanced external/local signing primitives; legacy spellings still work. + /// Open an offline viewer containing the attested report and acceptance links. + #[arg(long, conflicts_with = "cancel")] + html: bool, + #[arg(long, requires = "html")] + no_open: bool, + #[arg(short, long, requires = "html", value_name = "FILE")] + output: Option, + /// Cleanup only: cancel a retained job from the former agent publisher. + #[arg(long)] + cancel: Option, #[command(subcommand)] advanced: Option, } -#[derive(Debug, Serialize, Deserialize)] -struct Job { - schema: String, - id: String, - scope: Scope, - phase: String, - issuer: String, - reviewer: String, - reviewer_did: String, - delegation: String, - expires_at: String, - workdir: PathBuf, - runner: PathBuf, - run_id: Option, - publisher_session: Option, - publisher_manifest: Option, - #[serde(default)] - publisher_attestations: Vec, - review: Option, - artifacts: Vec, - error: Option, - credentials_retired: bool, - #[serde(default)] - inputs_ready: bool, -} - -fn bad(error: impl std::fmt::Display) -> CliError { - invalid(error.to_string()) -} - pub(super) fn run(args: &PublishArgs) -> CliResult<()> { if let Some(action) = &args.advanced { + if matches!(action, Advanced::Inspect) { + return inspect(); + } return PublicationReviewCommand { action: action.clone(), } @@ -104,1226 +83,205 @@ pub(super) fn run(args: &PublishArgs) -> CliResult<()> { Repository::open(&root) } .map_err(CliError::Repository)?; - let id = args.resume.as_ref().or(args.cancel.as_ref()); - if let Some(id) = id { - let id = - uuid::Uuid::parse_str(id).map_err(|_| invalid("publication job ID must be a UUID"))?; - let dir = repo.dot_dir().join("review-jobs").join(id.to_string()); - let _lock = lock_job(&dir)?; - let mut job: Job = serde_json::from_slice(&fs::read(dir.join("job.json"))?).map_err(bad)?; - if job.id != id.to_string() || job.schema != "atomic.review-job.v1" { - return Err(invalid("publication job identity/schema mismatch")); - } - verify_job_owner(&repo, &dir, &job)?; - if args.cancel.is_some() { - // Cleanup of an owned recording credential is not conditional on - // continued validity of a previously retained review approval. - retire_credentials(&mut job)?; - if job.phase != "published" { - job.phase = "cancelled".into(); - } - save_job(&dir, &job)?; - return output(args, &job); - } - if job.phase != "published" && dir.join("published.json").exists() { - // Recover the crash window after immutable receipt persistence but - // before the mutable job checkpoint, without signing another copy. - verify_completed_job(&repo, &dir, &job)?; - job.phase = "published".into(); - save_job(&dir, &job)?; - } - if job.phase == "published" { - if !job.credentials_retired { - retire_credentials(&mut job)?; - save_job(&dir, &job)?; - } - verify_completed_job(&repo, &dir, &job)?; - return output(args, &job); - } - if job.phase == "cancelled" { - // Never re-execute the independent agent for a completed receipt. - return output(args, &job); - } - if chrono::DateTime::parse_from_rfc3339(&job.expires_at).map_err(bad)? <= chrono::Utc::now() - { - return Err(invalid(format!("job authority expired; cancel job {} to retire its credentials; no renewal was performed",job.id))); - } - return execute_job(args, &root, &dir, &mut job); + if let Some(id) = &args.cancel { + return legacy_cancel::cancel(&repo, id, args.json); } - let scope = scope::resolve(&repo, args.view.as_deref(), args.session.as_deref())?; + let _boundary = if args.dry_run { + None + } else { + Some( + repo.lock_review_publication() + .map_err(CliError::Repository)?, + ) + }; + let source = args + .from + .as_deref() + .or(args.view.as_deref()) + .unwrap_or(repo.current_view()); + let target = args + .to + .clone() + .or_else(|| repo.get_view_info(source).ok()?.parent_name) + .ok_or_else(|| { + invalid("Supply --from --to ; no destination was inferred") + })?; + let report = incremental::resolve( + &repo, + &IncrementalArgs { + from: Some(source.into()), + to: Some(target.clone()), + ..Default::default() + }, + )?; + let mut value = + review_decision::normalize_report(serde_json::to_value(&report).map_err(invalid)?); + let scope = repo + .review_decision_scope(source, &target, &value) + .map_err(CliError::Repository)?; + let gate = repo + .review_decision_preflight(&scope) + .map_err(CliError::Repository)?; + value["publication_gate"] = json!({"allowed":gate.allowed(),"checked":gate.checked,"managed_changes":gate.managed_changes,"blocks":gate.blocks.iter().map(ToString::to_string).collect::>(),"limitations":gate.limitations,"retrospective_reviews":gate.retrospective_reviews.iter().map(|review|json!({"change":review.change,"session":review.session,"review_hash":review.review_hash})).collect::>()}); + let issues = review_decision::issues(&value).map_err(invalid)?; + let hash = review_decision::report_hash(&value); if args.dry_run { - let plan = json!({"status":"plan","operation":"review-publication","scope":scope, - "execution":"fresh OpenCode session and process-local ephemeral reviewer", - "insertion":false,"push":false,"production_enrollment":false}); - println!("{}", serde_json::to_string_pretty(&plan).map_err(bad)?); + println!("{}",serde_json::to_string_pretty(&json!({"schema":"atomic.review-publication-plan.v1","source":scope.source,"target":scope.target,"scope":scope,"scope_hash":scope.hash(),"report_hash":hash,"readiness":if issues.is_empty(){Disposition::Ready}else{Disposition::NotReady},"issues":issues,"evaluation_template":ReviewEvaluation::template(&scope,&value,&issues),"report":value,"execution":"native semantic/audit review only; no agent, model or credential creation","insertion":false,"push":false})).map_err(invalid)?); return Ok(()); } - let runner = executable(&args.runner)?; - let store = IdentityStore::open_default_existing().map_err(bad)?; - let issuer = match &args.identity { - Some(name) => store.load_by_name(name).map_err(bad)?, + let file=args.evaluation.as_ref().ok_or_else(||invalid("Supply --evaluation FILE after inspecting --dry-run --json and filling its exact evaluation_template. --yes does not evaluate or accept degradation."))?; + let mut bytes = Vec::new(); + fs::File::open(file)? + .take((review_decision::MAX_BYTES + 1) as u64) + .read_to_end(&mut bytes)?; + if bytes.len() > review_decision::MAX_BYTES { + return Err(invalid( + "Evaluation exceeds its explicit byte budget; nothing was truncated", + )); + } + let admitted = atomic_canonical::jcs::admit_document(&bytes).map_err(invalid)?; + let evaluation: ReviewEvaluation = serde_json::from_value( + admitted + .get("evaluation_template") + .unwrap_or(&admitted) + .clone(), + ) + .map_err(invalid)?; + evaluation + .validate(&scope, &value, &issues) + .map_err(invalid)?; + let store = IdentityStore::open_default_existing().map_err(invalid)?; + let identity = match &args.identity { + Some(name) => store.load_by_name(name).map_err(invalid)?, None => store .get_default() - .map_err(bad)? - .ok_or_else(|| invalid("no local publication issuer selected; pass --identity"))?, + .map_err(invalid)? + .ok_or_else(|| invalid("Select an existing review signing identity with --identity"))?, }; + let signer = atomic_canonical::did::did_for_public_key(&identity.public_key); let config = PublicationGateConfig::from_repo(&repo).map_err(CliError::Repository)?; - if issuer.identity_type.is_agent() || issuer.identity_type.is_delegated() { - return Err(invalid("an ephemeral review must be authorized by a trusted human issuer, not a delegation chain")); - } - let issuer_did = atomic_canonical::did::did_for_public_key(&issuer.public_key); if config .trust - .evaluate(&issuer_did, config.repository_identity.as_deref()) + .evaluate(&signer, config.repository_identity.as_deref()) != atomic_config::SignerTrust::Trusted { - return Err(invalid(format!("publication issuer {issuer_did} is not trusted by this repository; no agent or credential was created"))); - } - // Check the signing key BEFORE asking an independent reviewer to do work. - let pair = store.load_keypair(&issuer.id, None).map_err(bad)?; - if scope.intent_sources.is_empty() { - return Err(invalid("no source-backed work intent was resolved for this scope; supply genuine intent associations before publication")); - } - if !args.yes && !dialoguer::Confirm::new() - .with_prompt(format!("Authorize a local ephemeral publisher for {} view(s), {} recorded changes, at most {} seconds? No insertion, push or production enrollment",scope.views.len(),scope.closure.len(),args.timeout_seconds)) - .default(false).interact().map_err(bad)? - { return Err(invalid("publication cancelled before credentials or agent creation")); } - let id = uuid::Uuid::new_v4().to_string(); - let dir = repo.dot_dir().join("review-jobs").join(&id); - fs::create_dir_all(&dir)?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(&dir, fs::Permissions::from_mode(0o700))?; - } - let _lock = lock_job(&dir)?; - let temp = tempfile::Builder::new() - .prefix("atomic-review-") - .tempdir()? - .keep(); - let reviewer_pair = KeyPair::generate(); - let reviewer = Identity::builder(format!("review-{id}")) - .identity_type(IdentityType::Agent) - .usage(IdentityUsage::Bot) - .public_key(reviewer_pair.public.clone()) - .delegated_by(issuer.id) - .build() - .map_err(bad)?; - let expiry = - chrono::Utc::now() + chrono::Duration::seconds((args.timeout_seconds + 300) as i64); - let mut builder = DelegationScope::builder() - .permissions(vec![ - DelegationPermission::Read, - DelegationPermission::Record, - ]) - .project( - scope - .project - .strip_prefix("urn:atomic:project:") - .unwrap_or(&scope.project), - ) - .server(format!( - "atomic-local://{}", - scope - .project - .strip_prefix("urn:atomic:project:") - .unwrap_or(&scope.project) - )) - .max_changes(3); - for pin in &scope.views { - builder = builder.view(&pin.name); - } - let terms = Delegation::new(&issuer, &reviewer, builder.build()).expires_in( - chrono::Duration::seconds((args.timeout_seconds + 300) as i64), - ); - let certificate = atomic_canonical::delegation::mint(&issuer, &pair, &terms); - let document = atomic_canonical::delegation::encode_for_storage(&certificate).map_err(bad)?; - let mut job = Job { - schema: "atomic.review-job.v1".into(), - id, - scope, - phase: "prepared".into(), - issuer: issuer.name.clone(), - reviewer: reviewer.name.clone(), - reviewer_did: atomic_canonical::did::did_for_public_key(&reviewer.public_key), - delegation: terms.id.to_base32(), - expires_at: expiry.to_rfc3339(), - workdir: temp, - runner, - run_id: None, - publisher_session: None, - publisher_manifest: None, - publisher_attestations: vec![], - review: None, - artifacts: vec![], - error: None, - credentials_retired: false, - inputs_ready: false, - }; - // Persist recovery identifiers before effects. There are never shared default - // signer/profile mutations, remote enrollment, or credential copies. - save_job(&dir, &job)?; - let ownership = atomic_canonical::proof::attest_value(job_ownership(&job), &issuer, &pair); - fs::write( - dir.join("owner.json"), - serde_json::to_vec_pretty(&ownership).map_err(bad)?, - )?; - store - .save_with_keypair(&reviewer, &reviewer_pair, None) - .map_err(bad)?; - store - .save_delegation(&job.delegation, &document) - .map_err(bad)?; - drop(reviewer_pair); - drop(pair); - drop(store); - drop(repo); - execute_job(args, &root, &dir, &mut job) -} - -fn execute_job(args: &PublishArgs, root: &Path, dir: &Path, job: &mut Job) -> CliResult<()> { - let result = execute_inner(args, root, dir, job); - match result { - Ok(()) => { - job.phase = "published".into(); - job.error = None; - // The retained purpose-bound approval remains valid historically. - // Revoke the recording credential, NOT the publication approval. - let cleanup = retire_credentials(job); - save_job(dir, job)?; - output(args, job)?; - cleanup - } - Err(error) => { - job.phase = "blocked".into(); - job.error = Some(error.to_string()); - save_job(dir, job)?; - eprintln!("Review job {} retained at {}. Resume with `atomic review publish --resume {}` or cancel with `--cancel {}`; credentials were not prematurely revoked.",job.id,dir.display(),job.id,job.id); - Err(error) - } - } -} - -fn execute_inner(args: &PublishArgs, root: &Path, dir: &Path, job: &mut Job) -> CliResult<()> { - let repo = Repository::open(root).map_err(CliError::Repository)?; - verify_job_owner(&repo, dir, job)?; - let workspace = job.workdir.join("reviewer"); - if job.publisher_session.is_none() { - if job.run_id.is_some() && dir.join("agent.jsonl").exists() { - // A missing durable exit receipt must not be repaired by guessing a - // prior process completed or blindly starting a duplicate reviewer. - return Err(invalid("previous publisher execution has no verified completion receipt; inspect the retained run or cancel this job before starting another")); - } - scope::recheck(&repo, &job.scope, None, None)?; - if !workspace.exists() { - repo.provision_recorded_sandbox(&workspace, &job.scope.views[0].name) - .map_err(CliError::Repository)?; - } - // Directory existence or a mutable job-state flag is not evidence that - // compatible, complete collection inputs were prepared. - prepare_inputs(&repo, dir, job)?; - job.inputs_ready = true; - save_job(dir, job)?; - let brief = dir.join("reviewer.md"); - fs::write(&brief, brief_text(job, dir)?)?; - let scope_bytes = serde_json::to_vec_pretty(&job.scope).map_err(bad)?; - fs::write(dir.join("scope.json"), scope_bytes)?; - let begin = atomic_output( - &workspace, - &[ - "agent", - "lifecycle", - "begin", - "--owner", - "atomic-review-publish", - "--session", - &job.id, - "--executor", - "opencode", - "--view", - &job.scope.views[0].name, - "--workdir", - workspace - .to_str() - .ok_or_else(|| invalid("non-UTF8 reviewer workdir"))?, - "--ttl-seconds", - &(args.timeout_seconds + 300).to_string(), - "--json", - ], - )?; - let value: Value = serde_json::from_slice(&begin).map_err(bad)?; - job.run_id = Some( - value - .get("run_id") - .and_then(Value::as_str) - .ok_or_else(|| invalid("lifecycle begin returned no run_id"))? - .into(), - ); - job.phase = "running".into(); - save_job(dir, job)?; - let log = dir.join("agent.jsonl"); - let mut process = Process::new(&job.runner); - process.current_dir(&workspace).env("ATOMIC_AGENT_IDENTITY",&job.reviewer) - .args(["run","--standalone","--format","json","--title"]) - .arg(format!("Atomic publication {}",job.id)).arg("--file").arg(&brief) - .arg("Perform the independently authorized review in the attached bounded CLI handoff. Do not invoke review publish recursively. Save prepared unsigned publication documents, and finish your turn for automatic recording.") - .stdin(Stdio::null()).stdout(File::create(&log)?).stderr(File::create(dir.join("agent.stderr"))?); - let status = run_bounded(&mut process, Duration::from_secs(args.timeout_seconds))?; - if !status.success() { - return Err(invalid(format!( - "publisher process failed ({status}); see {}", - dir.join("agent.stderr").display() - ))); - } - job.publisher_session = Some(read_session_id(&log)?); - save_job(dir, job)?; - } - let session = job - .publisher_session - .as_deref() - .ok_or_else(|| invalid("missing publisher session"))?; - let review_id = find_review(&repo, &job.reviewer_did)?; - // Tests may create build products, but may not change the source bytes or - // modes in the compatible collection tree and attest those repaired bytes - // as though the original frozen implementation passed. - recheck_input_sources(&repo, job)?; - let inputs = intent_bridge::read_intent(&repo, &review_id).map_err(CliError::Repository)?; - let node = intent_bridge::lift(&inputs).map_err(CliError::Repository)?; - let uid = review_id - .strip_prefix("urn:atomic:intent:") - .unwrap_or(&review_id); - scope::recheck(&repo, &job.scope, Some(uid), Some(session))?; - if node.status != "done" - || node.kind != "review" - || node.has_acceptance_criterion.is_empty() - || node - .has_acceptance_criterion - .iter() - .any(|ac| ac.ac_status != "met") - { - return Err(invalid( - "independent review has unresolved findings or is not complete; publication refused", - )); - } - for work in job.scope.intent_sources.keys() { - if !node - .depends_on - .iter() - .any(|r| r.edge == "reviews" && &r.to == work) - { - return Err(invalid(format!( - "independent review does not cover work intent {work}" - ))); - } - } - job.review = Some(review_id.clone()); - let run = job - .run_id - .as_deref() - .ok_or_else(|| invalid("missing owned publisher run"))?; - let completion = crate::commands::agent::finish_publisher_session( - &workspace, - session, - run, - &job.id, - &job.reviewer, - &job.scope.views[0].name, - )?; - job.publisher_manifest = Some(completion.manifest.to_base32()); - job.publisher_attestations = completion - .attestations - .iter() - .map(Base32::to_base32) - .collect(); - job.phase = "session-ended".into(); - save_job(dir, job)?; - let _ = atomic_output( - &workspace, - &["agent", "lifecycle", "end", "--run-id", run, "--json"], - )?; - let _publication_boundary = repo - .lock_review_publication() - .map_err(CliError::Repository)?; - scope::recheck(&repo, &job.scope, Some(uid), Some(session))?; - // Final signatures are added only after authentic native session_end. The - // independently prepared documents bind pre-output snapshots, avoiding a - // recursive requirement to review a publication's own generated receipt. - let store = IdentityStore::open_default_existing().map_err(bad)?; - let issuer = store.load_by_name(&job.issuer).map_err(bad)?; - let issuer_pair = store.load_keypair(&issuer.id, None).map_err(bad)?; - let reviewer = store.load_by_name(&job.reviewer).map_err(bad)?; - let reviewer_pair = store.load_keypair(&reviewer.id, None).map_err(bad)?; - let config = PublicationGateConfig::from_repo(&repo).map_err(CliError::Repository)?; - let keys = atomic_repository::repository::provenance_gate::local_did_key_provider(&repo); - for (index, pin) in job.scope.views.iter().enumerate() { - if let Some(hash) = job.artifacts.get(index) { - let all = repo.publication_reviews().map_err(CliError::Repository)?; - let retained = all - .iter() - .find(|r| r.artifact_hash() == *hash) - .ok_or_else(|| invalid("partial publication artifact is missing"))?; - if retained - .subject - .roots - .iter() - .cloned() - .collect::>() - != pin.roots.iter().cloned().collect() - || retained.subject.review.id != review_id - || retained.attributed_to != job.reviewer_did - || !repo - .validate_publication_review(retained, &config, &keys) - .map_err(CliError::Repository)? - .conforms - { - return Err(invalid( - "partial publication no longer matches this job's verified scope", - )); - } - continue; - } - let prepared_path = dir.join(format!("prepared-{index}.json")); - if fs::metadata(&prepared_path)?.len() - > atomic_canonical::publication_review::MAX_BYTES as u64 - { - return Err(invalid( - "prepared publication exceeds the canonical document size budget", - )); - } - let prepared = fs::read(prepared_path)?; - let value = atomic_canonical::jcs::admit_document(&prepared).map_err(bad)?; - let value = value.get("document").unwrap_or(&value); - let mut review = - PublicationReview::parse(&serde_json::to_vec(value).map_err(bad)?).map_err(bad)?; - let selected: BTreeSet<_> = review.subject.roots.iter().cloned().collect(); - if selected != pin.roots.iter().cloned().collect() - || review.subject.review.id != review_id - || review.attributed_to != job.reviewer_did - || review.subject.project != job.scope.project - || review.subject.view_chain.first().map(|p| p.name.as_str()) != Some(pin.name.as_str()) - || review.proof.is_some() - { - return Err(invalid("publisher prepared a different project/review/view/change scope or an already signed document")); - } - scope::check_prepared_context(pin, &review.subject)?; - let pending = dir.join(format!("signed-{index}.json")); - if pending.exists() { - let retained = PublicationReview::parse(&fs::read(&pending)?).map_err(bad)?; - if retained.subject != review.subject || retained.attributed_to != job.reviewer_did { - return Err(invalid( - "pending signature belongs to another publication subject", - )); - } - repo.record_publication_review(&retained, &config, &keys) - .map_err(CliError::Repository)?; - job.artifacts.push(retained.artifact_hash()); - save_job(dir, job)?; - continue; - } - atomic_repository::repository::review_authorization::mint_and_store( - &repo, - &review.subject, - &reviewer.public_key, - &issuer, - &issuer_pair, - chrono::DateTime::parse_from_rfc3339(&job.expires_at) - .map_err(bad)? - .with_timezone(&chrono::Utc), - &config, - ) - .map_err(CliError::Repository)?; - review.reviewed_at = chrono::Utc::now().to_rfc3339(); - if !atomic_repository::repository::review_authorization::reviewer_may_sign_now( - &repo, &review, &config, &keys, - ) - .map_err(CliError::Repository)? - { - return Err(invalid("exact-scope publication authority was not accepted; no publication signature retained")); - } - let signed = - atomic_canonical::proof::attest_value(review.value(), &reviewer, &reviewer_pair); - let signed: PublicationReview = serde_json::from_value(signed).map_err(bad)?; - // Persist exact signed bytes BEFORE the canonical retention effect, so - // a crash cannot turn retry into a new timestamp/new approval artifact. - write_immutable(&pending, &serde_json::to_vec_pretty(&signed).map_err(bad)?)?; - repo.record_publication_review(&signed, &config, &keys) - .map_err(CliError::Repository)?; - let artifact = signed.artifact_hash(); - if !job.artifacts.contains(&artifact) { - job.artifacts.push(artifact); - } - save_job(dir, job)?; - } - scope::recheck(&repo, &job.scope, Some(uid), Some(session))?; - let receipt = json!({"schema":"atomic.review-publication-receipt.v1","job":job.id,"scope":job.scope, - "review":review_id,"publisher_session":session,"session_end_manifest":job.publisher_manifest, - "session_end_attestations":job.publisher_attestations,"artifacts":job.artifacts, - "attributedTo":job.reviewer_did,"meaning":"finalized independent review; not insertion or push"}); - let receipt = atomic_canonical::proof::attest_value(receipt, &reviewer, &reviewer_pair); - write_immutable( - &dir.join("published.json"), - &serde_json::to_vec_pretty(&receipt).map_err(bad)?, - )?; - Ok(()) -} - -fn verify_completed_job(repo: &Repository, dir: &Path, job: &Job) -> CliResult<()> { - let store = IdentityStore::open_default_existing().map_err(bad)?; - let reviewer = store.load_by_name(&job.reviewer).map_err(bad)?; - let value = atomic_canonical::jcs::admit_document(&fs::read(dir.join("published.json"))?) - .map_err(bad)?; - atomic_canonical::proof::verify_value(&value, &reviewer.public_key).map_err(bad)?; - if value.get("job") != Some(&json!(job.id)) - || value.get("scope") != Some(&json!(job.scope)) - || value.get("artifacts") != Some(&json!(job.artifacts)) - || value.get("session_end_manifest") != Some(&json!(job.publisher_manifest)) - || value.get("session_end_attestations") != Some(&json!(job.publisher_attestations)) - || value.get("publisher_session") != Some(&json!(job.publisher_session)) - || value.get("review") != Some(&json!(job.review)) - || value.get("attributedTo") != Some(&json!(job.reviewer_did)) - { - return Err(invalid( - "retained job differs from its signed publication receipt", - )); + return Err(invalid("The selected signer is not trusted by repository policy. No identity, delegation or trust grant was created.")); } - let session = job - .publisher_session - .as_deref() - .ok_or_else(|| invalid("published receipt has no publisher session"))?; - let manifest = scope::hashes(&[job - .publisher_manifest - .clone() - .ok_or_else(|| invalid("missing publisher end manifest"))?])?[0]; - let manifest = repo - .get_session_manifest(&manifest) + let disposition = evaluation.insertion_disposition(); + eprintln!("Native review {} -> {}\nEvidence readiness: {:?}; explicit insertion disposition: {:?}\n{} outstanding issue(s), signer {}. The attestation retains every issue and rationale; it is not independent or clean-code approval.",source,target,if issues.is_empty(){Disposition::Ready}else{Disposition::NotReady},disposition,issues.len(),signer); + if !args.yes && !dialoguer::Confirm::new().with_prompt("Attest and retain this exact evaluated scope and its stated risks? No insert or push").default(false).interact().map_err(invalid)? {return Err(invalid("Native review publication cancelled; nothing was signed or stored"));} + let existing = repo + .native_review_decisions() .map_err(CliError::Repository)? - .ok_or_else(|| invalid("retained publisher manifest is unavailable"))?; - if manifest.session_id != session || job.publisher_attestations.is_empty() { - return Err(invalid( - "publisher completion evidence does not match the signed receipt", - )); - } - let mut covered = BTreeSet::new(); - for hash in scope::hashes(&job.publisher_attestations)? { - let attest = repo.load_attestation(&hash).map_err(CliError::Repository)?; - if attest.session_id != session - || attest.signer_did() != Some(job.reviewer_did.as_str()) - || !attest.verify_with_did(reviewer.public_key.as_bytes()) - { - return Err(invalid( - "retained publisher attestation signature/binding failed", - )); - } - covered.extend(attest.changes_covered); - } - if manifest - .turns - .iter() - .flat_map(|t| &t.change_hashes) - .any(|h| !covered.contains(h)) - { - return Err(invalid( - "retained publisher attestation does not cover its recorded review turns", - )); - } - for change in manifest.turns.iter().flat_map(|turn| &turn.change_hashes) { - for (_, attestation) in repo - .find_attestations_for_change(change) - .map_err(CliError::Repository)? - { - if attestation.session_id == session - && (attestation.signer_did() != Some(job.reviewer_did.as_str()) - || !attestation.verify_with_did(reviewer.public_key.as_bytes())) - { - return Err(invalid("invalid later same-session evidence cannot be hidden by a previously published receipt")); - } - } - } - let config = PublicationGateConfig::from_repo(repo).map_err(CliError::Repository)?; - let keys = atomic_repository::repository::provenance_gate::local_did_key_provider(repo); - let all = repo.publication_reviews().map_err(CliError::Repository)?; - if job.artifacts.len() != job.scope.views.len() || job.artifacts.is_empty() { - return Err(invalid( - "published receipt lacks exact per-view publication coverage", - )); - } - for (index, hash) in job.artifacts.iter().enumerate() { - let artifact = all - .iter() - .find(|r| r.artifact_hash() == *hash) - .ok_or_else(|| invalid("retained publication artifact is missing"))?; - if artifact - .subject - .roots - .iter() - .cloned() - .collect::>() - != job.scope.views[index].roots.iter().cloned().collect() - || artifact.subject.review.id != job.review.as_deref().unwrap_or("") - || artifact.attributed_to != job.reviewer_did - { - return Err(invalid( - "retained artifact does not cover this job's exact selected view roots", - )); - } - let report = repo - .validate_publication_review(artifact, &config, &keys) + .into_iter() + .find(|old| { + old.scope == scope + && old.report_hash == hash + && old.evaluation == evaluation + && old.attributed_to == signer + && (args.supersedes.is_empty() || old.supersedes == args.supersedes) + }); + let decision = if let Some(existing) = existing { + repo.inspect_review_decision(&existing) .map_err(CliError::Repository)?; - if !report.conforms { - return Err(invalid( - "retained publication no longer conforms to current authority/evidence policy", - )); - } - } - Ok(()) -} - -fn job_ownership(job: &Job) -> Value { - json!({"schema":"atomic.review-job-ownership.v1","job":job.id,"scope":job.scope, - "issuer":job.issuer,"reviewer":job.reviewer,"reviewer_did":job.reviewer_did, - "delegation":job.delegation,"expires_at":job.expires_at,"workdir":job.workdir,"runner":job.runner}) -} - -fn verify_job_owner(repo: &Repository, dir: &Path, job: &Job) -> CliResult<()> { - let store = IdentityStore::open_default_existing().map_err(bad)?; - let issuer = store.load_by_name(&job.issuer).map_err(bad)?; - let document = - atomic_canonical::jcs::admit_document(&fs::read(dir.join("owner.json"))?).map_err(bad)?; - atomic_canonical::proof::verify_value(&document, &issuer.public_key).map_err(bad)?; - for (key, value) in job_ownership(job) - .as_object() - .ok_or_else(|| invalid("invalid job ownership scope"))? - { - if document.get(key) != Some(value) { - return Err(invalid( - "mutable job scope differs from its issuer-signed ownership record", - )); - } - } - if repo.project_id().map_err(CliError::Repository)?.to_urn() != job.scope.project { - return Err(invalid("publication job belongs to a different project")); - } - if job.reviewer != format!("review-{}", job.id) { - return Err(invalid( - "publication job does not own this ephemeral identity name", - )); - } - let reviewer = store.load_by_name(&job.reviewer).map_err(bad)?; - if !reviewer.identity_type.is_agent() - || reviewer.delegated_by != Some(issuer.id) - || atomic_canonical::did::did_for_public_key(&reviewer.public_key) != job.reviewer_did - { - return Err(invalid( - "publication recovery refuses credentials not created for this issuer-owned job", - )); - } - Ok(()) -} - -fn brief_text(job: &Job, dir: &Path) -> CliResult { - Ok(format!("# Independent publisher job {}\n\nWork only in your current recorded-only working copy on existing view {}. Verify native project {}, same-view lifecycle run, and process identity {} before edits. Do not create/switch views, grant credentials, change defaults, push, insert, repair implementation or run atomic add/record. This is independent substantive inspection, not adoption of author conclusions.\n\nFrozen scope and work-intent source hashes:\n```json\n{}\n```\n\nRead the implementation, provenance and each listed work intent. Run relevant tests. For multiple views inspect per-view inputs and the combined compatible tree in {} and test interactions; do not approve separate views as an untested merge. Scope associations are context, not inferred governing ownership.\n\nReuse an appropriate group kind:review intent under your own identity, or create ONE using atomic intent new --review and explicit reviews links to every listed work intent. Record actual criterion judgments and exact scoped passing verification only when justified. Do not invent original capture evidence. Sign explicitly with --identity {}. Leave work intent definitions and lifecycle untouched. Finish your existing group review as done only if all its criteria genuinely pass; blockers must remain visible and must not yield a prepared passing publication.\n\nBefore ending this turn, for EACH views[index], run atomic triage publication-review prepare --review --view with that pin's exact roots as repeated --change. Read returned requiredVerification. Add genuine scope-check records with exact ref and observedAtMerkle to your SAME review (preserving actual test observation pins), sync/re-attest the final review revision, and re-prepare each envelope after final review edits. Save final UNSIGNED prepared envelopes to {}/prepared-.json. Do not invoke sign/record or review publish: coordinator finalizes your real session_end and only then signs eligible prepared subjects. No new views and no recursive reviews of reviews.\n\nLet normal hooks automatically record your final review turn. Do not manually call session-end or manufacture completion. Return your review ID, findings and results.\n",job.id,job.scope.views[0].name,job.scope.project,job.reviewer, - serde_json::to_string_pretty(&job.scope).map_err(bad)?,job.workdir.join("inputs").display(),job.reviewer,dir.display())) - .map(|mut brief| { - brief.push_str("\n\n"); - brief.push_str(include_str!("../../../skills/review/references/review-contract.md")); - brief - }) -} - -fn find_review(repo: &Repository, did: &str) -> CliResult { - let mut found = Vec::new(); - for info in repo.vault_intent_list(None).map_err(CliError::Repository)? { - let inputs = intent_bridge::read_intent(repo, &info.id).map_err(CliError::Repository)?; - let node = intent_bridge::lift(&inputs).map_err(CliError::Repository)?; - if node.kind == "review" && node.attributed_to.as_deref() == Some(did) { - found.push(node.id); - } - // Lifted source does not carry its proof: consult the signed revision. - else if node.kind == "review" { - if let intent_bridge::Attestation::Fresh(signed) = - intent_bridge::load_attestation(repo, &info.id, &inputs) - .map_err(CliError::Repository)? - { - if signed.attributed_to.as_deref() == Some(did) { - found.push(signed.id); - } - } - } - } - if found.len() != 1 { - return Err(invalid("publisher must produce exactly one attributable group review; missing or ambiguous review evidence")); - } - Ok(found.remove(0)) -} - -fn prepare_inputs(repo: &Repository, _dir: &Path, job: &Job) -> CliResult<()> { - if job.scope.views.len() < 2 { - return Ok(()); - } - let mut trees = Vec::new(); - let mut common: Option> = None; - // Use the shared ancestor as a real three-way baseline. If none exists, - // never pretend concatenating unrelated file trees is an integration. - let ancestry = |view: &str| -> CliResult> { - let mut names = Vec::new(); - let mut next = Some(view.to_string()); - while let Some(name) = next { - if names.contains(&name) || names.len() > 256 { - return Err(invalid("cyclic or excessive view ancestry")); - } - next = repo - .get_view_info(&name) - .map_err(CliError::Repository)? - .parent_name; - names.push(name); - } - Ok(names) + existing + } else { + let decision = ReviewDecision { + schema: review_decision::SCHEMA.into(), + reviewed_at: chrono::Utc::now().to_rfc3339(), + scope, + report_hash: hash, + report: value, + readiness: if issues.is_empty() { + Disposition::Ready + } else { + Disposition::NotReady + }, + issues, + evaluation, + independent_approval: false, + attributed_to: signer, + public_key: identity.public_key.to_base32(), + supersedes: args.supersedes.clone(), + content_hash: None, + proof: None, + }; + let pair = store.load_keypair(&identity.id, None).map_err(invalid)?; + let signed = atomic_canonical::proof::attest_value(decision.value(), &identity, &pair); + ReviewDecision::parse(&serde_json::to_vec(&signed).map_err(invalid)?).map_err(invalid)? }; - let chains = job - .scope - .views - .iter() - .map(|p| ancestry(&p.name)) - .collect::>>()?; - let ancestor = chains[0] - .iter() - .find(|name| chains.iter().all(|c| c.contains(name))) - .ok_or_else(|| invalid("view collection has no common recorded ancestor"))?; - for name in - std::iter::once(ancestor.as_str()).chain(job.scope.views.iter().map(|p| p.name.as_str())) - { - let mut tree = BTreeMap::new(); - repo.materialize_view_entries(name, |entry| { - tree.insert(entry.path.clone(), entry); - Ok::<_, CliError>(()) - }) - .map_err(CliError::Repository)??; - if common.is_none() { - common = Some(tree); - } else { - trees.push(tree); - } - } - let combined = scope::compose(&common.unwrap_or_default(), &trees)?; - let output = job.workdir.join("inputs"); - if output.exists() { - verify_inputs_tree(&output, &combined)?; - return stamp_input_sources(repo, _dir, job, &combined); - } - let staging = tempfile::Builder::new() - .prefix("inputs-stage-") - .tempdir_in(&job.workdir)?; - for (path, entry) in &combined { - let relative = Path::new(&path); - if relative - .components() - .any(|c| !matches!(c, Component::Normal(_))) - || relative.as_os_str().is_empty() - || matches!(relative.components().next(),Some(Component::Normal(n)) if n==".atomic" || n==".git" || n==".atomic-sandbox") - { - return Err(invalid("unsafe path in combined recorded snapshot")); - } - if entry.mode & !0o777 != 0 { - return Err(invalid( - "collection snapshot contains unsupported special permission bits", - )); - } - let dest = staging.path().join(relative); - if entry.kind == ViewEntryKind::Directory { - fs::create_dir_all(&dest)?; - continue; - } - if let Some(parent) = dest.parent() { - fs::create_dir_all(parent)?; - } - let mut file = OpenOptions::new() - .write(true) - .create_new(true) - .open(&dest)?; - file.write_all(&entry.content)?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(&dest, fs::Permissions::from_mode(entry.mode as u32 & 0o777))?; - } - } - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mut directories: Vec<_> = combined - .iter() - .filter(|(_, e)| e.kind == ViewEntryKind::Directory) - .collect(); - directories.sort_by_key(|(path, _)| std::cmp::Reverse(path.len())); - for (path, entry) in directories { - fs::set_permissions( - staging.path().join(path), - fs::Permissions::from_mode(entry.mode as u32), - )?; - } - } - verify_inputs_tree(staging.path(), &combined)?; - fs::rename(staging.path(), &output)?; - let _ = staging.keep(); - stamp_input_sources(repo, _dir, job, &combined)?; - Ok(()) -} - -#[derive(Debug, Serialize, Deserialize)] -struct InputSource { - path: String, - kind: ViewEntryKind, - mode: u16, - hash: String, -} - -fn stamp_input_sources( - repo: &Repository, - dir: &Path, - job: &Job, - entries: &BTreeMap, -) -> CliResult<()> { - scope::recheck(repo, &job.scope, None, None)?; - let sources: Vec<_> = entries - .values() - .map(|e| InputSource { - path: e.path.clone(), - kind: e.kind, - mode: e.mode, - hash: atomic_core::types::Hash::of(&e.content).to_base32(), - }) - .collect(); - let store = IdentityStore::open_default_existing().map_err(bad)?; - let issuer = store.load_by_name(&job.issuer).map_err(bad)?; - let key = store.load_keypair(&issuer.id, None).map_err(bad)?; - let document = json!({"schema":"atomic.review-input-sources.v1","job":job.id,"scope":job.scope,"sources":sources}); - let signed = atomic_canonical::proof::attest_value(document, &issuer, &key); - fs::write( - dir.join("inputs.json"), - serde_json::to_vec_pretty(&signed).map_err(bad)?, - )?; - Ok(()) -} - -fn recheck_input_sources(repo: &Repository, job: &Job) -> CliResult<()> { - if job.scope.views.len() < 2 { - return Ok(()); - } - let store = IdentityStore::open_default_existing().map_err(bad)?; - let issuer = store.load_by_name(&job.issuer).map_err(bad)?; - let dir = repo.dot_dir().join("review-jobs").join(&job.id); - let document = - atomic_canonical::jcs::admit_document(&fs::read(dir.join("inputs.json"))?).map_err(bad)?; - atomic_canonical::proof::verify_value(&document, &issuer.public_key).map_err(bad)?; - if document.get("job") != Some(&json!(job.id)) - || document.get("scope") != Some(&json!(job.scope)) - { - return Err(invalid( - "collection source fingerprints do not belong to the issuer-approved job", - )); - } - let sources: Vec = serde_json::from_value( - document - .get("sources") - .cloned() - .ok_or_else(|| invalid("collection source fingerprints are missing"))?, - ) - .map_err(bad)?; - verify_source_files(&job.workdir.join("inputs"), &sources) -} - -fn verify_source_files(root: &Path, sources: &[InputSource]) -> CliResult<()> { - for source in sources { - let relative = Path::new(&source.path); - if relative.as_os_str().is_empty() - || relative - .components() - .any(|c| !matches!(c, Component::Normal(_))) - { - return Err(invalid("unsafe path in collection source fingerprint")); - } - let mut path = root.to_path_buf(); - for component in relative.components() { - path.push(component.as_os_str()); - if fs::symlink_metadata(&path)?.file_type().is_symlink() { - return Err(invalid( - "publisher replaced a frozen collection source with a symlink", - )); - } - } - let metadata = fs::symlink_metadata(&path)?; - if (source.kind == ViewEntryKind::Directory) != metadata.is_dir() - || (source.kind == ViewEntryKind::File - && atomic_core::types::Hash::of(&fs::read(&path)?).to_base32() != source.hash) - { - return Err(invalid("publisher changed frozen collection source bytes; its repaired-tree test result cannot approve the original inputs")); - } - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - if metadata.permissions().mode() & 0o777 != source.mode as u32 & 0o777 { - return Err(invalid( - "publisher changed frozen collection source permissions", - )); - } - } - } - Ok(()) -} - -fn verify_inputs_tree(root: &Path, expected: &BTreeMap) -> CliResult<()> { - let mut expected_paths = BTreeSet::new(); - for (path, entry) in expected { - let relative = Path::new(path); - if relative - .components() - .any(|c| !matches!(c, Component::Normal(_))) - { - return Err(invalid("unsafe recorded input path")); - } - let mut parent = Some(relative); - while let Some(path) = parent { - if !path.as_os_str().is_empty() { - expected_paths.insert(path.to_path_buf()); - } - parent = path.parent(); - } - let actual = root.join(relative); - let metadata = fs::symlink_metadata(&actual)?; - if metadata.file_type().is_symlink() - || (entry.kind == ViewEntryKind::Directory) != metadata.is_dir() - || (entry.kind == ViewEntryKind::File && fs::read(&actual)? != entry.content) - { - return Err(invalid( - "retained collection inputs differ from the frozen recorded composition", - )); - } - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - if metadata.permissions().mode() & 0o777 != entry.mode as u32 & 0o777 { - return Err(invalid("retained collection input permissions changed")); - } - } - } - let mut actual_paths = BTreeSet::new(); - let mut pending = vec![root.to_path_buf()]; - while let Some(directory) = pending.pop() { - for entry in fs::read_dir(&directory)? { - let entry = entry?; - let path = entry.path(); - let metadata = fs::symlink_metadata(&path)?; - if metadata.file_type().is_symlink() { - return Err(invalid("unexpected symlink in retained collection inputs")); - } - actual_paths.insert(path.strip_prefix(root).map_err(bad)?.to_path_buf()); - if metadata.is_dir() { - pending.push(path); - } - } - } - if actual_paths != expected_paths { - return Err(invalid( - "retained collection inputs contain missing or extra files", - )); - } - Ok(()) -} - -fn retire_credentials(job: &mut Job) -> CliResult<()> { - if job.credentials_retired { - return Ok(()); - } - let store = IdentityStore::open_default_existing().map_err(bad)?; - let issuer = store.load_by_name(&job.issuer).map_err(bad)?; - let issuer_pair = store.load_keypair(&issuer.id, None).map_err(bad)?; - let id = atomic_identity::delegation::DelegationId::from_base32(&job.delegation) - .ok_or_else(|| invalid("invalid recording delegation ID in retained job"))?; - let revoke = atomic_canonical::delegation::mint_revocation( - &issuer, - &issuer_pair, - &id, - Some("Owned review publication finished or explicitly cancelled"), + let evidence = repo + .record_review_decision(&decision) + .map_err(CliError::Repository)?; + eprintln!( + "Retained attested review {} (report {}). No insert or push performed.", + evidence.decision, evidence.report_hash ); - store - .save_revocation( - &job.delegation, - &serde_json::to_string_pretty(&revoke).map_err(bad)?, - ) - .map_err(bad)?; - let reviewer = store.load_by_name(&job.reviewer).map_err(bad)?; - if atomic_canonical::did::did_for_public_key(&reviewer.public_key) != job.reviewer_did { - return Err(invalid("refusing to retire a different identity")); + if args.html { + let html = super::html::render_published(&repo, &report, &decision)?; + return present_html(&html, args); } - // Keep public identity material so past signatures remain verifiable. - store.retire_secret_key(&reviewer.id).map_err(bad)?; - job.credentials_retired = true; - Ok(()) -} - -fn executable(path: &Path) -> CliResult { - let candidates = if path.components().count() > 1 { - vec![path.to_path_buf()] + if args.json { + println!("{}",serde_json::to_string_pretty(&json!({"status":"attested","review":evidence,"vault_path":format!("review-decisions/{}/review.md",decision.artifact_hash()),"scope":decision.scope,"document":decision,"insertion":false,"push":false,"agent_execution":false})).map_err(invalid)?); } else { - std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()) - .map(|p| p.join(path)) - .collect() - }; - candidates.into_iter().find(|p| p.is_file()).ok_or_else(|| { - invalid(format!( - "publisher executable '{}' not found; no credentials created", - path.display() - )) - }) -} - -fn atomic_output(root: &Path, args: &[&str]) -> CliResult> { - let output = Process::new(std::env::current_exe()?) - .current_dir(root) - .args(args) - .output()?; - if !output.status.success() { - return Err(invalid(format!( - "Atomic lifecycle refused: {}", - String::from_utf8_lossy(&output.stderr) - ))); - } - Ok(output.stdout) -} - -fn run_bounded(command: &mut Process, timeout: Duration) -> CliResult { - #[cfg(unix)] - { - use std::os::unix::process::CommandExt; - command.process_group(0); - } - struct OwnedChild { - child: std::process::Child, - finished: bool, - } - impl Drop for OwnedChild { - fn drop(&mut self) { - if !self.finished { - #[cfg(unix)] - unsafe { - libc::kill(-(self.child.id() as i32), libc::SIGKILL); - } - let _ = self.child.kill(); - let _ = self.child.wait(); - } - } - } - let mut owned = OwnedChild { - child: command.spawn()?, - finished: false, - }; - let start = Instant::now(); - loop { - if let Some(status) = owned.child.try_wait()? { - owned.finished = true; - return Ok(status); - } - if start.elapsed() >= timeout { - // Drop kills only the process group created and owned here, never - // a PID restored from mutable recovery metadata. - return Err(invalid("publisher timed out; no successful session_end or publication asserted; job retained for recovery")); - } - std::thread::sleep(Duration::from_millis(100)); - } -} - -fn read_session_id(path: &Path) -> CliResult { - if fs::metadata(path)?.len() > 64 * 1024 * 1024 { - return Err(invalid("publisher output exceeds the bounded session-discovery budget; retained log was not truncated into approval")); - } - let mut ids = BTreeSet::new(); - for line in fs::read_to_string(path)?.lines() { - let Ok(value) = serde_json::from_str::(line) else { - continue; - }; - if let Some(id) = value.get("sessionID").and_then(Value::as_str) { - ids.insert(id.to_string()); + println!("Attested native review {}\nReport: {}\nEvidence readiness: {:?}\nInsertion disposition: {:?}\nAccepted degradation entries: {}\nNo agent/model, automatic insertion, or push.",evidence.decision,evidence.report_hash,evidence.readiness,evidence.disposition,evidence.accepted_degradations); + if evidence.disposition != Disposition::NotReady { + println!("Insert the same source/target using atomic insert view {} --to {}; the retained decision is revalidated at that boundary.",shell_quote(source),shell_quote(&target)); } } - if ids.len() != 1 { - return Err(invalid( - "publisher output has no unique native session identity", - )); - } - Ok(ids.into_iter().next().unwrap()) -} - -fn lock_job(dir: &Path) -> CliResult { - let file = OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) - .open(dir.join("job.lock"))?; - file.try_lock_exclusive() - .map_err(|_| invalid("publication job is already owned by another process; retry later"))?; - Ok(file) -} - -fn save_job(dir: &Path, job: &Job) -> CliResult<()> { - let mut temp = tempfile::NamedTempFile::new_in(dir)?; - temp.write_all(&serde_json::to_vec_pretty(job).map_err(bad)?)?; - temp.as_file().sync_all()?; - temp.persist(dir.join("job.json")).map_err(bad)?; Ok(()) } -fn write_immutable(path: &Path, bytes: &[u8]) -> CliResult<()> { - if fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_symlink()) { - return Err(invalid( - "immutable publication recovery output must not be a symlink", - )); - } - if path.exists() { - if fs::read(path)? == bytes { - return Ok(()); - } - return Err(invalid( - "immutable publication recovery bytes already exist and differ; refusing replacement", - )); - } - let parent = path - .parent() - .ok_or_else(|| invalid("publication receipt has no parent directory"))?; - let mut staging = tempfile::NamedTempFile::new_in(parent)?; - staging.write_all(bytes)?; - staging.as_file().sync_all()?; - match staging.persist_noclobber(path) { - Ok(_) => Ok(()), - Err(e) - if e.error.kind() == std::io::ErrorKind::AlreadyExists && fs::read(path)? == bytes => - { - Ok(()) - } - Err(e) => Err(bad(e)), - } +fn shell_quote(value: &str) -> String { + format!("'{}'", value.replace('\'', "'\\''")) } -fn output(args: &PublishArgs, job: &Job) -> CliResult<()> { - if args.json { - println!("{}", serde_json::to_string_pretty(job).map_err(bad)?); +fn present_html(html: &str, args: &PublishArgs) -> CliResult<()> { + if let Some(path) = &args.output { + fs::write(path, html)?; + if !args.no_open { + open::that(path).map_err(invalid)?; + } + } else if args.no_open { + println!("{html}"); } else { - println!("review publication {}: {}\nreview: {}\nartifacts: {}\ncredentials retired: {}\nNo insertion or push performed.",job.id,job.phase,job.review.as_deref().unwrap_or("none"),job.artifacts.len(),job.credentials_retired); + let file = tempfile::Builder::new() + .prefix("atomic-attested-review-") + .suffix(".html") + .tempfile()?; + fs::write(file.path(), html)?; + let (_file, path) = file.keep().map_err(invalid)?; + open::that(path).map_err(invalid)?; } Ok(()) } -#[cfg(test)] -mod tests { - use super::*; - use clap::Parser; - #[derive(Parser)] - struct Cli { - #[command(flatten)] - args: PublishArgs, - } - #[test] - fn scope_forms_are_exclusive() { - assert!(Cli::try_parse_from(["publish", "--view", "a,b", "--session", "s"]).is_err()); - assert!(Cli::try_parse_from(["publish", "--view", "a", "--resume", "id"]).is_err()); - assert!(Cli::try_parse_from(["publish", "--timeout-seconds", "0"]).is_err()); - } - #[test] - fn session_identity_is_never_guessed_from_ambiguous_agent_output() { - let file = tempfile::NamedTempFile::new().unwrap(); - fs::write( - file.path(), - "{\"sessionID\":\"a\"}\n{\"sessionID\":\"b\"}\n", - ) - .unwrap(); - assert!(read_session_id(file.path()).is_err()); - fs::write( - file.path(), - "{\"sessionID\":\"a\"}\n{\"sessionID\":\"a\"}\n", - ) - .unwrap(); - assert_eq!(read_session_id(file.path()).unwrap(), "a"); - } - #[test] - fn job_lock_refuses_concurrent_owners() { - let dir = tempfile::tempdir().unwrap(); - let _first = lock_job(dir.path()).unwrap(); - assert!(lock_job(dir.path()).is_err()); - } - #[test] - fn signature_recovery_bytes_are_idempotent_and_never_replaced() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("signed-0.json"); - write_immutable(&path, b"original signed bytes").unwrap(); - write_immutable(&path, b"original signed bytes").unwrap(); - assert!(write_immutable(&path, b"new approval must not replace original").is_err()); - assert_eq!(fs::read(path).unwrap(), b"original signed bytes"); - } - #[test] - fn recording_certificate_is_local_only_and_has_no_push() { - let issuer_key = KeyPair::generate(); - let issuer = Identity::new("issuer", &issuer_key); - let reviewer_key = KeyPair::generate(); - let reviewer = Identity::builder("temporary-reviewer") - .identity_type(IdentityType::Agent) - .public_key(reviewer_key.public) - .delegated_by(issuer.id) - .build() - .unwrap(); - let scope = DelegationScope::builder() - .permissions(vec![ - DelegationPermission::Read, - DelegationPermission::Record, - ]) - .server("atomic-local://project") - .project("project") - .view("view") - .max_changes(3) - .build(); - let grant = - Delegation::new(&issuer, &reviewer, scope).expires_in(chrono::Duration::minutes(30)); - let value = atomic_canonical::delegation::mint(&issuer, &issuer_key, &grant); - let encoded = atomic_canonical::delegation::encode_for_storage(&value).unwrap(); - assert!(encoded.contains("atomic-local://project")); - assert!(!encoded.contains("\"push\"")); - } - #[test] - fn collection_tests_may_add_build_outputs_but_not_repair_the_reviewed_sources() { - let dir = tempfile::tempdir().unwrap(); - let source = dir.path().join("source.ts"); - fs::write(&source, b"original").unwrap(); - #[cfg(unix)] - let mode = { - use std::os::unix::fs::PermissionsExt; - fs::metadata(&source).unwrap().permissions().mode() as u16 & 0o777 +fn inspect() -> CliResult<()> { + let root = find_repository_root()?; + let repo = Repository::open_readonly(&root).map_err(CliError::Repository)?; + let mut results = Vec::new(); + for decision in repo + .native_review_decisions() + .map_err(CliError::Repository)? + { + let validation = match repo.inspect_review_decision(&decision) { + Ok(evidence) => json!({"currently_applicable":true,"evidence":evidence}), + Err(error) => json!({"currently_applicable":false,"error":error.to_string()}), }; - #[cfg(not(unix))] - let mode = 0o644; - let sources = vec![InputSource { - path: "source.ts".into(), - kind: ViewEntryKind::File, - mode, - hash: atomic_core::types::Hash::of(b"original").to_base32(), - }]; - fs::create_dir(dir.path().join("target")).unwrap(); - fs::write(dir.path().join("target/build-output"), b"not source").unwrap(); - verify_source_files(dir.path(), &sources).unwrap(); - fs::write(&source, b"repaired by reviewer").unwrap(); - assert!(verify_source_files(dir.path(), &sources).is_err()); + results.push(json!({"kind":"native_review_decision","review":decision.artifact_hash(),"document":decision,"validation":validation})); } - #[cfg(unix)] - #[test] - fn failing_or_timed_out_runner_cannot_be_reported_successful() { - assert!(!run_bounded( - Process::new("/bin/sh").args(["-c", "exit 7"]), - Duration::from_secs(1) - ) - .unwrap() - .success()); - assert!(run_bounded( - Process::new("/bin/sleep").arg("2"), - Duration::from_millis(10) - ) - .is_err()); + let keys = atomic_repository::repository::provenance_gate::local_did_key_provider(&repo); + let config = PublicationGateConfig::from_repo(&repo).map_err(CliError::Repository)?; + for review in repo.publication_reviews().map_err(CliError::Repository)? { + let validation = match repo.validate_publication_review(&review, &config, &keys) { + Ok(value) => serde_json::to_value(value).map_err(invalid)?, + Err(error) => json!({"conforms":false,"error":error.to_string()}), + }; + results.push(json!({"kind":"retrospective_publication_review","review":review.artifact_hash(),"subject":review.subject,"document":review,"validation":validation})); } + println!( + "{}", + serde_json::to_string_pretty(&results).map_err(invalid)? + ); + Ok(()) } diff --git a/atomic-cli/src/commands/review/publish/legacy_cancel.rs b/atomic-cli/src/commands/review/publish/legacy_cancel.rs new file mode 100644 index 00000000..f990d5c6 --- /dev/null +++ b/atomic-cli/src/commands/review/publish/legacy_cancel.rs @@ -0,0 +1,114 @@ +//! Cleanup only for retained jobs created by the former agent publisher. +//! No code here can resume an agent, execute its runner, or create credentials. +use crate::error::{CliError, CliResult}; +use atomic_identity::IdentityStore; +use atomic_repository::Repository; +use fs2::FileExt; +use serde_json::{json, Value}; +use std::{fs, fs::OpenOptions, io::Write}; + +fn invalid(message: impl std::fmt::Display) -> CliError { + CliError::InvalidArgument { + message: message.to_string(), + } +} +fn text<'a>(value: &'a Value, key: &str) -> CliResult<&'a str> { + value[key] + .as_str() + .ok_or_else(|| invalid(format!("Retained job has no {key}"))) +} + +pub(super) fn cancel(repo: &Repository, id: &str, json_output: bool) -> CliResult<()> { + let id = uuid::Uuid::parse_str(id).map_err(invalid)?.to_string(); + let dir = repo.dot_dir().join("review-jobs").join(&id); + if !fs::symlink_metadata(&dir)?.file_type().is_dir() { + return Err(invalid("Legacy job path is not a regular directory")); + } + let lock = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(dir.join("job.lock"))?; + lock.try_lock_exclusive() + .map_err(|_| invalid("Legacy publication job is owned by another process; retry later"))?; + let mut job = + atomic_canonical::jcs::admit_document(&fs::read(dir.join("job.json"))?).map_err(invalid)?; + if text(&job, "id")? != id || text(&job, "schema")? != "atomic.review-job.v1" { + return Err(invalid("Legacy job identity/schema mismatch")); + } + let store = IdentityStore::open_default_existing().map_err(invalid)?; + let issuer = store.load_by_name(text(&job, "issuer")?).map_err(invalid)?; + let owner = atomic_canonical::jcs::admit_document(&fs::read(dir.join("owner.json"))?) + .map_err(invalid)?; + atomic_canonical::proof::verify_value(&owner, &issuer.public_key).map_err(invalid)?; + if owner["schema"] != "atomic.review-job-ownership.v1" || owner["job"] != job["id"] { + return Err(invalid("Legacy ownership record is not for this job")); + } + for key in [ + "scope", + "issuer", + "reviewer", + "reviewer_did", + "delegation", + "expires_at", + "workdir", + "runner", + ] { + if owner[key] != job[key] { + return Err(invalid( + "Mutable legacy job differs from its signed ownership record", + )); + } + } + if job["scope"]["project"] != repo.project_id().map_err(CliError::Repository)?.to_urn() + || text(&job, "reviewer")? != format!("review-{id}") + { + return Err(invalid("Legacy job belongs to another project or identity")); + } + let reviewer = store + .load_by_name(text(&job, "reviewer")?) + .map_err(invalid)?; + if !reviewer.identity_type.is_agent() + || reviewer.delegated_by != Some(issuer.id) + || atomic_canonical::did::did_for_public_key(&reviewer.public_key) + != text(&job, "reviewer_did")? + { + return Err(invalid( + "Refusing to retire an identity not owned by this issuer's legacy job", + )); + } + if job["credentials_retired"] != true { + let pair = store.load_keypair(&issuer.id, None).map_err(invalid)?; + let delegation = + atomic_identity::delegation::DelegationId::from_base32(text(&job, "delegation")?) + .ok_or_else(|| invalid("Invalid legacy delegation ID"))?; + let revoke = atomic_canonical::delegation::mint_revocation( + &issuer, + &pair, + &delegation, + Some("Explicit cleanup of a former agent-based review job"), + ); + store + .save_revocation( + text(&job, "delegation")?, + &serde_json::to_string_pretty(&revoke).map_err(invalid)?, + ) + .map_err(invalid)?; + store.retire_secret_key(&reviewer.id).map_err(invalid)?; + job["credentials_retired"] = json!(true); + } + if job["phase"] != "published" { + job["phase"] = json!("cancelled"); + } + let mut temp = tempfile::NamedTempFile::new_in(&dir)?; + temp.write_all(&serde_json::to_vec_pretty(&job).map_err(invalid)?)?; + temp.as_file().sync_all()?; + temp.persist(dir.join("job.json")).map_err(invalid)?; + if json_output { + println!("{}", serde_json::to_string_pretty(&job).map_err(invalid)?); + } else { + println!("Legacy review job {id} cancelled/retired. No agent was resumed and no new credentials were created."); + } + Ok(()) +} diff --git a/atomic-cli/src/commands/review/scope.rs b/atomic-cli/src/commands/review/scope.rs deleted file mode 100644 index 8af8d5d1..00000000 --- a/atomic-cli/src/commands/review/scope.rs +++ /dev/null @@ -1,564 +0,0 @@ -//! Frozen publication subjects. Collection order never chooses a winning tree. -use std::collections::{BTreeMap, BTreeSet}; - -use atomic_core::pristine::{GraphTxnT, ViewTxnT}; -use atomic_core::types::{Base32, Hash}; -use atomic_repository::{intent_bridge, Repository, ViewEntry, ViewEntryKind}; -use serde::{Deserialize, Serialize}; - -use crate::error::{CliError, CliResult}; - -pub(super) fn invalid(message: impl Into) -> CliError { - CliError::InvalidArgument { - message: message.into(), - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub(super) struct ViewPin { - pub name: String, - pub state: String, - pub members: BTreeSet, - pub roots: Vec, - pub set_id: String, - pub chain: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub(super) struct SourcePin { - pub name: String, - pub state: String, - pub scope: String, - pub log: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub(super) struct Scope { - pub project: String, - pub views: Vec, - pub source_session: Option, - pub source_manifest: Option, - pub roots: Vec, - pub closure: Vec, - pub intent_sources: BTreeMap, -} - -pub(super) fn view_names(value: &str) -> CliResult> { - let mut names = BTreeSet::new(); - for part in value.split(',') { - let name = part.trim(); - if name.is_empty() || name.chars().any(|c| c.is_control() || "*?[]{}".contains(c)) { - return Err(invalid( - "--view requires literal nonempty view names separated by commas", - )); - } - names.insert(name.to_string()); - if names.len() > 256 { - return Err(invalid( - "publication collection exceeds 256 views; no names were truncated", - )); - } - } - Ok(names.into_iter().collect()) -} - -pub(super) fn hashes(values: &[String]) -> CliResult> { - values - .iter() - .map(|value| { - Hash::from_base32(value.as_bytes()) - .filter(|h| h.to_base32() == *value) - .ok_or_else(|| invalid("review scope contains a noncanonical change hash")) - }) - .collect() -} - -fn frontier(repo: &Repository, members: &BTreeSet) -> CliResult> { - let mut roots = members.clone(); - for hash in hashes(&members.iter().cloned().collect::>())? { - let change = repo.load_change(&hash).map_err(CliError::Repository)?; - for dependency in change.dependencies() { - roots.remove(&dependency.to_base32()); - } - } - if roots.len() > 64 { - return Err(invalid("scope exceeds the canonical publication limit of 64 independent roots; nothing was truncated")); - } - Ok(roots.into_iter().collect()) -} - -fn projection_members(repo: &Repository, name: &str) -> CliResult> { - let txn = repo - .pristine() - .read_txn() - .map_err(|e| invalid(e.to_string()))?; - let view = txn - .get_view(name) - .map_err(|e| invalid(e.to_string()))? - .ok_or_else(|| invalid(format!("unknown publication view '{name}'")))?; - let closure = atomic_repository::repository::effective_projection_closure(&txn, &view) - .map_err(CliError::Repository)?; - closure - .iter_dependency_first() - .map(|id| { - txn.get_external(*id) - .map_err(|e| invalid(e.to_string()))? - .map(|h| h.to_base32()) - .ok_or_else(|| { - invalid("publication projection member has no external change identity") - }) - }) - .collect() -} - -pub(super) fn resolve( - repo: &Repository, - views: Option<&str>, - session: Option<&str>, -) -> CliResult { - let mut source_manifest = None; - let mut session_roots = None; - let names = if let Some(session) = session { - let (record, turns) = repo - .get_session_ledger(session) - .map_err(CliError::Repository)? - .ok_or_else(|| invalid(format!("unknown session '{session}'")))?; - if record.status.incomplete().is_some() { - return Err(invalid("source session has incomplete execution; review its recorded changes explicitly before publication")); - } - let roots: BTreeSet<_> = turns - .iter() - .flat_map(|t| &t.change_hashes) - .map(Base32::to_base32) - .collect(); - if roots.is_empty() { - return Err(invalid( - "pending: source session has no recorded changes to publish", - )); - } - session_roots = Some(roots); - source_manifest = repo - .get_session_head(session) - .map_err(CliError::Repository)? - .map(|h| h.to_base32()); - vec![record - .view_name - .ok_or_else(|| invalid("source session has no recorded view binding"))?] - } else { - view_names(views.unwrap_or(repo.current_view()))? - }; - let mut pins = Vec::new(); - let mut selected = BTreeSet::new(); - for name in names { - let info = repo.get_view_info(&name).map_err(CliError::Repository)?; - let direct: BTreeSet<_> = repo - .effective_history(Some(&name)) - .map_err(CliError::Repository)? - .into_iter() - .map(|entry| entry.hash.to_base32()) - .collect(); - let all = projection_members(repo, &name)?; - let members = session_roots.clone().unwrap_or(direct); - if !members.is_subset(&all) { - return Err(invalid( - "source session changes are not contained in its recorded source view", - )); - } - let roots = frontier(repo, &members)?; - selected.extend(members.iter().cloned()); - let mut chain = Vec::new(); - let mut next = Some(name.clone()); - while let Some(source) = next { - if chain.iter().any(|p: &SourcePin| p.name == source) || chain.len() >= 256 { - return Err(invalid("cyclic or excessive publication source chain")); - } - let source_info = repo.get_view_info(&source).map_err(CliError::Repository)?; - let manifest = repo.view_manifest(&source).map_err(CliError::Repository)?; - next = source_info.parent_name.clone(); - chain.push(SourcePin { - name: source, - state: source_info.state_base32(), - scope: source_info.kind_label().to_string(), - log: manifest.changes.iter().map(Base32::to_base32).collect(), - }); - } - let set_id = repo - .view_set_id(&name) - .map_err(CliError::Repository)? - .to_base32(); - if chain.first().map(|p| p.state.as_str()) != Some(info.state_base32().as_str()) - || repo - .get_view_info(&name) - .map_err(CliError::Repository)? - .state_base32() - != info.state_base32() - { - return Err(invalid("publication source changed while its scope was being frozen; retry without widening the original request")); - } - pins.push(ViewPin { - name, - state: info.state_base32(), - members: all, - roots, - set_id, - chain, - }); - } - if selected.is_empty() { - return Err(invalid( - "selected publication scope has no recorded changes", - )); - } - let roots = frontier(repo, &selected)?; - let closure = - atomic_repository::repository::provenance_gate::reachable_closure(repo, &hashes(&roots)?) - .map_err(CliError::Repository)?; - if closure.len() > 4096 { - return Err(invalid( - "publication dependency closure exceeds 4096 changes; nothing was truncated", - )); - } - let mut intent_sources = BTreeMap::new(); - for hash in &closure { - let change = repo.load_change(hash).map_err(CliError::Repository)?; - let graphs = repo - .find_provenance_for_change_scan(hash) - .map_err(CliError::Repository)?; - let context = repo.change_intent_context(hash, &change, &graphs); - let ids = context - .plans - .iter() - .filter_map(|p| p.intent.as_ref()) - .chain( - context - .associated_intents - .iter() - .filter_map(|p| p.intent.as_ref()), - ); - for identity in ids { - let inputs = - intent_bridge::read_intent(repo, &identity.uid).map_err(CliError::Repository)?; - let node = intent_bridge::lift(&inputs).map_err(CliError::Repository)?; - if node.kind != "review" { - intent_sources.insert(node.id, intent_bridge::source_content_hash(&inputs)); - } - } - } - Ok(Scope { - project: repo.project_id().map_err(CliError::Repository)?.to_urn(), - views: pins, - source_session: session.map(str::to_string), - source_manifest, - roots, - closure: closure - .iter() - .map(Base32::to_base32) - .collect::>() - .into_iter() - .collect(), - intent_sources, - }) -} - -/// Allow only the owned review's metadata additions, never implementation drift. -pub(super) fn recheck( - repo: &Repository, - scope: &Scope, - review_uid: Option<&str>, - reviewer_session: Option<&str>, -) -> CliResult<()> { - if repo.project_id().map_err(CliError::Repository)?.to_urn() != scope.project { - return Err(invalid("stale publication: project identity changed")); - } - for (id, expected) in &scope.intent_sources { - let inputs = intent_bridge::read_intent(repo, id).map_err(CliError::Repository)?; - if intent_bridge::source_content_hash(&inputs) != *expected { - return Err(invalid(format!( - "stale publication: reviewed intent '{id}' changed" - ))); - } - } - for pin in &scope.views { - for (index, source) in pin.chain.iter().enumerate() { - let manifest = repo - .view_manifest(&source.name) - .map_err(CliError::Repository)?; - if repo - .get_view_info(&source.name) - .map_err(CliError::Repository)? - .kind_label() - != source.scope - { - return Err(invalid("stale publication: a source view changed scope")); - } - let log: Vec<_> = manifest.changes.iter().map(Base32::to_base32).collect(); - if !log.starts_with(&source.log) - || manifest.parent.as_deref() != pin.chain.get(index + 1).map(|p| p.name.as_str()) - { - return Err(invalid( - "stale publication: source ancestry or ordered membership was rewritten", - )); - } - } - let now = projection_members(repo, &pin.name)?; - if !pin.members.is_subset(&now) { - return Err(invalid(format!( - "stale publication: '{}' lost recorded changes", - pin.name - ))); - } - for added in now.difference(&pin.members) { - let (Some(uid), Some(session)) = (review_uid, reviewer_session) else { - return Err(invalid(format!( - "stale publication: '{}' changed after it was frozen", - pin.name - ))); - }; - let hash = hashes(std::slice::from_ref(added))?[0]; - let change = repo.load_change(&hash).map_err(CliError::Repository)?; - if change.provenance().is_empty() - || change - .provenance() - .iter() - .any(|p| p.session_id.as_deref() != Some(session)) - { - return Err(invalid( - "stale publication: another execution changed the source view", - )); - } - let paths = repo - .change_modified_paths(&hash) - .map_err(CliError::Repository)?; - let intent_path = format!(".vault/intents/{uid}/intent.md"); - let attestation_path = format!( - ".vault/{}", - intent_bridge::attestation_vault_path(repo, uid).map_err(CliError::Repository)? - ); - if paths.is_empty() - || paths - .iter() - .any(|p| p != &intent_path && p != &attestation_path) - { - return Err(invalid("publisher modified implementation or unrelated evidence; review scope is stale")); - } - } - } - Ok(()) -} - -pub(super) fn check_prepared_context( - pin: &ViewPin, - subject: &atomic_canonical::publication_review::ReviewSubject, -) -> CliResult<()> { - let snapshot = subject - .snapshot - .as_ref() - .ok_or_else(|| invalid("prepared publication lacks an immutable source snapshot"))?; - if subject.effective_set_id != pin.set_id - || snapshot.membership != pin.members.iter().cloned().collect::>() - || subject.view_chain.len() != pin.chain.len() - || snapshot.view_logs.len() != pin.chain.len() - { - return Err(invalid( - "prepared publication context differs from the approved frozen view membership", - )); - } - for (index, (actual, expected)) in subject.view_chain.iter().zip(&pin.chain).enumerate() { - if actual.name != expected.name - || actual.state != expected.state - || actual.scope != expected.scope - || snapshot.view_logs[index] != expected.log - { - return Err(invalid( - "prepared publication source chain/log is not the approved frozen perspective", - )); - } - } - Ok(()) -} - -/// Conservative composition: unequal deltas at the same path require an -/// explicit integration view. Never pick a winner based on --view order. -pub(super) fn compose( - base: &BTreeMap, - inputs: &[BTreeMap], -) -> CliResult> { - let mut deltas: BTreeMap> = BTreeMap::new(); - for tree in inputs { - for path in base.keys().chain(tree.keys()).collect::>() { - let before = base.get(path); - let after = tree.get(path); - if equivalent(before, after) { - continue; - } - if let Some(existing) = deltas.get(path) { - if !equivalent(existing.as_ref(), after) { - return Err(invalid(format!("collection has incompatible deltas at '{path}'; record an explicit integration view first"))); - } - } else { - deltas.insert(path.clone(), after.cloned()); - } - } - } - let mut combined = base.clone(); - for (path, entry) in deltas { - match entry { - Some(entry) => { - combined.insert(path, entry); - } - None => { - combined.remove(&path); - } - } - } - if combined - .values() - .any(|e| e.kind == ViewEntryKind::Symlink || e.conflict_marker_line.is_some()) - { - return Err(invalid("collection composition refuses symlinks and unresolved conflicts; use an explicit integration view")); - } - Ok(combined) -} - -fn equivalent(a: Option<&ViewEntry>, b: Option<&ViewEntry>) -> bool { - match (a, b) { - (None, None) => true, - (Some(a), Some(b)) => a.kind == b.kind && a.mode == b.mode && a.content == b.content, - _ => false, - } -} - -#[cfg(test)] -mod tests { - use super::*; - fn file(path: &str, bytes: &[u8]) -> ViewEntry { - ViewEntry { - path: path.into(), - inode: 0, - kind: ViewEntryKind::File, - mode: 0o644, - content: bytes.into(), - hash: Hash::of(bytes), - conflict_marker_line: None, - } - } - #[test] - fn comma_views_are_literal_sorted_and_deduplicated() { - assert_eq!(view_names(" b,a,b ").unwrap(), ["a", "b"]); - for bad in ["", "a,", ",a", "a,,b", "*", "a,?"] { - assert!(view_names(bad).is_err()); - } - } - #[test] - fn disjoint_collection_changes_compose_and_order_does_not_choose_a_winner() { - let base = BTreeMap::from([("a".into(), file("a", b"old"))]); - let a = BTreeMap::from([("a".into(), file("a", b"new"))]); - let b = BTreeMap::from([ - ("a".into(), file("a", b"old")), - ("b".into(), file("b", b"new")), - ]); - let result = compose(&base, &[a.clone(), b.clone()]).unwrap(); - assert_eq!(result["a"].content, b"new"); - assert!(result.contains_key("b")); - assert_eq!( - serde_json::to_value(&result).unwrap(), - serde_json::to_value(compose(&base, &[b, a]).unwrap()).unwrap() - ); - } - #[test] - fn conflicting_edits_or_delete_write_are_refused() { - let base = BTreeMap::from([("a".into(), file("a", b"old"))]); - let a = BTreeMap::from([("a".into(), file("a", b"one"))]); - let b = BTreeMap::from([("a".into(), file("a", b"two"))]); - assert!(compose(&base, &[a.clone(), b]).is_err()); - assert!(compose(&base, &[a, BTreeMap::new()]).is_err()); - } - #[test] - fn prepared_context_must_match_frozen_membership_and_ordered_ancestry() { - use atomic_canonical::publication_review::{ - IntentPin, ReviewSnapshot, ReviewSubject, ReviewViewPin, - }; - let pin = ViewPin { - name: "v".into(), - state: "state".into(), - members: BTreeSet::from(["original".into()]), - roots: vec!["original".into()], - set_id: "set".into(), - chain: vec![SourcePin { - name: "v".into(), - state: "state".into(), - scope: "draft".into(), - log: vec!["original".into()], - }], - }; - let mut subject = ReviewSubject { - project: "p".into(), - roots: pin.roots.clone(), - changes: vec![], - review: IntentPin { - id: "review".into(), - source_hash: "s".into(), - signed_hash: "h".into(), - public_key: "k".into(), - }, - work: vec![], - set_aside: vec![], - profile_hash: "policy".into(), - view_chain: vec![ReviewViewPin { - name: "v".into(), - state: "state".into(), - scope: "draft".into(), - }], - effective_set_id: "set".into(), - snapshot: Some(ReviewSnapshot { - version: 1, - view_logs: vec![vec!["original".into()]], - membership: vec!["original".into()], - intent_revisions: vec![], - }), - }; - assert!(check_prepared_context(&pin, &subject).is_ok()); - subject - .snapshot - .as_mut() - .unwrap() - .membership - .push("foreign".into()); - assert!(check_prepared_context(&pin, &subject).is_err()); - subject.snapshot.as_mut().unwrap().membership = vec!["original".into()]; - subject.view_chain[0].state = "other".into(); - assert!(check_prepared_context(&pin, &subject).is_err()); - } - - #[test] - fn frozen_membership_includes_dependency_only_projection_members() { - use atomic_core::change::{Change, ChangeHeader}; - use atomic_core::pristine::MutTxnT; - let dir = tempfile::tempdir().unwrap(); - let repo = Repository::init(dir.path()).unwrap(); - repo.init_vault().unwrap(); - let dependency = repo - .save_change(&Change::empty(ChangeHeader::new("dependency context"))) - .unwrap(); - let mut change = Change::empty(ChangeHeader::new("selected root")); - change.hashed.dependencies.push(dependency); - let root = repo.save_change(&change).unwrap(); - let mut txn = repo.pristine().write_txn().unwrap(); - let dependency_id = txn.register_change(&dependency).unwrap(); - let root_id = txn.register_change(&root).unwrap(); - txn.put_dep(root_id, dependency_id).unwrap(); - txn.put_change_deps(dependency_id, &[]).unwrap(); - txn.put_change_deps(root_id, &[dependency]).unwrap(); - let mut view = txn.get_view("dev").unwrap().unwrap(); - txn.put_change(&mut view, root_id, &root).unwrap(); - txn.update_view(&view).unwrap(); - txn.commit().unwrap(); - let frozen = resolve(&repo, Some("dev"), None).unwrap(); - assert_eq!(frozen.roots, vec![root.to_base32()]); - assert_eq!( - frozen.views[0].members, - BTreeSet::from([root.to_base32(), dependency.to_base32()]) - ); - recheck(&repo, &frozen, None, None).unwrap(); - } -} diff --git a/atomic-cli/src/commands/review/terminal.rs b/atomic-cli/src/commands/review/terminal.rs index bcb37816..7caf75c3 100644 --- a/atomic-cli/src/commands/review/terminal.rs +++ b/atomic-cli/src/commands/review/terminal.rs @@ -16,7 +16,7 @@ pub(super) fn render(graph: &ReviewGraph, details: bool) -> String { graph.scope.view, graph.scope.view_state, graph.findings.len(), - if let Some(comparison)=comparison {format!("View comparison: BEFORE {} -> AFTER {}",comparison.properties["from"]["view"].as_str().unwrap_or("?"),comparison.properties["to"]["view"].as_str().unwrap_or("?"))} else if snapshot.is_some(){format!("Selected view snapshot: {}",graph.scope.view)}else{format!("Selected changes: {}",graph.scope.selected_roots.join(", "))} + if let Some(comparison)=comparison {format!("Review source {} -> target {}\nMeasurements: BEFORE {} -> AFTER {}",comparison.properties["from"]["view"].as_str().unwrap_or("?"),comparison.properties["to"]["view"].as_str().unwrap_or("?"),comparison.properties["before"]["view"].as_str().unwrap_or("?"),comparison.properties["after"]["view"].as_str().unwrap_or("?"))} else if snapshot.is_some(){format!("Selected view snapshot: {}",graph.scope.view)}else{format!("Selected changes: {}",graph.scope.selected_roots.join(", "))} ); if let Some(snapshot) = snapshot { writeln!( diff --git a/atomic-cli/src/commands/review/view_comparison.rs b/atomic-cli/src/commands/review/view_comparison.rs index 352d27dd..fbd7869f 100644 --- a/atomic-cli/src/commands/review/view_comparison.rs +++ b/atomic-cli/src/commands/review/view_comparison.rs @@ -114,8 +114,12 @@ pub struct ComparedFile { #[derive(Debug, Serialize)] pub struct ViewComparison { pub source_ref: String, + /// Proposed source and insertion destination (CLI direction). pub from: ViewPin, pub to: ViewPin, + /// Destination baseline and proposed source state (measurement direction). + pub before: ViewPin, + pub after: ViewPin, pub files: Vec, pub diagnostics: Vec, pub conformance: conformance::Conformance, @@ -150,16 +154,16 @@ pub(super) fn resolve(repo: &Repository, args: &IncrementalArgs) -> CliResult CliResult CliResult {to}")),reason:"From is the recorded before state; To is the recorded after state. Both complete view corpora are inspected locally.".into() }; + after.selection=Selection { kind:"view_comparison".into(),value:Some(format!("{from} -> {to}")),reason:"From is the proposed source view; To is the insertion destination. Measurements compare target-before with source-after, using both complete recorded corpora.".into() }; after.source["from_view"] = json!(from); after.source["from_state"] = json!(comparison.from.state); + after.source["to_view"] = json!(to); + after.source["to_state"] = json!(comparison.to.state); + after.source["before_view"] = json!(to); + after.source["after_view"] = json!(from); let mut refs = BTreeMap::new(); for reference in before .dependency_references @@ -294,7 +304,7 @@ pub(super) fn resolve(repo: &Repository, args: &IncrementalArgs) -> CliResult AFTER {to}. No view switch, working-copy bytes, model or network calls."), + format!("Local review source {from} -> target {to}; measurements BEFORE {to} -> AFTER {from}. No view switch, working-copy bytes, model or network calls."), "Audit lifecycles compare local rule/AST observations within recorded file identities and qualified metric owners. Changed/unknown observations are not fabricated resolutions or proof of behavioral equivalence.".into(), "Each side uses the same explicit semantic/metric bounds as --view. Unsupported, unavailable and over-budget data stay unknown, not absent or zero.".into(), "Metric comparisons use the complete supplied corpus on each side. Renames are based on canonical recorded inode identity, never filename/content similarity.".into(), diff --git a/atomic-cli/src/commands/review/view_comparison/conformance.rs b/atomic-cli/src/commands/review/view_comparison/conformance.rs index 8f6dfadd..a636e794 100644 --- a/atomic-cli/src/commands/review/view_comparison/conformance.rs +++ b/atomic-cli/src/commands/review/view_comparison/conformance.rs @@ -105,45 +105,22 @@ struct CurrentScope { diagnostics: Vec, } -fn vault_path(path: &str) -> String { - if path.starts_with(".vault/") { - path.into() - } else { - format!(".vault/{path}") - } -} - fn current_scope(repo: &Repository, view: &str) -> CliResult { - let manifest = if repo.has_vault().map_err(CliError::Repository)? { - repo.vault_manifest().map_err(CliError::Repository)? - } else { - Default::default() - }; + let bridge::ViewIntentSources { + entries, + hash, + mut diagnostics, + } = bridge::view_intent_sources(repo, view).map_err(CliError::Repository)?; let mut intents = Vec::new(); - let mut inventory = BTreeMap::new(); - let mut diagnostics = Vec::new(); - for (key, summary) in manifest.intents { - let inputs = if summary.vault_path.is_empty() { - bridge::read_intent(repo, &key).map_err(CliError::Repository)? - } else { - let Some(entry) = repo - .vault_retrieve(summary.vault_path.trim_start_matches(".vault/")) - .map_err(CliError::Repository)? - else { - inventory.insert(key.clone(), "missing_definition".into()); - diagnostics.push(format!( - "{key}: vault definition missing; view assignment unavailable" - )); - continue; - }; - bridge::inputs_from_entry(&entry).map_err(CliError::Repository)? - }; - if inputs.frontmatter.get("view").and_then(Value::as_str) != Some(view) { - continue; - } - let hash = bridge::source_content_hash(&inputs); - inventory.insert(key.clone(), hash.clone()); - let path = vault_path(&summary.vault_path); + for source in entries { + let bridge::ViewIntentSource { + key, + path, + inputs, + hash, + fallback_title, + fallback_status, + } = source; let lifted = bridge::lift(&inputs); let (node, error) = match lifted { Ok(node) => (Some(node), None), @@ -168,13 +145,13 @@ fn current_scope(repo: &Repository, view: &str) -> CliResult { .frontmatter .get("title") .and_then(Value::as_str) - .unwrap_or(&summary.title) + .unwrap_or(&fallback_title) .into(), status: inputs .frontmatter .get("status") .and_then(Value::as_str) - .unwrap_or(&summary.status) + .unwrap_or(&fallback_status) .into(), view: view.into(), source_kind: "current_vault_context".into(), @@ -191,10 +168,6 @@ fn current_scope(repo: &Repository, view: &str) -> CliResult { }); intents.push(CurrentIntent { row, definition }); } - let hash = Hash::of( - &serde_json::to_vec(&inventory).map_err(|error| CliError::Internal(error.into()))?, - ) - .to_base32(); Ok(CurrentScope { intents, hash, @@ -291,8 +264,8 @@ pub(super) fn collect( } } let sources = Sources { - before: Some(&comparison.from.view), - after: &comparison.to.view, + before: Some(&comparison.before.view), + after: &comparison.after.view, paths: files.keys().cloned().collect(), files, }; diff --git a/atomic-cli/src/commands/review/view_comparison/impact.rs b/atomic-cli/src/commands/review/view_comparison/impact.rs index aa7a52ae..d21ccb1e 100644 --- a/atomic-cli/src/commands/review/view_comparison/impact.rs +++ b/atomic-cli/src/commands/review/view_comparison/impact.rs @@ -7,8 +7,8 @@ use std::collections::BTreeSet; use super::ViewComparison; pub(in super::super) fn changed_paths(comparison: &ViewComparison) -> Vec { - if comparison.from.state == comparison.to.state - && comparison.from.membership_hash == comparison.to.membership_hash + if comparison.before.state == comparison.after.state + && comparison.before.membership_hash == comparison.after.membership_hash { return vec![]; } @@ -55,8 +55,8 @@ pub(in super::super) fn inspect( result.gaps.push("Changed paths have no supported semantic source; configuration/non-code runtime effects are not inferred".into()); } else { match ( - repo.semantic_view_on_view(&comparison.from.view), - repo.semantic_view_on_view(&comparison.to.view), + repo.semantic_view_on_view(&comparison.before.view), + repo.semantic_view_on_view(&comparison.after.view), ) { (Ok(before), Ok(after)) => { result = super::super::impact::inspect_views( diff --git a/atomic-cli/src/commands/review/viewer.html b/atomic-cli/src/commands/review/viewer.html index 8038874a..d1b25d84 100644 --- a/atomic-cli/src/commands/review/viewer.html +++ b/atomic-cli/src/commands/review/viewer.html @@ -23,7 +23,7 @@
-

Review summary

+

Review summary

diff --git a/atomic-cli/src/commands/review/viewer.js b/atomic-cli/src/commands/review/viewer.js index d681aaea..8e029074 100644 --- a/atomic-cli/src/commands/review/viewer.js +++ b/atomic-cli/src/commands/review/viewer.js @@ -3,8 +3,13 @@ const data = JSON.parse(document.getElementById('review-data').textContent); const report = data.view; const graph = report.graph; + const decision = data.review_decision; + const degradationAcceptances = new Map((decision?.evaluation.passes || []).flatMap(pass=>pass.accepted_degradations.map(entry=>[entry.issue,entry]))); + const acceptedFor = reference => (decision?.issues || []).filter(issue=>issue.reference===reference && degradationAcceptances.has(issue.id)).map(issue=>({issue,acceptance:degradationAcceptances.get(issue.id)})); const viewSnapshot = report.view_snapshot; const viewComparison = report.view_comparison; + const comparisonBefore = viewComparison?.before || viewComparison?.from; + const comparisonAfter = viewComparison?.after || viewComparison?.to; const viewConformance = viewComparison?.conformance || viewSnapshot?.conformance; const comparedFiles = new Map((viewComparison?.files || []).map(file=>[file.source_ref,file])); const regions = data.regions; @@ -151,10 +156,12 @@ const heading = el('h3'); heading.append(el('span', 'finding-number', 'F' + number), el('span', '', finding.summary), badge(title(finding.severity), finding.severity)); if (item.comparison) heading.append(badge(title(item.comparison.status),item.comparison.status)); + if(acceptedFor(item.id).length)heading.append(badge('Accepted degradation','changed')); host.append(heading); const links = el('div', 'callouts'); links.append(cardCallout(finding.requirement_or_rule.id, 'Audit: ' + (auditCards.get(finding.requirement_or_rule.id)?.title || finding.requirement_or_rule.id))); host.append(links, el('p', 'region-meta', viewComparison ? `Confidence: ${title(finding.confidence)} · ${title(item.comparison?.status || 'unknown')} local observation between the selected views` : `Confidence: ${title(finding.confidence)} · Introduced by this change: ${finding.introduced_by_change.status}`)); + const acceptance=acceptanceBlock(item.id);if(acceptance)host.append(acceptance); const evidence = el('div', 'evidence'); if (item.comparison) evidence.append(el('p','',item.comparison.rationale)); evidence.append(el('p', '', finding.introduced_by_change.rationale)); @@ -168,6 +175,18 @@ return host; } + function acceptanceBlock(reference) { + const entries=acceptedFor(reference);if(!entries.length)return null; + const host=el('div'); + host.append(el('p','muted',`Signer ${decision.signer} explicitly accepted this degradation in attested review ${decision.id}. The finding/unknown state has not been removed or relabelled ready.`)); + for(const {issue,acceptance} of entries) { + host.append(el('p','source-path',issue.id),el('p','',acceptance.rationale)); + for(const evidence of acceptance.evidence)host.append(el('p','source-path',evidence)); + if(acceptance.follow_up)host.append(el('p','','Follow-up: '+acceptance.follow_up)); + } + return detail('Attested accepted degradation — risk remains',host); + } + function metricTable(region) { const host = el('section', 'metrics-block'); const own = region.metrics.length ? region.metrics : region.context_metrics; @@ -239,7 +258,7 @@ const diff = button('Recorded change diff', () => { side = 'diff'; update(); }); const expand = button('Show full file', () => { full = !full; update(); }); if (viewSnapshot) { before.hidden = true; diff.hidden = true; after.textContent = 'View snapshot'; side = 'after'; } - if (viewComparison) { diff.hidden=true;before.textContent='Before: '+viewComparison.from.view;after.textContent='After: '+viewComparison.to.view; } + if (viewComparison) { diff.hidden=true;before.textContent='Before: '+comparisonBefore.view;after.textContent='After: '+comparisonAfter.view; } toolbar.append(before, after, diff, expand); host.append(toolbar, body, caption); function update() { @@ -259,7 +278,7 @@ if (!source || source.status !== 'present') { body.append(el('p', 'empty', source?.status === 'absent' ? 'This file is absent in this recorded revision.' : source?.reason || 'Recorded source was not exported. No working-copy bytes are substituted.')); expand.hidden = true; - caption.textContent = viewComparison ? `${side==='before'?'Before':'After'} view ${viewComparison[side==='before'?'from':'to'].view}` : viewSnapshot ? `Recorded view ${viewSnapshot.view} @ ${viewSnapshot.state}` : `${side} snapshot · change ${region.change}`; + caption.textContent = viewComparison ? `${side==='before'?'Before':'After'} view ${(side==='before'?comparisonBefore:comparisonAfter).view}` : viewSnapshot ? `Recorded view ${viewSnapshot.view} @ ${viewSnapshot.state}` : `${side} snapshot · change ${region.change}`; return; } const range = counterpart(region, side); @@ -275,7 +294,7 @@ } body.append(code); expand.textContent = full ? 'Show region context' : 'Show full file'; - const compared=comparedFiles.get(region.change), pin=viewComparison?.[side==='before'?'from':'to']; + const compared=comparedFiles.get(region.change), pin=side==='before'?comparisonBefore:comparisonAfter; caption.textContent = viewComparison ? `${side==='before'?'Before':'After'} ${pin.view}: ${compared?.[side+'_path'] || region.path}, lines ${start}–${end} of ${lines.length}. State ${pin.state}. ${range.note}.` : viewSnapshot ? `Recorded view ${viewSnapshot.view}: lines ${start}–${end} of ${lines.length}. State ${viewSnapshot.state}. No working-copy bytes or before revision.` : `Recorded ${side}: lines ${start}–${end} of ${lines.length}. ${range.note}. ${snapshot.reviewed_root ? 'Selected source file.' : 'Caller context only, not an additional reviewed root.'}`; } update(); @@ -434,7 +453,7 @@ function comparisonOverview() { const host=el('div'), direction=el('div','comparison-direction'); - for (const [index,[label,pin]] of [['From · before',viewComparison.from],['To · after',viewComparison.to]].entries()) { + for (const [index,[label,pin]] of [['From · source (after)',viewComparison.from],['To · target (before)',viewComparison.to]].entries()) { if (index) direction.append(el('span','direction-arrow','→')); const side=el('div');side.append(el('small','',label),el('strong','',pin.view),el('small','',`state ${pin.state.slice(0,12)} · filter ${pin.membership_hash.slice(0,12)}`));direction.append(side); } @@ -502,7 +521,7 @@ if (viewComparison) { const conformance=viewComparison.conformance; const changes=conformance?.changes || []; - host.append(el('p','',`${changes.filter(change=>change.direction==='added_to_after').length} recorded change(s) added to To · ${changes.filter(change=>change.direction==='removed_from_after').length} removed from From · ${(conformance?.criteria || []).length} criterion/criteria in scope`)); + host.append(el('p','',`${changes.filter(change=>change.direction==='added_to_after').length} recorded change(s) only in source · ${changes.filter(change=>change.direction==='removed_from_after').length} only in target · ${(conformance?.criteria || []).length} criterion/criteria in scope`)); const evidence=el('div'); for(const change of changes) evidence.append(el('p','',`${title(change.direction)} · ${change.hash} · governing intent: ${change.intent_context.status}`)); for(const note of conformance?.diagnostics || []) evidence.append(el('p','muted',note)); @@ -524,11 +543,12 @@ if (!criterion) { host.append(el('p', 'empty', 'No scoped criterion assessment is available. File overlap and author completion claims are not acceptance evidence.')); return; } const article = el('article', 'criterion'), heading = el('div', 'criterion-title'); heading.append(badge('Review: ' + title(criterion.review_assessment), criterion.review_assessment), badge('Author declared: ' + criterion.declared_status, 'declared')); + if(acceptedFor(criterion.id).length)heading.append(badge('Accepted degradation','changed')); article.append(heading, el('h2', '', criterion.text), el('small', '', `Criterion ${criterion.id}`), el('small', '', `Intent ${criterion.intent}`)); article.append(detail('Criteria source and authentication', el('pre', '', viewConformance ? `Definition hash: ${criterion.source_hash}\nRecorded view definitions are preferred; any current-vault fallback is labelled context only. Recorded author verification claims are not independently re-executed or authenticated acceptance proof.` : `Current source hash: ${criterion.source_hash}\nCurrent intent definitions are source-hashed context, not authenticated historical criteria. A report-local judgment is not independent signed approval.`))); if(viewConformance) { const compared=viewConformance.criteria.find(item=>item.id===criterion.id); - for(const [label,declaration] of [['From · before',compared?.before],[viewSnapshot?'Recorded view · '+viewSnapshot.view:'To · after',compared?.after],['Current vault · context only',compared?.current_context]]) { + for(const [label,declaration] of [['Target · before',compared?.before],[viewSnapshot?'Recorded view · '+viewSnapshot.view:'Source · after',compared?.after],['Current vault · context only',compared?.current_context]]) { if(!declaration)continue; const section=el('section','criterion-declaration'); section.append(el('h3','',label),el('p','',declaration.text),el('p','region-meta',`Author declared: ${declaration.status} · ${declaration.source_kind} · ${declaration.view || 'not a pinned historical view'} · ${declaration.path} · ${declaration.source_hash}`)); @@ -548,6 +568,7 @@ } } host.append(article); + const acceptance=acceptanceBlock(criterion.id);if(acceptance)host.append(acceptance); for (const number of criterion.findings) { host.append(findingBlock(number)); const links = el('div', 'callouts'); @@ -601,6 +622,26 @@ } function renderSummary() { + if(decision) { + const host=$('summary-decision');host.className='overview'; + host.append(el('h2','','Attested review decision'),el('p','',`Evidence readiness: ${title(decision.readiness)} · User insertion disposition: ${title(decision.disposition)}`),el('p','muted',`Accountable signer: ${decision.signer}. This records explicit evaluation and accepted risks, not a clean-code or independent-approval claim.`),el('p','source-path',`Review ${decision.id} · Report ${decision.report_hash}`)); + for(const pass of decision.evaluation.passes) { + const row=el('section','criterion-declaration');row.dataset.passEvaluation=pass.pass; + row.append(el('h3','',title(pass.pass)+' · '+title(pass.disposition)),el('p','',pass.rationale)); + host.append(row); + } + const issues=el('div'); + for(const issue of decision.issues) { + const acceptance=degradationAcceptances.get(issue.id),row=el('article','finding'); + row.dataset.reviewIssue=issue.id; + row.append(el('h3','',title(issue.pass)+' · '+issue.summary),badge(acceptance?'Accepted degradation':issue.waivable?'Not accepted':'Not waivable',acceptance?'changed':'high'),el('p','source-path',issue.id),el('p','',acceptance?.rationale || 'No acceptance of this issue was attested.')); + for(const entry of issue.evidence)row.append(el('p','source-path',entry)); + for(const entry of acceptance?.evidence || [])row.append(el('p','source-path','Acceptance evidence: '+entry)); + if(acceptance?.follow_up)row.append(el('p','','Follow-up: '+acceptance.follow_up)); + issues.append(row); + } + host.append(detail(`Outstanding evidence and explicit dispositions (${decision.issues.length})`,issues)); + } const actions = $('summary-actions'); for (const [section, label] of [['slop', 'Review audit findings'], ['conformance', 'Review conformance'], ['risk', 'Review blast radius']]) { const control = button(label, () => { activate(section); $('tab-' + section).focus(); }); @@ -676,6 +717,7 @@ $('risk-status').textContent = risk ? `${title(risk.assessment.rating)} · ${title(risk.assessment.coverage)}` : 'Unavailable'; $('provenance').append(el('h2', '', 'Recorded review scope'), el('pre', '', JSON.stringify(graph.scope, null, 2)), el('h3', '', 'Scope notes'), el('pre', '', [...graph.diagnostics, ...report.warnings].join('\n')), el('p', '', 'Additional source snapshots are bounded exports from this recorded scope. Working-copy bytes are never substituted. Keep this artifact private if its source/evidence is sensitive.')); if (typeof DecompressionStream !== 'function') $('download').textContent = 'Download JSON.gz'; + else if(decision)$('download').textContent='Download attested JSON'; $('download').addEventListener('click', async () => { const control = $('download'), label = control.textContent; control.disabled = true; control.textContent = 'Preparing JSON…'; diff --git a/atomic-cli/src/commands/rpc.rs b/atomic-cli/src/commands/rpc.rs index aa513c25..73a9f7a4 100644 --- a/atomic-cli/src/commands/rpc.rs +++ b/atomic-cli/src/commands/rpc.rs @@ -3969,6 +3969,24 @@ fn insert_cross_view_outcome( response: &pb::InsertChangesResponse, ) -> atomic_repository::CrossViewInsertOutcome { atomic_repository::CrossViewInsertOutcome { + review_decision: response.review_decision.as_ref().map(|review| { + let disposition = |value: &str| match value { + "ready" => atomic_canonical::review_decision::Disposition::Ready, + "accepted_degradation" => { + atomic_canonical::review_decision::Disposition::AcceptedDegradation + } + _ => atomic_canonical::review_decision::Disposition::NotReady, + }; + atomic_repository::repository::ReviewDecisionEvidence { + decision: review.decision.clone(), + report_hash: review.report_hash.clone(), + readiness: disposition(&review.readiness), + disposition: disposition(&review.disposition), + accepted_degradations: usize::try_from(review.accepted_degradations) + .unwrap_or(usize::MAX), + signer: review.signer.clone(), + } + }), changes_applied: response.inserted.len(), applied_hashes: insert_applied_hashes(response), skipped_hashes: vec![Merkle::ZERO; response.skipped_count as usize], diff --git a/atomic-cli/src/main.rs b/atomic-cli/src/main.rs index 45938d83..24a24629 100644 --- a/atomic-cli/src/main.rs +++ b/atomic-cli/src/main.rs @@ -935,7 +935,7 @@ enum Commands { /// with no arguments asks whether the current view is ready to promote. Triage(Triage), - /// Inspect a recorded turn/intent/change, or independently publish view reviews. + /// Review recorded work, or attest native source-to-target readiness and accepted risk. Review(Review), /// Generate a shell completion script. diff --git a/atomic-cli/tests/review_comparison.rs b/atomic-cli/tests/review_comparison.rs index 6e2c94ed..889ea8b1 100644 --- a/atomic-cli/tests/review_comparison.rs +++ b/atomic-cli/tests/review_comparison.rs @@ -42,8 +42,8 @@ fn command(root: &Path, args: &[&str]) -> std::process::Output { .output() .unwrap() } -fn review(root: &Path, from: &str, to: &str) -> Value { - let output = command(root, &["review", "--from", from, "--to", to, "--json"]); +fn review(root: &Path, before: &str, after: &str) -> Value { + let output = command(root, &["review", "--from", after, "--to", before, "--json"]); assert!( output.status.success(), "{}", @@ -159,10 +159,12 @@ fn compare_recorded_views_in_both_directions_without_touching_the_working_copy() let db_bytes = std::fs::read(&database).unwrap(); let report = review(directory.path(), &from, "after"); - assert_eq!(report["schema_version"], 4); + assert_eq!(report["schema_version"], 5); assert_eq!(report["selection"]["kind"], "view_comparison"); - assert_eq!(report["view_comparison"]["from"]["view"], from); - assert_eq!(report["view_comparison"]["to"]["state"], expected_after); + assert_eq!(report["view_comparison"]["from"]["view"], "after"); + assert_eq!(report["view_comparison"]["to"]["view"], from); + assert_eq!(report["view_comparison"]["after"]["state"], expected_after); + assert_eq!(report["view_comparison"]["before"]["view"], from); assert!(report["changes"].as_array().unwrap().is_empty()); assert!(report["selected_roots"].as_array().unwrap().is_empty()); assert!(report.get("view_snapshot").is_none()); @@ -292,9 +294,9 @@ fn compare_recorded_views_in_both_directions_without_touching_the_working_copy() &[ "review", "--from", - &from, - "--to", "after", + "--to", + &from, "--html", "--no-open", ], @@ -339,7 +341,7 @@ fn compare_recorded_views_in_both_directions_without_touching_the_working_copy() assert_eq!(restored, report); let terminal = command( directory.path(), - &["review", "--from", &from, "--to", "after"], + &["review", "--from", "after", "--to", &from], ); assert!(terminal.status.success()); assert!(String::from_utf8_lossy(&terminal.stdout) diff --git a/atomic-cli/tests/review_comparison_passes.rs b/atomic-cli/tests/review_comparison_passes.rs index 2574e954..f898ff46 100644 --- a/atomic-cli/tests/review_comparison_passes.rs +++ b/atomic-cli/tests/review_comparison_passes.rs @@ -175,10 +175,10 @@ fn command(root: &Path, args: &[&str]) -> String { ); String::from_utf8(output.stdout).unwrap() } -fn review(root: &Path, from: &str, to: &str) -> Value { +fn review(root: &Path, before: &str, after: &str) -> Value { serde_json::from_str(&command( root, - &["review", "--from", from, "--to", to, "--json"], + &["review", "--from", after, "--to", before, "--json"], )) .unwrap() } @@ -306,9 +306,9 @@ fn unlinked_view_intents_are_scoped_to_the_requested_view_not_the_active_view() vec![ "review", "--from", - base.as_str(), - "--to", "target", + "--to", + base.as_str(), "--html", "--no-open", ], @@ -401,9 +401,9 @@ fn recorded_view_assignment_survives_dirty_or_missing_current_vault_definitions( &[ "review", "--from", - &base, - "--to", "target", + "--to", + &base, "--html", "--no-open", ], @@ -565,9 +565,9 @@ fn pinned_conformance_and_semantic_blast_radius_export_every_contract_finding() &[ "review", "--from", - &from, - "--to", "after", + "--to", + &from, "--html", "--no-open", ], @@ -607,7 +607,7 @@ fn pinned_conformance_and_semantic_blast_radius_export_every_contract_finding() let archive: Value = serde_json::from_reader(flate2::read::GzDecoder::new(compressed.as_slice())).unwrap(); assert_eq!(archive, report); - let terminal = command(dir.path(), &["review", "--from", &from, "--to", "after"]); + let terminal = command(dir.path(), &["review", "--from", "after", "--to", &from]); assert!( terminal.contains("RECORDED_CONTRACT_CRITERION") && terminal.contains("137 current bound caller(s)") diff --git a/atomic-cli/tests/review_publish_native.rs b/atomic-cli/tests/review_publish_native.rs new file mode 100644 index 00000000..f3555c7b --- /dev/null +++ b/atomic-cli/tests/review_publish_native.rs @@ -0,0 +1,406 @@ +//! Provider-free native publication, explicit degradation, and insertion linkage. +use atomic_core::{ + change::ChangeHeader, + pristine::OperationTxnT, + types::{Base32, Hash}, +}; +use atomic_identity::{Identity, IdentityStore, KeyPair}; +use atomic_repository::{record::RecordOptions, tracking::TrackingOptions, Repository}; +use serde_json::Value; +use std::{ + path::PathBuf, + process::{Command, Output}, +}; + +struct Fixture { + root: tempfile::TempDir, + global: tempfile::TempDir, + base: String, +} +impl Fixture { + fn new(callers: usize) -> Self { + let root = tempfile::tempdir().unwrap(); + let global = tempfile::tempdir().unwrap(); + let mut repo = Repository::init(root.path()).unwrap(); + repo.init_vault().unwrap(); + let base = repo.current_view().to_owned(); + let wc = repo.require_working_copy_id().unwrap(); + std::fs::create_dir_all(root.path().join("src")).unwrap(); + std::fs::write( + root.path().join("src/lib.rs"), + "mod consumers;\npub fn work(a:i32) {}\n", + ) + .unwrap(); + std::fs::write( + root.path().join("src/consumers.rs"), + (0..callers) + .map(|index| format!("pub fn consumer_{index}() {{ crate::work(1); }}\n")) + .collect::(), + ) + .unwrap(); + repo.add(wc, "src", TrackingOptions::default()).unwrap(); + repo.add(wc, ".vault", TrackingOptions::default()).unwrap(); + record(&repo); + repo.create_draft_view("draft", &base).unwrap(); + repo.switch_view(wc, "draft").unwrap(); + std::fs::write( + root.path().join("src/lib.rs"), + "mod consumers;\npub fn work(a:i32,b:i32) { todo!(); }\n", + ) + .unwrap(); + record(&repo); + drop(repo); + Self { root, global, base } + } + fn run(&self, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_atomic")) + .current_dir(self.root.path()) + .env("ATOMIC_CONFIG_DIR", self.global.path()) + .env("PATH", self.global.path().join("no-executables")) + .env("ATOMIC_SESSION_ID", "../must-not-be-used") + .env_remove("OPENAI_API_KEY") + .env_remove("ANTHROPIC_API_KEY") + .env_remove("GITHUB_TOKEN") + .env("OPENAI_BASE_URL", "http://127.0.0.1:1") + .env("ANTHROPIC_BASE_URL", "http://127.0.0.1:1") + .args(args) + .output() + .unwrap() + } + fn json(&self, args: &[&str]) -> Value { + let output = self.run(args); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).unwrap() + } + fn plan(&self) -> Value { + self.json(&[ + "review", + "publish", + "--from", + "draft", + "--to", + &self.base, + "--dry-run", + "--json", + ]) + } + fn signer(&self) -> Identity { + let pair = KeyPair::generate(); + let identity = Identity::new("reviewer", &pair); + let mut store = IdentityStore::open(&self.global.path().join("identities")).unwrap(); + store.save_with_keypair(&identity, &pair, None).unwrap(); + store.set_default(&identity.id).unwrap(); + let repo = Repository::open(self.root.path()).unwrap(); + let path = repo.dot_dir().join("config.toml"); + let mut config = atomic_config::RepoConfig::load(&path).unwrap(); + config.git.trust.signers = vec![atomic_canonical::did::did_for_public_key( + &identity.public_key, + )]; + config.save(&path).unwrap(); + identity + } + fn evaluate(&self, mut plan: Value, not_ready: bool) -> PathBuf { + let evaluation = &mut plan["evaluation_template"]; + for pass in evaluation["passes"].as_array_mut().unwrap() { + pass["evaluated"] = Value::Bool(true); + pass["rationale"] = Value::String( + "Responsible test signer evaluated the complete recorded pass and its limits" + .into(), + ); + for issue in pass["accepted_degradations"].as_array_mut().unwrap() { + issue["rationale"]=Value::String("Known degradation explicitly accepted for this fixture's bounded rollout; compatibility follow-up is required".into()); + } + } + if not_ready { + evaluation["passes"][0]["disposition"] = Value::String("not_ready".into()); + evaluation["passes"][0]["accepted_degradations"] = Value::Array(vec![]); + } + let path = self.global.path().join("evaluation.json"); + std::fs::write(&path, serde_json::to_vec_pretty(&plan).unwrap()).unwrap(); + path + } +} +fn record(repo: &Repository) -> Hash { + *repo + .record( + repo.require_working_copy_id().unwrap(), + ChangeHeader::new("native publication fixture"), + RecordOptions::new() + .with_all(true) + .save_to_store(true) + .apply_after_record(true) + .enrich_kg(false), + ) + .unwrap() + .hash() +} +fn document(html: &str) -> Value { + serde_json::from_str( + html.split("id=\"review-data\"") + .nth(1) + .unwrap() + .split_once('>') + .unwrap() + .1 + .split("") + .next() + .unwrap(), + ) + .unwrap() +} + +#[test] +fn native_publish_retains_all_findings_rationales_and_unready_evidence_without_any_agent() { + let f = Fixture::new(137); + let repo = Repository::open_readonly(f.root.path()).unwrap(); + let database = repo.dot_dir().join("atomic.redb"); + drop(repo); + let before = std::fs::read(&database).unwrap(); + let plan = f.plan(); + assert_eq!(std::fs::read(&database).unwrap(), before); + assert!( + !f.global.path().join("identities").exists(), + "Dry-run must not create credentials" + ); + assert_eq!(plan["scope"]["source"]["view"], "draft"); + assert_eq!(plan["scope"]["target"]["view"], f.base); + assert_eq!(plan["readiness"], "not_ready"); + assert_eq!(plan["report"]["schema_version"], 5); + assert_eq!( + plan["report"]["graph"]["risk"]["impact"][0]["issues"] + .as_array() + .unwrap() + .len(), + 137 + ); + let local = f.json(&["review", "--from", "draft", "--to", &f.base, "--json"]); + assert_eq!( + local["graph"]["findings"], + plan["report"]["graph"]["findings"] + ); + let evaluation = f.evaluate(plan, false); + let identity = f.signer(); + // A physical working-copy switch must not change the normalized evidence. + let mut repo = Repository::open(f.root.path()).unwrap(); + repo.switch_view(repo.require_working_copy_id().unwrap(), &f.base) + .unwrap(); + drop(repo); + let args = [ + "review", + "publish", + "--from", + "draft", + "--to", + f.base.as_str(), + "--evaluation", + evaluation.to_str().unwrap(), + "--identity", + "reviewer", + "--yes", + "--json", + ]; + // Another process owns the same evidence/operation boundary: neither + // publication nor insertion may race past it or retain a partial decision. + let lock = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(f.root.path().join(".atomic/bridge.lock")) + .unwrap(); + fs2::FileExt::try_lock_exclusive(&lock).unwrap(); + let contended = f.run(&args); + assert!(!contended.status.success()); + fs2::FileExt::unlock(&lock).unwrap(); + assert!(Repository::open_readonly(f.root.path()) + .unwrap() + .native_review_decisions() + .unwrap() + .is_empty()); + let published = f.json(&args); + assert!(published.get("path").is_none()); + assert!(published["vault_path"] + .as_str() + .unwrap() + .starts_with("review-decisions/")); + assert!( + !f.root.path().join(".vault/review-decisions").exists(), + "Retaining an attestation must not dirty the working copy" + ); + assert_eq!(published["status"], "attested"); + assert_eq!(published["review"]["readiness"], "not_ready"); + assert_eq!(published["review"]["disposition"], "accepted_degradation"); + assert_eq!( + published["document"]["report"]["graph"]["findings"], + local["graph"]["findings"] + ); + assert_eq!(published["agent_execution"], false); + assert_eq!(published["document"]["independent_approval"], false); + atomic_canonical::proof::verify_value(&published["document"], &identity.public_key).unwrap(); + let repeated = f.json(&args); + assert_eq!( + repeated["review"]["decision"], published["review"]["decision"], + "Exact repeat must reuse the immutable attestation" + ); + let output = f.run(&[ + "review", + "publish", + "--from", + "draft", + "--to", + &f.base, + "--evaluation", + evaluation.to_str().unwrap(), + "--identity", + "reviewer", + "--yes", + "--html", + "--no-open", + ]); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let html = String::from_utf8(output.stdout).unwrap(); + if let Some(path) = std::env::var_os("ATOMIC_REVIEW_NATIVE_PUBLICATION_ARTIFACT") { + std::fs::write(path, &html).unwrap(); + } + let data = document(&html); + assert_eq!( + data["review_decision"]["disposition"], + "accepted_degradation" + ); + assert_eq!(data["review_decision"]["readiness"], "not_ready"); + assert_eq!( + data["view"]["graph"]["findings"], + local["graph"]["findings"] + ); + let compressed = data_encoding::BASE64 + .decode(data["report_archive"]["data"].as_str().unwrap().as_bytes()) + .unwrap(); + let archived: Value = + serde_json::from_reader(flate2::read::GzDecoder::new(compressed.as_slice())).unwrap(); + assert_eq!(archived, published["document"]); + let inspect = f.json(&["review", "publish", "inspect"]); + assert_eq!(inspect.as_array().unwrap().len(), 1); + assert_eq!(inspect[0]["validation"]["currently_applicable"], true); + fs2::FileExt::try_lock_exclusive(&lock).unwrap(); + let contended_insert = f.run(&["insert", "view", "draft", "--to", &f.base]); + fs2::FileExt::unlock(&lock).unwrap(); + assert!(!contended_insert.status.success()); + assert_eq!( + f.json(&["review", "publish", "inspect"])[0]["validation"]["currently_applicable"], + true, + "A contended insertion must not mutate the scope or consume the decision" + ); + let status = f.run(&["status", "--short"]); + let inserted = f.run(&["insert", "view", "draft", "--to", &f.base]); + assert!( + inserted.status.success(), + "{}\nPre-insert status:\n{}", + String::from_utf8_lossy(&inserted.stderr), + String::from_utf8_lossy(&status.stdout) + ); + assert!( + String::from_utf8_lossy(&inserted.stderr) + .contains(published["review"]["decision"].as_str().unwrap()), + "Insertion must surface the attested risk decision" + ); + let repo = Repository::open_readonly(f.root.path()).unwrap(); + let hash = + Hash::from_base32(published["review"]["decision"].as_str().unwrap().as_bytes()).unwrap(); + assert!(repo + .pristine() + .read_txn() + .unwrap() + .list_operations() + .unwrap() + .iter() + .any(|op| op.payload().evidence.contains(&hash))); + assert!(!repo.dot_dir().join("review-jobs").exists()); + let store = IdentityStore::open_existing(&f.global.path().join("identities")).unwrap(); + assert_eq!(store.list().unwrap().len(), 1); + assert!(!f.global.path().join("identities/delegations").exists()); +} + +#[test] +fn yes_missing_or_partial_evaluation_cannot_publish_or_hide_findings() { + let f = Fixture::new(2); + let plan = f.plan(); + let output = f.run(&[ + "review", "publish", "--from", "draft", "--to", &f.base, "--yes", "--json", + ]); + assert!(!output.status.success()); + assert!(!f.global.path().join("identities").exists()); + let path = f.global.path().join("unfilled.json"); + std::fs::write(&path, serde_json::to_vec(&plan).unwrap()).unwrap(); + let output = f.run(&[ + "review", + "publish", + "--from", + "draft", + "--to", + &f.base, + "--evaluation", + path.to_str().unwrap(), + "--yes", + ]); + assert!(!output.status.success()); + let mut plan = plan; + plan["evaluation_template"]["report_hash"] = Value::String("foreign-or-stale".into()); + let path = f.evaluate(plan, false); + let output = f.run(&[ + "review", + "publish", + "--from", + "draft", + "--to", + &f.base, + "--evaluation", + path.to_str().unwrap(), + "--yes", + ]); + assert!(!output.status.success()); + assert!(Repository::open_readonly(f.root.path()) + .unwrap() + .native_review_decisions() + .unwrap() + .is_empty()); + for flag in ["--runner", "--timeout-seconds", "--resume", "--session"] { + let output = f.run(&["review", "publish", flag, "forbidden"]); + assert!(!output.status.success()); + } +} + +#[test] +fn attested_not_ready_remains_visible_and_does_not_allow_insertion() { + let f = Fixture::new(2); + let plan = f.plan(); + let path = f.evaluate(plan, true); + f.signer(); + let published = f.json(&[ + "review", + "publish", + "--from", + "draft", + "--to", + &f.base, + "--evaluation", + path.to_str().unwrap(), + "--identity", + "reviewer", + "--yes", + "--json", + ]); + assert_eq!(published["review"]["disposition"], "not_ready"); + let output = f.run(&["insert", "view", "draft", "--to", &f.base]); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr).contains("not_ready")); + let report = f.json(&["review", "--from", "draft", "--to", &f.base, "--json"]); + assert!(!report["graph"]["findings"].as_array().unwrap().is_empty()); +} diff --git a/atomic-cli/tests/review_viewer_browser.mjs b/atomic-cli/tests/review_viewer_browser.mjs index 3db2b20c..b8404c65 100644 --- a/atomic-cli/tests/review_viewer_browser.mjs +++ b/atomic-cli/tests/review_viewer_browser.mjs @@ -76,7 +76,23 @@ try { assert(await evaluate(`document.getElementById('review-toolbar').hidden && document.getElementById('file-navigation').hidden && document.getElementById('card-inspector').hidden`)); assert(await evaluate(`['audit-overview','conformance-overview','risk-overview'].every(id=>document.getElementById(id).closest('[role="tabpanel"]').id==='panel-summary')`),'Report-wide overviews belong only to Summary'); assert.equal(await evaluate(`document.querySelectorAll('#summary-actions button').length`),3); - let image = await page('Page.captureScreenshot', { format: 'png' }); + const published = await evaluate(`JSON.parse(document.getElementById('review-data').textContent).review_decision || null`); + if(published) { + assert.equal(await evaluate(`document.querySelectorAll('#summary-decision [data-review-issue]').length`),published.issues.length,'Every attested issue must remain accessible in the Summary ledger'); + assert.equal(await evaluate(`document.querySelectorAll('#summary-decision [data-pass-evaluation]').length`),3); + for(const pass of published.evaluation.passes)assert(await evaluate(`Array.from(document.querySelectorAll('#summary-decision [data-pass-evaluation]')).some(row=>row.dataset.passEvaluation===${JSON.stringify(pass.pass)} && row.textContent.includes(${JSON.stringify(pass.rationale)}))`)); + assert(await evaluate(`document.getElementById('summary-decision').textContent.includes('Not ready') && document.getElementById('summary-decision').textContent.includes('Accepted degradation')`),'Accepted risk must not rewrite evidence readiness'); + for(const pass of published.evaluation.passes) for(const acceptance of pass.accepted_degradations) { + assert(await evaluate(`Array.from(document.querySelectorAll('#summary-decision [data-review-issue]')).some(row=>row.dataset.reviewIssue===${JSON.stringify(acceptance.issue)} && row.textContent.includes(${JSON.stringify(acceptance.rationale)}))`)); + } + const archive=await evaluate(`(async()=>{let captured,ready;const prepared=new Promise(resolve=>ready=resolve),create=URL.createObjectURL,click=HTMLAnchorElement.prototype.click;URL.createObjectURL=blob=>{captured=blob;ready();return create.call(URL,blob)};HTMLAnchorElement.prototype.click=function(){};document.getElementById('download').click();await prepared;const text=await captured.text();URL.createObjectURL=create;HTMLAnchorElement.prototype.click=click;return JSON.parse(text);})()`); + assert.equal(archive.schema,'atomic.review-decision.v1'); + assert.equal(archive.report_hash,published.report_hash); + assert.deepEqual(archive.evaluation,published.evaluation); + assert.deepEqual(archive.proof,published.proof); + assert.equal(archive.readiness,'not_ready'); + } + let image = await page('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(directory,'summary-desktop.png'),Buffer.from(image.data,'base64')); const expected = await evaluate(`(() => { const d=JSON.parse(document.getElementById('review-data').textContent); const r=d.view; const c=r.view_comparison?.conformance || r.view_snapshot?.conformance; return { findings:r.graph.findings.filter(f=>f.passes.includes('anti_slop')).length, riskFindings:r.graph.findings.filter(f=>f.passes.includes('blast_radius_risk')).map(f=>f.number), criteria:r.graph.criteria.length, viewIntents:c?.intents || [], intentView:c?.scope?.view || null, metrics:d.metric_cards.length, observations:r.graph.nodes.filter(n=>n.kind==='metric').length, scope:r.graph.scope.selected_roots, snapshot:r.view_snapshot?.view || null, comparison:r.view_comparison || null }; })()`); assert(await evaluate(`(()=>{const logo=document.querySelector('.atomic-logo');return logo?.complete && logo.naturalWidth===560 && logo.src.startsWith('data:image/png;base64,') && logo.alt==='Atomic';})()`), 'Official logo must be embedded and decoded offline'); @@ -94,7 +110,7 @@ try { })()`); assert(contrasts.every(item=>item.ratio>=4.5),'Review text must meet AA contrast: '+JSON.stringify(contrasts)); if (expected.comparison) { - assert(await evaluate(`document.querySelector('.comparison-direction').textContent.includes('From · before') && document.querySelector('.comparison-direction').textContent.includes('To · after')`)); + assert(await evaluate(`document.querySelector('.comparison-direction').textContent.includes('From · source (after)') && document.querySelector('.comparison-direction').textContent.includes('To · target (before)')`)); assert.equal(await evaluate(`document.querySelectorAll('[data-file-comparison]').length`),expected.comparison.files.length); } assert.equal(expected.metrics, 10); @@ -230,7 +246,18 @@ try { const d=JSON.parse(document.getElementById('review-data').textContent),numbers=new Set(d.view.graph.findings.filter(f=>f.passes.includes('blast_radius_risk')).map(f=>f.number)),seen=new Set(); for(const region of d.regions.filter(region=>region.findings.some(number=>numbers.has(number)))) { const control=Array.from(document.querySelectorAll('#files .region-button')).find(button=>button.dataset.region===region.id);if(!control)continue;control.click(); - for(const finding of document.querySelectorAll('#risk-selection .finding'))seen.add(Number(finding.dataset.finding)); + for(const finding of document.querySelectorAll('#risk-selection .finding')) { + const number=Number(finding.dataset.finding);seen.add(number); + if(d.review_decision) { + const graphFinding=d.view.graph.findings.find(item=>item.number===number); + const issues=d.review_decision.issues.filter(issue=>issue.reference===graphFinding.id); + const acceptances=d.review_decision.evaluation.passes.flatMap(pass=>pass.accepted_degradations); + for(const issue of issues) { + const acceptance=acceptances.find(item=>item.issue===issue.id); + if(acceptance && !finding.textContent.includes(acceptance.rationale))throw new Error('Missing per-finding acceptance rationale: '+number); + } + } + } } return [...seen].sort((a,b)=>a-b); })()`); @@ -273,7 +300,12 @@ try { const pattern = /(]*\bid="review-data"[^>]*>)([\s\S]*?)(<\/script>)/; const fixture = JSON.parse(original.match(pattern)[2]); const hostile = ''; - fixture.view.graph.scope.view = hostile; + if(fixture.review_decision) { + fixture.review_decision.signer=hostile; + fixture.review_decision.issues[0].summary=hostile; + for(const pass of fixture.review_decision.evaluation.passes)if(pass.accepted_degradations.length)pass.accepted_degradations[0].rationale=hostile; + } + fixture.view.graph.scope.view = hostile; fixture.view.warnings.push(hostile); if(fixture.view.view_comparison) { fixture.view.view_comparison.from.view=hostile; diff --git a/atomic-repository/src/apply/cross_view.rs b/atomic-repository/src/apply/cross_view.rs index 5f0f999b..ff8577ca 100644 --- a/atomic-repository/src/apply/cross_view.rs +++ b/atomic-repository/src/apply/cross_view.rs @@ -102,6 +102,8 @@ impl CrossViewInsertOptions { /// Result of a cross-view insert operation. #[derive(Debug, Clone)] pub struct CrossViewInsertOutcome { + /// Attested native review used at the insertion boundary, when one exists. + pub review_decision: Option, /// Number of changes inserted. pub changes_applied: usize, @@ -131,6 +133,7 @@ impl CrossViewInsertOutcome { /// Create a new outcome. pub fn new() -> Self { Self { + review_decision: None, changes_applied: 0, applied_hashes: Vec::new(), skipped_hashes: Vec::new(), diff --git a/atomic-repository/src/apply/types.rs b/atomic-repository/src/apply/types.rs index 345e4f89..c5c0038b 100644 --- a/atomic-repository/src/apply/types.rs +++ b/atomic-repository/src/apply/types.rs @@ -154,6 +154,8 @@ pub struct InsertOptions { /// inserting its first dependency does not invalidate its own review pin. /// Default: `false` pub(crate) skip_publication_gate: bool, + /// Set only after native review verification inside the evidence boundary. + pub(crate) review_decision: Option, #[cfg(feature = "prototype-context-completion")] pub(crate) prototype_context: Option>, @@ -169,6 +171,7 @@ impl Default for InsertOptions { track_conflicts: true, skip_validation: false, skip_publication_gate: false, + review_decision: None, #[cfg(feature = "prototype-context-completion")] prototype_context: None, } diff --git a/atomic-repository/src/intent_bridge.rs b/atomic-repository/src/intent_bridge.rs index 2fe6396e..746cfaf5 100644 --- a/atomic-repository/src/intent_bridge.rs +++ b/atomic-repository/src/intent_bridge.rs @@ -57,6 +57,79 @@ pub struct LiftInputs { pub body: String, } +/// Current vault sources explicitly assigned to one view. This is context, +/// not recorded governance, signature verification or historical approval. +pub struct ViewIntentSources { + pub entries: Vec, + pub hash: String, + pub diagnostics: Vec, +} + +pub struct ViewIntentSource { + pub key: String, + pub path: String, + pub inputs: LiftInputs, + pub hash: String, + pub fallback_title: String, + pub fallback_status: String, +} + +/// Shared inventory identity used by local review and insertion-time revalidation. +pub fn view_intent_sources(repo: &Repository, view: &str) -> BridgeResult { + use atomic_core::types::{Base32, Hash}; + let manifest = if repo.has_vault()? { + repo.vault_manifest()? + } else { + Default::default() + }; + let mut entries = Vec::new(); + let mut inventory = std::collections::BTreeMap::new(); + let mut diagnostics = Vec::new(); + for (key, summary) in manifest.intents { + let inputs = if summary.vault_path.is_empty() { + read_intent(repo, &key)? + } else { + let Some(entry) = + repo.vault_retrieve(summary.vault_path.trim_start_matches(".vault/"))? + else { + inventory.insert(key.clone(), "missing_definition".to_string()); + diagnostics.push(format!( + "{key}: vault definition missing; view assignment unavailable" + )); + continue; + }; + inputs_from_entry(&entry)? + }; + if inputs.frontmatter.get("view").and_then(Value::as_str) != Some(view) { + continue; + } + let hash = source_content_hash(&inputs); + inventory.insert(key.clone(), hash.clone()); + let path = if summary.vault_path.starts_with(".vault/") { + summary.vault_path + } else { + format!(".vault/{}", summary.vault_path) + }; + entries.push(ViewIntentSource { + key, + path, + inputs, + hash, + fallback_title: summary.title, + fallback_status: summary.status, + }); + } + let bytes = + serde_json::to_vec(&inventory).map_err(|error| RepositoryError::InvalidOperation { + message: error.to_string(), + })?; + Ok(ViewIntentSources { + entries, + hash: Hash::of(&bytes).to_base32(), + diagnostics, + }) +} + /// Parse a `VaultEntry` into the frontmatter map + body the lift consumes. /// /// `frontmatter_json` is parsed exactly as the repository itself parses it diff --git a/atomic-repository/src/repository/insert.rs b/atomic-repository/src/repository/insert.rs index cc838432..d84a520d 100644 --- a/atomic-repository/src/repository/insert.rs +++ b/atomic-repository/src/repository/insert.rs @@ -2428,7 +2428,7 @@ impl Repository { pub fn insert_change( &self, hash: &Hash, - options: InsertOptions, + mut options: InsertOptions, ) -> Result { let _review_boundary = self.review_evidence_lock()?; let change = self.load_change(hash)?; @@ -2467,6 +2467,12 @@ impl Repository { .unwrap_or(false) }; if shared_target { + options.review_decision = self + .review_decision_for_direct_insert(&view_name, std::slice::from_ref(hash))? + .map(|review| { + Hash::from_base32(review.decision.as_bytes()) + .expect("verified review decision") + }); let closure = super::provenance_gate::reachable_closure(self, std::slice::from_ref(hash))?; let provider = super::provenance_gate::local_session_mac_key_provider(self); @@ -2558,7 +2564,9 @@ impl Repository { expected_old: MetadataValue::Absent, expected_new: MetadataValue::Sequence(sequence), }], - vec![*hash], + std::iter::once(*hash) + .chain(options.review_decision) + .collect(), ActorRef::System { name: "repository-insert".to_string(), }, @@ -2974,6 +2982,12 @@ impl Repository { Some(&provider), Some(&did_provider), )?; + options.review_decision = self + .review_decision_for_direct_insert(view_name, std::slice::from_ref(hash))? + .map(|review| { + Hash::from_base32(review.decision.as_bytes()) + .expect("verified review decision") + }); options.skip_publication_gate = true; } } @@ -3542,6 +3556,17 @@ impl Repository { // not just the selected changes) and fails closed before any // VIEW_CHANGES metadata movement. if target_is_shared { + outcome.review_decision = match self.review_decision_for_insert( + &options.from_view, + &options.to_view, + &missing, + )? { + Some(review) => Some(review), + // Hash-set/cherry-pick callers have no source label. A + // different unreviewed label must not bypass a known + // decision over the same incoming changes either. + None => self.review_decision_for_direct_insert(&options.to_view, &missing)?, + }; let closure = super::provenance_gate::reachable_closure(self, &source_changes)?; let provider = super::provenance_gate::local_session_mac_key_provider(self); let did_provider = super::provenance_gate::local_did_key_provider(self); @@ -3576,6 +3601,9 @@ impl Repository { // The closure-level gate above already covered every change this // loop is about to insert; skip the redundant per-change gate. apply_opts.skip_publication_gate = target_is_shared; + apply_opts.review_decision = outcome.review_decision.as_ref().map(|review| { + Hash::from_base32(review.decision.as_bytes()).expect("verified review decision hash") + }); let total_missing = missing.len(); for (i, hash) in missing.iter().enumerate() { diff --git a/atomic-repository/src/repository/mod.rs b/atomic-repository/src/repository/mod.rs index ddbe2374..445f36c9 100644 --- a/atomic-repository/src/repository/mod.rs +++ b/atomic-repository/src/repository/mod.rs @@ -265,6 +265,8 @@ mod project_identity; pub mod provenance_gate; mod provenance_summary; pub mod publication_review; +pub mod review_decision; +pub use review_decision::ReviewDecisionEvidence; pub mod review_authorization; pub use project_identity::{ build_project_identity, project_identity_hash, verify_project_identity, IdentityAdoption, diff --git a/atomic-repository/src/repository/review_decision.rs b/atomic-repository/src/repository/review_decision.rs new file mode 100644 index 00000000..930382ed --- /dev/null +++ b/atomic-repository/src/repository/review_decision.rs @@ -0,0 +1,418 @@ +//! Retained, attested native review evaluations and exact-scope insertion checks. +use std::collections::{BTreeMap, BTreeSet}; + +use atomic_canonical::review_decision::{Disposition, ReviewDecision, ReviewScope, ViewPin}; +use atomic_core::types::{Base32, Hash}; +use atomic_identity::keypair::PublicKey; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use super::provenance_gate::{ + local_did_key_provider, local_session_mac_key_provider, PublicationGateConfig, +}; +use super::{Repository, RepositoryError}; +use crate::intent_bridge; + +pub const PREFIX: &str = "review-decisions/"; +const MAX_DECISIONS: usize = 4096; + +fn refused(message: impl std::fmt::Display) -> RepositoryError { + RepositoryError::InvalidOperation { + message: format!("native review decision: {message}"), + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct ReviewDecisionEvidence { + pub decision: String, + pub report_hash: String, + pub readiness: Disposition, + pub disposition: Disposition, + pub accepted_degradations: usize, + pub signer: String, +} + +impl ReviewDecisionEvidence { + fn from_decision(decision: &ReviewDecision) -> Self { + Self { + decision: decision.artifact_hash(), + report_hash: decision.report_hash.clone(), + readiness: decision.readiness, + disposition: decision.evaluation.insertion_disposition(), + accepted_degradations: decision + .evaluation + .passes + .iter() + .map(|pass| pass.accepted_degradations.len()) + .sum(), + signer: decision.attributed_to.clone(), + } + } +} + +impl Repository { + fn review_decision_view_pin(&self, view: &str) -> Result { + let info = self.get_view_info(view)?; + let members: Vec<_> = self + .effective_history(Some(view))? + .into_iter() + .map(|entry| entry.hash.to_base32()) + .collect(); + let membership_hash = Hash::of(&serde_json::to_vec(&members).map_err(refused)?).to_base32(); + Ok(ViewPin { + view: view.into(), + scope: info.kind_label().into(), + state: info.state.to_base32(), + membership_hash, + members, + }) + } + + /// Freeze the same source/destination and current intent context as a v5 + /// native report. This does not grant trust, sign, store or insert anything. + pub fn review_decision_scope( + &self, + source: &str, + target: &str, + report: &Value, + ) -> Result { + let source = self.review_decision_view_pin(source)?; + let target = self.review_decision_view_pin(target)?; + if source.scope != "draft" || target.scope != "shared" || source.view == target.view { + return Err(refused( + "publish requires --from a draft and --to a distinct shared view", + )); + } + let available: BTreeSet<_> = source.members.iter().collect(); + if !target.members.iter().all(|hash| available.contains(hash)) { + return Err(refused("the source does not incorporate the target's recorded state; update the draft and review the combined state before publishing insertion acceptance")); + } + let roots = self.get_missing_changes_between(&source.view, Some(&target.view))?; + let changes = super::provenance_gate::reachable_closure(self, &roots)? + .into_iter() + .map(|hash| hash.to_base32()) + .collect::>() + .into_iter() + .collect(); + let intent_scope_hash = intent_bridge::view_intent_sources(self, &source.view)?.hash; + let mut context_intent_hashes = BTreeMap::new(); + for criterion in report["view_comparison"]["conformance"]["criteria"] + .as_array() + .ok_or_else(|| refused("native conformance context unavailable"))? + { + if criterion["current_context"].is_object() { + let id = criterion["intent"] + .as_str() + .ok_or_else(|| refused("current intent identity missing"))?; + let key = id.strip_prefix("urn:atomic:intent:").unwrap_or(id); + let inputs = intent_bridge::read_intent(self, key)?; + context_intent_hashes + .insert(id.into(), intent_bridge::source_content_hash(&inputs)); + } + } + let scope = ReviewScope { + project: self.project_id()?.to_urn(), + source, + target, + changes, + intent_scope_hash, + context_intent_hashes, + }; + scope.validate_report(report).map_err(refused)?; + Ok(scope) + } + + /// Existing provenance/integrity preflight; accepting code degradation does + /// not replace or weaken this gate. + pub fn review_decision_preflight( + &self, + scope: &ReviewScope, + ) -> Result { + // Match the existing cross-view gate's complete source-root closure, + // including original evidence it already requires on shared insertion. + let roots: Vec<_> = self + .get_view_changes(Some(&scope.source.view))? + .into_iter() + .map(|(_, hash)| hash) + .collect(); + let hashes = super::provenance_gate::reachable_closure(self, &roots)?; + let config = PublicationGateConfig::from_repo(self)?; + self.evaluate_publication_gate( + &hashes, + &config, + Some(&local_session_mac_key_provider(self)), + Some(&local_did_key_provider(self)), + ) + } + + fn verify_review_decision_signature( + &self, + decision: &ReviewDecision, + require_trust: bool, + ) -> Result<(), RepositoryError> { + decision.validate().map_err(refused)?; + let key = PublicKey::from_base32(&decision.public_key).map_err(refused)?; + if !atomic_canonical::did::did_matches_public_key(&decision.attributed_to, &key) { + return Err(refused("review signer is not bound to the retained key")); + } + atomic_canonical::proof::verify_value(&decision.value(), &key).map_err(refused)?; + let config = PublicationGateConfig::from_repo(self)?; + if require_trust + && config.trust.evaluate( + &decision.attributed_to, + config.repository_identity.as_deref(), + ) != atomic_config::SignerTrust::Trusted + { + return Err(refused("review signer is not currently trusted by repository policy; publication does not enroll or elevate an identity")); + } + Ok(()) + } + + fn verify_review_decision_scope( + &self, + decision: &ReviewDecision, + ) -> Result<(), RepositoryError> { + let actual = self.review_decision_scope( + &decision.scope.source.view, + &decision.scope.target.view, + &decision.report, + )?; + if actual != decision.scope { + return Err(refused("review scope, insertion closure or intent context is stale; regenerate and evaluate the review")); + } + Ok(()) + } + + /// Strict retained inventory. Invalid or misaddressed evidence is not hidden + /// behind a best-effort filter, and no decision is truncated. + pub fn native_review_decisions(&self) -> Result, RepositoryError> { + let mut result = Vec::new(); + for entry in self.vault_list(PREFIX, None)? { + if result.len() >= MAX_DECISIONS { + return Err(refused( + "native review inventory exceeds its explicit artifact-count budget", + )); + } + let stored = self + .vault_retrieve(&entry.path)? + .ok_or_else(|| refused("registered decision missing"))?; + let decision = ReviewDecision::parse(&stored.content_bytes).map_err(refused)?; + if entry.path != format!("{PREFIX}{}/review.md", decision.artifact_hash()) { + return Err(refused("stored decision address differs from signed bytes")); + } + result.push(decision); + } + result.sort_by_key(ReviewDecision::artifact_hash); + Ok(result) + } + + /// Retain an accountable evaluation of complete native evidence. An accepted + /// degradation remains not-ready evidence, not an independent/clean verdict. + pub fn record_review_decision( + &self, + decision: &ReviewDecision, + ) -> Result { + let _boundary = self.review_evidence_lock()?; + let bytes = serde_json::to_vec(decision).map_err(refused)?; + if ReviewDecision::parse(&bytes).map_err(refused)? != *decision { + return Err(refused("decision does not read back as signed")); + } + self.verify_review_decision_signature(decision, true)?; + self.verify_review_decision_scope(decision)?; + if decision.evaluation.insertion_disposition() != Disposition::NotReady { + let gate = self.review_decision_preflight(&decision.scope)?; + if !gate.allowed() { + return Err(refused(gate.refusal_report())); + } + } + let inventory = self.native_review_decisions()?; + if inventory.len() >= MAX_DECISIONS + && !inventory + .iter() + .any(|old| old.artifact_hash() == decision.artifact_hash()) + { + return Err(refused( + "native review inventory is full; nothing was truncated or overwritten", + )); + } + let mut superseded = BTreeSet::new(); + for hash in &decision.supersedes { + if !superseded.insert(hash) { + return Err(refused("duplicate superseded decision")); + } + let old = inventory + .iter() + .find(|old| old.artifact_hash() == *hash) + .ok_or_else(|| refused("superseded review decision is unavailable"))?; + self.verify_review_decision_signature(old, false)?; + if old.scope.project != decision.scope.project + || old.scope.source.view != decision.scope.source.view + || old.scope.target.view != decision.scope.target.view + { + return Err(refused( + "supersession cannot change the original project/source/target", + )); + } + } + let hash = decision.artifact_hash(); + let path = format!("{PREFIX}{hash}/review.md"); + let retired: BTreeSet<_> = inventory + .iter() + .flat_map(|old| old.supersedes.iter().cloned()) + .chain(decision.supersedes.iter().cloned()) + .collect(); + if let Some(old) = inventory.iter().find(|old| { + old.scope == decision.scope + && old.artifact_hash() != hash + && !retired.contains(&old.artifact_hash()) + }) { + return Err(refused(format!("exact-scope review head {} already exists; explicitly --supersedes it rather than silently replacing its evaluation",old.artifact_hash()))); + } + let existing = self.vault_retrieve(&path)?; + if let Some(existing) = &existing { + if existing.content_bytes != bytes { + return Err(refused("review decision content-address collision")); + } + } + if existing.is_none() { + self.vault_store( + &path, + atomic_core::pristine::VaultEntryType::Attestation, + bytes, + "{}".into(), + )?; + } + // Retention must not dirty the working copy and thereby block the + // insertion this decision evaluates. Export is an explicit CLI action. + Ok(ReviewDecisionEvidence::from_decision(decision)) + } + + /// Inspect current applicability without treating a stale retained artifact + /// as corrupt history or silently reusing it for a new insertion. + pub fn inspect_review_decision( + &self, + decision: &ReviewDecision, + ) -> Result { + self.verify_review_decision_signature(decision, true)?; + if self + .native_review_decisions()? + .iter() + .any(|new| new.supersedes.contains(&decision.artifact_hash())) + { + return Err(refused("this attested decision has been explicitly superseded; its historical report is retained but no longer authorizes insertion")); + } + self.verify_review_decision_scope(decision)?; + if decision.evaluation.insertion_disposition() != Disposition::NotReady { + let gate = self.review_decision_preflight(&decision.scope)?; + if !gate.allowed() { + return Err(refused(gate.refusal_report())); + } + } + Ok(ReviewDecisionEvidence::from_decision(decision)) + } + + /// Called inside the insertion evidence boundary. A published decision for a + /// pair must match exactly; moving either side requires a new evaluation. + pub(super) fn review_decision_for_insert( + &self, + source: &str, + target: &str, + selected: &[Hash], + ) -> Result, RepositoryError> { + let inventory = self.native_review_decisions()?; + let pair: Vec<_> = inventory + .iter() + .filter(|decision| { + decision.scope.source.view == source && decision.scope.target.view == target + }) + .collect(); + if pair.is_empty() { + return Ok(None); + } + let mut relevant = Vec::new(); + for decision in &pair { + self.verify_review_decision_signature(decision, false)?; + if self.verify_review_decision_scope(decision).is_ok() { + relevant.push(*decision); + } + } + if relevant.is_empty() { + return Err(refused("published review decision is stale for this source/target; regenerate, evaluate and publish it before inserting")); + } + let superseded: BTreeSet<_> = pair + .iter() + .flat_map(|decision| decision.supersedes.iter().cloned()) + .collect(); + relevant.retain(|decision| !superseded.contains(&decision.artifact_hash())); + if relevant.len() != 1 { + return Err(refused("native review decisions have competing or withdrawn heads; publish an explicit signed supersession")); + } + let decision = relevant[0]; + let evidence = self.inspect_review_decision(decision)?; + if evidence.disposition == Disposition::NotReady { + return Err(refused(format!( + "attested review {} explicitly remains not_ready; insertion has not been accepted", + evidence.decision + ))); + } + let selected = super::provenance_gate::reachable_closure(self, selected)? + .into_iter() + .map(|hash| hash.to_base32()) + .collect::>(); + if selected != decision.scope.changes.iter().cloned().collect() { + return Err(refused( + "published decision does not cover this exact insertion selection", + )); + } + Ok(Some(evidence)) + } + + /// Direct hash/tag insertion cannot evade an applicable registered decision + /// simply by omitting the source view's name. + pub(super) fn review_decision_for_direct_insert( + &self, + target: &str, + selected: &[Hash], + ) -> Result, RepositoryError> { + let target_pin = self.review_decision_view_pin(target)?; + let present: BTreeSet<_> = target_pin.members.iter().cloned().collect(); + let wanted: BTreeSet<_> = super::provenance_gate::reachable_closure(self, selected)? + .into_iter() + .map(|hash| hash.to_base32()) + .filter(|hash| !present.contains(hash)) + .collect(); + if wanted.is_empty() { + return Ok(None); + } + let inventory = self.native_review_decisions()?; + let mut sources = BTreeSet::new(); + for decision in inventory + .iter() + .filter(|decision| decision.scope.target.view == target) + { + let original_target: BTreeSet<_> = decision.scope.target.members.iter().collect(); + let known = decision + .scope + .changes + .iter() + .any(|hash| !original_target.contains(hash) && wanted.contains(hash)); + let current = self + .review_decision_view_pin(&decision.scope.source.view) + .ok() + .is_some_and(|pin| pin.members.iter().any(|hash| wanted.contains(hash))); + if known || current { + sources.insert(decision.scope.source.view.clone()); + } + } + if sources.len() > 1 { + return Err(refused("multiple reviewed source contexts apply; insert the explicitly reviewed source view instead of an ambiguous hash selection")); + } + let Some(source) = sources.into_iter().next() else { + return Ok(None); + }; + self.review_decision_for_insert(&source, target, selected) + } +} + +#[cfg(test)] +mod tests; diff --git a/atomic-repository/src/repository/review_decision/tests.rs b/atomic-repository/src/repository/review_decision/tests.rs new file mode 100644 index 00000000..6fe87f3a --- /dev/null +++ b/atomic-repository/src/repository/review_decision/tests.rs @@ -0,0 +1,300 @@ +use super::*; +use crate::{ + record::RecordOptions, tracking::TrackingOptions, CrossViewInsertOptions, InsertOptions, +}; +use atomic_canonical::{ + review_decision::{self, ReviewEvaluation}, + review_graph::ReviewPass, +}; +use atomic_core::{change::ChangeHeader, pristine::OperationTxnT}; +use atomic_identity::{Identity, KeyPair}; +use serde_json::json; + +struct Fixture { + _dir: tempfile::TempDir, + repo: Repository, + signer: Identity, + pair: KeyPair, + base: String, +} +impl Fixture { + fn new() -> Self { + let dir = tempfile::tempdir().unwrap(); + let mut repo = Repository::init(dir.path()).unwrap(); + repo.init_vault().unwrap(); + let base = repo.current_view().to_owned(); + std::fs::write(dir.path().join("lib.rs"), "pub fn original() {}\n").unwrap(); + repo.add( + repo.require_working_copy_id().unwrap(), + "lib.rs", + TrackingOptions::default(), + ) + .unwrap(); + record(&repo); + repo.create_draft_view("draft", &base).unwrap(); + repo.switch_view(repo.require_working_copy_id().unwrap(), "draft") + .unwrap(); + std::fs::write(dir.path().join("lib.rs"), "pub fn changed() { todo!(); }\n").unwrap(); + record(&repo); + let pair = KeyPair::generate(); + let signer = Identity::new("accountable-reviewer", &pair); + let mut value = Self { + _dir: dir, + repo, + signer, + pair, + base, + }; + value.trust(false); + value + } + fn trust(&mut self, revoked: bool) { + let path = self.repo.dot_dir().join("config.toml"); + let mut config = atomic_config::RepoConfig::load(&path).unwrap(); + let did = atomic_canonical::did::did_for_public_key(&self.signer.public_key); + config.git.trust.signers = vec![did.clone()]; + config.git.trust.revoked = if revoked { vec![did] } else { vec![] }; + config.save(&path).unwrap(); + } + fn report(&self) -> Value { + let source = self.repo.review_decision_view_pin("draft").unwrap(); + let target = self.repo.review_decision_view_pin(&self.base).unwrap(); + let scope = intent_bridge::view_intent_sources(&self.repo, "draft") + .unwrap() + .hash; + let pin = |value: &ViewPin| json!({"view":value.view,"state":value.state,"membership_hash":value.membership_hash}); + json!({"schema_version":5,"selection":{"kind":"view_comparison"},"view_comparison":{"from":pin(&source),"to":pin(&target),"before":pin(&target),"after":pin(&source),"conformance":{"scope":{"view":"draft","current_inventory_hash":scope},"criteria":[],"diagnostics":[]}},"graph":{"scope":{"project":self.repo.project_id().unwrap().to_urn(),"view":"draft","view_state":source.state},"findings":[{"number":1,"id":"finding:placeholder","passes":["anti_slop"],"finding":{"summary":"Unfinished placeholder remains"},"comparison":{"status":"new"}}],"criteria":[],"nodes":[],"passes":ReviewPass::ALL.map(|pass|json!({"pass":pass,"status":"partial","detail":"Static inspection has explicit limitations"})),"risk":{"assessment":{"rating":"medium","coverage":"partial","rationale":"User must evaluate the changed implementation","limitations":["No runtime tests executed by review"]}}},"publication_gate":{"allowed":true,"blocks":[]}}) + } + fn decision(&self, not_ready: bool, supersedes: Vec) -> ReviewDecision { + let report = self.report(); + let scope = self + .repo + .review_decision_scope("draft", &self.base, &report) + .unwrap(); + let issues = review_decision::issues(&report).unwrap(); + let mut evaluation = ReviewEvaluation::template(&scope, &report, &issues); + for pass in &mut evaluation.passes { + pass.evaluated = true; + pass.rationale = + "Responsible user inspected this complete pass and its source/coverage".into(); + for issue in &mut pass.accepted_degradations { + issue.rationale="Explicitly accepted technical debt for this exact reviewed scope; tracked follow-up".into(); + } + } + if not_ready { + evaluation.passes[0].disposition = Disposition::NotReady; + evaluation.passes[0].accepted_degradations.clear(); + } + let decision = ReviewDecision { + schema: review_decision::SCHEMA.into(), + reviewed_at: "2026-11-25T00:00:00Z".into(), + scope, + report_hash: review_decision::report_hash(&report), + report, + issues, + readiness: Disposition::NotReady, + evaluation, + independent_approval: false, + attributed_to: atomic_canonical::did::did_for_public_key(&self.signer.public_key), + public_key: self.signer.public_key.to_base32(), + supersedes, + content_hash: None, + proof: None, + }; + serde_json::from_value(atomic_canonical::proof::attest_value( + decision.value(), + &self.signer, + &self.pair, + )) + .unwrap() + } + fn insert(&self) -> Result { + self.repo + .insert_from_view(CrossViewInsertOptions::new("draft", &self.base)) + } +} +fn record(repo: &Repository) -> Hash { + *repo + .record( + repo.require_working_copy_id().unwrap(), + ChangeHeader::new("native review fixture"), + RecordOptions::new() + .with_all(true) + .save_to_store(true) + .apply_after_record(true) + .enrich_kg(false), + ) + .unwrap() + .hash() +} + +#[test] +fn accepted_degradation_inserts_and_links_the_attested_unready_report_to_operations() { + let f = Fixture::new(); + let decision = f.decision(false, vec![]); + let evidence = f.repo.record_review_decision(&decision).unwrap(); + assert_eq!(evidence.readiness, Disposition::NotReady); + assert_eq!(evidence.disposition, Disposition::AcceptedDegradation); + let outcome = f.insert().unwrap(); + assert!(outcome.changes_applied > 0); + assert_eq!(outcome.review_decision.unwrap().decision, evidence.decision); + assert!(String::from_utf8( + f.repo + .get_file_content_on_view("lib.rs", &f.base) + .unwrap() + .unwrap() + ) + .unwrap() + .contains("todo!()")); + let hash = Hash::from_base32(evidence.decision.as_bytes()).unwrap(); + let operations = f + .repo + .pristine() + .read_txn() + .unwrap() + .list_operations() + .unwrap(); + assert!(operations.iter().any(|operation| operation.payload().kind + == atomic_core::operation::OperationKind::Insert + && operation.payload().evidence.contains(&hash))); + let retained = f.repo.native_review_decisions().unwrap(); + assert_eq!(retained[0], decision); + assert!(!retained[0].independent_approval); + assert!(f.repo.inspect_review_decision(&retained[0]).is_err(),"Historical report stays retained but its old target-before state no longer authorizes a new insertion"); +} + +#[test] +fn explicitly_not_ready_refuses_view_and_direct_insertion_before_mutation() { + let f = Fixture::new(); + let decision = f.decision(true, vec![]); + f.repo.record_review_decision(&decision).unwrap(); + let state = f.repo.get_view_info(&f.base).unwrap().state; + assert!(f.insert().unwrap_err().to_string().contains("not_ready")); + let hash = f + .repo + .get_view_changes(Some("draft")) + .unwrap() + .last() + .unwrap() + .1; + assert!(f + .repo + .insert_change_rec(&hash, InsertOptions::default().view(&f.base)) + .is_err()); + assert!(f.repo.cherry_pick(&[hash], "", Some(&f.base)).is_err()); + assert!( + f.repo + .insert_from_view(CrossViewInsertOptions::new("", &f.base).only_changes(vec![hash])) + .is_err(), + "An omitted source label must not bypass the native decision" + ); + assert_eq!(f.repo.get_view_info(&f.base).unwrap().state, state); +} + +#[test] +fn hash_set_insertion_reuses_the_exact_registered_evaluation() { + let f = Fixture::new(); + let decision = f.decision(false, vec![]); + f.repo.record_review_decision(&decision).unwrap(); + let hash = f + .repo + .get_view_changes(Some("draft")) + .unwrap() + .last() + .unwrap() + .1; + let outcome = f.repo.cherry_pick(&[hash], "", Some(&f.base)).unwrap(); + assert_eq!( + outcome.review_decision.unwrap().decision, + decision.artifact_hash() + ); +} + +#[test] +fn moving_either_endpoint_or_current_intent_context_requires_re_evaluation() { + for change in ["source", "target", "intent"] { + let mut f = Fixture::new(); + let decision = f.decision(false, vec![]); + f.repo.record_review_decision(&decision).unwrap(); + match change { + "source" => { + std::fs::write(f.repo.root().join("lib.rs"), "pub fn later_source() {}\n").unwrap(); + record(&f.repo); + } + "target" => { + let wc = f.repo.require_working_copy_id().unwrap(); + f.repo.switch_view(wc, &f.base).unwrap(); + std::fs::write(f.repo.root().join("lib.rs"), "pub fn later_target() {}\n").unwrap(); + record(&f.repo); + } + _ => { + f.repo + .vault_intent_create(crate::IntentCreateOptions { + title: "New context after review".into(), + priority: None, + assignee: None, + labels: vec![], + session_id: None, + turn_id: None, + kind: None, + }) + .unwrap(); + } + } + let state = f.repo.get_view_info(&f.base).unwrap().state; + assert!(f.insert().is_err(), "{change}"); + assert_eq!(f.repo.get_view_info(&f.base).unwrap().state, state); + } +} + +#[test] +fn signatures_trust_and_full_evaluation_are_not_waivable() { + let mut f = Fixture::new(); + let good = f.decision(false, vec![]); + let mut tampered = good.clone(); + tampered.evaluation.passes[0].rationale = "tampered after signing".into(); + assert!(f.repo.record_review_decision(&tampered).is_err()); + let mut omitted = good.clone(); + omitted.evaluation.passes[0].accepted_degradations.clear(); + assert!(f.repo.record_review_decision(&omitted).is_err()); + let mut fake = good.clone(); + fake.attributed_to = "did:atomic:someone-else".into(); + assert!(f.repo.record_review_decision(&fake).is_err()); + f.repo.record_review_decision(&good).unwrap(); + f.trust(true); + assert!(f.insert().is_err()); +} + +#[test] +fn decisions_are_immutable_and_replacing_a_current_head_is_explicit() { + let f = Fixture::new(); + let denied = f.decision(true, vec![]); + let first = f.repo.record_review_decision(&denied).unwrap(); + let implicit = f.decision(false, vec![]); + assert!(f.repo.record_review_decision(&implicit).is_err()); + let approved = f.decision(false, vec![first.decision.clone()]); + f.repo.record_review_decision(&approved).unwrap(); + assert!(f.repo.inspect_review_decision(&denied).is_err()); + assert!(f.insert().is_ok()); + let path = format!("{PREFIX}{}/review.md", first.decision); + assert!(f + .repo + .vault_store( + &path, + atomic_core::pristine::VaultEntryType::Attestation, + b"replacement".to_vec(), + "{}".into() + ) + .is_err()); + assert_eq!(f.repo.native_review_decisions().unwrap().len(), 2); +} + +#[test] +fn unreviewed_existing_paths_keep_their_prior_policy_and_foreign_scope_is_refused() { + let f = Fixture::new(); + assert!(f.insert().is_ok()); + let f = Fixture::new(); + let mut decision = f.decision(false, vec![]); + decision.scope.project = "urn:atomic:project:foreign".into(); + assert!(f.repo.record_review_decision(&decision).is_err()); +} diff --git a/atomic-repository/src/repository/sandbox.rs b/atomic-repository/src/repository/sandbox.rs index e7785d17..e1b2ed49 100644 --- a/atomic-repository/src/repository/sandbox.rs +++ b/atomic-repository/src/repository/sandbox.rs @@ -440,12 +440,14 @@ impl Repository { .filter(|p| !p.as_os_str().is_empty()) .unwrap_or(Path::new(".")); let dest = parent.canonicalize()?.join(name); - let mut builder = std::fs::DirBuilder::new(); + let builder = std::fs::DirBuilder::new(); #[cfg(unix)] - { + let builder = { use std::os::unix::fs::DirBuilderExt; + let mut builder = builder; builder.mode(0o700); - } + builder + }; builder.create(&dest)?; let snapshot = self.materialize_view_entries(view, |entry| { write_recorded_snapshot_entry(&dest, &entry) @@ -905,6 +907,14 @@ mod tests { let dest = dir.path().join("review"); let snapshot = repo.provision_recorded_sandbox(&dest, "dev").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&dest).unwrap().permissions().mode() & 0o077, + 0 + ); + } assert_eq!(snapshot.view, "dev"); assert_eq!(snapshot.change_count, 1); let expected = repo diff --git a/atomic-repository/src/repository/vault.rs b/atomic-repository/src/repository/vault.rs index 7d22d149..0c954841 100644 --- a/atomic-repository/src/repository/vault.rs +++ b/atomic-repository/src/repository/vault.rs @@ -12,6 +12,7 @@ const VAULT_DIR: &str = ".vault"; /// evidence. Generic vault mutation must not erase or rewrite either side. fn retained_review_evidence(path: &str) -> bool { path.starts_with(super::publication_review::PREFIX) + || path.starts_with(super::review_decision::PREFIX) || path.starts_with(super::review_authorization::PREFIX) } diff --git a/atomic-repository/tests/native_span_record.rs b/atomic-repository/tests/native_span_record.rs index 8d6a2462..603cd0cf 100644 --- a/atomic-repository/tests/native_span_record.rs +++ b/atomic-repository/tests/native_span_record.rs @@ -286,12 +286,12 @@ fn native_span_queries_use_recorded_view_content() { repo.switch_view(wc, "feature").unwrap(); std::fs::write( &source, - "pub fn target(secret: SiblingSecret) {}\npub fn caller() {}\n", + "pub fn target(secret: SiblingSecret) {}\npub fn caller() {}\nmod sibling;\n", ) .unwrap(); std::fs::write( dir.path().join("src/sibling.rs"), - "pub fn sibling_only() { target(); }\n", + "pub fn sibling_only() { crate::target(); }\n", ) .unwrap(); repo.add(wc, "src/sibling.rs", Default::default()).unwrap(); diff --git a/libatomic/proto/atomic/services/repository_mutation/repository_mutation_messages.proto b/libatomic/proto/atomic/services/repository_mutation/repository_mutation_messages.proto index 1970bfe3..44c416e0 100644 --- a/libatomic/proto/atomic/services/repository_mutation/repository_mutation_messages.proto +++ b/libatomic/proto/atomic/services/repository_mutation/repository_mutation_messages.proto @@ -266,9 +266,20 @@ message InsertChangesResponse { optional uint64 files_updated = 10; optional uint64 directories_created = 11; bool has_conflicts = 12; // the insert outcome's own flag + optional NativeReviewDecisionEvidence review_decision = 13; ResponseMeta meta = 100; } +// Output evidence only; insertion authority is revalidated by the repository. +message NativeReviewDecisionEvidence { + string decision = 1; + string report_hash = 2; + string readiness = 3; + string disposition = 4; + uint64 accepted_degradations = 5; + string signer = 6; +} + message UnrecordRequest { RepositoryRef repository = 1; RequestMeta meta = 2; diff --git a/libatomic/src/daemon/change_impact.rs b/libatomic/src/daemon/change_impact.rs index b7693008..9ba67351 100644 --- a/libatomic/src/daemon/change_impact.rs +++ b/libatomic/src/daemon/change_impact.rs @@ -312,9 +312,13 @@ mod tests { ), ( "tests/caller.ts".into(), - "function caller() { target(); }".into(), + "import { target } from '../src/a';\nfunction caller() { target(); }".into(), ), ("wrong.ts".into(), "function outgoing() {}".into()), + ( + "unbound.ts".into(), + "function unbound() { target(); }".into(), + ), ]); let mut files = BTreeMap::from([("src/a.ts".into(), 1)]); let mut links = BTreeSet::new(); @@ -329,6 +333,10 @@ mod tests { ); assert_eq!(files.get("tests/caller.ts"), Some(&2)); assert!(!files.contains_key("wrong.ts")); + assert!( + !files.contains_key("unbound.ts"), + "An unimported name is not a bound caller" + ); add_link( "src/a.ts", "tests/caller.ts", @@ -346,7 +354,9 @@ mod tests { sources.extend((0..31).map(|i| { ( format!("caller{i}.ts"), - format!("function caller{i}() {{ target(); }}"), + format!( + "import {{ target }} from './src/a';\nfunction caller{i}() {{ target(); }}" + ), ) })); let index = SyntaxIndex::from_sources(&sources); diff --git a/libatomic/src/daemon/services.rs b/libatomic/src/daemon/services.rs index e17792d6..af15f6c5 100644 --- a/libatomic/src/daemon/services.rs +++ b/libatomic/src/daemon/services.rs @@ -2359,6 +2359,7 @@ impl repository_mutation_service_server::RepositoryMutationService for MutationI let cross_view_error = |error: atomic_repository::RepositoryError| -> Status { domain_status(ErrorCode::ChangeRejected, error.to_string()) }; + let mut review_decision = None; let report = match request.source { // A resolved single change: the direct domain calls the // local single-insert body makes (the --deps=false @@ -2418,6 +2419,7 @@ impl repository_mutation_service_server::RepositoryMutationService for MutationI .allow_conflicts(request.allow_conflicts) .dry_run(dry_run); let outcome = repo.insert_from_view(options).map_err(cross_view_error)?; + review_decision = outcome.review_decision.clone(); ArmReport { applied: outcome.applied_hashes.clone(), affected_paths: outcome.affected_paths.clone(), @@ -2445,6 +2447,7 @@ impl repository_mutation_service_server::RepositoryMutationService for MutationI .allow_conflicts(request.allow_conflicts) .dry_run(dry_run); let outcome = repo.insert_from_view(options).map_err(cross_view_error)?; + review_decision = outcome.review_decision.clone(); ArmReport { applied: outcome.applied_hashes.clone(), affected_paths: outcome.affected_paths.clone(), @@ -2529,6 +2532,7 @@ impl repository_mutation_service_server::RepositoryMutationService for MutationI .allow_conflicts(request.allow_conflicts); let outcome = repo.insert_from_view(options).map_err(cross_view_error)?; + review_decision = outcome.review_decision.clone(); ArmReport { applied: outcome.applied_hashes.clone(), affected_paths: outcome.affected_paths.clone(), @@ -2563,6 +2567,7 @@ impl repository_mutation_service_server::RepositoryMutationService for MutationI repo.cherry_pick(&hashes, "", Some(&target)) .map_err(cross_view_error)? }; + review_decision = outcome.review_decision.clone(); ArmReport { applied: outcome.applied_hashes.clone(), affected_paths: outcome.affected_paths.clone(), @@ -2657,6 +2662,14 @@ impl repository_mutation_service_server::RepositoryMutationService for MutationI files_updated, directories_created, has_conflicts: report.has_conflicts, + review_decision: review_decision.map(|review| NativeReviewDecisionEvidence { + decision: review.decision, + report_hash: review.report_hash, + readiness: review.readiness.as_str().into(), + disposition: review.disposition.as_str().into(), + accepted_degradations: review.accepted_degradations as u64, + signer: review.signer, + }), meta: None, }) }) diff --git a/libatomic/tests/local_service_test.rs b/libatomic/tests/local_service_test.rs index 8d660ada..5ebd9d33 100644 --- a/libatomic/tests/local_service_test.rs +++ b/libatomic/tests/local_service_test.rs @@ -646,7 +646,10 @@ async fn change_blast_radius_is_readonly_change_local_and_uses_view_syntax() { repo.add(wc, "src/api.ts", Default::default()).unwrap(); std::fs::create_dir(dir.path().join("tests")).unwrap(); for (path, source) in [ - ("tests/api.ts", "function test() { changed(); }\n"), + ( + "tests/api.ts", + "import { changed } from '../src/api';\nfunction test() { changed(); }\n", + ), ("src/ui.ts", "import { changed } from './api';\n"), ("unrelated.ts", "function unrelated() { return 1; }\n"), ] { @@ -715,7 +718,23 @@ async fn change_blast_radius_is_readonly_change_local_and_uses_view_syntax() { .iter() .any(|file| file.path == "src/ui.ts" && file.hop == 2)); assert!(!impact.files.iter().any(|file| file.path == "unrelated.ts")); - assert_eq!(impact.edges.len(), 2); + assert_eq!(impact.edges.len(), 3); + assert_eq!( + impact + .edges + .iter() + .filter(|edge| edge.relation == "calls") + .count(), + 1 + ); + assert_eq!( + impact + .edges + .iter() + .filter(|edge| edge.relation == "includes") + .count(), + 2 + ); assert_eq!( before, std::fs::read(database).unwrap(), @@ -739,7 +758,10 @@ async fn change_impact_and_recorded_bytes_use_the_selected_view_not_the_working_ }; for (path, source) in [ ("api.ts", "function changed() { return 1; }\n"), - ("caller.ts", "function caller() { changed(); }\n"), + ( + "caller.ts", + "import { changed } from './api';\nfunction caller() { changed(); }\n", + ), ] { std::fs::write(dir.path().join(path), source).unwrap(); repo.add(wc, path, Default::default()).unwrap(); @@ -798,9 +820,13 @@ async fn change_impact_and_recorded_bytes_use_the_selected_view_not_the_working_ assert_eq!(impact.mode, "structural", "{:?}", impact.warnings); assert!(impact.context.contains(&selected_view)); assert_eq!(impact.files.len(), 2); - assert_eq!(impact.edges.len(), 1); - assert_eq!(impact.edges[0].from_path, "caller.ts"); - assert_eq!(impact.edges[0].to_path, "api.ts"); + assert_eq!(impact.edges.len(), 2); + assert!(impact + .edges + .iter() + .all(|edge| edge.from_path == "caller.ts" && edge.to_path == "api.ts")); + assert!(impact.edges.iter().any(|edge| edge.relation == "calls")); + assert!(impact.edges.iter().any(|edge| edge.relation == "includes")); let file = response .file_contents .iter() diff --git a/libatomic/tests/query_view_service_test.rs b/libatomic/tests/query_view_service_test.rs index 6eb6444c..0dcea8e0 100644 --- a/libatomic/tests/query_view_service_test.rs +++ b/libatomic/tests/query_view_service_test.rs @@ -38,12 +38,12 @@ async fn fixture() -> (tempfile::TempDir, LocalService, pb::RepositoryRef) { repo.switch_view(wc, "feature").unwrap(); std::fs::write( dir.path().join("src/lib.rs"), - "pub fn target(secret: SiblingSecret) {}\npub fn caller() {}\n// inherited_marker\n", + "pub fn target(secret: SiblingSecret) {}\npub fn caller() {}\nmod hidden;\n// inherited_marker\n", ) .unwrap(); std::fs::write( dir.path().join("src/hidden.rs"), - "pub fn sibling_only() { target(); }\n// sibling_marker\n", + "pub fn sibling_only() { crate::target(); }\n// sibling_marker\n", ) .unwrap(); repo.add(wc, "src/hidden.rs", TrackingOptions::default()) From e0e155d4b8c1bd6c2551255bf5deaaf4c3f9cb18 Mon Sep 17 00:00:00 2001 From: Lee Faus Date: Wed, 25 Nov 2026 16:17:06 -0500 Subject: [PATCH 3/4] fix ci --- atomic-cli/tests/review_view.rs | 1 + atomic-semantic/src/relationships.rs | 12 +++-- atomic-semantic/src/source.rs | 8 ++- atomic-semantic/src/source/tests.rs | 77 ++++++++++++++++++++++++++++ 4 files changed, 93 insertions(+), 5 deletions(-) diff --git a/atomic-cli/tests/review_view.rs b/atomic-cli/tests/review_view.rs index ec81a990..cb75bc43 100644 --- a/atomic-cli/tests/review_view.rs +++ b/atomic-cli/tests/review_view.rs @@ -65,6 +65,7 @@ fn document(html: &str) -> Value { #[test] fn named_view_audits_live_snapshot_once_without_switching_or_reading_dirty_bytes() { let directory = tempfile::tempdir().unwrap(); + #[cfg(unix)] let outside = tempfile::tempdir().unwrap(); let mut repo = Repository::init(directory.path()).unwrap(); repo.init_vault().unwrap(); diff --git a/atomic-semantic/src/relationships.rs b/atomic-semantic/src/relationships.rs index b0a8a81e..23917ddd 100644 --- a/atomic-semantic/src/relationships.rs +++ b/atomic-semantic/src/relationships.rs @@ -53,10 +53,14 @@ pub fn module_candidates(file: &str, scope: &[String]) -> Vec { for name in scope { base.push(name); } - vec![ - base.with_extension("rs").to_string_lossy().into_owned(), - base.join("mod.rs").to_string_lossy().into_owned(), - ] + // Source inventories use repository-relative '/' paths on every host. + [base.with_extension("rs"), base.join("mod.rs")] + .into_iter() + .map(|path| { + path.to_string_lossy() + .replace(std::path::MAIN_SEPARATOR, "/") + }) + .collect() } /// Standard explicit relative script import candidates. Full source inventory is diff --git a/atomic-semantic/src/source.rs b/atomic-semantic/src/source.rs index 12e53064..51f07984 100644 --- a/atomic-semantic/src/source.rs +++ b/atomic-semantic/src/source.rs @@ -369,7 +369,13 @@ fn rust_import( } "use_wildcard" => {} _ => { - let argument = node.child_by_field_name("path").unwrap_or(node); + // A scoped_identifier's `path` is only its prefix; unwrapping it + // drops the imported symbol. Only an alias wraps a complete path. + let argument = if node.kind() == "use_as_clause" { + node.child_by_field_name("path").unwrap_or(node) + } else { + node + }; let Some(target) = qualified_path(text(argument, source), "::") else { return; }; diff --git a/atomic-semantic/src/source/tests.rs b/atomic-semantic/src/source/tests.rs index 78e1c55c..d16cbd30 100644 --- a/atomic-semantic/src/source/tests.rs +++ b/atomic-semantic/src/source/tests.rs @@ -1,5 +1,82 @@ use crate::{relationships::SourceGraph, ParserRegistry, Reference}; +#[test] +fn rust_module_candidates_use_repository_separators_on_every_host() { + use crate::relationships::module_candidates; + assert_eq!( + module_candidates("src/main.rs", &["foundation".into()]), + ["src/foundation.rs", "src/foundation/mod.rs",] + ); + assert_eq!( + module_candidates("src/service.rs", &["inner".into()]), + ["src/service/inner.rs", "src/service/inner/mod.rs",] + ); +} + +#[test] +fn rust_imports_keep_terminal_symbols_in_plain_grouped_and_aliased_paths() { + let source = "use crate::foundation::foundation;\nuse crate::foundation::foundation as aliased;\nuse crate::foundation::{foundation as grouped, helper};\nuse crate::{foundation::foundation as nested, service::service};\n"; + let mut parser = ParserRegistry::new(); + let file = parser.analyze_source("src/service.rs", source).unwrap(); + let imports: Vec<_> = file + .imports + .iter() + .map(|import| (import.local.as_str(), import.target.join("::"))) + .collect(); + assert_eq!( + imports, + vec![ + ("foundation", "crate::foundation::foundation".into()), + ("aliased", "crate::foundation::foundation".into()), + ("grouped", "crate::foundation::foundation".into()), + ("helper", "crate::foundation::helper".into()), + ("nested", "crate::foundation::foundation".into()), + ("service", "crate::service::service".into()), + ] + ); +} + +#[test] +fn rust_imported_calls_bind_through_the_declared_module_chain() { + for (import, call) in [ + ("use crate::foundation::foundation;", "foundation"), + ("use crate::foundation::foundation as base;", "base"), + ("use crate::foundation::{foundation};", "foundation"), + ("use crate::{foundation::foundation};", "foundation"), + ("use crate::foundation::{foundation as base};", "base"), + ] { + let sources = [ + ("src/foundation.rs", "pub fn foundation() -> u32 { 1 }".to_owned()), + ("src/service.rs", format!("{import}\npub fn service() -> u32 {{ {call}() }}")), + ("src/main.rs", "mod foundation; mod service; fn main() { service::service(); crate::missing::foundation(); }".to_owned()), + ]; + let mut parser = ParserRegistry::new(); + let files = sources + .iter() + .map(|(path, source)| parser.analyze_source(path, source).unwrap()) + .collect(); + let graph = SourceGraph::new( + files, + sources.iter().map(|(path, _)| (*path).to_owned()), + true, + ); + let calls = graph.bind_calls(None); + let bindings: std::collections::BTreeSet<_> = calls + .iter() + .map(|call| (call.call.caller.as_str(), call.symbol.id.as_str())) + .collect(); + assert_eq!( + bindings, + std::collections::BTreeSet::from([ + ("src/service.rs#service", "src/foundation.rs#foundation"), + ("src/main.rs#main", "src/service.rs#service"), + ]), + "{import}" + ); + assert!(calls.iter().all(|call| call.present && call.accessible)); + } +} + #[test] fn shared_entity_and_reference_apis_keep_qualified_targets_and_owners() { let source = "struct Reader; impl Reader { fn value(&self, x:i32) {} fn run(&self) { self.value(1); } } fn value(x:i32) {} fn consumer(reader:&Reader) { reader.value(2); value(3); module::value(4); }"; From d50705656d9990c64e8bbf4ac037fbcad51013c3 Mon Sep 17 00:00:00 2001 From: Lee Faus Date: Wed, 25 Nov 2026 22:18:57 -0500 Subject: [PATCH 4/4] fix windows --- atomic-cli/src/commands/review/incremental.rs | 60 +++++++++---------- 1 file changed, 29 insertions(+), 31 deletions(-) diff --git a/atomic-cli/src/commands/review/incremental.rs b/atomic-cli/src/commands/review/incremental.rs index 613fe71e..629caccb 100644 --- a/atomic-cli/src/commands/review/incremental.rs +++ b/atomic-cli/src/commands/review/incremental.rs @@ -1176,6 +1176,22 @@ mod tests { (dir, repo) } + // Windows enforces redb's byte-range locks on ordinary file reads too. + // Snapshot only while closed, then exercise the real read-only open path. + fn readonly_snapshot(repo: Repository) -> (Repository, Vec) { + let root = repo.root().to_path_buf(); + let database = repo.dot_dir().join("atomic.redb"); + drop(repo); + let before = std::fs::read(database).unwrap(); + (Repository::open_readonly(root).unwrap(), before) + } + + fn assert_database_unchanged(repo: Repository, before: Vec) { + let database = repo.dot_dir().join("atomic.redb"); + drop(repo); + assert_eq!(before, std::fs::read(database).unwrap()); + } + fn record(repo: &Repository, content: &str) -> Hash { record_path(repo, "subject.txt", content) } @@ -1353,9 +1369,9 @@ mod tests { finding, }], ); - let database_before = std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap(); let source_before = bridge::source_content_hash(&bridge::read_intent(&repo, &intent.id).unwrap()); + let (repo, database_before) = readonly_snapshot(repo); let reviewed = inspect( &repo, IncrementalArgs { @@ -1408,10 +1424,7 @@ mod tests { source_before, bridge::source_content_hash(&bridge::read_intent(&repo, &intent.id).unwrap()) ); - assert_eq!( - database_before, - std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap() - ); + assert_database_unchanged(repo, database_before); } #[test] @@ -1697,7 +1710,7 @@ mod tests { "export function later() { return 0; }\n", ); std::fs::write(repo.root().join("src/user.ts"), "function dirty() {}\n").unwrap(); - let database_before = std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap(); + let (repo, database_before) = readonly_snapshot(repo); let report = inspect( &repo, IncrementalArgs { @@ -1742,10 +1755,7 @@ mod tests { let text = super::super::graph::render(graph); assert!(text.contains("Risk: High") && text.contains("1 current bound caller(s)")); assert!(text.contains("F1") && text.contains("1 incompatible after-contract(s)")); - assert_eq!( - database_before, - std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap() - ); + assert_database_unchanged(repo, database_before); } #[test] @@ -2052,7 +2062,7 @@ mod tests { "evidence": [{"kind": "source", "reference": "src/api.ts:1", "observation": "Selected function returns a constant; caller and export inspection found no incompatible consumers in scoped recorded context"}], }); std::fs::write(&path, serde_json::to_vec(&input).unwrap()).unwrap(); - let database_before = std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap(); + let (repo, database_before) = readonly_snapshot(repo); let reviewed = inspect( &repo, IncrementalArgs { @@ -2073,10 +2083,6 @@ mod tests { ); assert!(graph.findings.is_empty()); assert!(super::super::graph::render(graph).contains("Risk: Low")); - assert_eq!( - database_before, - std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap() - ); input["scope"]["view_state"] = json!("stale"); std::fs::write(&path, serde_json::to_vec(&input).unwrap()).unwrap(); assert!(inspect( @@ -2087,6 +2093,7 @@ mod tests { } ) .is_err()); + assert_database_unchanged(repo, database_before); } #[derive(Parser)] @@ -2165,7 +2172,7 @@ mod tests { }, ) .unwrap(); - let before = std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap(); + let (repo, before) = readonly_snapshot(repo); let archive_only = "selected patch archive probe ".repeat(20_000); report.changes[0].recorded_patch["archive_only_probe"] = json!({"payload":&archive_only,"id":u64::MAX}); @@ -2231,10 +2238,7 @@ mod tests { .collect() ); assert!(projected.iter().any(|region| region.findings.contains(&1))); - assert_eq!( - before, - std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap() - ); + assert_database_unchanged(repo, before); } #[test] @@ -2299,7 +2303,7 @@ mod tests { "export class Dirty {}\n", ) .unwrap(); - let database_before = std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap(); + let (repo, database_before) = readonly_snapshot(repo); let report = inspect( &repo, IncrementalArgs { @@ -2396,10 +2400,7 @@ mod tests { .subject .contains("Later") || record.observation.subject.contains("Dirty"))); - assert_eq!( - database_before, - std::fs::read(repo.dot_dir().join("atomic.redb")).unwrap() - ); + assert_database_unchanged(repo, database_before); } #[test] @@ -3169,12 +3170,9 @@ fn large(x:i32) { #[test] fn inspection_reopened_readonly_does_not_change_database_or_create_session_store() { - let (dir, repo) = fixture(); + let (_dir, repo) = fixture(); let hash = record(&repo, "stable\n"); - let database = repo.dot_dir().join("atomic.redb"); - drop(repo); - let before = std::fs::read(&database).unwrap(); - let repo = Repository::open_readonly(dir.path()).unwrap(); + let (repo, before) = readonly_snapshot(repo); let args = IncrementalArgs { change: Some(hash.to_base32()), ..Default::default() @@ -3182,7 +3180,7 @@ fn large(x:i32) { let first = encode(&inspect(&repo, args.clone()).unwrap()).unwrap(); let second = encode(&inspect(&repo, args).unwrap()).unwrap(); assert_eq!(first, second); - assert_eq!(before, std::fs::read(&database).unwrap()); assert!(!repo.dot_dir().join("sessions").exists()); + assert_database_unchanged(repo, before); } }