diff --git a/.github/skills/tlalink-inspect-correspondence/SKILL.md b/.github/skills/tlalink-inspect-correspondence/SKILL.md index c48a5f7..2c3a7df 100644 --- a/.github/skills/tlalink-inspect-correspondence/SKILL.md +++ b/.github/skills/tlalink-inspect-correspondence/SKILL.md @@ -1,6 +1,6 @@ --- name: tlalink-inspect-correspondence -description: 'Inspect TlaLink source/model correspondence by inlining TLA+/PlusCal, Dafny or P declarations with resolved C# code. Use for reviewing bindings, guards, captures, cleanup, unresolved attachments or targeted agent responses; filter and page links inspect output instead of post-processing large JSON. Read-only inspection, not editing or proof approval.' +description: 'Inspect TlaLink source/model correspondence with inline TLA+/PlusCal, Dafny or P and resolved C#. Use for bindings, guards, captures, multi-step ownership/cleanup review, grouped member context, bounded callee source, unresolved attachments or targeted responses; filter and page links inspect rather than post-process large JSON. Read-only, not editing or proof approval.' --- # Inspect correspondence without editing it @@ -75,7 +75,9 @@ Reuse the same explicit context when refining the query: | Literal name, ID or selected-code fragment | `--search `; not regex or surrounding-context search | | Earlier guard checks or sibling statements | `--section context --context block` | | Whole member, handlers and cleanup | `--section context --context member` | +| Related attachments in source order, shared context once | `--group-by member --context member --section context` plus needed model/source sections | | Explicit call IDs and available source-definition locations | `--section calls`; this requests call resolution automatically | +| One-level selected-source callee excerpts, deduplicated | `--section calls --callee-source true --callee-limit 5 --callee-max-lines 80` | | Only selected output blocks | Repeat `--section model\|source\|context\|captures\|observations\|calls` | | Smaller replies | `--include-unlinked false --limit 5`; continue with the returned `next_offset` | | Metadata/pin details | `--view full --format json`; default compact omits fingerprints | @@ -92,6 +94,38 @@ filters select bindings and retain their other capture entries. Different binding IDs may intentionally observe the same C# statement at different points; do not collapse those model actions as duplicate source locations. +## Multi-step ownership and cleanup review + +1. Discover the real member ID, then start with a member filter and + `--group-by member --context member --section model --section source + --section context --section captures`. The shared map orders attachments + physically and keeps capture points distinct; it is not an execution trace. +2. Add `--section calls --callee-source true --callee-limit 5 + --callee-max-lines 80` if understanding a selected call requires another + source fetch. Callee source implies call resolution; do not combine it with + `--calls false` or sections excluding calls. +3. Read the deduplicated `callee_sources` entries referenced by each call's + `callee_keys`. They are one-level declarations in the selected compilation, + not a recursively expanded program. Calls are collected from the selected + syntax, not automatically from the surrounding context excerpt. +4. Inspect `budget-omitted`, `truncated`, `declaration-only`, + `no-selected-source` and `no-declaration-id` statuses. Omitted cleanup can + invalidate a conclusion. Use `symbols describe` on an emitted ID for the + next justified step rather than blindly raising every budget or recursively + following all calls. Partial method declarations/implementation parts can + have separate catalogue entries. +5. Account for acquisitions, ownership transfers, normal/exception exits and + release attempts versus successful effects in the authored review. Grouping + and body availability do not infer those semantics. Follow relevant implicit + disposal/getters and callback/await behavior separately. + +Paging remains endpoint-based: a member group may contain only part of its +matching attachments, and member-wide filtering is not whole-member coverage. +Unavailable bodies are a review boundary, not permission to invent their +effects. Even when concrete source is present, do not cross a declared +interface/environment boundary or treat a virtual body as the runtime target. +These options never introduce fault injection, scheduling hooks or execution. + ## Read the result before concluding - Check diagnostics and exit code first: `0` resolved structurally, `1` diff --git a/.github/skills/tlalink-source-navigation/SKILL.md b/.github/skills/tlalink-source-navigation/SKILL.md index 37ccff6..3d66852 100644 --- a/.github/skills/tlalink-source-navigation/SKILL.md +++ b/.github/skills/tlalink-source-navigation/SKILL.md @@ -76,6 +76,13 @@ only when the complete pinned result is needed. Symbol commands do not need - Follow emitted call targets with `show`/`describe` when a selected source body exists. `references`/`callers` can also target metadata IDs but still search only selected source; they do not scan framework bodies. +- When already inspecting model/C# pairs, avoid a second lookup for every helper: + use `links inspect --section calls --callee-source true --callee-limit 5 + --callee-max-lines 80` with that inspection's explicit context. Review + page-local callee references, dispatch and omitted/truncated status first. + Expand only a justified next source member with `symbols describe`. + One-level callee excerpts are not recursive call/effect analysis and do not + authorize crossing a declared interface boundary. - Use [source inventory](../../../REFERENCE.md#current-c-source-inventory) when the question needs member-wide access/await/cleanup facts or CFG flow, rather than replacing Roslyn analysis with regexes. diff --git a/AGENTS.md b/AGENTS.md index 2e80616..636380e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,6 +78,14 @@ Skills do not install tools, approve correspondence or discharge human gates. Select the scenario explicitly for preflight as well as execution when only that scenario is needed. Start from synthetic examples, but do not treat their acceptance policies as requirements for a consumer system. +- Reassess existing runs with `accept` before rerunning. Review-only changes + require revisiting the affected decisions, not replaying unchanged execution. + Keep execution applicability, changed review inputs and review status separate; + never carry approval forward merely because native inputs remain current. +- Keep the established caller path spelling during an evidence campaign. + Host-equivalent paths can still produce different native cache keys or be + embedded differently in generated compiler inputs and binaries. Diagnose that + byte drift rather than rewriting receipts or weakening currentness checks. - Report the requested claim, scope, native outcomes, evidence locations, archive consistency, current applicability and acceptance separately. Identify coverage gaps, uncaptured causal edges and outstanding reviews. @@ -365,6 +373,17 @@ its prerequisites; see [testing](REFERENCE.md#tests-and-evidence). Dafny verification/oracles and the individual P checker claims are not interchangeable. State adapter availability and native test coverage separately; missing dependencies never justify weakening requirements. + Do not restrict Dafny to arithmetic, equate TLA+ with finite TLC exploration, + or equate P with sampled schedules. Consider inductive safety for general + data/resource histories, explicit phases for races and dependencies, and + temporal/progress checks with stated environment premises. Keep language + potential separate from supported profiles and measured results. A history + theorem requires a separate argument that C# obeys its legal transitions; + lemma termination is not asynchronous progress. P's ordinary nonblocking + sends must not erase source backpressure, synchronous reentry or memory + lifetimes. Pilot overlapping approaches on one unresolved obligation and + compare proof maintenance, counterexamples, source-bridge effort and runtime + before duplicating models or assuming a different engine scales better. - Tests cache exact selected immutable tool paths once per session, including workflow children through an explicit test host. Hold read leases; on Unix recheck bytes before reporting success. Keep source/configuration/generated diff --git a/DESIGN.md b/DESIGN.md index da31ad7..5c367ae 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -166,6 +166,23 @@ transitive body expansion. Filters/pages cannot hide validation failures or turn an empty selection into an adequacy claim; page-to-page inputs are not transactionally frozen. +Member grouping reuses the already resolved source attachments and merges their +physical excerpts once per containing declaration on the returned page. +Per-attachment lexical context, model identity and capture points remain +separate; source order is not runtime order or a complete member-coverage claim. +Optional callee source expansion uses the same compilation and original +declaration identities as symbol queries, including selected partial +implementation parts. It emits a deduplicated page-local catalogue with +per-call references and explicit unavailable/declaration-only statuses. Unique +declaration and physical-line budgets expose omissions and truncation rather +than hiding them or classifying them as semantic failures. Expansion is exactly +one level from calls in the selected syntax, not from arbitrary surrounding +context; no transitive effects, dynamic dispatch, exception propagation or +resource transfer are inferred. All source/compiler pins remain checked. +Public controls use independent synthetic member/handler/call fixtures and +exercise budget thresholds, generic/extension identities, partial methods, +nested functions, paging and section projection. + One schema-4 `correspondence-scope` names explicit language/input aliases and symbol-resolved routine omission rules. Each connection has one unique `scope::name` ID, a compiler-resolved source attachment and a native attachment. @@ -401,6 +418,9 @@ integration, a causal trace or model conformance. Build projects, the harness, compiler/source-generator behavior and OS/runtime remain trusted. Inputs exposed at the MSBuild capture boundary are recorded; this is not a complete MSBuild workspace or authenticated compiler/runtime closure. +The SDK version is captured from `NETCoreSdkVersion` in that same observed +build, not from an extra `dotnet --version` process in a different directory. +The archived `sdk.log` contains this build-reported value. Source inventories can use that recorded reference closure and defines with explicit nullable mode, rather than silently adding the tool host's framework @@ -613,6 +633,24 @@ Unsupported dependencies or incomplete searches do not justify substituting another checker or weakening an acceptance requirement. Native test coverage is stated separately from adapter availability. +Language expressiveness, checker guarantees and integrated profiles are separate +design dimensions. Dafny supports inductive concurrent-system safety arguments, +not just arithmetic; TLA+ supports deduction as well as explicit-state checking; +P supports deductive invariants as well as schedule exploration. Unsupported +upstream backends do not become evidence stages merely by being named here. +Keep a suitable existing model when another checker can discharge its obligation; +use a focused comparison before introducing a second specification. + +For history-based safety, one-step preservation and induction establish what +legal abstract executions preserve. Showing that C# produces those legal steps +is a separate source-language bridge, not a consequence of a transition guard. +Unbounded finite histories do not imply arbitrary parameters or eventual +completion. Preserve synchronous reentry, shared storage, backpressure and +effect/settlement phases when choosing an event-driven abstraction; P's ordinary +nonblocking sends, for example, do not implement a blocking I/O contract. +Cross-backend results compose only through justified relations and compatible +assumptions, never merely through passing stages. + Production hashing streams original bytes without tool-sized allocations. The console harness installs an internal, test-session lookup only for exact canonical paths to its selected immutable tool distributions, pinned Java @@ -635,9 +673,19 @@ solver cost; the cache does not remove JVM startup or archive-copy costs. ## Authoritative frontends and paths -TLA+ parsing uses SANY, not a local interpreter or replacement parser. The companion -embedded in the C# bridge supplies declared variables/operator arities. The -bridge creates fresh processes +Integrated inspection may select only TLA+ targets, without initializing a +Dafny frontend or fabricating a proof binding. Its TLA+ native inventory and +formal-owned source attachments are checked against archived model/source bytes +and compiler references. Native declaration extents are recorded frontend +evidence, not a second model parser or authenticated proof of frontend behavior. +Verification/oracle commands still require selected Dafny bindings. An +inspection cannot claim proof, audit or execution outcomes, and neither an empty +manifest nor missing selected attachments can produce ready evidence. + +TLA+ parsing uses SANY, not a local interpreter or replacement parser. One typed +bridge response supplies endpoints, dependencies, declared variables and operator +arities from the same SANY pass; metadata does not start a second JVM or repeat +parsing. The bridge compiles one adapter and creates fresh processes to isolate upstream static state and cleans its own temporary compiler outputs. SANY/PlusCal compilation and execution, TLC stages and trace matching share the repository's `java-toolchain.json` pin through `Common/JavaToolchain.cs`. @@ -859,6 +907,8 @@ not a reuse decision. The adapter version, not the TlaLink binary hash, scopes entries, so it must change whenever TLC invocation or result interpretation changes. Requiring passes under several fingerprint functions reduces, but does not eliminate, fingerprint collision risk. +Stored-key input lookup uses the host filepath comparer for absolute paths and +ordinal comparison for named metadata inputs, rejecting aliased path keys. Run metadata separates execution completion from stage outcomes and acceptance. Acceptance rechecks exact declared stages, semantic result consistency, @@ -866,6 +916,44 @@ artifacts, archived bytes, current inputs and required review dispositions. Artifacts are run-relative; source paths inside a relocated project are mapped relative to its recorded root. External tool/reference paths remain explicit. +Review-only inputs are dependencies of review decisions, not native execution. +New runs do not add required review inputs to their execution fingerprints. +For a completed run with broad input pins, acceptance can classify an input as +review-only only when a required review explicitly declares it and validated +stage evidence establishes the execution closure. Authoring documents, compiler +references, stage declarations, method-summary support and backend fingerprints +remain execution dependencies; execution wins when roles overlap. Stored TLC +keys supply its complete execution inputs. Missing, inconsistent or unknown +closures keep current-byte checks conservative. Every original archived input +is still checked, and `changed_review_inputs` exposes exempted current-file +drift without renewing any review. + +Project/policy authoring is compared semantically before review-only drift is +exempted. Acceptance independently reconstructs the archived project and +validates its saved expansion, root hash and archived policy hash. Typed +projections retain the entire execution definition except review obligations, +review-directory selection and policy-document location. Every requirement +field except its review references remains in the checker-expectation +projection. New fields are retained by those record projections and unknown +JSON fields fail boundary decoding; there is no DOM field-stripping allowlist. +Complete-project comparison deliberately remains conservative about ordering, +path spellings, unused tools and other scenarios. + +Only equivalent execution and checker projections permit automatic current-policy +reassessment in the existing accept/explain/report flow. The resulting typed +policy comparison links recorded/current project, policy and authoring hashes, +compatibility judgments and changed areas. Native stage/compiler/summary input +roles override this exemption, including when a stage consumed authoring bytes. +Incomplete evidence or an unknown execution closure cannot turn a changed +project into current execution. All original archived inputs and artifacts are +still checked; approvals are never inherited from different review identities +or origins. Current policy authorship remains trusted, not authenticated. + +This reassesses existing provenance, writes only new acceptance/report outputs, +and does not record a new execution or introduce a backend cache. Incompatible +execution/requirement changes remain stale and require appropriate fresh +evidence; pending or stale current reviews remain separate acceptance blockers. + Review decisions are append-only sidecar records, never edits to pinned run inputs. They pin the claim/assumptions, explicit source inputs and supporting evidence. Claim or input drift invalidates prior review. The newest decision diff --git a/README.md b/README.md index 64943df..67be096 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,12 @@ checkable: earlier results no longer apply. The agent then updates the model and reruns the affected checks. +Before rerunning, the agent can reassess an existing run. Changes confined to +review policy or review context do not replay unchanged execution: TlaLink +checks the archived execution and checker requirements, then evaluates the +current reviews separately. New or changed reviews are never approved merely +because the execution still applies. + The goal is to move from **"the agent says this looks correct"** to **"here is the evidence, its scope and what remains unproven."** You do not need to read or write TLA+, Dafny or P yourself. @@ -124,6 +130,9 @@ declaration alongside its selected C# code, surrounding control/lock context and observation metadata, without changing either source. Filter by source member, attachment status or capture point, and request only the sections needed for the review. +Group related attachments by C# member and optionally inline bounded, +one-level selected-source callee excerpts to review multi-step cleanup paths +without repeatedly fetching the same code. Agents can load the focused [workspace CLI skills](AGENTS.md#agent-cli-skills) for source navigation, correspondence inspection and deliberate link maintenance. @@ -160,6 +169,8 @@ TlaLink does not model a whole program at once. For a larger system: TLC searches are reused while their models and configurations are unchanged, like an incremental build. Expensive searches can run once, separately, with a larger budget. See [reusing results](REFERENCE.md#reusing-completed-tlc-results). + Reassess existing runs with `accept` before executing again: review-only + document changes require fresh reviews, not fresh native execution. Combining checks in one project is for organization and repeatability. It does not prove that the separate results add up to a system-wide guarantee. @@ -229,11 +240,14 @@ need the ones your chosen checks use. | [Roslyn](https://github.com/dotnet/roslyn) | Resolving the C# side of the links. | | [TLA+ tools](https://github.com/tlaplus/tlaplus) (SANY, PlusCal, TLC) | Parsing TLA+ models, exploring their states and checking recorded executions. | | [Apalache](https://apalache-mc.org/) | Symbolic checking of TLA+ safety properties. | -| [Dafny](https://dafny.org/) | Verifying algorithms and comparing selected C# calls with verified results. | +| [Dafny](https://dafny.org/) | Proving algorithmic contracts and modeled safety invariants, including arbitrary finite histories; comparing selected C# calls with verified results. | | [P](https://p-org.github.io/P/) | Checking asynchronous state-machine models and logs. | -Each checker gives a different kind of guarantee; the -[selection guide](REFERENCE.md#choosing-tools-and-checkers) compares them. +Choose by the question, not a fixed language ranking. General safety proofs, +interleaving exploration and eventual-progress checks need different evidence; +none automatically proves the linked C#. The +[selection guide](REFERENCE.md#choosing-tools-and-checkers) compares modeling +fit, checker guarantees and current integration limits. ## Limitations diff --git a/REFERENCE.md b/REFERENCE.md index 13573e9..f48f038 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -456,7 +456,7 @@ capability: | Apalache typechecking | Catch inconsistent model data types before behavioral analysis | Requires native type annotations where inference is insufficient. Successful typing is not safety. | | Apalache bounded safety | Search typed TLA+ safety models through an explicit transition bound, without enumerating every concrete state | SMT encodings can help with data combinations but solver cost is model-dependent. A pass is only bounded safety; this integration excludes temporal checking, simulation and trace matching. | | Apalache induction | Establish initiation, preservation and safety implication for a supplied invariant | Can establish safety beyond a search bound, but requires a sufficiently strong typed/domain-constrained invariant and all three feasible obligations. Limited to the selected constants and supported profile, not arbitrary parameters or C# refinement. | -| Dafny verification / assumption audit | Verify supplied algorithmic contracts, loop invariants and lemmas, and inspect trusted assumptions | Deductive reasoning can avoid state enumeration but needs proof annotations and solver support. Verification establishes the scoped Dafny program under its assumptions, not linked C#. | +| Dafny verification / assumption audit | Verify algorithmic contracts, data/resource invariants and inductive safety arguments over arbitrary legal finite histories; inspect trusted assumptions | Deductive reasoning can avoid state enumeration but needs proof annotations and solver support. History proofs establish properties of the modeled transitions, not that linked C# generates only legal transitions or eventually completes. | | Dafny executable oracle comparisons | Compare concrete C# adapter calls with upstream-compiled, verified Dafny behavior | Useful executable examples, but only for selected cases and supported synchronous int/bool adapters. Passing comparisons are not C# verification or exhaustive testing. | | P frontend | Resolve state machines, events and qualified P/C# correspondence bindings | Native declarations and structural links only; no schedule exploration or automatic execution of the linked C#. | | PChecker | Explore explicitly budgeted schedules of an asynchronous P model, with reproducible seeds | Often useful for finding interleaving bugs. Schedule sampling is not finite exhaustion; step limits and deadlines leave checks incomplete. | @@ -477,6 +477,76 @@ exhaustion, induction, oracle comparisons and log monitoring are distinct claims. Keep the selected configuration, assumptions, bounds and independent acceptance requirements explicit; one claim cannot silently substitute for another. +### Match the obligation, not a language stereotype + +Do not restrict Dafny to arithmetic, TLA+ to small finite instances, or P to +sampled schedules. Distinguish the language's expressive power, the selected +checker, the supported TlaLink profile, provisioned dependencies and actual +native evidence. The following are modeling choices, not a fixed tool order +or claims that these obligations have already been discharged: + +| Obligation | Useful approach | Boundary to preserve | +|---|---|---| +| Numeric bounds, sequence contents and data transformations | Dafny contracts, loop invariants and sequence lemmas | Mathematical values need explicit machine-range premises; content equality does not establish allocator, exception or concurrent-access behavior. | +| Ownership, conservation, identity maps and one-shot authorization | Dafny state invariants and induction over transitions or histories; TLA+ induction when the state machine is already authored there | Distinguish authorization, effect attempt, successful effect and completion. Shared storage and every relevant source transition need justification. | +| Cancellation, callback reentry, notification replacement and reuse races | Explicit TLA+ phases with TLC exploration; P when its event semantics faithfully represent those phases | Do not merge registration, synchronous callbacks, notification and cleanup into one convenient atomic step. A discovered invariant can subsequently support a general deductive argument. | +| Communicating protocols, peer failures and asynchronous coordination | P state machines and monitors, or TLA+ actions; choose the P backend by the required exploration/proof claim | Model capacity, blocking, ordering and failures explicitly rather than inheriting stronger communication guarantees. | +| Deadlock, shutdown dependencies and eventual progress | TLA+ dependency/temporal models with an appropriate checker, or P progress specifications with a supported backend | State scheduling, consumer, callback and external-settlement premises. Safety, absence of deadlock and eventual completion are different obligations. | +| Generalizing beyond explored instances | Dafny induction, supported Apalache invariant induction, or an explicitly supported deductive backend | Unbounded history length, arbitrary participant count and arbitrary numeric parameters are separate dimensions. A larger run or symmetry audit is not a cutoff theorem. | +| Relating a model to C# | Roslyn source premises, source-pinned inspection, meaningful controls and supported execution evidence | Neither a model theorem nor matching declarations establishes general C# refinement. Cross-model assumptions and relations remain explicit obligations. | + +### Deductive safety and the source bridge + +Dafny can define an event datatype, state, transition relation and invariant, +prove one-step preservation, then induct over a finite event sequence. An +arbitrary-finite-history theorem covers every permitted finite sequence with +no fixed length cutoff; a prefix may end with operations still pending. +Participant domains, capacity bounds and other parameters retain their +separately declared scope. Proving termination of the replay function or lemma +does not prove progress of the modeled asynchronous system. + +Review the legal-transition premises independently. If a transition permits an +effect only after authorization, the model proof does not also prove that C# +enforces authorization. Establish that bridge through supported source premises +and an explicit semantic argument, including competing accesses, failures, +cleanup and relevant callees. Use defect-relevant controls to challenge that +bridge as well as the invariant; do not make a counterexample disappear by +declaring the offending source behavior illegal without justification. + +### Capabilities beyond a single checker + +TLA+ is not synonymous with TLC. Existing TLA+ safety models may benefit from +Apalache induction without translation to another language. Upstream +[TLAPS](https://proofs.tlapl.us/doc/web/content/Home.html) also checks deductive +safety proofs, potentially with parameterized arguments; it is not a supported +TlaLink evidence adapter, and its documented temporal-reasoning limitations +must remain explicit. Do not present upstream capabilities as provisioned +project stages. Likewise, upstream Apalache modes outside the supported +profile are not enabled by their presence in upstream documentation. + +P has deductive verification through +[PVerifier](https://p-org.github.io/P/advanced/PVerifierLanguageExtensions/announcement/), +not only schedule exploration. Its suitability still depends on the authored +invariant, supported model and available dependencies. Under +[P's communication semantics](https://p-org.github.io/P/advanced/psemantics/), +ordinary sends are reliable, buffered and nonblocking. Backpressured I/O, +borrowed-storage lifetimes, shared-memory operations and synchronous reentry +need explicit modeling; an actor rewrite must not remove relevant waits or races. +Observed-log monitoring remains limited to the events and ordering actually +supported by the log, not all implementation behavior. + +When several approaches fit, pilot the smallest unresolved obligation and +compare counterexample usefulness, proof/model maintenance, source-bridge +effort and measured runtime/resources. State explosion motivates investigation, +not an assumption that symbolic checking or induction will be cheaper. +Exploration can discover an invariant that deduction generalizes; neither +automatically composes with another language's theorem. Prefer retaining a +suitable existing model over maintaining duplicate specifications without a +specific evidence benefit. See upstream +[Dafny induction guidance](https://dafny.org/latest/OnlineTutorial/Lemmas), +[TLA+ tools](https://lamport.azurewebsites.net/tla/tools.html) and +[Apalache modes](https://apalache-mc.org/docs/apalache/running.html). + ### Using Apalache with TLA+ Apalache uses the same TLA+ language, not a simpler replacement language. @@ -1161,6 +1231,73 @@ requirement unsatisfied (`WF015`, exit 1) even when run inputs are current. If run inputs also changed, their stale-evidence diagnostic instead makes the exit 2. Do not infer review approval from current run applicability. +Before rerunning a scenario, use `accept` on its existing run. Changes to files +declared only as required review inputs affect review freshness, not execution +applicability. New runs do not pin these files as execution inputs. Acceptance +also recognizes review-only pins in completed runs when validated stage +evidence supplies the execution closure; `changed_review_inputs` lists changed +or removed files whose execution checks were exempted. Archive bytes remain +strictly checked. A file also used by a stage, compiler context or selected +method summary remains an execution input. Unknown or invalid closures remain +conservative. +This does not rerun or cache native work, renew reviews or imply acceptance. +The existing TLC result store is still the only native execution reuse mechanism. + +#### Automatic review-policy reassessment + +Use the ordinary commands; there is no bypass flag or separate update command: + +```powershell +.\TlaLink.ps1 accept --project .\tlalink.project.json --run .\Results\existing-run --output .\Results\reassessment-new.json --format summary +``` + +`accept`, `explain` and project `report` automatically reconstruct the recorded +project from archived authoring and independently check its saved expansion. +When project/policy bytes changed, they compare the complete normalized +execution definition and every acceptance requirement with only its `reviews` +list excluded. Review obligations, review storage and the policy document's +path may differ; stages, dependencies, source/model/config selections, compiler +context, tools, resources, budgets, summary dependencies, check-coverage +declarations and every non-review requirement field must remain identical. +The comparison is conservative about list order and path spelling. + +The typed `policy_reassessment` result is retained in full acceptance receipts, +summaries and project report acceptance snapshots: + +- `unchanged`: recorded/current authoring and policy identities match. +- `review-only`: the validated archived execution definition and non-review + requirements match; the explicitly authored current review policy is evaluated. +- `incompatible`: an execution definition or checker expectation changed. +- `unavailable`: archived comparison material is missing or invalid. + +It includes recorded/current project, policy and authoring hashes, two explicit +compatibility judgments and bounded changed-area labels. This classification +does not replace `archive_status`, `current_applicability` or `acceptance_status`. +A file also consumed by native execution remains an execution dependency even +when it is project/policy authoring. Unknown stage closures do not receive +exemptions. Missing or corrupted archived files still fail integrity checks. +Unknown JSON fields are rejected, not projected away. + +Review consolidation therefore can leave execution applicability `current` +while acceptance remains `not-accepted` because the replacement review is +`pending`. Current obligations, origins, claims, assumptions, input bytes and +decisions are checked normally; old IDs and agent decisions cannot grant a new +human approval. The current policy is an explicit trusted authoring input: +reassessment does not authenticate or authorize its edits. + +The original run, outcomes and input archive are never rewritten. A new +acceptance receipt identifies both policies and the unchanged run hash. +This is reevaluation of existing evidence, not execution reuse for additional +backends or permission to change properties/configuration pins to fit results. + +Keep caller path spelling consistent across a campaign. Native build tools can +embed it in generated configuration, assemblies and debug information; changed +bytes remain actual drift even when the host considers the paths equivalent. +Likewise, stored key bytes retain their original path spelling. Acceptance uses +the host comparer for filepath lookups, not case-folded metadata IDs or rewritten +historical paths. Shared build outputs can stale earlier compiler observations; +recollect affected observations rather than treating those outputs as review-only. + ### Persistent review decisions Review decisions live outside the project/run files so review after execution @@ -1478,7 +1615,7 @@ bytes, not only source files. Keep shared-machine disk usage in mind. | Command | Evidence produced | |---|---| -| `inspect-integrated` | Resolved C#/Dafny links, inventories, optional TLA links, explicit correspondence obligations; no proof or execution | +| `inspect-integrated` | Resolved C#/formal links and inventories for selected TLA+ targets and/or Dafny bindings; no proof or execution | | `verify-integrated` | The above plus Dafny verification and a clean assumption audit over the complete local include closure | | `test-integrated` | The above plus verified concrete call preconditions, generated Dafny C# oracle/runtime and actual C# adapter comparisons | | `read-integrated` | Archived byte consistency and optional current-file applicability, separately from recorded outcomes; no rerun or project acceptance | @@ -1488,6 +1625,13 @@ and `--baseline` (a prior current-format result). A baseline detects changed, ad removed maintained inputs; it does not replace review. `--jar` is required only when the manifest selects TLA+ models. Existing TLA-only commands retain their command names and do not require Dafny; their JSON uses the same current schema. +`inspect-integrated` and project `inspect` stages also support a TLA+-only +manifest (`bindings: []`, nonempty `tla_targets`) without selecting or launching +Dafny. Such results remain inspection-only: proof, audit and execution are +`not-run`. `verify-integrated`, `test-integrated`, `verify` and `oracle` still +require actual selected Dafny bindings; an empty manifest never succeeds. +Archived readers check the selected TLA+ declarations, native source extents, +formal-owned selectors, C# attachments and pinned input closure independently. ### One explicit binding manifest, not another source annotation language @@ -1497,12 +1641,12 @@ command names and do not require Dafny; their JSON uses the same current schema. - `scope`: one correspondence scope whose aliases select explicit native files. Proof/model inputs come from the selected inline bindings' aliases, not duplicate `proofs`/`models` arrays. -- `tla_targets`: explicit TLA+ aliases to review alongside Dafny; default `[]`. +- `tla_targets`: explicit TLA+ aliases to review alone or alongside Dafny; default `[]`. Merely declaring another alias or having links in C# does not select that native frontend or require its tool. - `bindings`: unique inline binding `id`, nullable C# `adapter`, and explicit - `cases` with unique IDs and typed `inputs`. Source/formal endpoints belong in - C# `bind` entries; duplicate manifest endpoints are rejected. + `cases` with unique IDs and typed `inputs`. Formal-owned `bind.source` + selectors resolve the C# endpoints; duplicate manifest endpoints are rejected. - Roslyn resolves the attached C# declaration directly, including overloads. Review-only bindings can target fields/properties. Explicit adapters retain resolved C# symbol selectors where the native oracle requires them. @@ -1925,6 +2069,10 @@ and sufficient compiler context, just like `links check`. | `--context 0..20` | Surrounding physical C# lines; default `3`. Selected multiline syntax is always shown in full. | | `--context block` | Show the nearest enclosing C# block, including sibling statements. | | `--context member` | Show the containing member; useful for earlier guard clauses and cleanup paths. | +| `--group-by member` | Add a source-ordered attachment map per containing C# member and show shared context once instead of repeating it per binding. Default `endpoint` keeps the original view. Paging still counts native endpoints; groups report returned versus matching attachment counts. | +| `--callee-source true` | Request calls and inline one-level selected-source declarations in a deduplicated catalogue. Default `false`. Requires the calls section and conflicts with `--calls false`; does not infer concrete virtual/interface/delegate dispatch or expand transitive callees. | +| `--callee-limit 1..100` | With callee source enabled, maximum unique declaration excerpts across the returned page; default `10`. Repeated calls reuse catalogue entries. Omitted declarations remain listed as `budget-omitted`. | +| `--callee-max-lines 1..500` | Maximum physical lines per callee excerpt; default `80`. Truncated entries report total and omitted lines. Both callee budgets require `--callee-source true`. | | `--view compact` | Default. Concise readable captures; JSON omits the potentially large fingerprint map. Compiler settings, diagnostics and omission counts remain visible. | | `--view full` | Include raw capture/selector JSON in readable output and the complete checked fingerprint map in JSON. | | `--include-unlinked false` | Hide unlinked and declared-hidden native declarations; report how many were omitted. Default `true`. | @@ -1965,6 +2113,35 @@ omits unrequested JSON fields and readable blocks consistently; source context can itself contain selected code even when the separate `source` section is omitted. +For multi-step ownership or cleanup review, combine `--symbol +--group-by member --context member --callee-source true` with the ordinary +filters and sections. `member_groups` lists returned attachments in physical +source order with their model endpoint names and capture points, not runtime +execution order. Shared context merges the selected excerpts; numbered gaps +remain omissions. With member grouping, JSON places these shared `lines` in +the group instead of each attachment, but retains each attachment's exact +selection, lexical frames and calls. The context section controls shared lines; +identities and group counts remain present when context is omitted. +Unresolved and unlinked entries remain in the endpoint list rather than being +silently assigned to a source member. + +`callee_sources` contains one excerpt per selected-source declaration, referenced +by page-local `callee_keys` on calls. The catalogue is populated only from calls +within returned selected syntax, not the surrounding member excerpt unless that +whole member is itself selected. Budgets are consumed in deterministic endpoint/ +binding/call order; partial declarations and implementation parts count separately. +An interface/abstract signature can be `declaration-only`; metadata or other +unavailable bodies report `no-selected-source`. Calls without an addressable +declaration ID report `no-declaration-id`. These are explicit inspection limits, +not inferred concrete implementations. Original generic/reduced-extension IDs, +constructed target signatures and nested-function flags remain visible. +No recursive expansion, property/implicit-disposal expansion, exception summary +or ownership inference is performed. A truncated excerpt can omit its cleanup; +inspect the reported remaining lines before drawing a conclusion. Source +availability does not override an authored interface/environment scope boundary. +Budget omissions do not fail an otherwise structurally ready inspection; +summary output counts omitted/truncated declaration excerpts separately. + Use the existing explicit references/defines/language settings, or `--regression-result ` to reuse a recorded compiler context; selected sources must actually occur in that compiler's input list. @@ -2518,6 +2695,12 @@ drift, finite caller-state counts, result reuse, report composition and native misuse controls. It requires only the selected TLA+ JAR and pinned Java toolchain. Core summary controls also run under `--core`. +`--frontend` selects the native SANY/PlusCal parity, metadata/arity, import, +translation freshness, source extent and failure controls without running +unrelated proof or trace suites. It requires only the selected TLA+ JAR and +pinned Java toolchain. Endpoint and metadata resolution share one SANY pass; +parsing remains fresh, not a cached native result. + `--trace` selects scalar argument, entity/guard, causal-order and whole-trace controls. It requires only the selected TLC JAR and pinned Java toolchain, not Dafny, Apalache or P. diff --git a/src/tlalink/Common/AcceptanceWorklist.cs b/src/tlalink/Common/AcceptanceWorklist.cs index 9b8d81f..fa51f64 100644 --- a/src/tlalink/Common/AcceptanceWorklist.cs +++ b/src/tlalink/Common/AcceptanceWorklist.cs @@ -72,7 +72,8 @@ void Group(string kind, string action, List items) .Select(g => new DiagnosticItem(g.Key.Code, g.Key.Severity, g.Count(), g.First())).ToList()); Dictionary counts = new(StringComparer.Ordinal) { ["diagnostics"] = summary.Diagnostics.Count, ["requirements"] = summary.Requirements.Count, - ["check_coverage"] = summary.CheckCoverage.Count, ["review_status"] = summary.ReviewStatus.Count + ["check_coverage"] = summary.CheckCoverage.Count, ["review_status"] = summary.ReviewStatus.Count, + ["changed_review_inputs"] = summary.ChangedReviewInputs.Count }; Dictionary? Omitted(params (string Name, int Count)[] fields) { @@ -97,7 +98,8 @@ static Dictionary StatusCounts(IEnumerable statuses) => sta Requirements = c.Requirements.Take(detailLimit).ToList(), Gaps = c.Gaps.Take(detailLimit).ToList(), Omitted = Omitted(("requirements", c.Requirements.Count), ("gaps", c.Gaps.Count)) }).ToList(), - ReviewStatus = summary.ReviewStatus.Take(detailLimit).ToList() + ReviewStatus = summary.ReviewStatus.Take(detailLimit).ToList(), + ChangedReviewInputs = summary.ChangedReviewInputs.Take(detailLimit).ToList() }; } } diff --git a/src/tlalink/Common/CliOptions.cs b/src/tlalink/Common/CliOptions.cs index 0a9ce27..d4328be 100644 --- a/src/tlalink/Common/CliOptions.cs +++ b/src/tlalink/Common/CliOptions.cs @@ -30,7 +30,7 @@ public CliOptions(string[] args) "regression-result", "jar", "dafny", "p", "binding", "endpoint", "symbol", "syntax", "tokens", "match", "expected-matches", "capture", "clear-capture", "reason", "output", "timeout", "format", "apply", "strip-source", "reason-policy", "context", "view", "include-unlinked", "calls", "source-file", "kind", "status", "capture-point", - "search", "section", "offset", "limit"], + "search", "section", "offset", "limit", "group-by", "callee-source", "callee-limit", "callee-max-lines"], ["check-dafny"] = ["config", "dafny", "output", "timeout", "format"], ["read-dafny"] = ["result", "current", "format"], ["check-regression"] = ["config", "output", "timeout", "format"], @@ -88,7 +88,8 @@ public CliOptions(string[] args) !(Command == "links" && Action == "inspect" && Get("format", "json") == "markdown")) throw new InputException("Format must be json, text or summary; links inspect also accepts markdown."); if (Command == "links" && Action != "inspect" && new[] { "context", "view", "include-unlinked", "calls", - "source-file", "kind", "status", "capture-point", "search", "section", "offset", "limit" }.Any(Has)) + "source-file", "kind", "status", "capture-point", "search", "section", "offset", "limit", + "group-by", "callee-source", "callee-limit", "callee-max-lines" }.Any(Has)) throw new InputException(ErrorCode.InvalidAnnotation, "Inspection filters and presentation options require links inspect."); int maximum = Command == "check-stage" ? 172800 : 7200; if (!int.TryParse(Get("timeout", "30"), out int timeout) || timeout < 1 || timeout > maximum) throw new InputException($"Timeout must be 1..{maximum} seconds."); diff --git a/src/tlalink/Common/CommandSummary.cs b/src/tlalink/Common/CommandSummary.cs index fef0365..79553d9 100644 --- a/src/tlalink/Common/CommandSummary.cs +++ b/src/tlalink/Common/CommandSummary.cs @@ -11,7 +11,8 @@ internal static CommandSummaryResult Create(object value, CliOptions options, Ac WorkflowRun run => Workflow(run), ProjectPlan plan => new ProjectPlanSummary(plan.Kind, plan.Project, plan.Status, plan.AnnotationVersion, plan.MethodSummaries.Select(s => new PlannedMethodSummaryView(s.Scope, s.Summary, s.Method, - s.InspectionStatus, s.InspectionOrigin, s.Boundary)).ToList(), + s.InspectionStatus, s.InspectionOrigin, s.Boundary, + s.Precondition is { } p ? new(p.Name, p.Scope, p.Kind, p.Location) : null)).ToList(), plan.CheckCoverage.Select(Coverage).ToList(), plan.Diagnostics, plan.Scenarios.Select(s => new PlannedScenarioSummary(s.Id, s.Stages.Select(stage => new PlannedStageSummary(stage.Id, stage.Kind, stage.DependsOn, stage.RequestedResources, @@ -115,7 +116,8 @@ private static AcceptanceSummary Acceptance(AcceptanceResult result, AcceptanceW result.Diagnostics, result.CheckCoverage.Select(Coverage).ToList(), result.MethodSummaries, result.Reviews.Select(r => new ReviewSummary(r.Obligation, r.Status, r.Decision?.Disposition, r.Decision?.Reviewer, r.Decision?.Rationale, r.Decision?.RecordedAt, r.Decision?.Origin)).ToList(), - result.NextActions, result.Boundary) { Run = result.Run }; + result.NextActions, result.Boundary) { Run = result.Run, ChangedReviewInputs = result.ChangedReviewInputs, + PolicyReassessment = result.PolicyReassessment }; return worklist == null ? summary : worklist.Apply(summary); } diff --git a/src/tlalink/Common/InspectionFiltering.cs b/src/tlalink/Common/InspectionFiltering.cs index 6219078..d386a23 100644 --- a/src/tlalink/Common/InspectionFiltering.cs +++ b/src/tlalink/Common/InspectionFiltering.cs @@ -9,7 +9,13 @@ namespace TlaLink; public sealed record InspectionQuery(List Bindings, List Endpoints, List Symbols, List SyntaxKinds, List SourceFiles, List Kinds, List Statuses, List CapturePoints, - string? Search, List Sections, int Offset, int? Limit); + string? Search, List Sections, int Offset, int? Limit) +{ + public string GroupBy { get; init; } = "endpoint"; + public bool CalleeSource { get; init; } + public int CalleeLimit { get; init; } = 10; + public int CalleeMaxLines { get; init; } = 80; +} internal static class InspectionFiltering { @@ -45,15 +51,30 @@ int Number(string key, int fallback, int minimum) throw Invalid("--syntax requires a Roslyn SyntaxKind name."); string? search = options.Optional("search"); if (search != null && string.IsNullOrWhiteSpace(search)) throw Invalid("--search must be nonempty."); + string groupBy = options.Get("group-by", "endpoint"); + if (groupBy is not ("endpoint" or "member")) throw Invalid("--group-by must be endpoint or member."); + string calleeSource = options.Get("callee-source", "false"); + if (calleeSource is not ("true" or "false")) throw Invalid("--callee-source must be true or false."); + if (calleeSource == "true" && (options.Get("calls", "true") == "false" || !sections.Contains("calls"))) + throw Invalid("--callee-source true requires the calls section and cannot be combined with --calls false."); + if (calleeSource == "false" && new[] { "callee-limit", "callee-max-lines" }.Any(options.Has)) + throw Invalid("Callee budgets require --callee-source true."); + int calleeLimit = Number("callee-limit", 10, 1), calleeMaxLines = Number("callee-max-lines", 80, 1); + if (calleeLimit > 100 || calleeMaxLines > 500) + throw Invalid("--callee-limit must be 1..100 and --callee-max-lines must be 1..500."); return new(Values("binding"), Values("endpoint"), symbols, syntax, Values("source-file").Select(FilePaths.Full).Distinct(FilePaths.Comparer).ToList(), Values("kind"), Values("status", ["linked", "unlinked", "declared-hidden", "unresolved"]), Values("capture-point", ["invoke", "commit", "complete", "fault", "cleanup", "none"]), - search, sections, Number("offset", 0, 0), options.Has("limit") ? Number("limit", 1, 1) : null); + search, sections, Number("offset", 0, 0), options.Has("limit") ? Number("limit", 1, 1) : null) + { + GroupBy = groupBy, CalleeSource = calleeSource == "true", + CalleeLimit = calleeLimit, CalleeMaxLines = calleeMaxLines + }; } internal static bool IncludeCalls(CliOptions options, InspectionQuery query) => - options.Get("calls", "false") == "true" || options.Has("section") && query.Sections.Contains("calls"); + query.CalleeSource || options.Get("calls", "false") == "true" || options.Has("section") && query.Sections.Contains("calls"); internal static string? SourceSymbol(SourceBinding binding) { @@ -119,8 +140,16 @@ void Section(string section, params string[] members) Section("source", nameof(InspectionSource.SelectedText)); Section("context", nameof(InspectionSource.Lines), nameof(InspectionSource.Context), nameof(InspectionSource.Boundaries), nameof(InspectionSource.Locks)); + if (result.Query?.GroupBy == "member") + foreach (JsonPropertyInfo property in type.Properties.Where(p => + p.Name == Files.Json.PropertyNamingPolicy!.ConvertName(nameof(InspectionSource.Lines)))) + property.ShouldSerialize = (_, _) => false; Section("calls", nameof(InspectionSource.Calls)); } + else if (type.Type == typeof(InspectionMemberGroup)) + Section("context", nameof(InspectionMemberGroup.Lines)); + else if (type.Type == typeof(LinkInspectionResult)) + Section("calls", nameof(LinkInspectionResult.CalleeSources)); }); return JsonSerializer.Serialize(result, new JsonSerializerOptions(Files.Json) { TypeInfoResolver = resolver }); } diff --git a/src/tlalink/Common/InspectionReviewContext.cs b/src/tlalink/Common/InspectionReviewContext.cs new file mode 100644 index 0000000..c90bddc --- /dev/null +++ b/src/tlalink/Common/InspectionReviewContext.cs @@ -0,0 +1,119 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace TlaLink; + +public sealed record InspectionMemberAttachment(string Binding, string Endpoint, Place Location, + List CapturePoints); +public sealed record InspectionMemberGroup(InspectionMember Member, List Lines, + List Attachments, int MatchingAttachments); +public sealed record InspectionCalleeSource(string Key, string Symbol, Place Location, string Status, + List Lines, int TotalLines, int OmittedLines); + +internal static class InspectionReviewContext +{ + internal static string? MemberSymbol(SourceBinding binding, SyntaxNode member) + { + SyntaxNode declaration = member is FieldDeclarationSyntax field && field.Declaration.Variables.Count == 1 + ? field.Declaration.Variables[0] : member; + return binding.Semantics.GetDeclaredSymbol(declaration)?.GetDocumentationCommentId(); + } + + internal static List GroupMembers(List entries, + List matching) + { + bool Same(InspectionMember? left, InspectionMember? right) => left != null && right != null && + left.Symbol == right.Symbol && FilePaths.Comparer.Equals(left.Location.Path, right.Location.Path) && + left.Location.Line == right.Location.Line && left.Location.Column == right.Location.Column; + List members = []; + foreach (InspectionMember member in entries.SelectMany(e => e.Links).Select(l => l.Source?.Member).OfType()) + if (!members.Any(m => Same(m, member))) members.Add(member); + List groups = []; + foreach (InspectionMember member in members.OrderBy(m => m.Location.Path, FilePaths.Comparer) + .ThenBy(m => m.Location.Line).ThenBy(m => m.Location.Column)) + { + var links = entries.SelectMany(e => e.Links.Select(l => (Endpoint: e.Model.Name, Link: l))) + .Where(e => Same(e.Link.Source?.Member, member)) + .OrderBy(e => e.Link.Source!.Location.Line).ThenBy(e => e.Link.Source!.Location.Column) + .ThenBy(e => e.Link.Binding, StringComparer.Ordinal).ToList(); + List lines = links.SelectMany(e => e.Link.Source!.Lines) + .Where(l => l.Number >= member.Location.Line && l.Number <= member.Location.EndLine) + .GroupBy(l => l.Number).OrderBy(g => g.Key) + .Select(g => new InspectionLine(g.Key, g.First().Text, g.Any(l => l.Selected))).ToList(); + groups.Add(new(member, lines, links.Select(e => new InspectionMemberAttachment(e.Link.Binding, e.Endpoint, + e.Link.Source!.Location, e.Link.Captures.Where(c => c.Point != null).Select(c => c.Point!.Value).ToList())).ToList(), + matching.SelectMany(e => e.Links).Count(l => Same(l.Source?.Member, member)))); + } + return groups; + } + + internal static List ExpandCallees(CSharpScope source, List entries, + InspectionQuery query) + { + List catalogue = []; + Dictionary> byTarget = new(StringComparer.Ordinal); + int expanded = 0; + List Read(string id) + { + if (byTarget.TryGetValue(id, out var cached)) return cached; + List result = []; + foreach (ISymbol symbol in SourceSymbols.ResolveId(id, source.Compilation)) + { + IEnumerable references = symbol.DeclaringSyntaxReferences; + if (symbol is IMethodSymbol { PartialImplementationPart: { } implementation }) + references = references.Concat(implementation.DeclaringSyntaxReferences); + foreach (SyntaxReference reference in references.OrderBy(r => r.SyntaxTree.FilePath, FilePaths.Comparer) + .ThenBy(r => r.Span.Start)) + { + SyntaxNode node = reference.GetSyntax(); + string path = node.SyntaxTree.FilePath; + if (!source.Texts.TryGetValue(path, out string? text)) continue; + Place location = Files.At(path, text, node.SpanStart, node.Span.End); + if (result.Any(c => c.Location == location)) continue; + var lines = node.SyntaxTree.GetText().Lines; + int first = lines.GetLineFromPosition(node.SpanStart).LineNumber; + int last = lines.GetLineFromPosition(Math.Max(node.SpanStart, node.Span.End - 1)).LineNumber; + int total = last - first + 1; + bool omitted = expanded >= query.CalleeLimit; + List excerpt = omitted ? [] : Enumerable.Range(first, Math.Min(total, query.CalleeMaxLines)) + .Select(i => new InspectionLine(i + 1, lines[i].ToString(), false)).ToList(); + bool body = node is BaseMethodDeclarationSyntax { Body: not null } or + BaseMethodDeclarationSyntax { ExpressionBody: not null } or + LocalFunctionStatementSyntax { Body: not null } or LocalFunctionStatementSyntax { ExpressionBody: not null }; + string status = omitted ? "budget-omitted" : excerpt.Count < total ? "truncated" : + body ? "included" : "declaration-only"; + InspectionCalleeSource entry = new("callee-" + (catalogue.Count + 1), id, location, status, + excerpt, total, total - excerpt.Count); + catalogue.Add(entry); + result.Add(entry); + if (!omitted) expanded++; + } + } + byTarget[id] = result; + return result; + } + foreach (InspectedEndpoint endpoint in entries) + { + for (int index = 0; index < endpoint.Links.Count; index++) + { + InspectedLink link = endpoint.Links[index]; + if (link.Source?.Calls == null) continue; + List calls = []; + foreach (InspectionCall call in link.Source.Calls) + { + List targets = call.Site.Target == null ? [] : Read(call.Site.Target); + calls.Add(call with + { + ExpansionStatus = call.Site.Target == null ? "no-declaration-id" : targets.Count == 0 ? "no-selected-source" : + targets.Any(t => t.Status == "budget-omitted") ? "budget-omitted" : + targets.Any(t => t.Status == "truncated") ? "truncated" : + targets.All(t => t.Status == "declaration-only") ? "declaration-only" : "included", + CalleeKeys = targets.Select(t => t.Key).ToList() + }); + } + endpoint.Links[index] = link with { Source = link.Source with { Calls = calls } }; + } + } + return catalogue; + } +} diff --git a/src/tlalink/Common/IntegratedEvidence.cs b/src/tlalink/Common/IntegratedEvidence.cs index 2f56475..3168b9d 100644 --- a/src/tlalink/Common/IntegratedEvidence.cs +++ b/src/tlalink/Common/IntegratedEvidence.cs @@ -282,6 +282,9 @@ string Recorded(string file) if (hasTla != (policy.TlaTargets.Count > 0) || hasTla && !result.Tla!.SelectedTargets.ToHashSet(StringComparer.Ordinal).SetEquals(policy.TlaTargets)) Error("Recorded TLA+ selection differs from the pinned binding manifest."); + if (hasTla) + IntegratedTlaEvidence.ValidateArchive(result.Tla!, policy, manifestPath, scope, + recordedPins, archiveDirectory); foreach (DafnyLink link in links) { string id = link?.Id ?? ""; @@ -309,7 +312,15 @@ string Recorded(string file) foreach (DafnyLink link in links) if (string.IsNullOrWhiteSpace(link?.Id) || !linked.Add(link.Id)) Error("Link identifiers must be nonempty and unique."); - if (linksStatus == "passed" && linked.Count == 0) Error("Passed links require resolved bindings."); + bool tlaOnly = linked.Count == 0 && result.Tla is { LinksStatus: "passed", Links.Length: > 0 }; + if (tlaOnly && (result.Tla!.SchemaVersion != Schema.Version || result.Tla.Kind != "source-review" || + result.Tla.Inventory.Length == 0 || result.Tla.SelectedTargets.Length == 0 || + result.Tla.ConformanceStatus != "not-run" || result.Tla.Diagnostics.Any(d => d.Severity == "error"))) + Error("TLA+-only results require native inventory, selected targets and ready structural links."); + if (linksStatus == "passed" && linked.Count == 0 && !tlaOnly) Error("Passed links require resolved bindings."); + if (tlaOnly && (command != "inspect-integrated" || result.Inventory.Length != 0 || stages.Count != 0 || + proof != "not-run" || audit != "not-run" || conformance != "not-run")) + Error("TLA+-only results must be inspection-only without Dafny or execution stages."); if (correspondence != (claims.Length == 0 ? "not-specified" : "requires-review")) Error("Correspondence status disagrees with recorded claims."); HashSet ids = []; @@ -354,7 +365,7 @@ void NeedArtifact(string name) NeedArtifact(entry.Key + ".invocation.json"); } } - if (linksStatus == "passed") + if (linksStatus == "passed" && linked.Count > 0) { foreach (string name in new[] { "dafny-version", "dafny-bridge", "dafny-discover", "dafny-resolve" }) NeedStage(name); NeedArtifact("dafny-discover.json"); diff --git a/src/tlalink/Common/IntegratedReview.cs b/src/tlalink/Common/IntegratedReview.cs index bfee9da..7425ec8 100644 --- a/src/tlalink/Common/IntegratedReview.cs +++ b/src/tlalink/Common/IntegratedReview.cs @@ -17,6 +17,8 @@ public static int Run(CliOptions options) { packet.Bindings = FilePaths.Full(options.Required("bindings")); IntegratedManifest manifest = IntegratedInputs.Load(packet.Bindings, packet.Fingerprints); + if (manifest.Bindings.Count == 0 && options.Command != "inspect-integrated") + throw new InputException(ErrorCode.InvalidIntegratedInput, "Verification and oracle execution require selected Dafny bindings; TLA+-only inputs support inspection."); Program.PinTool(packet.Fingerprints); packet.Fingerprints["tool:integrated-schema"] = Schema.Version.ToString(System.Globalization.CultureInfo.InvariantCulture); CSharpScope source = CSharpScope.Parse(manifest.Sources, options.Many("reference"), @@ -28,11 +30,14 @@ public static int Run(CliOptions options) source.RequireCompilable(); if (source.Diagnostics.Any(d => d.Severity == "error")) throw new InputException(ErrorCode.InvalidIntegratedBinding, "Invalid C# annotations; see source diagnostics."); - DafnyBackend backend = new(options.Required("dafny"), output, options.Timeout, packet); - backend.Initialize(); - DafnyIndexResult index = backend.Index(manifest.Proofs); - packet.Inventory.AddRange(index.Declarations); - List formal = FormalCorrespondence.Dafny(index.Declarations, packet.Fingerprints); + DafnyBackend? backend = null; + if (manifest.Bindings.Count > 0) + { + backend = new(options.Required("dafny"), output, options.Timeout, packet); + backend.Initialize(); + packet.Inventory.AddRange(backend.Index(manifest.Proofs).Declarations); + } + List formal = FormalCorrespondence.Dafny(packet.Inventory, packet.Fingerprints); List pairing = []; foreach (var group in manifest.Bindings.GroupBy(b => Markup.Name(b.Id).Alias, StringComparer.Ordinal)) FormalCorrespondence.Match(source, formal, group.Key, group.Select(b => b.Id), pairing); @@ -47,7 +52,7 @@ public static int Run(CliOptions options) packet.SourceInventory.AddRange(symbols.Select(s => s.Endpoint)); foreach (DafnyBinding binding in manifest.Bindings) { - List declarations = index.Declarations.Where(d => d.Name == binding.Dafny).ToList(); + List declarations = packet.Inventory.Where(d => d.Name == binding.Dafny).ToList(); if (declarations.Count != 1) throw new InputException(ErrorCode.InvalidIntegratedBinding, $"{binding.Id}: expected one resolved Dafny declaration '{binding.Dafny}', found {declarations.Count}."); SourceBinding inline = source.Bindings.Single(b => b.BindingId == binding.Id); @@ -98,9 +103,13 @@ public static int Run(CliOptions options) ErrorCode.SourceObligationIncomplete, premise.Obligation.Id + ": " + premise.Reason)); if (options.Optional("baseline") is string baseline) Baseline(baseline, packet); if (packet.LinksStatus == "passed" && packet.SourceObligationsStatus is "passed" or "not-specified" && - options.Command != "inspect-integrated" && backend.Verify(manifest.Proofs) && - options.Command == "test-integrated") - DafnyConformance.Run(manifest, source, symbols, backend, packet); + options.Command != "inspect-integrated") + { + DafnyBackend verifier = backend ?? throw new InputException(ErrorCode.InvalidIntegratedInput, + "Native verification requires selected Dafny bindings."); + if (verifier.Verify(manifest.Proofs) && options.Command == "test-integrated") + DafnyConformance.Run(manifest, source, symbols, verifier, packet); + } IntegratedInputs.CheckPins(packet.Fingerprints); IntegratedInputs.CheckPins(packet.GeneratedFiles); packet.ProvenanceStatus = "consistent"; diff --git a/src/tlalink/Common/IntegratedTlaEvidence.cs b/src/tlalink/Common/IntegratedTlaEvidence.cs new file mode 100644 index 0000000..aa45a95 --- /dev/null +++ b/src/tlalink/Common/IntegratedTlaEvidence.cs @@ -0,0 +1,82 @@ +namespace TlaLink; + +internal static class IntegratedTlaEvidence +{ + internal static void ValidateArchive(IntegratedTlaResult result, IntegratedManifest manifest, + string manifestPath, CorrespondenceConfiguration scope, Dictionary pins, + string archive) + { + if (result.SchemaVersion != Schema.Version || result.Kind != "source-review" || + result.LinksStatus != "passed" || result.ConformanceStatus != "not-run" || + result.Diagnostics.Any(d => d.Severity == "error") || result.Links.Length == 0) + throw Invalid("Selected TLA+ inspection lacks successful structural links."); + Dictionary files = new(FilePaths.Comparer); + foreach (var pin in pins.Where(p => FilePaths.IsAbsolute(p.Key))) + { + StageEvidence.RequireHash(pin.Value); + if (!files.TryAdd(pin.Key, pin.Value)) + throw Invalid("TLA+ inputs contain aliased paths: " + pin.Key); + } + foreach (var pin in result.Fingerprints) + if (!(FilePaths.IsAbsolute(pin.Key) ? files : pins).TryGetValue(pin.Key, out string? hash) || hash != pin.Value) + throw Invalid("Nested TLA+ input differs from its parent: " + pin.Key); + string ReadInput(string path) + { + if (!files.TryGetValue(path, out string? hash)) + throw Invalid("Missing archived TLA+/source input: " + path); + string copy = Path.Combine(archive, hash); + if (!File.Exists(copy) || Files.Hash(copy) != hash) + throw Invalid("Changed archived TLA+/source input: " + path); + return Files.Read(copy); + } + string scopePath = ProjectInputs.Resolve(manifestPath, manifest.Scope); + HashSet models = scope.Targets.Where(t => manifest.TlaTargets.Contains(t.Id, StringComparer.Ordinal)) + .SelectMany(t => t.Inputs.Select(p => ProjectInputs.Resolve(scopePath, p))).ToHashSet(FilePaths.Comparer); + List formal = []; + foreach (var file in result.Inventory.GroupBy(e => e.Location.Path, FilePaths.Comparer)) + { + if (!models.Contains(file.Key)) throw Invalid("Unselected TLA+ inventory input: " + file.Key); + string text = ReadInput(file.Key); + List spans = []; + foreach (Endpoint endpoint in file) + { + int start = TlaBackend.ArchivedOffset(text, endpoint.Location.Line, endpoint.Location.Column); + if (endpoint.Source.Length == 0 || start > text.Length - endpoint.Source.Length || + endpoint.Location.EndLine != endpoint.Location.Line + endpoint.Source.Count(c => c == '\n') || + !text.AsSpan(start, endpoint.Source.Length).SequenceEqual(endpoint.Source.AsSpan())) + throw Invalid("TLA+ inventory span differs from archived source: " + endpoint.Name); + spans.Add(new(endpoint, start, start + endpoint.Source.Length)); + } + formal.AddRange(FormalCorrespondence.Attach(file.Key, text, spans, ModelScope.FormalComments(text))); + } + formal = formal.Where(d => manifest.TlaTargets.Contains(Markup.Name(d.Binding.Id).Alias, StringComparer.Ordinal)).ToList(); + HashSet expected = formal.Select(d => d.Binding.Id).ToHashSet(StringComparer.Ordinal); + expected.UnionWith(scope.Targets.Where(t => manifest.TlaTargets.Contains(t.Id, StringComparer.Ordinal)) + .SelectMany(t => t.RequiredBindings ?? [])); + if (expected.Count == 0 || result.Links.Length != expected.Count || + !result.Links.Select(l => l.Key).ToHashSet(StringComparer.Ordinal).SetEquals(expected)) + throw Invalid("TLA+ links differ from selected formal declarations and required bindings."); + Dictionary sources = CorrespondenceEvidence.Bindings( + manifest.Sources.Select(p => ProjectInputs.Resolve(manifestPath, p)), expected, pins, ReadInput, formal, + hash => Path.Combine(archive, hash)); + foreach (Link link in result.Links) + { + List target = formal.Where(d => d.Binding.Id == link.Key).ToList(); + if (target.Count != 1 || !sources.TryGetValue(link.Key, out ArchivedSourceBinding? source) || + !SamePlace(source.Location, link.Implementation.Location) || + !SameEndpoint(target[0].Endpoint, link.Specification) || + link.Model != Markup.Name(link.Key).Alias) + throw Invalid("TLA+ link differs from its archived formal/source attachment: " + link.Key); + } + } + + private static bool SamePlace(Place left, Place right) => + FilePaths.Comparer.Equals(left.Path, right.Path) && left.Line == right.Line && + left.EndLine == right.EndLine && left.Column == right.Column; + + private static bool SameEndpoint(Endpoint left, Endpoint right) => + left.Name == right.Name && left.Scope == right.Scope && left.Kind == right.Kind && + left.Source == right.Source && SamePlace(left.Location, right.Location); + + private static InputException Invalid(string message) => new(ErrorCode.InvalidIntegratedEvidence, message); +} diff --git a/src/tlalink/Common/LinkInspection.cs b/src/tlalink/Common/LinkInspection.cs index 625f378..1fc539b 100644 --- a/src/tlalink/Common/LinkInspection.cs +++ b/src/tlalink/Common/LinkInspection.cs @@ -10,8 +10,16 @@ namespace TlaLink; public sealed record InspectionLine(int Number, string Text, bool Selected); public sealed record InspectionSource(Place Location, string SelectedText, List Lines, List Context, List Boundaries, List Locks, bool InNestedFunction, - List? Calls); -public sealed record InspectionCall(SourceCallSite Site, List SourceDeclarations); + List? Calls) +{ + public InspectionMember? Member { get; init; } +} +public sealed record InspectionMember(string? Symbol, Place Location); +public sealed record InspectionCall(SourceCallSite Site, List SourceDeclarations) +{ + public string ExpansionStatus { get; init; } = "not-requested"; + public List CalleeKeys { get; init; } = []; +} public sealed record InspectionObservation(string Binding, string Status, string? Expression, Place? Location, string? Guard, CapturedType? Type); public sealed record InspectedLink(string Binding, string? Reason, PreparationTarget? Selector, @@ -39,13 +47,21 @@ public sealed record LinkInspectionResult(int SchemaVersion, string Kind, string public int MatchedLinks { get; init; } public int ReturnedLinks => Endpoints.Sum(e => e.Links.Count); public int? NextOffset { get; init; } + public List MemberGroups { get; init; } = []; + public List CalleeSources { get; init; } = []; } public sealed record LinkInspectionSummary(int SchemaVersion, string Kind, string Status, string Target, int Endpoints, int Links, int UnlinkedEndpoints, int OmittedUnlinkedEndpoints, string View, bool CallsIncluded, int InputPinCount, InspectionQuery? Query, int CandidateEndpoints, int MatchedEndpoints, int? NextOffset, int CandidateLinks, int MatchedLinks, int ReturnedLinks, - List Diagnostics, string Boundary); + List Diagnostics, string Boundary) +{ + public int MemberGroups { get; init; } + public int CalleeSources { get; init; } + public int OmittedCalleeDeclarations { get; init; } + public int TruncatedCalleeSources { get; init; } +} internal static class LinkInspection { @@ -169,9 +185,13 @@ bool Same(Endpoint left, Endpoint right) => left.Name == right.Name && left.Kind entries.RemoveAll(e => e.Status is "unlinked" or "declared-hidden"); } entries = InspectionFiltering.Apply(entries, query); + List matchingEntries = entries; int matched = entries.Count; int matchedLinks = entries.Sum(e => e.Links.Count); entries = entries.Skip(query.Offset).Take(query.Limit ?? int.MaxValue).ToList(); + List callees = query.CalleeSource ? InspectionReviewContext.ExpandCallees(source, entries, query) : []; + List groups = query.GroupBy == "member" ? + InspectionReviewContext.GroupMembers(entries, matchingEntries) : []; return new(Schema.Version, "link-inspection", diagnostics.Any(d => d.Severity == "error") ? "failed" : "ready", target.Id, target.Language, options.Get("context", "3"), entries, diagnostics, options.Get("view", "compact") == "full" ? pins : null, BoundaryText) @@ -180,6 +200,7 @@ bool Same(Endpoint left, Endpoint right) => left.Name == right.Name && left.Kind OmittedUnlinkedEndpoints = omitted, InputPinCount = pins.Count, Compiler = compiler, Query = query, CandidateEndpoints = candidates, MatchedEndpoints = matched, CandidateLinks = candidateLinks, MatchedLinks = matchedLinks, + MemberGroups = groups, CalleeSources = callees, NextOffset = query.Offset < matched && entries.Count < matched - query.Offset ? query.Offset + entries.Count : null }; } @@ -248,7 +269,11 @@ TryStatementSyntax value when value.Block.Span.Contains(node.Span) => "try", .OfType().Where(l => l.Statement.Span.Contains(node.Span)) .Reverse().Select(l => l.Expression.ToString()).ToList(); return new(binding.Endpoint.Location, binding.Endpoint.Source, excerpt, frames, CSharpScope.Boundaries(binding), - locks, SourceQueries.Nested(node, member), callSites); + locks, SourceQueries.Nested(node, member), callSites) + { + Member = new(InspectionReviewContext.MemberSymbol(binding, member), + Files.At(binding.Path, binding.Text, member.SpanStart, member.Span.End)) + }; } internal static void Render(LinkInspectionResult result, CliOptions options) @@ -264,7 +289,12 @@ internal static void Render(LinkInspectionResult result, CliOptions options) result.OmittedUnlinkedEndpoints, result.View, result.CallsIncluded, result.InputPinCount, result.Query, result.CandidateEndpoints, result.MatchedEndpoints, result.NextOffset, result.CandidateLinks, result.MatchedLinks, result.ReturnedLinks, - result.Diagnostics, result.Boundary), Files.Json), + result.Diagnostics, result.Boundary) + { + MemberGroups = result.MemberGroups.Count, CalleeSources = result.CalleeSources.Count, + OmittedCalleeDeclarations = result.CalleeSources.Count(c => c.Status == "budget-omitted"), + TruncatedCalleeSources = result.CalleeSources.Count(c => c.OmittedLines > 0 && c.Status != "budget-omitted") + }, Files.Json), _ => InspectionFiltering.Json(result) }; if (options.Optional("output") is string output) @@ -307,6 +337,25 @@ void Code(string language, string value) if (result.Compiler is SourceCompilerContext compiler) text.AppendLine($"Compiler: C# {compiler.LanguageVersion}, nullable={compiler.Nullable}, target={compiler.TargetFramework ?? "explicit compilation"}" + (compiler.RegressionResult == null ? "" : "; recorded context: " + compiler.RegressionResult)); + if (result.Query?.GroupBy == "member") + { + text.AppendLine("Member groups contain only returned attachments in source order, not execution order or complete member coverage."); + foreach (InspectionMemberGroup group in result.MemberGroups) + { + Heading(2, "C# member: " + (group.Member.Symbol ?? "unnamed declaration")); + text.AppendLine(Location(group.Member.Location) + + $"; attachments: {group.Attachments.Count} returned / {group.MatchingAttachments} matching (before paging)."); + foreach (InspectionMemberAttachment attachment in group.Attachments) + text.AppendLine($" {attachment.Location.Line}:{attachment.Location.Column} {attachment.Binding} -> {attachment.Endpoint}" + + " [" + string.Join(", ", attachment.CapturePoints) + "]"); + if (Includes("context")) + { + text.AppendLine("Shared context (gaps are omitted physical lines; >>> intersects a returned attachment):"); + Code("text", string.Join("\n", group.Lines.Select(l => + $"{(l.Selected ? ">>>" : " ")} {l.Number,5} | {l.Text}"))); + } + } + } foreach (InspectedEndpoint endpoint in result.Endpoints) { text.AppendLine(); @@ -336,8 +385,11 @@ void Code(string language, string value) } if (Includes("context")) { - text.AppendLine("Context (>>> marks lines intersecting the selection):"); - Code("text", string.Join("\n", source.Lines.Select(l => $"{(l.Selected ? ">>>" : " ")} {l.Number,5} | {l.Text}"))); + if (result.Query?.GroupBy != "member") + { + text.AppendLine("Context (>>> marks lines intersecting the selection):"); + Code("text", string.Join("\n", source.Lines.Select(l => $"{(l.Selected ? ">>>" : " ")} {l.Number,5} | {l.Text}"))); + } foreach (Boundary frame in source.Context) text.AppendLine("Enclosing: " + frame.Text + " at " + Location(frame.Location)); text.AppendLine("Enclosing source locks: " + (source.Locks.Count == 0 ? "none" : string.Join(", ", source.Locks))); @@ -354,6 +406,9 @@ void Code(string language, string value) " at " + string.Join(", ", call.SourceDeclarations.Select(Location)))); if (call.Site.InNestedFunction) text.AppendLine("Call is in a nested function; its execution is not established by the enclosing member."); + if (result.Query?.CalleeSource == true) + text.AppendLine("Callee expansion: " + call.ExpansionStatus + + (call.CalleeKeys.Count == 0 ? "" : " -> " + string.Join(", ", call.CalleeKeys))); } } if (Includes("captures") && link.Captures.Count == 0) text.AppendLine("Capture: none (review-only attachment)."); @@ -369,6 +424,18 @@ void Code(string language, string value) (observation.Location == null ? "" : " at " + Location(observation.Location))); } } + if (result.Query?.CalleeSource == true && Includes("calls")) + { + Heading(2, "Selected-source callees (one level, deduplicated)"); + text.AppendLine("Declared targets only; bodies are not a runtime dispatch, transitive effect, nonthrowing or ownership proof."); + foreach (InspectionCalleeSource callee in result.CalleeSources) + { + Heading(3, callee.Key + " [" + callee.Status + "]"); + text.AppendLine(callee.Symbol + " at " + Location(callee.Location) + + $"; {callee.Lines.Count}/{callee.TotalLines} lines; omitted: {callee.OmittedLines}."); + if (callee.Lines.Count > 0) Code("csharp", string.Join("\n", callee.Lines.Select(l => $"{l.Number,5} | {l.Text}"))); + } + } if (result.Diagnostics.Count > 0) Heading(2, "Diagnostics"); foreach (Issue diagnostic in result.Diagnostics) text.AppendLine($"{diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}" + diff --git a/src/tlalink/Common/ObservedExecution.cs b/src/tlalink/Common/ObservedExecution.cs index 968bde0..6dbf3ae 100644 --- a/src/tlalink/Common/ObservedExecution.cs +++ b/src/tlalink/Common/ObservedExecution.cs @@ -24,6 +24,7 @@ public static ObservedBuild Build(string project, string output, int timeout, st string binaries = Path.Combine(output, "binary.txt"), context = Path.Combine(output, "context.txt"); string inputs = Path.Combine(output, "build-inputs.txt"); string missing = Path.Combine(output, "missing-build-inputs.txt"); + string sdk = Path.Combine(output, "sdk.log"); string Escape(string value) => System.Security.SecurityElement.Escape(value); File.WriteAllText(target, $""" @@ -42,6 +43,7 @@ public static ObservedBuild Build(string project, string output, int timeout, st + @@ -50,8 +52,6 @@ public static ObservedBuild Build(string project, string output, int timeout, st """); - ObservedProcess sdkProcess = Invoke(["--version"], output, timeout, "sdk"); - RequireSuccess(sdkProcess); List arguments = BuildArguments(project, output, configuration); RequireSuccess(Invoke(arguments, output, timeout, "build")); Dictionary compiled = ReadHashes(sources), refs = ReadHashes(references), binary = ReadHashes(binaries); @@ -61,8 +61,11 @@ public static ObservedBuild Build(string project, string output, int timeout, st if (binary.Count != 1) throw new InputException(ErrorCode.InvalidExecution, "Expected exactly one target binary; multi-target projects are not supported."); Dictionary settings = ReadContext(context); + string sdkVersion = Files.Read(sdk).Trim(); + if (string.IsNullOrWhiteSpace(sdkVersion)) + throw new InputException(ErrorCode.InvalidExecution, "Build did not report its selected .NET SDK version."); ObservedBuild result = new(project, compiled, refs, buildInputs, binary.Single().Key, binary.Single().Value, - Files.Read(sdkProcess.Log).Trim(), settings, arguments, + sdkVersion, settings, arguments, File.ReadAllLines(missing).Select(p => FilePaths.Full(p)).Distinct(FilePaths.Comparer).ToList()); Check(result); return result; diff --git a/src/tlalink/Common/ProjectAcceptance.cs b/src/tlalink/Common/ProjectAcceptance.cs index 1c9f747..093f115 100644 --- a/src/tlalink/Common/ProjectAcceptance.cs +++ b/src/tlalink/Common/ProjectAcceptance.cs @@ -26,10 +26,25 @@ void Error(ErrorCode code, string message, bool grouped = false) issues.Add(issue); if (grouped) groupedDiagnostics.Add(issue); } - if (run.Project != project.Id || run.ProjectSha256 != Files.Hash(path) || - run.RequirementsSha256 != Files.Hash(ProjectInputs.Resolve(path, project.Requirements))) - Error(ErrorCode.WorkflowProjectChanged, "Project or acceptance requirements differ from the run."); - issues.AddRange(ProjectComposition.ValidateArchive(path, project, run, directory)); + Dictionary recordedPaths = new(FilePaths.Comparer); + foreach (var pin in run.Fingerprints.Where(p => FilePaths.IsAbsolute(p.Key))) + if (!recordedPaths.TryAdd(pin.Key, pin.Value)) + Error(ErrorCode.WorkflowProvenanceInconsistent, "Run contains aliased input paths: " + pin.Key); + issues.AddRange(ProjectComposition.ValidateArchive(path, project, run, directory, out AnalysisProject? archivedProject)); + WorkflowPolicyComparison.Result comparison; + try { comparison = WorkflowPolicyComparison.Compare(path, project, policy, run, directory, archivedProject); } + catch (Exception error) when (error is InputException or IOException or UnauthorizedAccessException or JsonException) + { + Error(error is InputException { Code: ErrorCode.WorkflowEvidenceStale } + ? ErrorCode.WorkflowEvidenceStale : ErrorCode.WorkflowProvenanceInconsistent, + "Policy comparison: " + error.Message); + comparison = new(new("unavailable", new(run.ProjectSha256, run.RequirementsSha256, null), + new(project.Authoring!.Fingerprints[path], null, null), + null, null, ["archive-validation"], "Policy comparison did not complete."), new(FilePaths.Comparer)); + } + if (comparison.Report.Status is "incompatible" or "unavailable") + Error(ErrorCode.WorkflowProjectChanged, "Execution/policy reassessment blocked: " + + string.Join(", ", comparison.Report.ChangedAreas) + "."); AnalysisScenario? scenario = project.Scenarios.SingleOrDefault(s => s.Id == run.Scenario); if (scenario == null) throw new InputException(ErrorCode.WorkflowProjectChanged, "Run scenario does not exist in this project."); List selectedSummaries = MethodSummaries.Select(path, project, scenario.Stages); @@ -46,7 +61,7 @@ void Error(ErrorCode code, string message, bool grouped = false) FormalTarget target = CorrespondenceInputs.Target(summary.Configuration, Markup.Name(summary.Summary.Binding).Alias, "tla"); foreach (string input in summary.Summary.Sources.Select(p => ProjectInputs.Resolve(summary.Scope, p)) .Concat(target.Inputs).Append(summary.Scope)) - if (!run.Fingerprints.ContainsKey(RecordedSummaryPath(input))) + if (!recordedPaths.ContainsKey(RecordedSummaryPath(input))) Error(ErrorCode.WorkflowProvenanceInconsistent, "Run is missing a method-summary input pin: " + input); } AcceptanceWorklist worklist = new(run, scenario, policy.Requirements.Where(r => r.Scenario == run.Scenario).ToList(), issues, groupedDiagnostics); @@ -64,17 +79,6 @@ void Error(ErrorCode code, string message, bool grouped = false) string archived = SafePath(directory, Path.Combine("inputs", pin.Value)); if (!File.Exists(archived) || Files.Hash(archived) != pin.Value) Error(ErrorCode.WorkflowProvenanceInconsistent, "Missing/changed archived input: " + pin.Key); - if (!FilePaths.IsNativeAbsolute(pin.Key)) - { - Error(ErrorCode.WorkflowEvidenceStale, "Input uses a foreign filesystem root: " + pin.Key); - continue; - } - string current = pin.Key; - string relative = Path.GetRelativePath(run.ProjectDirectory, pin.Key); - if (!Path.IsPathRooted(relative) && relative != ".." && !relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal)) - current = ProjectInputs.Resolve(path, relative); - if (!File.Exists(current) || Files.Hash(current) != pin.Value) - Error(ErrorCode.WorkflowEvidenceStale, "Stale current input: " + current); } foreach (var artifact in run.Artifacts) { @@ -165,6 +169,32 @@ void Error(ErrorCode code, string message, bool grouped = false) } evidence[stage.Id] = result; } + HashSet reviewOnly = issues.Count == 0 + ? WorkflowInputRoles.ReviewOnly(path, project, policy, run, directory, evidence, selectedSummaries, + comparison.ReviewInputs) + : new(FilePaths.Comparer); + List changedReviewInputs = []; + foreach (var pin in run.Fingerprints.Where(p => FilePaths.IsAbsolute(p.Key))) + { + if (!FilePaths.IsNativeAbsolute(pin.Key)) + { + Error(ErrorCode.WorkflowEvidenceStale, "Input uses a foreign filesystem root: " + pin.Key); + continue; + } + string current = WorkflowInputRoles.CurrentInput(path, run, pin.Key); + if (!File.Exists(current) || Files.Hash(current) != pin.Value) + { + if (reviewOnly.Contains(current)) changedReviewInputs.Add(current); + else Error(ErrorCode.WorkflowEvidenceStale, "Stale current input: " + current); + } + } + foreach (var pin in project.Authoring!.Fingerprints) + if (!File.Exists(pin.Key) || Files.Hash(pin.Key) != pin.Value) + Error(ErrorCode.WorkflowEvidenceStale, "Current project authoring changed during reassessment: " + pin.Key); + string currentPolicy = ProjectInputs.Resolve(path, project.Requirements); + if (comparison.Report.Current.RequirementsSha256 is string currentPolicyHash && + (!File.Exists(currentPolicy) || Files.Hash(currentPolicy) != currentPolicyHash)) + Error(ErrorCode.WorkflowEvidenceStale, "Current acceptance policy changed during reassessment: " + currentPolicy); List requirements = []; foreach (AnalysisRequirement requirement in policy.Requirements.Where(r => r.Scenario == run.Scenario)) { @@ -180,7 +210,7 @@ void Missing(string reason, bool grouped = false) if (selected.Config != null) { string recordedConfig = FilePaths.Full(selected.Config, run.ProjectDirectory); - if (!run.Fingerprints.TryGetValue(recordedConfig, out string? hash) || + if (!recordedPaths.TryGetValue(recordedConfig, out string? hash) || !hash.Equals(requirement.ConfigSha256, StringComparison.OrdinalIgnoreCase)) Missing("independently approved configuration bounds/properties"); } @@ -263,7 +293,8 @@ void Missing(string reason, bool grouped = false) .Distinct().Select(id => new ReviewResult(id, ReviewStatus(path, project, id), LatestReview(path, project, id))).ToList(), issues.Select(i => i.Message).Distinct().ToList(), - "Acceptance of declared bounded evidence and explicit reviews, not general C# refinement or host authentication."); + "Acceptance of declared bounded evidence and explicit reviews, not general C# refinement or host authentication.") + { ChangedReviewInputs = changedReviewInputs, PolicyReassessment = comparison.Report }; return (report, accepted ? 0 : issues.Any(i => i.Is(ErrorCode.WorkflowProjectChanged, ErrorCode.WorkflowExecutionIncomplete, ErrorCode.WorkflowEvidenceStale)) ? 2 : 1, worklist); diff --git a/src/tlalink/Common/ProjectComposition.cs b/src/tlalink/Common/ProjectComposition.cs index 092db16..7b7330a 100644 --- a/src/tlalink/Common/ProjectComposition.cs +++ b/src/tlalink/Common/ProjectComposition.cs @@ -69,8 +69,10 @@ internal static ProjectExpansion Expansion(string path, AnalysisProject project) new(Schema.Version, "project-expansion", project.Id, Path.GetDirectoryName(path)!, project, new(project.Authoring!.Fingerprints, FilePaths.Comparer)); - internal static List ValidateArchive(string path, AnalysisProject project, WorkflowRun run, string directory) + internal static List ValidateArchive(string path, AnalysisProject project, WorkflowRun run, string directory, + out AnalysisProject? archivedProject) { + archivedProject = null; const string snapshot = "expanded-project.json"; if (!run.Artifacts.ContainsKey(snapshot)) return project.Authoring?.Composed == true @@ -95,12 +97,9 @@ internal static List ValidateArchive(string path, AnalysisProject project saved.Fingerprints.Count != archived.Authoring!.Fingerprints.Count || saved.Fingerprints.Any(p => !archived.Authoring.Fingerprints.TryGetValue(p.Key, out string? hash) || hash != p.Value)) throw new InputException("Expanded project does not match its archived authoring files."); - foreach (var pin in project.Authoring!.Fingerprints) - { - string recorded = FilePaths.Full(Path.GetRelativePath(Path.GetDirectoryName(path)!, pin.Key), run.ProjectDirectory); - if (!run.Fingerprints.TryGetValue(recorded, out string? hash) || hash != pin.Value) - return [new(ErrorCode.WorkflowProjectChanged, "Project composition differs from the run: " + pin.Key)]; - } + if (!run.Fingerprints.TryGetValue(recordedRoot, out string? rootHash) || rootHash != run.ProjectSha256) + throw new InputException("Archived project root contradicts its recorded hash."); + archivedProject = archived; return []; } catch (Exception error) when (error is InputException or IOException or UnauthorizedAccessException or JsonException) diff --git a/src/tlalink/Common/ProjectContracts.cs b/src/tlalink/Common/ProjectContracts.cs index 5408266..0803456 100644 --- a/src/tlalink/Common/ProjectContracts.cs +++ b/src/tlalink/Common/ProjectContracts.cs @@ -184,10 +184,16 @@ public static (AnalysisProject Project, AcceptancePolicy Policy) Load(string pat } else if (stage.Kind is "inspect" or "verify" or "oracle") { - if (stage.Bindings == null || project.Tools.Dafny == null) - throw new InputException(ErrorCode.InvalidWorkflowInput, "Integrated stages require bindings and pinned Dafny."); + if (stage.Bindings == null) + throw new InputException(ErrorCode.InvalidWorkflowInput, "Integrated stages require a binding manifest."); if (stage.Sources != null || stage.Models != null || stage.Config != null || stage.Arguments != null) throw new InputException(ErrorCode.InvalidWorkflowInput, "Integrated stages take source/model scope only from their binding manifest."); + IntegratedManifest manifest = IntegratedInputs.Load(Resolve(path, stage.Bindings), new(FilePaths.Comparer)); + if (manifest.Bindings.Count > 0 && project.Tools.Dafny == null || + stage.Kind != "inspect" && manifest.Bindings.Count == 0) + throw new InputException(ErrorCode.InvalidWorkflowInput, "Dafny binding stages require pinned Dafny; verify/oracle stages require selected Dafny bindings."); + if (manifest.Models.Count > 0 && project.Tools.Jar == null) + throw new InputException(ErrorCode.InvalidWorkflowInput, "Selected TLA+ targets require a pinned JAR."); } else if (stage.Models is not { Count: > 0 } || project.Tools.Jar == null) throw new InputException(ErrorCode.InvalidWorkflowInput, "TLA stages require explicit models and a pinned JAR."); diff --git a/src/tlalink/Common/ProjectReport.cs b/src/tlalink/Common/ProjectReport.cs index 8445d54..c5ae43e 100644 --- a/src/tlalink/Common/ProjectReport.cs +++ b/src/tlalink/Common/ProjectReport.cs @@ -152,7 +152,9 @@ void Pin(string file) nodes.Add(new(prefix, "milestone", scenario.Id, "Independent acceptance of this explicit run. Archive: " + evaluation.Report.ArchiveStatus + "; current applicability: " + evaluation.Report.CurrentApplicability + - "; execution: " + run.ExecutionStatus + ".", + "; execution: " + run.ExecutionStatus + + "; review-only input changes: " + evaluation.Report.ChangedReviewInputs.Count + + "; policy reassessment: " + evaluation.Report.PolicyReassessment?.Status + ".", evaluation.Report.AcceptanceStatus, "accepted", requirementIds, [runPath, evaluations[i], path], [], missing)); } diff --git a/src/tlalink/Common/ProjectWorkflow.cs b/src/tlalink/Common/ProjectWorkflow.cs index a651551..2c2dd08 100644 --- a/src/tlalink/Common/ProjectWorkflow.cs +++ b/src/tlalink/Common/ProjectWorkflow.cs @@ -176,7 +176,7 @@ private static Dictionary Pins(string path, AnalysisProject proj if (stage.Bindings != null) { IntegratedManifest manifest = IntegratedInputs.Load(ProjectInputs.Resolve(path, stage.Bindings), pins); - needDafny = true; + needDafny |= manifest.Bindings.Count > 0; needJar |= manifest.Models.Count > 0; foreach (string file in manifest.Sources.Concat(manifest.Proofs).Concat(manifest.Models)) Pin(file); if (manifest.Models.Count > 0 && project.Tools.Jar == null) @@ -200,11 +200,6 @@ private static Dictionary Pins(string path, AnalysisProject proj throw new InputException(ErrorCode.WorkflowInputChanged, "Configuration differs from the independently approved bounds/properties: " + config); } } - HashSet requiredReviews = policy.Requirements.Where(r => scenarios.Any(s => s.Id == r.Scenario)) - .SelectMany(r => r.Reviews ?? []).ToHashSet(StringComparer.Ordinal); - requiredReviews.UnionWith(selectedSummaries.Select(s => s.Summary.Inspection)); - foreach (ReviewObligation obligation in project.Obligations.Where(o => requiredReviews.Contains(o.Id))) - foreach (string file in obligation.Inputs) Pin(ProjectInputs.Resolve(path, file)); foreach (ToolPin tool in new[] { needDafny ? project.Tools.Dafny : null, needJar ? project.Tools.Jar : null, needP ? project.Tools.P : null, needApalache ? project.Tools.Apalache : null }.OfType()) { @@ -306,8 +301,11 @@ void Compiler() else if (stage.Kind is "inspect" or "verify" or "oracle") { arguments.Add(stage.Kind switch { "inspect" => "inspect-integrated", "verify" => "verify-integrated", _ => "test-integrated" }); - arguments.AddRange(["--bindings", ProjectInputs.Resolve(path, stage.Bindings!), "--dafny", - ProjectInputs.Resolve(path, project.Tools.Dafny!.Path), "--output", Path.Combine(output, "engine")]); + string bindings = ProjectInputs.Resolve(path, stage.Bindings!); + IntegratedManifest manifest = IntegratedInputs.Load(bindings, pins); + arguments.AddRange(["--bindings", bindings, "--output", Path.Combine(output, "engine")]); + if (manifest.Bindings.Count > 0) + arguments.AddRange(["--dafny", ProjectInputs.Resolve(path, project.Tools.Dafny!.Path)]); if (project.Tools.Jar != null) Jar(); Compiler(); } @@ -514,6 +512,7 @@ void Field(string name, string? value) Field("project", acceptance.Project); Field("scenario", acceptance.Scenario); Field("execution_status", acceptance.ExecutionStatus); Field("archive_status", acceptance.ArchiveStatus); Field("current_applicability", acceptance.CurrentApplicability); Field("acceptance_status", acceptance.AcceptanceStatus); + Field("changed_review_inputs", acceptance.ChangedReviewInputs.Count.ToString(System.Globalization.CultureInfo.InvariantCulture)); foreach (RequirementSummary requirement in acceptance.Requirements) Console.WriteLine($"requirement {requirement.Id}: {requirement.Status}"); break; diff --git a/src/tlalink/Common/SummaryContracts.cs b/src/tlalink/Common/SummaryContracts.cs index e64a3aa..a92e98c 100644 --- a/src/tlalink/Common/SummaryContracts.cs +++ b/src/tlalink/Common/SummaryContracts.cs @@ -47,6 +47,8 @@ public sealed record AcceptanceSummary(string Project, string Scenario, string E public Dictionary? Counts { get; init; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public Dictionary? Omitted { get; init; } + public List ChangedReviewInputs { get; init; } = []; + public WorkflowPolicyReassessment? PolicyReassessment { get; init; } } public sealed record WorkflowStageSummary(string Id, string Kind, string ExecutionStatus, string Outcome, double DurationSeconds, string Evidence, List Diagnostics, TlcStatistics? Statistics, @@ -58,7 +60,7 @@ public sealed record WorkflowRunSummary(string Project, string Scenario, string public sealed record ResolvedMethodSummaryView(string Scope, MethodSummary Summary, string Method, EndpointSummary? Precondition); public sealed record PlannedMethodSummaryView(string Scope, MethodSummary Summary, string Method, - string InspectionStatus, ReviewOrigin InspectionOrigin, string Boundary); + string InspectionStatus, ReviewOrigin InspectionOrigin, string Boundary, EndpointSummary? Precondition); public sealed record PlannedStageSummary(string Id, string Kind, List DependsOn, TlcResources? RequestedResources, TlcResources? Resources, int? Fingerprint, List? Stored, List? MethodSummaries); diff --git a/src/tlalink/Common/WorkflowInputRoles.cs b/src/tlalink/Common/WorkflowInputRoles.cs new file mode 100644 index 0000000..bb06405 --- /dev/null +++ b/src/tlalink/Common/WorkflowInputRoles.cs @@ -0,0 +1,71 @@ +namespace TlaLink; + +internal static class WorkflowInputRoles +{ + internal static HashSet ReviewOnly(string path, AnalysisProject project, AcceptancePolicy policy, + WorkflowRun run, string directory, IReadOnlyDictionary evidence, + List summaries, HashSet? policyInputs = null) + { + HashSet result = new(FilePaths.Comparer); + if (run.ExecutionStatus != "completed" || evidence.Count != run.Stages.Count) return result; + result.UnionWith(policyInputs ?? []); + HashSet reviewIds = policy.Requirements.Where(r => r.Scenario == run.Scenario) + .SelectMany(r => r.Reviews ?? []).Concat(summaries.Select(s => s.Summary.Inspection)) + .ToHashSet(StringComparer.Ordinal); + foreach (ReviewObligation review in project.Obligations.Where(o => reviewIds.Contains(o.Id))) + foreach (string input in review.Inputs) result.Add(ProjectInputs.Resolve(path, input)); + + HashSet execution = new(FilePaths.Comparer) { + path, ProjectInputs.Resolve(path, project.Requirements) + }; + execution.UnionWith(project.Authoring!.Fingerprints.Keys); + execution.ExceptWith(policyInputs ?? []); + execution.UnionWith(project.Compiler.References.Select(p => ProjectInputs.Resolve(path, p))); + AnalysisScenario scenario = project.Scenarios.Single(s => s.Id == run.Scenario); + foreach (AnalysisStage stage in scenario.Stages) + { + foreach (string input in (stage.Sources ?? []).Concat(stage.Models ?? []) + .Concat(new[] { stage.Config, stage.Bindings, stage.Scope }.OfType())) + execution.Add(ProjectInputs.Resolve(path, input)); + } + foreach (SelectedMethodSummary summary in summaries) + { + execution.Add(summary.Scope); + execution.UnionWith(summary.Summary.Sources.Select(p => ProjectInputs.Resolve(summary.Scope, p))); + execution.UnionWith(CorrespondenceInputs.Target(summary.Configuration, + Markup.Name(summary.Summary.Binding).Alias, "tla").Inputs); + } + foreach (WorkflowStageResult stage in run.Stages) + { + if (evidence[stage.Id] is IInputEvidence captured && captured.Fingerprints.Count > 0) + { + execution.UnionWith(captured.Fingerprints.Keys.Where(FilePaths.IsAbsolute) + .Select(p => CurrentInput(path, run, p))); + continue; + } + if (evidence[stage.Id] is not TlcResult || stage.StoredResults is not { Count: > 0 } stored) + return new(FilePaths.Comparer); + foreach (StoredStageResult reference in stored) + { + string entryPath = ProjectAcceptance.SafePath(directory, + Path.Combine(stage.Id, reference.Directory, "entry.json")); + TlcStoredResult entry = ProjectInputs.Read(entryPath); + execution.UnionWith(entry.Material.Inputs.Select(p => CurrentInput(path, run, p.Path))); + execution.Add(CurrentInput(path, run, entry.Material.Model)); + execution.Add(CurrentInput(path, run, entry.Material.Config)); + execution.Add(CurrentInput(path, run, entry.Material.Jar)); + } + } + result.ExceptWith(execution); + return result; + } + + internal static string CurrentInput(string path, WorkflowRun run, string input) + { + if (!FilePaths.IsNativeAbsolute(input)) return input; + string relative = Path.GetRelativePath(run.ProjectDirectory, input); + return !Path.IsPathRooted(relative) && relative != ".." && + !relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) + ? ProjectInputs.Resolve(path, relative) : input; + } +} diff --git a/src/tlalink/Common/WorkflowPolicyReassessment.cs b/src/tlalink/Common/WorkflowPolicyReassessment.cs new file mode 100644 index 0000000..3999f3d --- /dev/null +++ b/src/tlalink/Common/WorkflowPolicyReassessment.cs @@ -0,0 +1,110 @@ +using System.Text.Json; + +namespace TlaLink; + +public sealed record WorkflowPolicyIdentity(string? ProjectSha256, string? RequirementsSha256, string? AuthoringSha256); +public sealed record WorkflowPolicyReassessment(string Status, WorkflowPolicyIdentity Recorded, + WorkflowPolicyIdentity Current, bool? ExecutionDefinitionUnchanged, bool? CheckerExpectationsUnchanged, + List ChangedAreas, string Boundary); + +internal static class WorkflowPolicyComparison +{ + internal sealed record Result(WorkflowPolicyReassessment Report, HashSet ReviewInputs); + + internal static Result Compare(string path, AnalysisProject project, AcceptancePolicy policy, + WorkflowRun run, string directory, AnalysisProject? archived) + { + Dictionary currentAuthoring = new(project.Authoring!.Fingerprints, FilePaths.Comparer); + foreach (var pin in currentAuthoring) + if (!File.Exists(pin.Key) || Files.Hash(pin.Key) != pin.Value) + throw new InputException(ErrorCode.WorkflowEvidenceStale, "Current project authoring changed after loading: " + pin.Key); + string policyPath = ProjectInputs.Resolve(path, project.Requirements); + Dictionary policyPins = new(FilePaths.Comparer); + AcceptancePolicy currentPolicy; + try + { + currentPolicy = JsonSerializer.Deserialize(Files.ReadPinned(policyPath, policyPins), ProjectInputs.Json) + ?? throw new InputException(ErrorCode.WorkflowEvidenceStale, "Current acceptance policy is empty."); + } + catch (Exception error) when (error is JsonException or IOException or UnauthorizedAccessException) + { + throw new InputException(ErrorCode.WorkflowEvidenceStale, "Current acceptance policy could not be reread: " + error.Message); + } + if (Schema.Hash(currentPolicy) != Schema.Hash(policy)) + throw new InputException(ErrorCode.WorkflowEvidenceStale, "Current acceptance policy changed after loading: " + policyPath); + Dictionary? recordedAuthoring = archived?.Authoring?.Fingerprints; + WorkflowPolicyIdentity recorded = new(run.ProjectSha256, run.RequirementsSha256, + recordedAuthoring == null ? null : Schema.Hash(recordedAuthoring)); + WorkflowPolicyIdentity current = new(currentAuthoring[path], policyPins[policyPath], + Schema.Hash(currentAuthoring)); + List changes = []; + HashSet reviewInputs = new(FilePaths.Comparer); + WorkflowPolicyReassessment Report(string status, bool? execution, bool? expectations) => + new(status, recorded, current, execution, expectations, changes, + "Compares archived execution definitions and non-review requirements with the explicitly authored current policy. " + + "Archive integrity, actual execution inputs, evidence and current review decisions are checked independently; " + + "no run rewriting, execution cache or approval of policy edits is implied."); + if (run.Project != project.Id) + { + changes.Add("project-identity"); + return new(Report("incompatible", false, null), reviewInputs); + } + bool authoringChanged = recordedAuthoring != null && !SameAuthoring(path, run, recordedAuthoring, currentAuthoring); + bool changed = recorded.ProjectSha256 != current.ProjectSha256 || + recorded.RequirementsSha256 != current.RequirementsSha256 || authoringChanged; + if (!changed) return new(Report("unchanged", true, true), reviewInputs); + if (archived == null) + { + changes.Add("archived-project-unavailable"); + return new(Report("unavailable", null, null), reviewInputs); + } + + string recordedPolicy = ProjectInputs.Resolve( + FilePaths.Full(Path.GetFileName(path), run.ProjectDirectory), archived.Requirements); + if (!run.Fingerprints.TryGetValue(recordedPolicy, out string? hash) || hash != run.RequirementsSha256) + throw new InputException(ErrorCode.WorkflowProvenanceInconsistent, "Archived acceptance policy contradicts its recorded hash."); + string copy = ProjectAcceptance.SafePath(directory, Path.Combine("inputs", hash)); + if (!File.Exists(copy) || Files.Hash(copy) != hash) + throw new InputException(ErrorCode.WorkflowProvenanceInconsistent, "Missing/changed archived acceptance policy."); + AcceptancePolicy previous = ProjectInputs.Read(copy); + if (previous.SchemaVersion != Schema.Version || previous.Kind != "acceptance-policy" || previous.Project != run.Project) + throw new InputException(ErrorCode.WorkflowProvenanceInconsistent, "Archived acceptance policy identity contradicts the run."); + + bool executionSame = Schema.Hash(Execution(archived)) == Schema.Hash(Execution(project)); + bool expectationsSame = Schema.Hash(Expectations(previous)) == Schema.Hash(Expectations(policy)); + if (!executionSame) changes.Add("execution-definition"); + if (!expectationsSame) changes.Add("checker-expectations"); + if (Schema.Hash(archived.Obligations) != Schema.Hash(project.Obligations)) changes.Add("review-obligations"); + if (Schema.Hash(previous.Requirements.Select(r => new RequirementReviews(r.Id, r.Reviews)).ToList()) != + Schema.Hash(policy.Requirements.Select(r => new RequirementReviews(r.Id, r.Reviews)).ToList())) + changes.Add("requirement-reviews"); + if (archived.ReviewDirectory != project.ReviewDirectory) changes.Add("review-directory"); + if (archived.Requirements != project.Requirements) changes.Add("requirements-path"); + if (changes.Count == 0) changes.Add("authoring-bytes"); + if (!executionSame || !expectationsSame) + return new(Report("incompatible", executionSame, expectationsSame), reviewInputs); + + reviewInputs.UnionWith(recordedAuthoring!.Keys.Select(p => WorkflowInputRoles.CurrentInput(path, run, p))); + reviewInputs.Add(WorkflowInputRoles.CurrentInput(path, run, recordedPolicy)); + reviewInputs.UnionWith(archived.Obligations.SelectMany(o => o.Inputs).Select(p => ProjectInputs.Resolve(path, p))); + return new(Report("review-only", true, true), reviewInputs); + } + + private sealed record RequirementReviews(string Id, List? Reviews); + + private static AnalysisProject Execution(AnalysisProject project) => + project with { Obligations = [], ReviewDirectory = "", Requirements = "" }; + + private static AcceptancePolicy Expectations(AcceptancePolicy policy) => + policy with { Requirements = policy.Requirements.Select(r => r with { Reviews = null }).ToList() }; + + private static bool SameAuthoring(string path, WorkflowRun run, Dictionary recorded, + Dictionary current) + { + if (recorded.Count != current.Count) return false; + foreach (var pin in recorded) + if (!current.TryGetValue(WorkflowInputRoles.CurrentInput(path, run, pin.Key), out string? hash) || hash != pin.Value) + return false; + return true; + } +} diff --git a/src/tlalink/Common/WorkflowResults.cs b/src/tlalink/Common/WorkflowResults.cs index 67eca92..a64690d 100644 --- a/src/tlalink/Common/WorkflowResults.cs +++ b/src/tlalink/Common/WorkflowResults.cs @@ -23,7 +23,11 @@ public sealed record AcceptanceResult(int SchemaVersion, string Kind, string Pro string Run, string RunSha256, string ExecutionStatus, string ArchiveStatus, string CurrentApplicability, string AcceptanceStatus, List Requirements, List Diagnostics, List CheckCoverage, List MethodSummaries, - List Reviews, List NextActions, string Boundary); + List Reviews, List NextActions, string Boundary) +{ + public List ChangedReviewInputs { get; init; } = []; + public WorkflowPolicyReassessment? PolicyReassessment { get; init; } +} public sealed record PlannedMethodSummary(string Scope, MethodSummary Summary, string Method, Endpoint Implementation, Endpoint Specification, Endpoint? Precondition, string InspectionStatus, ReviewOrigin InspectionOrigin, string Boundary); diff --git a/src/tlalink/Dafny/DafnyContracts.cs b/src/tlalink/Dafny/DafnyContracts.cs index d51512a..e884ea7 100644 --- a/src/tlalink/Dafny/DafnyContracts.cs +++ b/src/tlalink/Dafny/DafnyContracts.cs @@ -161,8 +161,8 @@ public static IntegratedManifest Load(string path, Dictionary pi path = FilePaths.Full(path); IntegratedManifest manifest = Parse(Files.ReadPinned(path, pins)); if (manifest.SchemaVersion != Schema.Version || manifest.Kind != "integrated-bindings" || - manifest.Bindings.Count == 0 || manifest.Bindings.Count > 1000) - throw new InputException(ErrorCode.InvalidIntegratedInput, "Expected current integrated-bindings schema and 1..1000 bindings."); + manifest.Bindings.Count > 1000 || manifest.Bindings.Count == 0 && manifest.TlaTargets.Count == 0) + throw new InputException(ErrorCode.InvalidIntegratedInput, "Expected current integrated-bindings schema with selected Dafny bindings or TLA+ targets; maximum 1000 Dafny bindings."); if (manifest.Sources.Any(string.IsNullOrWhiteSpace) || string.IsNullOrWhiteSpace(manifest.Scope) || manifest.Bindings.Any(b => b is null) || manifest.Correspondences.Any(c => c is null)) throw new InputException(ErrorCode.InvalidIntegratedInput, "Scope paths and binding/correspondence records cannot be empty or null."); diff --git a/src/tlalink/Tla/ModelScope.cs b/src/tlalink/Tla/ModelScope.cs index 1ab68c0..4f1766e 100644 --- a/src/tlalink/Tla/ModelScope.cs +++ b/src/tlalink/Tla/ModelScope.cs @@ -23,11 +23,7 @@ public static ModelScope Load(List paths, string jar, int timeout, bool result.Diagnostics.AddRange(document.Diagnostics.Select(d => new Issue(d.Code, d.Severity, d.Message, d.Path is null ? null : new Place(d.Path, d.Line ?? 1, d.Line ?? 1)))); if (!annotations) continue; - List<(int Start, int End, string Content)> comments = Markup.TlaComments(document.Text); - foreach (var algorithm in comments.Where(c => c.Content.TrimStart().StartsWith("--algorithm", StringComparison.Ordinal) || - c.Content.TrimStart().StartsWith("--fair algorithm", StringComparison.Ordinal)).ToList()) - comments.AddRange(Markup.TlaComments(algorithm.Content).Select(c => - (c.Start + algorithm.Start + 2, c.End + algorithm.Start + 2, c.Content))); + List<(int Start, int End, string Content)> comments = FormalComments(document.Text); try { result.Declarations.AddRange(FormalCorrespondence.Attach(path, document.Text, @@ -41,6 +37,16 @@ public static ModelScope Load(List paths, string jar, int timeout, bool return result; } + internal static List<(int Start, int End, string Content)> FormalComments(string text) + { + List<(int Start, int End, string Content)> comments = Markup.TlaComments(text); + foreach (var algorithm in comments.Where(c => c.Content.TrimStart().StartsWith("--algorithm", StringComparison.Ordinal) || + c.Content.TrimStart().StartsWith("--fair algorithm", StringComparison.Ordinal)).ToList()) + comments.AddRange(Markup.TlaComments(algorithm.Content).Select(c => + (c.Start + algorithm.Start + 2, c.End + algorithm.Start + 2, c.Content))); + return comments; + } + public void BindSources(CSharpScope source, CorrespondenceConfiguration config, string? selected = null) { int previous = source.Bindings.Count; diff --git a/src/tlalink/Tla/TlaBackend.cs b/src/tlalink/Tla/TlaBackend.cs index 1da85a6..732cf84 100644 --- a/src/tlalink/Tla/TlaBackend.cs +++ b/src/tlalink/Tla/TlaBackend.cs @@ -67,13 +67,12 @@ public static TlaDocument Parse(string path, string jar, int timeoutSeconds) work = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(adapter)!, ".tlalink-backend-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(work); - string metadata = System.IO.Path.Combine(work, "TlaMetadata.java"); - File.WriteAllText(metadata, MetadataSource, new UTF8Encoding(false)); Run("javac", ["-J-Djava.io.tmpdir=" + work, "-encoding", "UTF-8", - "-cp", jar, "-d", work, adapter, metadata], work, timeoutSeconds); - index = Index(path, text, jar, work, timeoutSeconds); + "-cp", jar, "-d", work, adapter], work, timeoutSeconds); + TlaNativeParse parsed = Index(path, text, jar, work, timeoutSeconds); + index = parsed.Entries.AsReadOnly(); AddIndex(index, path, text, true, endpoints, diagnostics, dependencies); - (module, stateVariables) = AddMetadata(path, jar, work, timeoutSeconds, endpoints); + (module, stateVariables) = AddMetadata(parsed.Metadata, endpoints); CheckImports(path, jar, work, timeoutSeconds, endpoints, diagnostics, dependencies); foreach (var pin in java.Fingerprints) Files.Pin(dependencies, pin.Key, pin.Value); CheckFingerprints(dependencies); @@ -104,14 +103,9 @@ or UnauthorizedAccessException or ArgumentException or JsonException { Module = module, StateVariables = stateVariables, NativeIndex = index }; } - private static (string Module, IReadOnlyList Variables) AddMetadata(string path, string jar, string work, - int timeout, List endpoints) + private static (string Module, IReadOnlyList Variables) AddMetadata(TlaNativeMetadata metadata, + List endpoints) { - string json = Run("java", ["-Dfile.encoding=UTF-8", "-Djava.io.tmpdir=" + work, - "-cp", work + System.IO.Path.PathSeparator + jar, "pcal.TlaMetadata", path], - System.IO.Path.GetDirectoryName(path)!, timeout); - TlaNativeMetadata metadata = JsonSerializer.Deserialize(json, TlaNativeJson.Options) - ?? throw new BackendFailure("Invalid TLA parser metadata."); for (int i = 0; i < endpoints.Count; i++) if (endpoints[i].Kind == "operator") endpoints[i] = endpoints[i] with @@ -139,7 +133,7 @@ private static void CheckImports(string root, string jar, string work, int timeo if (hash != dependencies[path]) throw new BackendFailure($"Dependency changed while parsing: {path}"); if (AlgorithmArguments(text).Length > 0) - AddIndex(Index(path, text, jar, work, timeout), path, text, false, + AddIndex(Index(path, text, jar, work, timeout).Entries, path, text, false, endpoints, diagnostics, dependencies); } } @@ -151,13 +145,13 @@ private static void CheckFingerprints(Dictionary dependencies) throw new BackendFailure($"Dependency changed while parsing: {path}"); } - private static IReadOnlyList Index(string path, string text, string jar, string work, int timeout) + private static TlaNativeParse Index(string path, string text, string jar, string work, int timeout) { string[] arguments = ["-Dfile.encoding=UTF-8", "-Djava.io.tmpdir=" + work, "-cp", work + System.IO.Path.PathSeparator + jar, "pcal.TlaIndex", path, .. AlgorithmArguments(text)]; string json = Run("java", arguments, System.IO.Path.GetDirectoryName(path)!, timeout); - return TlaNativeJson.ReadIndex(json).AsReadOnly(); + return TlaNativeJson.ReadParse(json); } private static string Run(string executable, string[] arguments, string directory, int timeout) @@ -255,6 +249,12 @@ private static TlaEndpoint Endpoint(TlaNativeEndpoint row, string text) start, end, line, column, endLine, endColumn); } + internal static int ArchivedOffset(string text, int line, int column) + { + try { return Offset(text, line, column); } + catch (BackendFailure error) { throw new InputException(ErrorCode.InvalidModelBinding, error.Message); } + } + private static int Offset(string text, int line, int column) { if (line < 1 || column < 1) @@ -320,54 +320,4 @@ private static string FindAdapter() private sealed class BackendFailure(string message) : Exception(message); - // A separate companion keeps the archived adapter byte-identical on case-insensitive Windows. - private const string MetadataSource = """ - package pcal; - import java.io.*; - import java.util.*; - import tla2sany.drivers.SANY; - import tla2sany.modanalyzer.SpecObj; - import tla2sany.semantic.*; - import util.SimpleFilenameToStream; - public final class TlaMetadata { - public static void main(String[] args) throws Exception { - PrintStream output = System.out; - ByteArrayOutputStream messages = new ByteArrayOutputStream(); - try (PrintStream capture = new PrintStream(messages, true, "UTF-8")) { - System.setOut(capture); - try { - SpecObj spec = new SpecObj(args[0], new SimpleFilenameToStream()); - int status = SANY.frontEndMain(spec, args[0], capture); - if (status != 0 || spec.getErrorLevel() != 0 || spec.getRootModule() == null) - throw new IllegalArgumentException("SANY rejected " + args[0]); - ModuleNode root = spec.getRootModule(); - List variables = new ArrayList<>(); - for (OpDeclNode variable : root.getVariableDecls()) - variables.add(quote(variable.getName().toString())); - List arities = new ArrayList<>(); - for (OpDefNode operator : root.getOpDefs()) { - if (operator.getLocation().source().equals(root.getName().toString())) - arities.add(quote(operator.getName().toString()) + ":" + operator.getArity()); - } - output.println("{\"module\":" + quote(root.getName().toString()) - + ",\"variables\":[" + String.join(",", variables) - + "],\"arities\":{" + String.join(",", arities) + "}}"); - } catch (Exception error) { - System.err.println(messages.toString("UTF-8")); - System.err.println(error.toString()); - System.exit(1); - } finally { System.setOut(output); } - } - } - private static String quote(String value) { - StringBuilder result = new StringBuilder("\""); - for (char character : value.toCharArray()) { - if (character == '\\' || character == '"') result.append('\\'); - if (character < 32) result.append(String.format("\\u%04x", (int) character)); - else result.append(character); - } - return result.append('"').toString(); - } - } - """; } diff --git a/src/tlalink/Tla/TlaIndex.java b/src/tlalink/Tla/TlaIndex.java index 7251925..5653986 100644 --- a/src/tlalink/Tla/TlaIndex.java +++ b/src/tlalink/Tla/TlaIndex.java @@ -31,6 +31,7 @@ public final class TlaIndex { private final List entries = new ArrayList<>(); + private String metadata; private final IdentityHashMap visited = new IdentityHashMap<>(); public static void main(String[] args) throws Exception { @@ -41,7 +42,8 @@ public static void main(String[] args) throws Exception { try { TlaIndex index = new TlaIndex(); index.parse(Path.of(args[0]), args); - output.println("[" + String.join(",", index.entries) + "]"); + output.println("{\"entries\":[" + String.join(",", index.entries) + + "],\"metadata\":" + index.metadata + "}"); } catch (Exception error) { System.err.println(messages.toString("UTF-8")); System.err.println(error.getClass().getSimpleName() + ": " + error.getMessage()); @@ -61,6 +63,11 @@ private void parse(Path path, String[] args) throws Exception { throw new IllegalArgumentException("SANY rejected " + path); } String module = specification.getRootModule().getName().toString(); + List variables = new ArrayList<>(); + for (tla2sany.semantic.OpDeclNode variable : specification.getRootModule().getVariableDecls()) { + variables.add(quote(variable.getName().toString())); + } + List arities = new ArrayList<>(); for (tla2sany.semantic.ModuleNode loaded : specification.getExternalModuleTable().getModuleNodes()) { if (loaded.getAssumptions().length > 0) { entries.add("{\"kind\":\"assumptions\",\"module\":" + quote(loaded.getName().toString()) @@ -74,6 +81,7 @@ private void parse(Path path, String[] args) throws Exception { } entries.add(entry("operator", operator.getName().toString(), module, place.beginLine(), place.beginColumn(), place.endLine(), place.endColumn())); + arities.add(quote(operator.getName().toString()) + ":" + operator.getArity()); entries.add("{\"kind\":\"operator-level\",\"name\":" + quote(operator.getName().toString()) + ",\"level\":" + operator.getLevel() + "}"); } @@ -85,6 +93,8 @@ private void parse(Path path, String[] args) throws Exception { entries.add(entry("variable", variable.getName().toString(), module, place.beginLine(), place.beginColumn(), place.endLine(), place.endColumn())); } + metadata = "{\"module\":" + quote(module) + ",\"variables\":[" + + String.join(",", variables) + "],\"arities\":{" + String.join(",", arities) + "}}"; if (args.length > 1) { parsePlusCal(path, args, module); } diff --git a/src/tlalink/Tla/TlaNativeContracts.cs b/src/tlalink/Tla/TlaNativeContracts.cs index c5fe0dc..f4ec615 100644 --- a/src/tlalink/Tla/TlaNativeContracts.cs +++ b/src/tlalink/Tla/TlaNativeContracts.cs @@ -25,6 +25,25 @@ internal static List ReadIndex(string json) { throw new JsonException("Invalid TLA parser entry kind.", error); } + + } + + internal static TlaNativeParse ReadParse(string json) + { + try + { + TlaNativeParse parsed = JsonSerializer.Deserialize(json, Options) + ?? throw new JsonException("Invalid TLA parser response: expected an object."); + if (parsed.Entries.Any(row => row is null) || parsed.Metadata.Variables.Any(v => v is null) || + string.IsNullOrWhiteSpace(parsed.Metadata.Module) || + parsed.Metadata.Arities.Any(p => string.IsNullOrWhiteSpace(p.Key) || p.Value < 0)) + throw new JsonException("Invalid TLA parser entries or metadata."); + return parsed; + } + catch (NotSupportedException error) + { + throw new JsonException("Invalid TLA parser entry kind.", error); + } } } @@ -64,3 +83,5 @@ internal sealed record TlaNativeTranslation(string State, string Detail, int Lin internal sealed record TlaNativeAssumptions(string Module, int Count) : TlaNativeRow; internal sealed record TlaNativeOperatorLevel(string Name, int Level) : TlaNativeRow; internal sealed record TlaNativeMetadata(string Module, List Variables, Dictionary Arities); +[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)] +internal sealed record TlaNativeParse(List Entries, TlaNativeMetadata Metadata); diff --git a/src/tlalink/Tlc/TlcResultStore.cs b/src/tlalink/Tlc/TlcResultStore.cs index ac7b84b..841aa8e 100644 --- a/src/tlalink/Tlc/TlcResultStore.cs +++ b/src/tlalink/Tlc/TlcResultStore.cs @@ -150,6 +150,10 @@ internal static List ValidateRunStage(string path, AnalysisProject projec evidenceStage = declared; List issues = []; void Bad(string message) => issues.Add(new(ErrorCode.WorkflowStageInconsistent, "TLC stage " + stage.Id + ": " + message)); + Dictionary paths = new(FilePaths.Comparer), metadata = new(StringComparer.Ordinal); + foreach (var pin in fingerprints) + if (!(FilePaths.IsAbsolute(pin.Key) ? paths : metadata).TryAdd(pin.Key, pin.Value)) + Bad("recorded inputs contain aliased keys: " + pin.Key); string outcome = ProjectWorkflow.Outcome("tlc", result); int fingerprint = result.Fingerprint; List stored = stage.StoredResults ?? []; @@ -186,7 +190,7 @@ internal static List ValidateRunStage(string path, AnalysisProject projec !material.Options.SequenceEqual(Options)) Bad("stored result does not describe the declared stage"); foreach (TlcKeyInput input in material.Inputs) - if (!fingerprints.TryGetValue(input.Path, out string? hash) || hash != input.Sha256) + if (!(FilePaths.IsAbsolute(input.Path) ? paths : metadata).TryGetValue(input.Path, out string? hash) || hash != input.Sha256) Bad("stored result input differs from the run's recorded inputs: " + input.Path); if (reference.Primary) { diff --git a/tests/TlaLink.Tests/CoreTests.cs b/tests/TlaLink.Tests/CoreTests.cs index d13686c..fe24397 100644 --- a/tests/TlaLink.Tests/CoreTests.cs +++ b/tests/TlaLink.Tests/CoreTests.cs @@ -13,6 +13,7 @@ public static void Register(Action test, string work) SourcePreparationTests.Register(test, work); ActionArgumentTests.Register(test, work); AcceptanceSummaryTests.Register(test, work); + WorkflowFreshnessTests.Register(test, work); SourceInventoryTests.Register(test, work); SourceSymbolTests.Register(test, work); SourceObligationTests.Register(test, work); diff --git a/tests/TlaLink.Tests/Fixtures/InspectionReview/Review.tla b/tests/TlaLink.Tests/Fixtures/InspectionReview/Review.tla new file mode 100644 index 0000000..6fbf063 --- /dev/null +++ b/tests/TlaLink.Tests/Fixtures/InspectionReview/Review.tla @@ -0,0 +1,10 @@ +---- MODULE Review ---- +(* @link {"bind":[{"id":"review::commita","source":{"symbol":"M:InspectionExample.ReviewCounter.Adjust(System.Boolean)","syntax":"ExpressionStatement","tokens":"this.Commit(next);","match":1,"expected_matches":2}}]} *) +CommitA == TRUE +(* @link {"bind":[{"id":"review::commitb","source":{"symbol":"M:InspectionExample.ReviewCounter.Adjust(System.Boolean)","syntax":"ExpressionStatement","tokens":"this.Commit(next);","match":2,"expected_matches":2}}]} *) +CommitB == TRUE +(* @link {"bind":[{"id":"review::read","source":{"symbol":"M:InspectionExample.ReviewCounter.Adjust(System.Boolean)","syntax":"LocalDeclarationStatement","tokens":"int next = this.ReadNext();"}}]} *) +Read == TRUE +(* @link {"bind":[{"id":"review::release","source":{"symbol":"M:InspectionExample.ReviewCounter.Adjust(System.Boolean)","syntax":"ExpressionStatement","tokens":"this.Release();"}}]} *) +Release == TRUE +==== diff --git a/tests/TlaLink.Tests/Fixtures/InspectionReview/ReviewCounter.cs b/tests/TlaLink.Tests/Fixtures/InspectionReview/ReviewCounter.cs new file mode 100644 index 0000000..f3bc2ba --- /dev/null +++ b/tests/TlaLink.Tests/Fixtures/InspectionReview/ReviewCounter.cs @@ -0,0 +1,93 @@ +using System; + +namespace InspectionExample +{ + public interface ISink + { + void Write(int value); + } + + public partial class ReviewCounter + { + private int value; + + public void Adjust(bool enabled) + { + int next = this.ReadNext(); + try + { + if (enabled) + { + this.Commit(next); + this.Commit(next); + } + } + finally + { + this.Release(); + } + } + + private int ReadNext() + { + return checked(this.value + 1); + } + + private void Commit(int next) + { + this.Observe(next); + this.value = next; + } + + private void Release() + { + this.value = 0; + } + + public void Dispatch(ISink sink) + { + sink.Write(this.value); + this.VirtualWrite(this.value); + Console.WriteLine(this.value); + } + + protected virtual void VirtualWrite(int item) + { + this.value = item; + } + + public void Generic() + { + this.Observe(Echo(1).Identity()); + } + + private static T Echo(T item) + { + return item; + } + + partial void Observe(int item); + + public void Nested() + { + Action callback = () => this.Release(); + callback(); + } + } + + public partial class ReviewCounter + { + partial void Observe(int item) + { + this.value = item; + } + } + + public static class ReviewExtensions + { + public static T Identity(this T item) + { + return item; + } + } +} diff --git a/tests/TlaLink.Tests/Fixtures/TlaFrontend/MetadataBase.tla b/tests/TlaLink.Tests/Fixtures/TlaFrontend/MetadataBase.tla new file mode 100644 index 0000000..1fa1eec --- /dev/null +++ b/tests/TlaLink.Tests/Fixtures/TlaFrontend/MetadataBase.tla @@ -0,0 +1,4 @@ +---- MODULE MetadataBase ---- +VARIABLE inherited +Apply(F(_), arg) == F(arg) +==== diff --git a/tests/TlaLink.Tests/Fixtures/TlaFrontend/MetadataRoot.tla b/tests/TlaLink.Tests/Fixtures/TlaFrontend/MetadataRoot.tla new file mode 100644 index 0000000..3578641 --- /dev/null +++ b/tests/TlaLink.Tests/Fixtures/TlaFrontend/MetadataRoot.tla @@ -0,0 +1,5 @@ +---- MODULE MetadataRoot ---- +EXTENDS MetadataBase +VARIABLE own +RootApply(F(_), arg) == Apply(F, arg) +==== diff --git a/tests/TlaLink.Tests/Fixtures/TlaFrontend/Response.json b/tests/TlaLink.Tests/Fixtures/TlaFrontend/Response.json new file mode 100644 index 0000000..f2d16b6 --- /dev/null +++ b/tests/TlaLink.Tests/Fixtures/TlaFrontend/Response.json @@ -0,0 +1,11 @@ +{ + "entries": [ + {"kind": "operator", "name": "Apply", "scope": "Sample", "line": 3, "column": 1, "endLine": 3, "endColumn": 25}, + {"kind": "variable", "name": "state", "scope": "Sample", "line": 2, "column": 10, "endLine": 2, "endColumn": 14} + ], + "metadata": { + "module": "Sample", + "variables": ["state"], + "arities": {"Apply": 2} + } +} diff --git a/tests/TlaLink.Tests/Fixtures/TlaOnlyInspection/Counter.cs b/tests/TlaLink.Tests/Fixtures/TlaOnlyInspection/Counter.cs new file mode 100644 index 0000000..0d4bde7 --- /dev/null +++ b/tests/TlaLink.Tests/Fixtures/TlaOnlyInspection/Counter.cs @@ -0,0 +1,12 @@ +namespace TlaOnlyFixture +{ + public static class Counter + { + public static int Value; + + public static void Increment() + { + Value++; + } + } +} diff --git a/tests/TlaLink.Tests/Fixtures/TlaOnlyInspection/CounterModel.tla b/tests/TlaLink.Tests/Fixtures/TlaOnlyInspection/CounterModel.tla new file mode 100644 index 0000000..076d79d --- /dev/null +++ b/tests/TlaLink.Tests/Fixtures/TlaOnlyInspection/CounterModel.tla @@ -0,0 +1,7 @@ +---- MODULE CounterModel ---- +EXTENDS Integers +VARIABLE value +Init == value = 0 +(* @link {"bind":[{"id":"counter-only::increment","source":{"symbol":"M:TlaOnlyFixture.Counter.Increment","syntax":"ExpressionStatement","tokens":"Value\u002B\u002B;","match":1,"expected_matches":1}}]} *) +Increment == value' = value + 1 +==== diff --git a/tests/TlaLink.Tests/Fixtures/TlaOnlyInspection/bindings.json b/tests/TlaLink.Tests/Fixtures/TlaOnlyInspection/bindings.json new file mode 100644 index 0000000..a9eeb76 --- /dev/null +++ b/tests/TlaLink.Tests/Fixtures/TlaOnlyInspection/bindings.json @@ -0,0 +1,10 @@ +{ + "schema_version": 4, + "kind": "integrated-bindings", + "sources": ["Counter.cs"], + "scope": "scope.json", + "bindings": [], + "source_obligations": [], + "correspondences": [], + "tla_targets": ["counter-only"] +} diff --git a/tests/TlaLink.Tests/Fixtures/TlaOnlyInspection/scope.json b/tests/TlaLink.Tests/Fixtures/TlaOnlyInspection/scope.json new file mode 100644 index 0000000..2453159 --- /dev/null +++ b/tests/TlaLink.Tests/Fixtures/TlaOnlyInspection/scope.json @@ -0,0 +1,10 @@ +{ + "schema_version": 4, + "kind": "correspondence-scope", + "annotation_version": 4, + "targets": [ + { "id": "counter-only", "language": "tla", "inputs": ["CounterModel.tla"], + "required_bindings": ["counter-only::increment"] } + ], + "omissions": [] +} diff --git a/tests/TlaLink.Tests/Fixtures/WorkflowFreshness/Model.tla b/tests/TlaLink.Tests/Fixtures/WorkflowFreshness/Model.tla new file mode 100644 index 0000000..80d5133 --- /dev/null +++ b/tests/TlaLink.Tests/Fixtures/WorkflowFreshness/Model.tla @@ -0,0 +1,3 @@ +---- MODULE Model ---- +Init == TRUE +==== diff --git a/tests/TlaLink.Tests/Fixtures/WorkflowFreshness/review.md b/tests/TlaLink.Tests/Fixtures/WorkflowFreshness/review.md new file mode 100644 index 0000000..012af7f --- /dev/null +++ b/tests/TlaLink.Tests/Fixtures/WorkflowFreshness/review.md @@ -0,0 +1,3 @@ +# Review context + +Authored review material, not an execution input unless explicitly selected. diff --git a/tests/TlaLink.Tests/Fixtures/WorkflowFreshness/tool.txt b/tests/TlaLink.Tests/Fixtures/WorkflowFreshness/tool.txt new file mode 100644 index 0000000..40ff3b1 --- /dev/null +++ b/tests/TlaLink.Tests/Fixtures/WorkflowFreshness/tool.txt @@ -0,0 +1 @@ +Unexecuted tool placeholder for structural applicability unit tests. diff --git a/tests/TlaLink.Tests/Fixtures/WorkflowFreshness/unclassified.txt b/tests/TlaLink.Tests/Fixtures/WorkflowFreshness/unclassified.txt new file mode 100644 index 0000000..c6078cd --- /dev/null +++ b/tests/TlaLink.Tests/Fixtures/WorkflowFreshness/unclassified.txt @@ -0,0 +1 @@ +An input without a declared review-only role. diff --git a/tests/TlaLink.Tests/FormalOwnedLinksTests.cs b/tests/TlaLink.Tests/FormalOwnedLinksTests.cs index 571d2fe..3198f38 100644 --- a/tests/TlaLink.Tests/FormalOwnedLinksTests.cs +++ b/tests/TlaLink.Tests/FormalOwnedLinksTests.cs @@ -78,6 +78,7 @@ Dictionary Reconstruct(params string[] ids) => public static void RegisterNative(Action test, string root, string work) { + InspectionReviewContextTests.RegisterNative(test, root, work); test("bulk link migration plans first preserves tokens and captures and is idempotent", () => { string directory = Directory.CreateDirectory(Path.Combine(work, "link-migration")).FullName; diff --git a/tests/TlaLink.Tests/InspectionReviewContextTests.cs b/tests/TlaLink.Tests/InspectionReviewContextTests.cs new file mode 100644 index 0000000..24ad1d1 --- /dev/null +++ b/tests/TlaLink.Tests/InspectionReviewContextTests.cs @@ -0,0 +1,234 @@ +using System.Text.Json; +using TlaLink; + +namespace TlaLink.Tests; + +public static class InspectionReviewContextTests +{ + public static void Register(Action test, string work) + { + test("member grouping orders attachments by source and deduplicates shared context", () => + { + Inputs fixture = Fixture(work, "group"); + LinkInspectionResult result = Read(fixture, "--group-by", "member", "--context", "member"); + InspectionMemberGroup group = result.MemberGroups.Single(g => g.Member.Symbol == "M:InspectionExample.ReviewCounter.Adjust(System.Boolean)"); + CoreTests.Equal(4, group.Attachments.Count); + CoreTests.Equal("review::read", group.Attachments[0].Binding); + CoreTests.Equal("review::release", group.Attachments[^1].Binding); + CoreTests.Equal(group.Lines.Count, group.Lines.Select(l => l.Number).Distinct().Count()); + CoreTests.True(group.Lines.Any(l => l.Text.Contains("finally", StringComparison.Ordinal))); + CoreTests.Equal(4, group.Lines.Count(l => l.Selected)); + using JsonDocument document = JsonDocument.Parse(InspectionFiltering.Json(result)); + CoreTests.True(document.RootElement.GetProperty("member_groups").GetArrayLength() > 0); + JsonElement source = document.RootElement.GetProperty("endpoints")[0].GetProperty("links")[0].GetProperty("source"); + CoreTests.True(!source.TryGetProperty("lines", out _)); + CoreTests.True(source.TryGetProperty("context", out _)); + string text = LinkInspection.Readable(result, false); + CoreTests.Equal(1, Count(text, "Shared context")); + CoreTests.True(text.Contains("not execution order", StringComparison.Ordinal)); + CoreTests.True(!text.Contains("Context (>>>", StringComparison.Ordinal)); + }); + test("member grouping preserves page counts without treating a partial page as whole coverage", () => + { + Inputs fixture = Fixture(work, "group-page"); + LinkInspectionResult result = Read(fixture, "--group-by", "member", "--limit", "1", "--context", "member"); + InspectionMemberGroup group = result.MemberGroups.Single(); + CoreTests.Equal(1, group.Attachments.Count); + CoreTests.Equal(4, group.MatchingAttachments); + CoreTests.Equal(1, result.NextOffset); + using JsonDocument document = JsonDocument.Parse(InspectionFiltering.Json( + Read(fixture, "--group-by", "member", "--section", "source"))); + CoreTests.True(!document.RootElement.GetProperty("member_groups")[0].TryGetProperty("lines", out _)); + CoreTests.True(Read(fixture).MemberGroups.Count == 0); + }); + test("callee expansion emits each selected source declaration once with no recursive body traversal", () => + { + Inputs fixture = Fixture(work, "callees"); + LinkInspectionResult result = Read(fixture, "--callee-source", "true"); + CoreTests.True(result.CallsIncluded); + CoreTests.Equal(3, result.CalleeSources.Count); + CoreTests.True(result.CalleeSources.All(c => c.Status == "included")); + CoreTests.True(!result.CalleeSources.Any(c => c.Symbol.Contains("Observe", StringComparison.Ordinal))); + InspectionCall[] commits = result.Endpoints.SelectMany(e => e.Links).SelectMany(l => l.Source!.Calls!) + .Where(c => c.Site.Target == "M:InspectionExample.ReviewCounter.Commit(System.Int32)").ToArray(); + CoreTests.Equal(2, commits.Length); + CoreTests.Equal(commits[0].CalleeKeys.Single(), commits[1].CalleeKeys.Single()); + string text = LinkInspection.Readable(result, true); + CoreTests.Equal(1, Count(text, "Selected-source callees")); + CoreTests.Equal(1, Count(text, "this.Observe(next);")); + CoreTests.True(text.Contains("not a runtime dispatch", StringComparison.Ordinal)); + }); + test("callee budgets report truncated and omitted declarations and retain structural readiness", () => + { + Inputs fixture = Fixture(work, "budgets"); + LinkInspectionResult result = Read(fixture, "--callee-source", "true", "--callee-limit", "1", "--callee-max-lines", "2"); + CoreTests.Equal("ready", result.Status); + CoreTests.Equal(1, result.CalleeSources.Count(c => c.Status == "truncated")); + CoreTests.Equal(2, result.CalleeSources.Count(c => c.Status == "budget-omitted")); + CoreTests.Equal(2, result.CalleeSources.Sum(c => c.Lines.Count)); + CoreTests.True(result.CalleeSources.All(c => c.OmittedLines == c.TotalLines - c.Lines.Count)); + CoreTests.True(result.Endpoints.SelectMany(e => e.Links).SelectMany(l => l.Source!.Calls!) + .Any(c => c.ExpansionStatus == "budget-omitted")); + LinkInspectionResult paged = Read(fixture, "--callee-source", "true", "--limit", "1"); + CoreTests.Equal(1, paged.CalleeSources.Count); + CoreTests.Equal("M:InspectionExample.ReviewCounter.Commit(System.Int32)", paged.CalleeSources.Single().Symbol); + }); + test("callee expansion keeps interface virtual and metadata boundaries explicit", () => + { + Inputs fixture = Fixture(work, "dispatch", WholeMember("Dispatch")); + LinkInspectionResult result = Read(fixture, "--callee-source", "true", "--section", "calls"); + List calls = result.Endpoints.Single().Links.Single().Source!.Calls!; + CoreTests.Equal("declaration-only", calls.Single(c => c.Site.Dispatch == "interface").ExpansionStatus); + CoreTests.Equal("included", calls.Single(c => c.Site.Dispatch == "virtual").ExpansionStatus); + CoreTests.Equal("no-selected-source", calls.Single(c => c.Site.Target!.Contains("Console", StringComparison.Ordinal)).ExpansionStatus); + CoreTests.True(result.CalleeSources.Single(c => c.Symbol.Contains("ISink", StringComparison.Ordinal)).Lines.Count > 0); + CoreTests.True(result.CalleeSources.All(c => c.Symbol != "M:InspectionExample.ReviewCounter.Dispatch(InspectionExample.ISink)")); + using JsonDocument json = JsonDocument.Parse(InspectionFiltering.Json(result)); + CoreTests.True(json.RootElement.GetProperty("callee_sources").GetArrayLength() == 2); + CoreTests.True(!json.RootElement.GetProperty("endpoints")[0].GetProperty("model").TryGetProperty("source", out _)); + }); + test("callee expansion handles original generic extension and partial implementation identities", () => + { + Inputs fixture = Fixture(work, "generics", WholeMember("Generic")); + LinkInspectionResult result = Read(fixture, "--callee-source", "true"); + CoreTests.True(result.CalleeSources.Any(c => c.Symbol.Contains("Echo``1", StringComparison.Ordinal))); + CoreTests.True(result.CalleeSources.Any(c => c.Symbol.Contains("ReviewExtensions.Identity``1", StringComparison.Ordinal))); + List observe = result.CalleeSources.Where(c => c.Symbol.Contains("Observe", StringComparison.Ordinal)).ToList(); + CoreTests.Equal(2, observe.Count); + CoreTests.True(observe.Any(c => c.Status == "included" && c.Lines.Any(l => l.Text.Contains("this.value = item;", StringComparison.Ordinal)))); + CoreTests.True(observe.Any(c => c.Status == "declaration-only")); + }); + test("callee expansion marks nested execution and does not invent a delegate destination", () => + { + Inputs fixture = Fixture(work, "nested", WholeMember("Nested")); + LinkInspectionResult result = Read(fixture, "--callee-source", "true"); + List calls = result.Endpoints.Single().Links.Single().Source!.Calls!; + CoreTests.True(calls.Single(c => c.Site.Target == "M:InspectionExample.ReviewCounter.Release").Site.InNestedFunction); + CoreTests.Equal("no-selected-source", calls.Single(c => c.Site.Dispatch == "delegate").ExpansionStatus); + CoreTests.Equal(1, result.CalleeSources.Count); + }); + test("review options reject contradictory budgets and keep source-only sections small", () => + { + Inputs fixture = Fixture(work, "invalid"); + foreach (string[] args in new[] + { + new[] { "--group-by", "call" }, new[] { "--callee-source", "yes" }, + new[] { "--callee-source", "true", "--calls", "false" }, + new[] { "--callee-source", "true", "--section", "source" }, + new[] { "--callee-limit", "1" }, + new[] { "--callee-source", "true", "--callee-limit", "0" }, + new[] { "--callee-source", "true", "--callee-limit", "101" }, + new[] { "--callee-source", "true", "--callee-max-lines", "501" } + }) CoreTests.ThrowsAny(() => Read(fixture, args)); + CoreTests.ThrowsAny(() => new CliOptions(["links", "check", "--group-by", "member"])); + CoreTests.ThrowsAny(() => new CliOptions(["links", "set", "--callee-source", "true"])); + using JsonDocument document = JsonDocument.Parse(InspectionFiltering.Json( + Read(fixture, "--group-by", "member", "--section", "source"))); + CoreTests.True(!document.RootElement.TryGetProperty("callee_sources", out _)); + }); + test("grouped review retains unresolved entries diagnostics and empty-page semantics", () => + { + Inputs fixture = Fixture(work, "unresolved"); + fixture.Native.Declarations[0] = fixture.Native.Declarations[0] with + { + Binding = new("review::commita", Source: new("M:InspectionExample.ReviewCounter.Missing")) + }; + LinkInspectionResult result = Read(fixture, "--group-by", "member", "--callee-source", "true"); + CoreTests.Equal("failed", result.Status); + CoreTests.True(result.Diagnostics.Count > 0); + CoreTests.Equal(3, result.MemberGroups.Single().Attachments.Count); + CoreTests.Equal("unresolved", result.Endpoints[0].Links.Single().Status); + LinkInspectionResult empty = Read(fixture, "--group-by", "member", "--callee-source", "true", "--offset", "99"); + CoreTests.Equal("failed", empty.Status); + CoreTests.Equal(0, empty.MemberGroups.Count); + CoreTests.Equal(0, empty.CalleeSources.Count); + CoreTests.True(LinkInspection.Readable(empty, false).Contains("Diagnostics", StringComparison.Ordinal)); + }); + } + + public static void RegisterNative(Action test, string root, string work) + { + test("native CLI groups member context and projects bounded callee source across output formats", () => + { + string directory = Directory.CreateDirectory(Path.Combine(work, "review-context-native")).FullName; + string fixture = Path.Combine(AppContext.BaseDirectory, "Fixtures", "InspectionReview"); + string cs = Path.Combine(directory, "ReviewCounter.cs"), model = Path.Combine(directory, "Review.tla"); + File.Copy(Path.Combine(fixture, "ReviewCounter.cs"), cs); + File.Copy(Path.Combine(fixture, "Review.tla"), model); + string scope = Path.Combine(directory, "scope.json"); + Files.WriteNew(scope, new CorrespondenceConfiguration(Schema.Version, "correspondence-scope", Markup.Version, + [new("review", "tla", [model], RequiredBindings: ["review::commita", "review::commitb", "review::read", "review::release"])], [])); + string sourceHash = Files.Hash(cs), modelHash = Files.Hash(model); + (int Code, string Json) Run(params string[] args) => + TestCli.Run(["links", "inspect", "--annotation-version", "4", "--scope", scope, "--target", "review", + "--source", cs, "--jar", TestTools.Jar(root), "--group-by", "member", "--context", "member", + "--callee-source", "true", "--callee-limit", "1", "--callee-max-lines", "2", .. args]); + var json = Run(); + if (json.Code != 0) throw new InvalidOperationException(json.Json); + using (JsonDocument result = JsonDocument.Parse(json.Json)) + { + CoreTests.Equal(1, result.RootElement.GetProperty("member_groups").GetArrayLength()); + CoreTests.Equal(3, result.RootElement.GetProperty("callee_sources").GetArrayLength()); + CoreTests.Equal(2, result.RootElement.GetProperty("callee_sources").EnumerateArray() + .Count(c => c.GetProperty("status").GetString() == "budget-omitted")); + } + using (JsonDocument summary = JsonDocument.Parse(Run("--format", "summary").Json)) + { + CoreTests.Equal(1, summary.RootElement.GetProperty("member_groups").GetInt32()); + CoreTests.Equal(2, summary.RootElement.GetProperty("omitted_callee_declarations").GetInt32()); + CoreTests.Equal(1, summary.RootElement.GetProperty("truncated_callee_sources").GetInt32()); + } + var text = Run("--format", "text"); + CoreTests.Equal(0, text.Code); + CoreTests.Equal(1, Count(text.Json, "Shared context")); + string report = Path.Combine(directory, "review.md"); + var markdown = Run("--format", "markdown", "--output", report); + CoreTests.Equal(0, markdown.Code); + CoreTests.Equal(markdown.Json.Trim(), Files.Read(report).Trim()); + CoreTests.True(Files.Read(report).Contains("budget-omitted", StringComparison.Ordinal)); + CoreTests.Equal(sourceHash, Files.Hash(cs)); + CoreTests.Equal(modelHash, Files.Hash(model)); + }); + } + + private static int Count(string text, string value) => + text.Split(value, StringSplitOptions.None).Length - 1; + + private sealed record Inputs(string Source, string Model, FormalTarget Target, NativeLinkIndex Native); + + private static string WholeMember(string name) => "M:InspectionExample.ReviewCounter." + name + + (name == "Dispatch" ? "(InspectionExample.ISink)" : ""); + + private static Inputs Fixture(string work, string name, string? member = null) + { + string directory = Directory.CreateDirectory(Path.Combine(work, "review-context-" + name)).FullName; + string cs = Path.Combine(directory, "ReviewCounter.cs"), model = Path.Combine(directory, "Review.tla"); + File.Copy(Path.Combine(AppContext.BaseDirectory, "Fixtures", "InspectionReview", "ReviewCounter.cs"), cs); + List<(string Name, PreparationTarget Selector)> selectors = member == null ? + [ + ("CommitA", new("M:InspectionExample.ReviewCounter.Adjust(System.Boolean)", "ExpressionStatement", "this.Commit(next);", 1, 2)), + ("CommitB", new("M:InspectionExample.ReviewCounter.Adjust(System.Boolean)", "ExpressionStatement", "this.Commit(next);", 2, 2)), + ("Read", new("M:InspectionExample.ReviewCounter.Adjust(System.Boolean)", "LocalDeclarationStatement", "int next = this.ReadNext();")), + ("Release", new("M:InspectionExample.ReviewCounter.Adjust(System.Boolean)", "ExpressionStatement", "this.Release();")) + ] : [(name, new(member))]; + List spans = []; + List declarations = []; + string text = string.Join("\n", selectors.Select(s => s.Name + " == TRUE")); + File.WriteAllText(model, text); + foreach (var selection in selectors) + { + string definition = selection.Name + " == TRUE"; + int start = text.IndexOf(definition, StringComparison.Ordinal); + Endpoint endpoint = new(selection.Name, "Review", "operator", + Files.At(model, text, start, start + definition.Length), definition); + spans.Add(new(endpoint, start, start + definition.Length)); + declarations.Add(new(new("review::" + selection.Name.ToLowerInvariant(), Source: selection.Selector), endpoint, 0)); + } + FormalTarget target = new("review", "tla", [model], RequiredBindings: declarations.Select(d => d.Binding.Id).ToList()); + return new(cs, model, target, new(spans, declarations, [])); + } + + private static LinkInspectionResult Read(Inputs fixture, params string[] args) => + LinkInspection.Build(fixture.Target, fixture.Native, CSharpScope.Parse([fixture.Source]), + new(["links", "inspect", "--annotation-version", "4", .. args]), new(FilePaths.Comparer)); +} diff --git a/tests/TlaLink.Tests/IntegratedTlaOnlyTests.cs b/tests/TlaLink.Tests/IntegratedTlaOnlyTests.cs new file mode 100644 index 0000000..621cc53 --- /dev/null +++ b/tests/TlaLink.Tests/IntegratedTlaOnlyTests.cs @@ -0,0 +1,101 @@ +using System.Text.Json; +using System.Collections.Immutable; +using TlaLink; + +namespace TlaLink.Tests; + +public static class IntegratedTlaOnlyTests +{ + public static void Register(Action test, string root, string work) + { + string jar = TestTools.Jar(root); + string Fixture(string name) + { + string directory = Directory.CreateDirectory(Path.Combine(work, name)).FullName; + foreach (string file in new[] { "Counter.cs", "CounterModel.tla", "scope.json", "bindings.json" }) + File.Copy(Path.Combine(AppContext.BaseDirectory, "Fixtures", "TlaOnlyInspection", file), Path.Combine(directory, file)); + return directory; + } + test("TLA-only integrated inspection resolves and archives attachments without a Dafny tool or stages", () => + { + string directory = Fixture("tla-only"); + string output = Path.Combine(directory, "result"); + var response = TestCli.Run(["inspect-integrated", "--annotation-version", "4", "--bindings", + Path.Combine(directory, "bindings.json"), "--jar", jar, "--output", output]); + if (response.Code != 0) throw new InvalidOperationException(response.Json); + string resultPath = Path.Combine(output, "result.json"); + IntegratedResult result = ProjectInputs.Read(resultPath); + CoreTests.Equal("ready", result.Status); + CoreTests.Equal("not-run", result.ProofStatus); + CoreTests.Equal("not-run", result.ConformanceStatus); + CoreTests.Equal(0, result.Links.Length); + CoreTests.Equal(0, result.Stages.Count); + CoreTests.Equal("counter-only::increment", result.Tla!.Links.Single().Key); + CoreTests.Equal(0, IntegratedEvidence.Validate(result, Path.Combine(output, "inputs")).Count); + if (OperatingSystem.IsWindows()) + { + var recased = result.Tla with { + Inventory = result.Tla.Inventory.Select(e => e with { + Location = e.Location with { Path = char.ToLowerInvariant(e.Location.Path[0]) + e.Location.Path[1..] } + }).ToImmutableArray() + }; + CoreTests.Equal(0, IntegratedEvidence.Validate(result with { Tla = recased }, + Path.Combine(output, "inputs")).Count); + } + CoreTests.Equal(0, TestCli.Run(["read-integrated", "--result", resultPath, "--current", "true"]).Code); + CoreTests.True(IntegratedEvidence.Validate(result with { + Tla = result.Tla with { Links = [] } + }, Path.Combine(output, "inputs")).Count > 0); + CoreTests.True(IntegratedEvidence.Validate(result with { + Tla = result.Tla with { Inventory = [] } + }, Path.Combine(output, "inputs")).Count > 0); + Link original = result.Tla.Links.Single(); + CoreTests.True(IntegratedEvidence.Validate(result with { + Tla = result.Tla with { Links = [original with { + Implementation = original.Implementation with { + Location = original.Implementation.Location with { Line = 1 } + } + }] } + }, Path.Combine(output, "inputs")).Count > 0); + File.AppendAllText(Path.Combine(directory, "CounterModel.tla"), "\n"); + CoreTests.Equal(0, TestCli.Run(["read-integrated", "--result", resultPath]).Code); + CoreTests.Equal(2, TestCli.Run(["read-integrated", "--result", resultPath, "--current", "true"]).Code); + }); + test("TLA-only project inspection requires only the selected JAR and cannot become a proof stage", () => + { + string directory = Fixture("tla-only-project"); + string path = Path.Combine(directory, "project.json"); + AnalysisProject project = new(Schema.Version, "analysis-project", "tla-only", + new(Jar: new(jar, Files.Hash(jar))), new("net10.0", "14", "enable", false, true, []), + "requirements.json", [new("scope", [new("links", "inspect", [], 30, Bindings: "bindings.json")])], + [], "reviews"); + Files.WriteNew(path, project); + Files.WriteNew(Path.Combine(directory, "requirements.json"), + new AcceptancePolicy(Schema.Version, "acceptance-policy", project.Id, + [new("links", "scope", "links", "passed")])); + string output = Path.Combine(directory, "run"); + var run = TestCli.Run(["run", "--project", path, "--scenario", "scope", "--output", output]); + if (run.Code != 0) throw new InvalidOperationException(run.Json); + CoreTests.Equal(0, TestCli.Run(["accept", "--project", path, "--run", output]).Code); + foreach (string kind in new[] { "verify", "oracle" }) + { + AnalysisProject invalid = project with { + Scenarios = [new("scope", [new("links", kind, [], 30, Bindings: "bindings.json")])] + }; + File.WriteAllText(path, JsonSerializer.Serialize(invalid, Files.Json)); + CoreTests.Equal(2, TestCli.Run(["doctor", "--project", path, "--scenario", "scope"]).Code); + } + }); + test("TLA-only manifests reject proof and oracle commands rather than reporting vacuous success", () => + { + string directory = Fixture("tla-only-commands"); + foreach (string command in new[] { "verify-integrated", "test-integrated" }) + { + var response = TestCli.Run([command, "--annotation-version", "4", "--bindings", + Path.Combine(directory, "bindings.json"), "--jar", jar, "--output", Path.Combine(directory, command)]); + CoreTests.Equal(2, response.Code); + CoreTests.True(response.Json.Contains("require selected Dafny bindings", StringComparison.Ordinal)); + } + }); + } +} diff --git a/tests/TlaLink.Tests/LinkInspectionTests.cs b/tests/TlaLink.Tests/LinkInspectionTests.cs index 7d991a3..95a8c05 100644 --- a/tests/TlaLink.Tests/LinkInspectionTests.cs +++ b/tests/TlaLink.Tests/LinkInspectionTests.cs @@ -7,6 +7,7 @@ public static class LinkInspectionTests { public static void Register(Action test, string work) { + InspectionReviewContextTests.Register(test, work); test("inspection inlines native and exact source syntax with lexical guards and observations", () => { var fixture = Fixture(work, "context"); diff --git a/tests/TlaLink.Tests/MethodSummaryTests.cs b/tests/TlaLink.Tests/MethodSummaryTests.cs index 9e94467..402a801 100644 --- a/tests/TlaLink.Tests/MethodSummaryTests.cs +++ b/tests/TlaLink.Tests/MethodSummaryTests.cs @@ -120,6 +120,12 @@ public static void RegisterNative(Action test, string root, stri string runPath = Path.Combine(first, "run.json"), originalRun = File.ReadAllText(runPath); try { + string recordedSummary = initial.Fingerprints.Keys.Single(p => Path.GetFileName(p) == "PermitSummary.tla"); + string summaryHash = initial.Fingerprints[recordedSummary]; + initial.Fingerprints.Remove(recordedSummary); + initial.Fingerprints.Add(Path.Combine(Path.GetDirectoryName(recordedSummary)!, "permitsummary.tla"), summaryHash); + File.WriteAllText(runPath, JsonSerializer.Serialize(initial, Files.Json)); + CoreTests.Equal(OperatingSystem.IsWindows() ? 0 : 2, f.Cli("accept", "--run", first).Code); JsonObject changed = JsonNode.Parse(originalRun)!.AsObject(); changed["method_summaries"] = new JsonArray(); File.WriteAllText(runPath, changed.ToJsonString(Files.Json)); diff --git a/tests/TlaLink.Tests/NativeContractTests.cs b/tests/TlaLink.Tests/NativeContractTests.cs index 2b14ee3..fa13773 100644 --- a/tests/TlaLink.Tests/NativeContractTests.cs +++ b/tests/TlaLink.Tests/NativeContractTests.cs @@ -163,6 +163,29 @@ public static void Register(Action test, string work) CoreTests.ThrowsAny(() => JsonSerializer.Deserialize(json, TlaNativeJson.Options)); }); + test("one SANY response binds endpoint rows and native metadata without a second parse", () => + { + string json = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", "TlaFrontend", "Response.json")); + TlaNativeParse parsed = TlaNativeJson.ReadParse(json); + CoreTests.Equal(2, parsed.Entries.Count); + CoreTests.Equal("Sample", parsed.Metadata.Module); + CoreTests.Equal("state", parsed.Metadata.Variables.Single()); + CoreTests.Equal(2, parsed.Metadata.Arities["Apply"]); + foreach (string field in new[] { "entries", "metadata" }) + { + System.Text.Json.Nodes.JsonObject missing = System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject(); + missing.Remove(field); + CoreTests.ThrowsAny(() => TlaNativeJson.ReadParse(missing.ToJsonString())); + System.Text.Json.Nodes.JsonObject nulled = System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject(); + nulled[field] = null; + CoreTests.ThrowsAny(() => TlaNativeJson.ReadParse(nulled.ToJsonString())); + } + foreach (string invalid in new[] { "null", "[]", + """{"entries":[null],"metadata":{"module":"Sample","variables":[],"arities":{}}}""", + """{"entries":[],"metadata":{"module":"Sample","variables":[null],"arities":{}}}""", + """{"entries":[],"metadata":{"module":"Sample","variables":[],"arities":{"Apply":-1}}}""" }) + CoreTests.ThrowsAny(() => TlaNativeJson.ReadParse(invalid)); + }); test("native P and reused Dafny frontend contracts require typed envelope collections", () => { string path = JsonSerializer.Serialize(Path.Combine(work, "Demo.p")); diff --git a/tests/TlaLink.Tests/Program.cs b/tests/TlaLink.Tests/Program.cs index 815b322..c166d3e 100644 --- a/tests/TlaLink.Tests/Program.cs +++ b/tests/TlaLink.Tests/Program.cs @@ -19,13 +19,13 @@ public static int Main(string[] args) } string root = FilePaths.Full(args.FirstOrDefault() ?? Path.Combine(AppContext.BaseDirectory, @"..\..\..\..\..")); string[] testArguments = args.Skip(1).ToArray(); - string[] selections = ["--core", "--trace", "--apalache", "--p", "--diagnostics", "--integrated", "--workflow", "--evidence", "--summaries", "--symbols", "--links"]; + string[] selections = ["--core", "--trace", "--apalache", "--p", "--diagnostics", "--integrated", "--workflow", "--evidence", "--summaries", "--symbols", "--links", "--frontend"]; if (testArguments.Length > 2 || testArguments.Count(a => a.StartsWith("--", StringComparison.Ordinal)) > 1 || testArguments.Count(a => !a.StartsWith("--", StringComparison.Ordinal)) > 1 || testArguments.Any(a => a.StartsWith("--", StringComparison.Ordinal) && !selections.Contains(a))) { - Console.Error.WriteLine("Usage: TlaLink.Tests [root [report.json] [--core|--trace|--apalache|--p|--diagnostics|--integrated|--workflow|--evidence|--summaries|--symbols|--links]]"); + Console.Error.WriteLine("Usage: TlaLink.Tests [root [report.json] [--core|--trace|--apalache|--p|--diagnostics|--integrated|--workflow|--evidence|--summaries|--symbols|--links|--frontend]]"); return 2; } string? selection = testArguments.SingleOrDefault(a => a.StartsWith("--", StringComparison.Ordinal)); @@ -64,6 +64,14 @@ int Finish() ToolHashTests.Register(Test, work); if (selection is null or "--core" or "--apalache") ApalacheTests.RegisterExample(Test, root); DiagnosticTests.Register(Test); + if (selection == "--frontend") + { + Suite("tla-only-inspection", directory => IntegratedTlaOnlyTests.Register(Test, root, directory)); + Test("Java/SANY/PlusCal backend parity controls", () => + TlaBackendTests.Run(TestTools.Jar(root), + (condition, message) => { if (!condition) throw new InvalidOperationException(message); })); + return Finish(); + } if (selection is null or "--core") { Suite("native-contracts", directory => NativeContractTests.Register(Test, directory)); @@ -157,6 +165,7 @@ int Finish() Suite("java-native", directory => JavaToolchainTests.RegisterNative(Test, directory)); Suite("p", directory => PTests.Register(Test, root, directory)); Suite("integration", directory => IntegrationTests.Register(Test, root, directory)); + Suite("tla-only-inspection", directory => IntegratedTlaOnlyTests.Register(Test, root, directory)); Suite("integrated", directory => IntegratedTests.Register(Test, root, directory)); Suite("workflow", directory => ProjectWorkflowTests.Register(Test, root, directory)); Suite("tlc-store", directory => TlcResultStoreTests.RegisterNative(Test, root, directory)); diff --git a/tests/TlaLink.Tests/ProjectCompositionTests.cs b/tests/TlaLink.Tests/ProjectCompositionTests.cs index f80d459..edb7c44 100644 --- a/tests/TlaLink.Tests/ProjectCompositionTests.cs +++ b/tests/TlaLink.Tests/ProjectCompositionTests.cs @@ -197,7 +197,10 @@ public static void RegisterNative(Action test, string root, stri File.AppendAllText(f.ComponentPath, "\n"); var stale = TestCli.Run(["accept", "--project", f.Path, "--run", output]); CoreTests.Equal(2, stale.Code); - CoreTests.True(stale.Json.Contains("composition differs", StringComparison.Ordinal)); + CoreTests.True(stale.Json.Contains("Stale current input", StringComparison.Ordinal)); + using (JsonDocument classification = JsonDocument.Parse(stale.Json)) + CoreTests.Equal("review-only", classification.RootElement.GetProperty("policy_reassessment") + .GetProperty("status").GetString()); File.WriteAllText(f.ComponentPath, original); string snapshotPath = System.IO.Path.Combine(output, "expanded-project.json"); JsonObject snapshot = JsonNode.Parse(File.ReadAllText(snapshotPath))!.AsObject(); @@ -209,6 +212,36 @@ public static void RegisterNative(Action test, string root, stri var corrupted = TestCli.Run(["accept", "--project", f.Path, "--run", output]); CoreTests.True(corrupted.Code != 0 && corrupted.Json.Contains("archived authoring", StringComparison.Ordinal)); }); + test("native stored TLC evidence supports current-policy review consolidation without another search", () => { + Fixture f = new(work, TestTools.Jar(root)); + ProjectAuthoring authored = ProjectInputs.Read(f.Path); + Save(f.Path, authored with { ResultStore = "results" }); + string output = System.IO.Path.Combine(f.Root, "recorded"); + var execution = TestCli.Run(["run", "--project", f.Path, "--scenario", "complete", "--output", output]); + if (execution.Code != 0) throw new InvalidOperationException(execution.Json); + string runPath = System.IO.Path.Combine(output, "run.json"); + byte[] recordedRun = File.ReadAllBytes(runPath); + Dictionary archivedFiles = Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories) + .ToDictionary(file => file, Files.Hash, FilePaths.Comparer); + ProjectComponent component = ProjectInputs.Read(f.ComponentPath); + Save(f.ComponentPath, component with { Obligations = [] }); + Save(f.Path, authored with { ResultStore = "results", Obligations = + [new("adequacy", "Synthetic current-policy source/model assessment.", [], Inputs: ["verification/inputs.json"])] }); + string policyPath = ProjectInputs.Resolve(f.Path, authored.Requirements); + AcceptancePolicy policy = ProjectInputs.Read(policyPath); + Save(policyPath, policy with { Requirements = policy.Requirements.Select(r => + r with { Reviews = ["adequacy"] }).ToList() }); + var reassessed = TestCli.Run(["accept", "--project", f.Path, "--run", output]); + if (reassessed.Code != 1) throw new InvalidOperationException(reassessed.Json); + using JsonDocument result = JsonDocument.Parse(reassessed.Json); + CoreTests.Equal("consistent", result.RootElement.GetProperty("archive_status").GetString()); + CoreTests.Equal("current", result.RootElement.GetProperty("current_applicability").GetString()); + CoreTests.Equal("review-only", result.RootElement.GetProperty("policy_reassessment").GetProperty("status").GetString()); + CoreTests.Equal("pending", result.RootElement.GetProperty("reviews")[0].GetProperty("status").GetString()); + CoreTests.True(recordedRun.SequenceEqual(File.ReadAllBytes(runPath))); + CoreTests.Equal(archivedFiles.Count, Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Count()); + foreach (var file in archivedFiles) CoreTests.Equal(file.Value, Files.Hash(file.Key)); + }); } private static void Save(string path, object value) => File.WriteAllText(path, JsonSerializer.Serialize(value, Files.Json)); diff --git a/tests/TlaLink.Tests/ProjectWorkflowTests.cs b/tests/TlaLink.Tests/ProjectWorkflowTests.cs index be91ae2..03b596a 100644 --- a/tests/TlaLink.Tests/ProjectWorkflowTests.cs +++ b/tests/TlaLink.Tests/ProjectWorkflowTests.cs @@ -95,6 +95,36 @@ The depth of the complete state graph search is 61. CoreTests.Equal(0, text.Code); CoreTests.True(text.Json.Length < 4000 && text.Json.Contains("project-preflight", StringComparison.Ordinal)); }); + test("workflow execution does not pin review-only context as native input", () => + { + string review = Path.Combine(example, "review-context.md"); + File.Copy(Path.Combine(AppContext.BaseDirectory, "Fixtures", "WorkflowFreshness", "review.md"), review); + string variantPath = Path.Combine(example, "review-project.json"); + string variantPolicy = Path.Combine(example, "review-requirements.json"); + List models = original.Scenarios.Single(s => s.Id == "lanes").Stages + .SelectMany(s => s.Models ?? []).Distinct().ToList(); + AnalysisProject variant = original with { + Id = "review-inputs", Requirements = Path.GetFileName(variantPolicy), + Scenarios = [new("scope", [new("model-inputs", "inputs", [], 30, Models: models)])], + Obligations = [new("inspection", "Synthetic native input review.", [], ["review-context.md"])], + CheckObligations = [] + }; + Save(variantPath, variant); + Save(variantPolicy, new AcceptancePolicy(Schema.Version, "acceptance-policy", variant.Id, + [new("input-check", "scope", "model-inputs", "passed", Reviews: ["inspection"])])); + string output = Path.Combine(work, "review-input-run"); + var execution = TestCli.Run(["run", "--project", variantPath, "--scenario", "scope", "--output", output]); + if (execution.Code != 0) throw new InvalidOperationException(execution.Json); + WorkflowRun run = ProjectInputs.Read(Path.Combine(output, "run.json")); + CoreTests.True(!run.Fingerprints.ContainsKey(review)); + File.AppendAllText(review, "\nChanged review context after execution.\n"); + var response = TestCli.Run(["accept", "--project", variantPath, "--run", output]); + CoreTests.Equal(1, response.Code); + AcceptanceResult accepted = JsonSerializer.Deserialize(response.Json, Files.Json)!; + CoreTests.Equal("consistent", accepted.ArchiveStatus); + CoreTests.Equal("current", accepted.CurrentApplicability); + CoreTests.Equal("not-accepted", accepted.AcceptanceStatus); + }); test("project rejects obsolete schema unknown fields invalid compiler and cyclic dependencies", () => { try diff --git a/tests/TlaLink.Tests/StageEvidenceTests.cs b/tests/TlaLink.Tests/StageEvidenceTests.cs index c00474e..c603cfd 100644 --- a/tests/TlaLink.Tests/StageEvidenceTests.cs +++ b/tests/TlaLink.Tests/StageEvidenceTests.cs @@ -62,6 +62,10 @@ public static int Main(string[] args) { if (execution.Code != 0) throw new InvalidOperationException(execution.Json); string resultPath = Path.Combine(output, "result.json"); CoreTests.Equal(0, TestCli.Run(["read-regression", "--result", resultPath, "--current", "true"]).Code); + CSharpRegressionResult observed = ProjectInputs.Read(resultPath); + CoreTests.True(!string.IsNullOrWhiteSpace(observed.Build!.Sdk)); + CoreTests.Equal(observed.Build.Sdk, Files.Read(Path.Combine(output, "build", "sdk.log")).Trim()); + CoreTests.True(!File.Exists(Path.Combine(output, "build", "sdk.invocation.json"))); CoreTests.Equal(0, TestCli.Run(["inspect-source", "--annotation-version", "4", "--source", Path.Combine(directory, "Increment.cs"), "--regression-result", resultPath, "--output", Path.Combine(directory, "inventory.json")]).Code); diff --git a/tests/TlaLink.Tests/TestTools.cs b/tests/TlaLink.Tests/TestTools.cs index 429550e..fccfc51 100644 --- a/tests/TlaLink.Tests/TestTools.cs +++ b/tests/TlaLink.Tests/TestTools.cs @@ -12,7 +12,7 @@ public static IEnumerable ImmutableAssets(string root, string? selection "--core" or "--diagnostics" or "--symbols" => [], "--apalache" => [Jar(root), Apalache(root)], "--p" => [PCompiler(root)], - "--trace" or "--summaries" or "--links" => [Jar(root)], + "--trace" or "--summaries" or "--links" or "--frontend" => [Jar(root)], "--integrated" or "--workflow" or "--evidence" => [Jar(root), Dafny(root)], null => [Jar(root), Apalache(root), Dafny(root), PCompiler(root)], _ => throw new ArgumentException("Unknown test selection: " + selection) diff --git a/tests/TlaLink.Tests/TlaBackendTests.cs b/tests/TlaLink.Tests/TlaBackendTests.cs index 721e9ac..ffa7ff4 100644 --- a/tests/TlaLink.Tests/TlaBackendTests.cs +++ b/tests/TlaLink.Tests/TlaBackendTests.cs @@ -125,6 +125,15 @@ EXTENDS Naturals private static void MetadataAndOffsets(Fixture fixture) { + string imported = fixture.Sample("MetadataBase"); + TlaDocument composed = fixture.Parse(fixture.Sample("MetadataRoot")); + fixture.Check(composed.Module == "MetadataRoot", "Combined response root module"); + fixture.Check(composed.Variables.Order(StringComparer.Ordinal).SequenceEqual(new[] { "inherited", "own" }), + "Same-pass metadata retains imported state variables"); + fixture.Check(composed.Endpoints.Single(e => e.Kind == "operator").Name == "RootApply" && + composed.Endpoints.Single(e => e.Kind == "operator").Arity == 2, + "Same-pass metadata retains root higher-order arity without importing endpoints"); + fixture.Check(composed.DependencyFingerprints.ContainsKey(imported), "Same-pass metadata retains dependency pins"); var parsed = fixture.Parse(fixture.Write("Arity", "VARIABLE x\nApply(F(_), arg) == F(arg)\nPair(a,b) == <>")); fixture.Check(parsed.Variables.SequenceEqual(new[] { "x" }), "Declared state variable"); @@ -163,6 +172,12 @@ private sealed class Fixture(string jar, string directory, Action { public string Jar => jar; public void Check(bool condition, string message) => check(condition, message); + public string Sample(string module) + { + string path = Path.Combine(directory, module + ".tla"); + File.Copy(Path.Combine(AppContext.BaseDirectory, "Fixtures", "TlaFrontend", module + ".tla"), path); + return path; + } public string Write(string module, string body) { string path = Path.Combine(directory, module + ".tla"); diff --git a/tests/TlaLink.Tests/TlcResultStoreTests.cs b/tests/TlaLink.Tests/TlcResultStoreTests.cs index 78ebcea..bedb619 100644 --- a/tests/TlaLink.Tests/TlcResultStoreTests.cs +++ b/tests/TlaLink.Tests/TlcResultStoreTests.cs @@ -130,6 +130,27 @@ void Review() => CoreTests.Equal(0, TestCli.Run(["record-review", "--project", p CoreTests.Equal(Accept("first"), Accept("second")); Review(); CoreTests.Equal(0, Accept("second")); + string recordedPath = Path.Combine(work, "tlc-store-second", "run.json"); + string recorded = Files.Read(recordedPath); + try + { + WorkflowRun variant = ProjectInputs.Read(recordedPath); + string key = variant.Fingerprints.Keys.Single(p => FilePaths.Comparer.Equals(p, model)); + string hash = variant.Fingerprints[key]; + variant.Fingerprints.Remove(key); + variant.Fingerprints.Add(Path.Combine(Path.GetDirectoryName(key)!, "counter.tla"), hash); + File.WriteAllText(recordedPath, JsonSerializer.Serialize(variant, Files.Json)); + var casing = TestCli.Run(["accept", "--project", path, "--run", Path.Combine(work, "tlc-store-second")]); + CoreTests.Equal(OperatingSystem.IsWindows() ? 0 : 2, casing.Code); + CoreTests.Equal(!OperatingSystem.IsWindows(), casing.Json.Contains("WF014", StringComparison.Ordinal)); + if (OperatingSystem.IsWindows()) + { + variant.Fingerprints.Add(key, hash); + File.WriteAllText(recordedPath, JsonSerializer.Serialize(variant, Files.Json)); + CoreTests.True(Accept("second") != 0); + } + } + finally { File.WriteAllText(recordedPath, recorded); } var plan = TestCli.Run(["plan", "--project", path, "--scenario", "complete"]); CoreTests.Equal(0, plan.Code); CoreTests.True(plan.Json.Contains("\"stored\"", StringComparison.Ordinal)); diff --git a/tests/TlaLink.Tests/WorkflowFreshnessTests.cs b/tests/TlaLink.Tests/WorkflowFreshnessTests.cs new file mode 100644 index 0000000..616de9b --- /dev/null +++ b/tests/TlaLink.Tests/WorkflowFreshnessTests.cs @@ -0,0 +1,407 @@ +using System.Text.Json; +using TlaLink; + +namespace TlaLink.Tests; + +public static class WorkflowFreshnessTests +{ + private sealed record Fixture(string Directory, string ProjectPath, string RunDirectory, + AnalysisProject Project, AcceptancePolicy Policy, WorkflowRun Run) + { + internal (AcceptanceResult Report, int ExitCode, AcceptanceWorklist Worklist) Evaluate() => + ProjectAcceptance.Evaluate(ProjectPath, Project, Policy, RunDirectory); + } + + private static Fixture Create(string work, string name, bool executedReview = false, bool emptyClosure = false, + bool multipleReviews = false) + { + string directory = Directory.CreateDirectory(Path.Combine(work, "freshness-" + name)).FullName; + string samples = Path.Combine(AppContext.BaseDirectory, "Fixtures", "WorkflowFreshness"); + foreach (string file in new[] { "Model.tla", "review.md", "tool.txt", "unclassified.txt" }) + File.Copy(Path.Combine(samples, file), Path.Combine(directory, file)); + string projectPath = Path.Combine(directory, "project.json"), policyPath = Path.Combine(directory, "requirements.json"); + List obligations = [new("inspection", "Synthetic review context.", [], ["review.md"])]; + if (multipleReviews) obligations.Add(new("second-inspection", "A second synthetic review area.", [], ["review.md"])); + AnalysisProject authored = new(Schema.Version, "analysis-project", "freshness", new(Jar: + new("tool.txt", Files.Hash(Path.Combine(directory, "tool.txt")))), + new("net10.0", "14", "enable", false, true, []), "requirements.json", + [new("scope", [new("model-inputs", "inputs", [], 30, Models: ["Model.tla"])])], + obligations, "reviews"); + AcceptancePolicy policy = new(Schema.Version, "acceptance-policy", "freshness", + [new("scope-inputs", "scope", "model-inputs", "passed", + Reviews: multipleReviews ? ["inspection", "second-inspection"] : ["inspection"])]); + Files.WriteNew(projectPath, authored); + Files.WriteNew(policyPath, policy); + AnalysisProject project = ProjectInputs.Load(projectPath).Project; + string runDirectory = Directory.CreateDirectory(Path.Combine(directory, "run")).FullName; + Directory.CreateDirectory(Path.Combine(runDirectory, "inputs")); + string stageDirectory = Directory.CreateDirectory(Path.Combine(runDirectory, "model-inputs")).FullName; + string resultPath = Path.Combine(stageDirectory, "result.json"); + Dictionary captured = new(FilePaths.Comparer); + if (!emptyClosure) + { + string model = Path.Combine(directory, "Model.tla"); + captured.Add(model, Files.Hash(model)); + if (executedReview) + { + string review = Path.Combine(directory, "review.md"); + captured.Add(review, Files.Hash(review)); + } + } + Files.WriteNew(resultPath, new ModelInputsResult(Schema.Version, "model-inputs", "inputs", "ready", + captured, [], new(["inputs"], directory, "unexecuted synthetic producer"))); + string evidence = Path.Combine("model-inputs", "result.json"); + WorkflowRun run = new() { + Project = project.Id, ProjectDirectory = directory, Scenario = "scope", ExecutionStatus = "completed", + ProjectSha256 = Files.Hash(projectPath), RequirementsSha256 = Files.Hash(policyPath), + Stages = [new("model-inputs", "inputs", "completed", "passed", evidence, Files.Hash(resultPath), [], 1)] + }; + foreach (string file in new[] { projectPath, policyPath, "Model.tla", "review.md", "tool.txt", "unclassified.txt" }) + { + string input = FilePaths.IsAbsolute(file) ? file : Path.Combine(directory, file); + string hash = Files.Hash(input); + run.Fingerprints.Add(input, hash); + string copy = Path.Combine(runDirectory, "inputs", hash); + if (!File.Exists(copy)) File.Copy(input, copy); + } + run.Artifacts.Add(evidence, Files.Hash(resultPath)); + string expansion = Path.Combine(runDirectory, "expanded-project.json"); + Files.WriteNew(expansion, ProjectComposition.Expansion(projectPath, project)); + run.Artifacts.Add("expanded-project.json", Files.Hash(expansion)); + Files.WriteNew(Path.Combine(runDirectory, "run.json"), run); + return new(directory, projectPath, runDirectory, project, policy, run); + } + + private static void Save(string file, T value) => File.WriteAllText(file, JsonSerializer.Serialize(value, Files.Json)); + + private static Fixture Reload(Fixture fixture) + { + var current = ProjectInputs.Load(fixture.ProjectPath); + return fixture with { Project = current.Project, Policy = current.Policy }; + } + + private static Fixture ReplaceReview(Fixture fixture) + { + Save(fixture.ProjectPath, fixture.Project with { + Obligations = [new("adequacy", "One scoped synthetic mapping review.", ["Cooperative synthetic callers."], ["review.md"])] + }); + Save(Path.Combine(fixture.Directory, "requirements.json"), fixture.Policy with { + Requirements = fixture.Policy.Requirements.Select(r => r with { Reviews = ["adequacy"] }).ToList() + }); + return Reload(fixture); + } + + private static void Decision(Fixture fixture, string id, ReviewOrigin origin = ReviewOrigin.Human) + { + ReviewObligation obligation = fixture.Project.Obligations.Single(o => o.Id == id); + string directory = Directory.CreateDirectory(Path.Combine(fixture.Directory, "reviews", id)).FullName; + Files.WriteNew(Path.Combine(directory, "synthetic.json"), new ReviewDecision(Schema.Version, "review-decision", + id, Schema.Hash(obligation), "accepted", "unit-test-data-only", + "Synthetic acceptance data; not a real human approval.", DateTimeOffset.UtcNow, + new(FilePaths.Comparer) { ["review.md"] = Files.Hash(Path.Combine(fixture.Directory, "review.md")) }, + ["review.md"], origin)); + } + + public static void Register(Action test, string work) + { + test("review-only byte changes preserve execution applicability without satisfying human review", () => + { + Fixture f = Create(work, "review-only"); + string review = Path.Combine(f.Directory, "review.md"); + File.AppendAllText(review, "\nAdditional reviewed assumptions.\n"); + var result = f.Evaluate(); + CoreTests.Equal("consistent", result.Report.ArchiveStatus); + CoreTests.Equal("current", result.Report.CurrentApplicability); + CoreTests.Equal("not-accepted", result.Report.AcceptanceStatus); + CoreTests.Equal(1, result.ExitCode); + CoreTests.Equal(review, result.Report.ChangedReviewInputs.Single()); + CoreTests.True(result.Report.Diagnostics.All(d => d.Is(ErrorCode.WorkflowRequirementUnsatisfied))); + AcceptanceSummary summary = (AcceptanceSummary)CommandSummary.Create(result.Report, + new CliOptions(["accept", "--project", f.ProjectPath, "--run", f.RunDirectory]), result.Worklist); + CoreTests.Equal(review, summary.ChangedReviewInputs.Single()); + CoreTests.Equal(1, summary.Counts!["changed_review_inputs"]); + }); + test("execution dependencies win when a declared review input is also consumed by the stage", () => + { + Fixture f = Create(work, "dual-role", executedReview: true); + File.AppendAllText(Path.Combine(f.Directory, "review.md"), "\nChanged execution bytes.\n"); + var result = f.Evaluate(); + CoreTests.Equal("stale", result.Report.CurrentApplicability); + CoreTests.Equal(0, result.Report.ChangedReviewInputs.Count); + CoreTests.True(result.Report.Diagnostics.Any(d => d.Is(ErrorCode.WorkflowEvidenceStale))); + }); + test("review-only changes invalidate a recorded review without invalidating the native execution", () => + { + Fixture f = Create(work, "review-decision"); + string directory = Directory.CreateDirectory(Path.Combine(f.Directory, "reviews", "inspection")).FullName; + string review = Path.Combine(f.Directory, "review.md"); + Files.WriteNew(Path.Combine(directory, "decision.json"), new ReviewDecision(Schema.Version, "review-decision", + "inspection", Schema.Hash(f.Project.Obligations.Single()), "accepted", "synthetic-test-reviewer", + "Unit test data, not a real approval.", DateTimeOffset.UtcNow, + new(StringComparer.Ordinal) { ["review.md"] = Files.Hash(review) }, ["review.md"])); + CoreTests.Equal("accepted", f.Evaluate().Report.AcceptanceStatus); + File.AppendAllText(review, "\nChanged review premises.\n"); + var result = f.Evaluate(); + CoreTests.Equal("current", result.Report.CurrentApplicability); + CoreTests.Equal("not-accepted", result.Report.AcceptanceStatus); + CoreTests.Equal("stale", result.Report.Reviews.Single().Status); + }); + test("model and unclassified input changes still invalidate execution applicability", () => + { + foreach (string input in new[] { "Model.tla", "unclassified.txt" }) + { + Fixture f = Create(work, "changed-" + Path.GetFileNameWithoutExtension(input)); + File.AppendAllText(Path.Combine(f.Directory, input), "\nChanged bytes.\n"); + CoreTests.Equal("stale", f.Evaluate().Report.CurrentApplicability); + } + }); + test("unknown stage closures do not exempt review inputs from current-byte checks", () => + { + Fixture f = Create(work, "unknown", emptyClosure: true); + File.AppendAllText(Path.Combine(f.Directory, "review.md"), "\nChanged bytes.\n"); + CoreTests.Equal("stale", f.Evaluate().Report.CurrentApplicability); + }); + test("review input archives remain byte-checked independently of applicability", () => + { + Fixture f = Create(work, "archive"); + string review = Path.Combine(f.Directory, "review.md"); + File.AppendAllText(Path.Combine(f.RunDirectory, "inputs", f.Run.Fingerprints[review]), "tampered"); + File.AppendAllText(review, "\nChanged review context.\n"); + var result = f.Evaluate(); + CoreTests.Equal("inconsistent", result.Report.ArchiveStatus); + CoreTests.Equal("stale", result.Report.CurrentApplicability); + CoreTests.Equal(0, result.Report.ChangedReviewInputs.Count); + }); + test("review-only removal is explicit and cannot silently approve its review", () => + { + Fixture f = Create(work, "missing-review"); + string review = Path.Combine(f.Directory, "review.md"); + File.Delete(review); + var result = f.Evaluate(); + CoreTests.Equal("current", result.Report.CurrentApplicability); + CoreTests.Equal(review, result.Report.ChangedReviewInputs.Single()); + CoreTests.Equal("not-accepted", result.Report.AcceptanceStatus); + }); + test("review policy reassessment keeps execution current and requires the replacement decision", () => + { + Fixture original = Create(work, "policy-replacement", multipleReviews: true); + Decision(original, "inspection"); + Decision(original, "second-inspection"); + CoreTests.Equal("accepted", original.Evaluate().Report.AcceptanceStatus); + byte[] runBytes = File.ReadAllBytes(Path.Combine(original.RunDirectory, "run.json")); + Fixture current = ReplaceReview(original); + var result = current.Evaluate(); + CoreTests.Equal("consistent", result.Report.ArchiveStatus); + CoreTests.Equal("current", result.Report.CurrentApplicability); + CoreTests.Equal("review-only", result.Report.PolicyReassessment!.Status); + CoreTests.True(result.Report.PolicyReassessment.ExecutionDefinitionUnchanged == true); + CoreTests.True(result.Report.PolicyReassessment.CheckerExpectationsUnchanged == true); + CoreTests.Equal("pending", result.Report.Reviews.Single().Status); + CoreTests.Equal("adequacy", result.Report.Reviews.Single().Obligation); + CoreTests.Equal(1, result.ExitCode); + CoreTests.True(result.Report.Diagnostics.All(d => d.Is(ErrorCode.WorkflowRequirementUnsatisfied))); + CoreTests.True(runBytes.SequenceEqual(File.ReadAllBytes(Path.Combine(current.RunDirectory, "run.json")))); + AcceptanceSummary summary = (AcceptanceSummary)CommandSummary.Create(result.Report, + new CliOptions(["accept", "--project", current.ProjectPath, "--run", current.RunDirectory]), result.Worklist); + CoreTests.Equal("review-only", summary.PolicyReassessment!.Status); + CoreTests.True(summary.PolicyReassessment.Recorded.RequirementsSha256 != + summary.PolicyReassessment.Current.RequirementsSha256); + Decision(current, "adequacy"); + CoreTests.Equal("accepted", current.Evaluate().Report.AcceptanceStatus); + CoreTests.True(runBytes.SequenceEqual(File.ReadAllBytes(Path.Combine(current.RunDirectory, "run.json")))); + }); + test("review input-set edits and added context are reassessed without weakening execution inputs", () => + { + Fixture f = Create(work, "policy-input-set"); + File.Copy(Path.Combine(f.Directory, "review.md"), Path.Combine(f.Directory, "new-review.md")); + Save(Path.Combine(f.Directory, "review-inputs.json"), new ProjectInputSets(Schema.Version, + "project-input-sets", [new("context", ["new-review.md"])])); + Save(f.ProjectPath, new ProjectAuthoring(Schema.Version, "analysis-project", f.Project.Id, + f.Project.Tools, f.Project.Compiler, "requirements.json", + [new("scope", Stages: [new("model-inputs", "inputs", TimeoutSeconds: 30, Models: ["Model.tla"])])], + "reviews", Obligations: [new("inspection", "Changed review input set.", [], InputSets: ["context"])], + InputSets: ["review-inputs.json"], AnnotationVersion: 4)); + File.Delete(Path.Combine(f.Directory, "review.md")); + var result = Reload(f).Evaluate(); + CoreTests.Equal("review-only", result.Report.PolicyReassessment!.Status); + CoreTests.Equal("current", result.Report.CurrentApplicability); + CoreTests.Equal("pending", result.Report.Reviews.Single().Status); + CoreTests.True(result.Report.ChangedReviewInputs.Contains(Path.Combine(f.Directory, "review.md"))); + }); + test("component review consolidation reconstructs archived authoring instead of trusting edited snapshots", () => + { + Fixture f = Create(work, "component-policy"); + string component = Path.Combine(f.Directory, "component.json"); + Save(component, new ProjectComponent(Schema.Version, "project-component", "layer", + [new("model-inputs", "inputs", TimeoutSeconds: 30, Models: ["Model.tla"])], + [new("inspection", "Synthetic review context.", [], Inputs: ["review.md"])])); + ProjectAuthoring root = new(Schema.Version, "analysis-project", f.Project.Id, f.Project.Tools, + f.Project.Compiler, "requirements.json", [new("scope", Components: ["layer"])], "reviews", + Components: ["component.json"], AnnotationVersion: 4); + Save(f.ProjectPath, root); + f = Reload(f); + foreach (string input in new[] { f.ProjectPath, component }) + { + string hash = Files.Hash(input); + f.Run.Fingerprints[input] = hash; + File.Copy(input, Path.Combine(f.RunDirectory, "inputs", hash), overwrite: true); + } + WorkflowRun composed = new() { + Project = f.Run.Project, ProjectDirectory = f.Run.ProjectDirectory, Scenario = f.Run.Scenario, + ProjectSha256 = Files.Hash(f.ProjectPath), RequirementsSha256 = f.Run.RequirementsSha256, + ExecutionStatus = f.Run.ExecutionStatus, Stages = f.Run.Stages, Fingerprints = f.Run.Fingerprints, + Artifacts = new(f.Run.Artifacts, StringComparer.Ordinal) + }; + string expansion = Path.Combine(f.RunDirectory, "expanded-project.json"); + Save(expansion, ProjectComposition.Expansion(f.ProjectPath, f.Project)); + composed.Artifacts["expanded-project.json"] = Files.Hash(expansion); + Save(Path.Combine(f.RunDirectory, "run.json"), composed); + CoreTests.Equal("current", f.Evaluate().Report.CurrentApplicability); + ProjectComponent layer = ProjectInputs.Read(component); + Save(component, layer with { Obligations = [] }); + Save(f.ProjectPath, root with { Obligations = + [new("adequacy", "Consolidated synthetic review.", [], Inputs: ["review.md"])] }); + Save(Path.Combine(f.Directory, "requirements.json"), f.Policy with { + Requirements = [f.Policy.Requirements.Single() with { Reviews = ["adequacy"] }] + }); + var result = Reload(f).Evaluate(); + CoreTests.Equal("review-only", result.Report.PolicyReassessment!.Status); + CoreTests.Equal("current", result.Report.CurrentApplicability); + CoreTests.Equal("pending", result.Report.Reviews.Single().Status); + File.AppendAllText(expansion, "damaged"); + result = Reload(f).Evaluate(); + CoreTests.Equal("inconsistent", result.Report.ArchiveStatus); + CoreTests.Equal(0, result.Report.ChangedReviewInputs.Count); + }); + test("execution configuration compiler tools and check coverage are never review-only policy edits", () => + { + foreach (string kind in new[] { "deadline", "compiler", "tool", "coverage", "model" }) + { + Fixture f = Create(work, "execution-policy-" + kind); + AnalysisProject changed = kind switch { + "deadline" => f.Project with { Scenarios = [new("scope", + [f.Project.Scenarios.Single().Stages.Single() with { TimeoutSeconds = 31 }])] }, + "compiler" => f.Project with { Compiler = f.Project.Compiler with { Defines = ["SYNTHETIC_DEFINE"] } }, + "tool" => f.Project with { Tools = f.Project.Tools with { Jar = new("tool.txt", new string('A', 64)) } }, + "coverage" => f.Project with { CheckObligations = [new("new-check", "safety", "scope", ["scope-inputs"])] }, + _ => f.Project with { Scenarios = [new("scope", + [f.Project.Scenarios.Single().Stages.Single() with { Models = ["review.md"] }])] } + }; + Save(f.ProjectPath, changed); + var result = Reload(f).Evaluate(); + CoreTests.Equal("incompatible", result.Report.PolicyReassessment!.Status); + CoreTests.Equal("stale", result.Report.CurrentApplicability); + CoreTests.True(result.Report.Diagnostics.Any(d => d.Is(ErrorCode.WorkflowProjectChanged))); + } + }); + test("every non-review checker expectation remains part of the compatibility comparison", () => + { + Fixture f = Create(work, "native-expectations"); + AnalysisRequirement r = f.Policy.Requirements.Single(); + AnalysisRequirement[] changes = [ + r with { Expected = "rejected", Diagnostic = "SYN001" }, + r with { ConfigSha256 = new string('A', 64) }, + r with { Claim = "different-native-claim" }, + r with { Diagnostic = "SYN001" }, + r with { DiagnosticText = "different" }, + r with { DiagnosticCount = 2 }, + r with { Bindings = ["synthetic::different"] }, + r with { Cases = ["synthetic::case/different"] }, + r with { Tests = ["different-test"] }, + r with { FingerprintFunctions = 2 } + ]; + foreach (AnalysisRequirement changed in changes) + { + AcceptancePolicy current = f.Policy with { Requirements = [changed] }; + Save(Path.Combine(f.Directory, "requirements.json"), current); + WorkflowPolicyComparison.Result comparison = WorkflowPolicyComparison.Compare(f.ProjectPath, + f.Project, current, f.Run, f.RunDirectory, f.Project); + CoreTests.Equal("incompatible", comparison.Report.Status); + CoreTests.True(comparison.Report.CheckerExpectationsUnchanged == false); + } + }); + test("unknown authoring fields cannot enter automatic policy reassessment", () => + { + foreach (string kind in new[] { "project", "requirements" }) + { + Fixture f = Create(work, "unknown-policy-field-" + kind); + string path = kind == "project" ? f.ProjectPath : Path.Combine(f.Directory, "requirements.json"); + string content = File.ReadAllText(path); + File.WriteAllText(path, content.Insert(content.IndexOf('{') + 1, "\"unknown_execution_setting\":true,")); + if (kind == "project") CoreTests.ThrowsAny(() => Reload(f)); + else CoreTests.ThrowsAny(() => Reload(f)); + } + }); + test("authoring changes after loading cannot masquerade as an unchanged policy snapshot", () => + { + Fixture f = Create(work, "changed-after-loading-project"); + Save(f.ProjectPath, f.Project with { + Compiler = f.Project.Compiler with { Defines = ["LATER_EXECUTION_CHANGE"] } + }); + var result = f.Evaluate(); + CoreTests.Equal("stale", result.Report.CurrentApplicability); + CoreTests.True(result.Report.Diagnostics.Any(d => d.Is(ErrorCode.WorkflowEvidenceStale))); + f = Create(work, "changed-after-loading-policy"); + Save(Path.Combine(f.Directory, "requirements.json"), f.Policy with { + Requirements = [f.Policy.Requirements.Single() with { Expected = "rejected", Diagnostic = "SYN001" }] + }); + result = f.Evaluate(); + CoreTests.Equal("stale", result.Report.CurrentApplicability); + CoreTests.True(result.Report.Diagnostics.Any(d => d.Is(ErrorCode.WorkflowEvidenceStale))); + }); + test("a stage-consumed project remains an execution dependency even during policy reassessment", () => + { + Fixture f = Create(work, "project-dual-role"); + string resultPath = Path.Combine(f.RunDirectory, "model-inputs", "result.json"); + ModelInputsResult result = ProjectInputs.Read(resultPath); + result.Fingerprints.Add(f.ProjectPath, f.Run.ProjectSha256); + Save(resultPath, result); + string hash = Files.Hash(resultPath); + f.Run.Artifacts[Path.Combine("model-inputs", "result.json")] = hash; + f.Run.Stages[0] = f.Run.Stages[0] with { Sha256 = hash }; + Save(Path.Combine(f.RunDirectory, "run.json"), f.Run); + var evaluation = ReplaceReview(f).Evaluate(); + CoreTests.Equal("review-only", evaluation.Report.PolicyReassessment!.Status); + CoreTests.Equal("stale", evaluation.Report.CurrentApplicability); + CoreTests.True(evaluation.Report.Diagnostics.Any(d => d.Is(ErrorCode.WorkflowEvidenceStale))); + }); + test("missing policy snapshots unknown closures and damaged policy archives fail closed", () => + { + foreach (string kind in new[] { "snapshot", "closure", "policy" }) + { + Fixture f = Create(work, "policy-fail-closed-" + kind, emptyClosure: kind == "closure"); + if (kind == "snapshot") File.Delete(Path.Combine(f.RunDirectory, "expanded-project.json")); + if (kind == "policy") + File.AppendAllText(Path.Combine(f.RunDirectory, "inputs", f.Run.RequirementsSha256), "damaged"); + var result = ReplaceReview(f).Evaluate(); + CoreTests.Equal("not-accepted", result.Report.AcceptanceStatus); + CoreTests.Equal("stale", result.Report.CurrentApplicability); + CoreTests.True(result.Report.Diagnostics.Any(d => d.Is( + ErrorCode.WorkflowProvenanceInconsistent, ErrorCode.WorkflowEvidenceStale))); + } + }); + test("agent decisions cannot satisfy a human replacement policy", () => + { + Fixture f = ReplaceReview(Create(work, "policy-origin")); + Decision(f, "adequacy", ReviewOrigin.Agent); + var result = f.Evaluate(); + CoreTests.Equal("origin-mismatch", result.Report.Reviews.Single().Status); + CoreTests.Equal("current", result.Report.CurrentApplicability); + CoreTests.Equal("not-accepted", result.Report.AcceptanceStatus); + }); + test("project reports preserve reassessment and pending reviews without replaying the run", () => + { + Fixture f = ReplaceReview(Create(work, "policy-report")); + string output = Path.Combine(f.Directory, "report.md"); + byte[] run = File.ReadAllBytes(Path.Combine(f.RunDirectory, "run.json")); + CoreTests.Equal(0, TlaLink.Program.Main(["report", "--project", f.ProjectPath, "--run", f.RunDirectory, + "--output", output, "--format", "summary"])); + AcceptanceResult acceptance = ProjectInputs.Read(output + ".run-1.acceptance.json"); + CoreTests.Equal("review-only", acceptance.PolicyReassessment!.Status); + CoreTests.Equal("current", acceptance.CurrentApplicability); + CoreTests.Equal("pending", acceptance.Reviews.Single().Status); + CoreTests.True(File.ReadAllText(output).Contains("policy reassessment: review-only", StringComparison.Ordinal)); + CoreTests.True(run.SequenceEqual(File.ReadAllBytes(Path.Combine(f.RunDirectory, "run.json")))); + }); + } +}